How can I display binary image data as an Image in PHRETS - rets

I am using http://otw.rets.interealty.com/Login.asmx/Login
I am getting image as Binay Data. How can I display a binary data from RETS as an Image.
Here is my code
$sysid = $data['sysid'];
$photos = $rets->GetObject("Property", "Photo", $sysid, "*", 1);
echo $photos[0]['Data'];

According to the PHRETS documentation for GetObject, the last argument in GetObject, $location, can either be a "0" or "1". "1" returns the image's URL string and "0" returns the binary image data.
#1 Encoding the image data and outputting to browser without saving to a file. From this SO question
$photos = $rets->GetObject("Property", "Photo", $sysid, "*", 0);
foreach ($photos as $photo)
{
if ($photo['Success'] == true)
{
$contentType = $photo['Content-Type'];
$base64 = base64_encode($photo['Data']);
echo "<img src='data:{$contentType};base64," . $base64 . "' />";
}
else
{
echo "({$photo['Content-ID']}-{$photo['Object-ID']}): {$photo['ReplyCode']} = {$photo['ReplyText']}<br />";
}
}
#2 Saving the image to a file and then displaying it. From PHRETS
$photos = $rets->GetObject("Property", "Photo", $sysid, "*", 0);
foreach ($photos as $photo)
{
if ($photo['Success'] == true)
{
file_put_contents("image-{$listing}-{$number}.jpg", $photo['Data']);
echo "<img src='image-{$listing}-{$number}.jpg' />";
}
else
{
echo "({$photo['Content-ID']}-{$photo['Object-ID']}): {$photo['ReplyCode']} = {$photo['ReplyText']}<br />";
}
}

I would look at the content-type of the results/data you get back. I would save each file with there respective type (.jpg, .bmp) then reference the saved file in you PHP code.
https://github.com/troydavisson/PHRETS/wiki/GetObject

There's some good information in these answers already.
To address your later question, the Interealty server does not support pagination. To use Key Index, you must:
1) use RETS/1.7.2 or later
2) specify Limit => NONE in your SearchRequest
3) give only key index identified fields in your Select parameter within the SearchRequest
If you get those 3 things right, the server should suspend its records-per-response limit.

Related

Domain Meta Validation

I have a code set on Laravel. This is doing dns verification, I want to verify a specific field in the meta tag I want.
Example code
public function verifyDomainDns()
{
$fqdn = sprintf('%s.%s', $this->getVerificationTxtName(), $this->name);
$results = collect(dns_get_record($fqdn, DNS_TXT));
$results = $results->where('type', 'TXT')
->where('txt', $this->verification_token);
$this->domain_verified = $results->isEmpty() ? self::UNVERIFIED : self::VERIFIED;
$this->save();
}
verification_token Auto-generated numbers registered in database
The meta tag I want to verify.
<meta name="book" content="verification_token" />
There is no correlation between what your code is already doing and what you want to do.
One way you can achieve this is to get the contents of the URL with something like file_get_contents(), which will result in you getting the HTML content of the URL.
Once you have this, you can use something like DOMXpath to parse it and get the meta tag's contents.
$html = file_get_contents('https://example.com');
$dom = new DomDocument();
$dom->loadHTML($html);
$xpath = new DomXPath($dom);
$contents = $xpath->query('/html/head/meta[#name="book"]/#content');
if ($contents->length === 0) {
echo 'No tag found';
} else {
foreach ($contents as $content) {
echo $content->value;
}
}

$_SESSION variables use in queries

I have spent nearly two days going in circles on this one.
I seem to have difficulty using $_SESSION or $_POST as strings in any query or converting them to strings to use.
I am using a simple hash approach to login to a site.
Extract from script is
<?php
session_start();
echo "******Running Authenticate<br>";
echo "data submitted<br>".$_POST['site_login']."<br>".$_POST['site_password']."<br><br>";
$SiteLogin = $_POST['site_login']
$_SESSION['site_login'] = $_POST['site_login'];
$_SESSION['site_password'] = $_POST['site_password'];
$_SESSION['session_id'] = session_id();
$_SESSION['Now_val'] = date('Y-m-d H:i:s');
//include 'showallvars.php';
include 'dbconfig.php';
// Prepare our SQL
if ($stmt = $con->prepare('SELECT site_index, site_password FROM web_sites WHERE site_login = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['site_login']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
echo "account exists";
}
else
{
header('Location: badindex.php');
}
if (password_verify($_POST['site_password'], $password)) {
// Verification success! User has loggedin!
echo "password good";
}
else
{
header('Location: badindex.php');
}
}
$_SESSION['loggedin'] = TRUE;
?>
that works fine
BUT there is another field ( 'site_name') in the record which i want to carry forward.
This should be easy !!
and there is a dozen ways of doing it
for example the "standard" example is something like
$name = $mysqli->query("SELECT site_name FROM web_sites WHERE site_login = 'fred'")->fetch_object()->site_name;
That works fine
but no matter how i try - concatenating or or ... I cannot get $_SESSION['site_login'] or $_POST['site_login'] to replace 'fred'.
There seems to be white space added in.
Assistance or guidance ?
It should be possible to as easy as doing the following:
So:
if ($stmt = $con->prepare('SELECT site_index, site_password
FROM web_sites WHERE site_login = ?')) {
becomes:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $SiteLogin)) {
Do note, it is bad practice to do directly parse $SiteLogin to a query, because now someone can SQL Inject this and hack your website. All they need to do is use your form and figure out that which field is responsible for $SiteLogin. You would need to escape your $SiteLogin. Assuming Mysqli, it would become:
if ($stmt = $con->prepare('SELECT site_index, site_password, site_login
FROM web_sites WHERE site_login = ' . $con->real_escape_string($SiteLogin))) {
Thank you for that BUT the instant I saw the curly brackets in your answer - it all came flooding back to me. I had forgotten that PHP has problems with the square brackets
$sql = ("SELECT site_name FROM web_sites WHERE site_login = '". $_SESSION{'site_login'} ."' LIMIT 1");
I KNEW it was easy !
Your comments on injection are of course correct but this was an edited code excerpt and $SiteLogin was just added in as a "temporary working variable if needed"

jquery datatable with ajax based pagination

I have javascript function that populates datatable using Ajax. My javascript code looks like :
$('#results').dataTable({
// Ajax load data
"ajax": {
"url": "get_intl_tickets",
"type": "POST",
"data": {
"user_id": 451,
"csrfmiddlewaretoken" : csrftoken,
}
}
})
My server side script in django has a function that loads around 500 data rows. Now the problem is that I don't want to load whole data at a time. Instead I want to have first 10 data rows. Then with pagination, another 10 rows like that.
I read the page server side processing documentation of datatables. I tried with "serverSide": true option as well. I am not understanding server side script. There is given an example of PHP. It seems that they are not using any parameters like draw, recordsFiltered, recordsTotal there. There they have used php SSP class. And it is unknown what does it do. I am trying to implement it in django.
But I am not finding proper good documentation to implement. Any help will be appreciated.
Old question but one I also had a surprisingly difficult time finding an answer to, so in case anyone else ends up here... :P
I found this 2020 article very helpful, specifically part 6 showing the "complete code" that includes getting the correct variables, building the SQL query, and how to build/structure the data object that it responds with:
https://makitweb.com/datatables-ajax-pagination-with-search-and-sort-php/
Their example posted below:
<?php
## Database configuration
include 'config.php';
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = mysqli_real_escape_string($con,$_POST['search']['value']); // Search value
## Search
$searchQuery = " ";
if($searchValue != ''){
$searchQuery = " and (emp_name like '%".$searchValue."%' or
email like '%".$searchValue."%' or
city like'%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of record with filtering
$sel = mysqli_query($con,"select count(*) as allcount from employee WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from employee WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($con, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)) {
$data[] = array(
"emp_name"=>$row['emp_name'],
"email"=>$row['email'],
"gender"=>$row['gender'],
"salary"=>$row['salary'],
"city"=>$row['city']
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
Nice exemple:
https://datatables.net/examples/server_side/defer_loading.html
But you need edit server side.
Response demo
{
draw:2,
recordsFiltered:57,
recordsTotal:57
}

multi image upload in custom component for joomla

I have tried http://docs.joomla.org/Creating_a_file_uploader_in_your_component but first it shows Error: 500 after some research I have removed code
"'.$session->getName().'" : "'.$session->getId().'",
"format" : "raw"
and error is gone. Now Image is not uploading anywhere (I have set path '/images/' folder) I am confuse in code for uploading image PART 5 where to use this code?
function storeImageFile()
{
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder' );
$path = 'PATH_GOES_HERE'.'designs'.DS;
$folder_permissions = "0755";
$folder_permissions = octdec((int)$folder_permissions);
//create folder if not exists
if (!JFolder::exists($path)){
JFolder::create($path, $folder_permissions);
}
$file = JRequest::getVar('design_images', null, 'files',
$count = count($file['name']);
for($i=0;$i<$count;$i++)
{
//$i is the array position of the $_FILES array
if(empty($file['tmp_name'][$i]))
{
return false;
}
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name'][$i]);
//setting source and destination
$temporary_name = $file['tmp_name'][$i];
$filename = str_replace(' ', '_', $file['name'][$i]);
$dest = $path.$filename;
if(JFile::upload($temporary_name, $dest))
{
echo "File Upload Successful";
return true;
}
}
}

Auto refresh content in Mediawiki

I added a new tag (<news />) to my mediawiki to list the last modified pages.
Unfortunately the list is not updated unless I modify the page where the tag is.
I'm looking for a way to do it, and I think of AJAX. But I didn't manage to make AJAX refreshing my list.
Does anyone know a simple way to add an auto refresh feature on my Mediawiki ?
Here is my extension code :
$wgHooks['ParserFirstCallInit'][] = 'replaceTags';
function replaceTags( Parser $parser ) {
$parser->setHook( 'news', 'newsRender' );
return true;
}
function newsRender( $input, array $args, Parser $parser, PPFrame $frame ) {
// Titre =News=
$output = $parser->parse( "=News=", $parser->mTitle, $parser->mOptions, false, false )->getText();
$nb = 5;
$querySQL = "SELECT page_namespace, page_title, page_id, page_latest, rev_timestamp
FROM page, revision
WHERE page.page_latest = revision.rev_id
AND page_namespace = 0
ORDER BY rev_timestamp
DESC LIMIT 0,$nb";
$dbr = wfGetDB( DB_SLAVE );
$res = $dbr->query( $querySQL );
$count = $dbr->numRows( $res );
if( $count > 0 ) {
$output .= "<ul>";
while( $row = $dbr->fetchObject( $res ) )
{
$pageTitle = $row->page_title;
$nicerPageTitle = str_replace("_", " ", $pageTitle);
$pageNamespace = $row->page_namespace;
$title = Title::makeTitleSafe( $pageNamespace, $pageTitle );
$url = $title->getFullURL();
$date = $row->rev_timestamp;
$date = wfTimestamp( TS_RFC2822, $date );
$output .= "<li>$nicerPageTitle $date</li>";
}
$output .= "</ul>";
} else {
$output .= "A l'ouest rien de nouveau !!!";
}
return $output;
}
Thanks to nischayn22, I go into the cache problem in depth.
And I found that it's possible to deactivate it :
$parser->disableCache();
I tried it, and it works !!!
http://www.mediawiki.org/wiki/Extensions_FAQ#How_do_I_disable_caching_for_pages_using_my_extension.3F
This probably happens because MediaWiki uses Cache for pages. What you could rather do is make a SpecialPage for the feature needed. AFAIK Special Pages are not cached (confirm this on irc #mediawiki).
Also you might already find a similar implementation done by someone if you search the extensions that exist on Mediawiki.org .(Otherwise I would be happy to build one for you :)
Update: Extensions you could use Dynamic List(used in wikinews) and news . There could be more if you search mediawiki.org.

Resources