How to change legend text value amcharts - PHP - php

The legend values always showing same(Last updated value).
Input is text1 and text2 means result is value+s for all.
Which means I cannot change the legend.valueText
Download from https://github.com/amcharts/amcharts3/blob/master/samples/area100PercentStacked.html
Sample Code:
$.each(graphValues, function (graphKey, graphValue) {
var legend = new AmCharts.AmLegend();
legend.borderAlpha = 0.2;
legend.horizontalGap = 10;
legend.spacing = 30;
legend.position = "top";
legend.useGraphSettings = false;
legend.valueWidth = 100;
legend.labelWidth = 200;
legend.valueAlign = "left";
legend.equalWidths = true;
legend.markerLabelGap = 3;
/* Add prefix and suffix */
if (graphValue == 'text1') {
legend.valueText = ': $[[value]]'; //Add prefix "$"
} else if (graphValue == 'text2') {
legend.valueText = ': [[value]]s'; //Add suffix "s"
} else{
legend.valueText = ': [[value]]';
}
/* End of prefix and suffix */
chart.addLegend(legend);
}
Desired result
[[value]]s [[value]]s
Expected result
$[[value]] [[value]]s
Please suggest me!

Related

Sphinx Query is returning null results in PHP

I am currently using PHP to query from my sphinx index. The index is building properly, however the search is not.
Originally I had my query set up like the following:
private function _doMapSearchAll($textSearch, $typeFilterArr, $rads = array(), $centre = array(), $showFavourites = false) {
// lookup the location based on the search and return the results in that
// map bounds ignore for boundary searches
$rsArr = array();
$skipDataSearch = false;
if (!COUNT($rads)) {
// handle airport code lookups if we have 3 characters
if (strlen($textSearch) === 3) {
$rsArr = $this->_doMapAirportSearch($textSearch);
if (COUNT($rsArr)) {
$skipDataSearch = true;
}
}
// still no results based on the above search, do generic map search
if ($skipDataSearch === false) {
$rsArr = $this->_doMapGeoSearch($textSearch, $typeFilterArr, $centre);
if (COUNT($rsArr['results']) > 0) {
$skipDataSearch = false;
}
}
}
// if we are doing a boundary search, or we have no results from the above,
// get all results based on our location
if ($skipDataSearch === false) {
// fall back onto searching via the data
// normalise the search string
$originalSearchString = $this->doNormalisation($textSearch);
// use sphinx for the search
$sphinx = $this->_getSphinxConnection();
$sphinx->setLimits(0, $this->container->getParameter('search_max_results'), $this->container->getParameter('search_max_results'));
if (COUNT($typeFilterArr)) {
$sphinx->SetFilter('fldSiteTypeUID_attr', $typeFilterArr);
}
// if we're doing a boundary search, skip the search string
if (COUNT($rads) > 0) {
$originalSearchString = '';
if ($showFavourites === false) {
//$sphinx->SetFilterFloatRange('lat_radians', min($rads['minLat'], $rads['maxLat']), max($rads['minLat'], $rads['maxLat']));
//$sphinx->SetFilterFloatRange('long_radians', min($rads['minLon'], $rads['maxLon']), max($rads['minLon'], $rads['maxLon']));
if ($rads['minLat'] > $rads['maxLat']) {
$rads['minLat'] = $rads['minLat'] - 360;
}
if ($rads['minLon'] > $rads['maxLon']) {
$rads['minLon'] = $rads['minLon'] - 180;
}
$sphinx->SetFilterFloatRange('lat_radians', $rads['minLat'], $rads['maxLat']);
$sphinx->SetFilterFloatRange('long_radians', $rads['minLon'], $rads['maxLon']);
}
}
// order by centre point
if (COUNT($centre) > 0) {
// otherwise start in the centre
$sphinx->SetGeoAnchor('lat_radians', 'long_radians', (float) $centre['centreLat'], (float) $centre['centreLon']);
$lintDistanceLimit = 999999999.0; // everything
if ($showFavourites === false && isset($rads['maxLat'])) {
$radiusMiles = $this->get('geolocation_helper')->getSeparation(
rad2deg($rads['maxLat']),
rad2deg($rads['minLon']),
rad2deg($rads['minLat']),
rad2deg($rads['maxLon']),
"M"
);
$lintDistanceLimit = $radiusMiles * 1609; // miles to meters...
}
$sphinx->SetFilterFloatRange('geodist', 0.0, (float)$lintDistanceLimit);
$sphinx->SetSortMode(SPH_SORT_EXTENDED, 'geodist ASC');
} else {
// apply search weights
$sphinx->SetFieldWeights(array('fldTown_str' => 100, 'fldAddress1_str' => 30, 'fldSiteName_str' => 20));
}
// if we should be limiting to only favourites, pickup the selected
// favourites from cookies
if ($showFavourites === true) {
$request = $this->container->get('request_stack')->getCurrentRequest();
$favourites = explode(',', $request->cookies->get('HSF_favlist'));
if (count($favourites)) {
foreach ($favourites as $k => $favourite) {
$favourites[$k] = (int)$favourite;
}
$sphinx->SetFilter('fldUID_attr', $favourites);
}
}
$rs = $sphinx->Query($originalSearchString, $this->container->getParameter('sphinx_index'));
echo json_encode($sphinx);
$rsArr['results'] = array();
if (isset($rs['matches']) && count($rs['matches'])) {
// update the search text to what we actually searched for, this
// is needed in case we've updated/set $rsArr['searchText']
// after a geolookup
$rsArr['searchText'] = $textSearch;
// clear any previous bounds set by the geolookup, we don't want this
// if we have direct text match results
$rsArr['geobounds'] = array();
if (isset($rs['matches']) && count($rs['matches'])) {
foreach ($rs['matches'] as $k => $match) {
$rsArr['results'][$k] = $this->_remapSphinxData($k, $match);
}
}
// sort the results by distance
usort($rsArr['results'], function ($a, $b) {
return $a['fldDistance'] - $b['fldDistance'];
});
}
}
// add on the total record count
$rsArr['total'] = (int) COUNT($rsArr['results']);
return $rsArr;
}
That was returning nothing and giving me the error for GEODIST():
{"_host":"sphinx","_port":36307,"_path":"","_socket":false,"_offset":0,"_limit":250,"_mode":0,"_weights":[],"_sort":4,"_sortby":"geodist ASC","_min_id":0,"_max_id":0,"_filters":[{"type":2,"attr":"geodist","exclude":false,"min":0,"max":999999999}],"_groupby":"","_groupfunc":0,"_groupsort":"#group desc","_groupdistinct":"","_maxmatches":"250","_cutoff":0,"_retrycount":0,"_retrydelay":0,"_anchor":{"attrlat":"lat_radians","attrlong":"long_radians","lat":0.9300859583877783,"long":-2.0943951023931953},"_indexweights":[],"_ranker":0,"_rankexpr":"","_maxquerytime":0,"_fieldweights":[],"_overrides":[],"_select":"*","_error":"searchd error: geoanchor is deprecated (and slow); use GEODIST() expression","_warning":"","_connerror":false,"_reqs":[],"_mbenc":"","_arrayresult":false,"_timeout":0}{"results":[],"bounds":{"bllat":53.395603,"trlat":53.7159857,"bllng":-113.7138017,"trlng":-113.2716433},"geocentre":{"lat":53.5461245,"lon":-113.4938229},"checksum":"204a43923452936b00a10c8e566c4a48d4fdb280f97fd4042646eb45c8257bbc","searchText":"Edmonton, AB, Canada","skipResults":true,"showFavourites":false}
To fix this I changed the SetGeoAnchor function to the following:
private function _doMapSearchAll($textSearch, $typeFilterArr, $rads = array(), $centre = array(), $showFavourites = false) {
// lookup the location based on the search and return the results in that
// map bounds ignore for boundary searches
$rsArr = array();
$skipDataSearch = false;
if (!COUNT($rads)) {
// handle airport code lookups if we have 3 characters
if (strlen($textSearch) === 3) {
$rsArr = $this->_doMapAirportSearch($textSearch);
if (COUNT($rsArr)) {
$skipDataSearch = true;
}
}
// still no results based on the above search, do generic map search
if ($skipDataSearch === false) {
$rsArr = $this->_doMapGeoSearch($textSearch, $typeFilterArr, $centre);
if (COUNT($rsArr['results']) > 0) {
$skipDataSearch = false;
}
}
}
// if we are doing a boundary search, or we have no results from the above,
// get all results based on our location
if ($skipDataSearch === false) {
// fall back onto searching via the data
// normalise the search string
$originalSearchString = $this->doNormalisation($textSearch);
// use sphinx for the search
$sphinx = $this->_getSphinxConnection();
$sphinx->setLimits(0, $this->container->getParameter('search_max_results'), $this->container->getParameter('search_max_results'));
if (COUNT($typeFilterArr)) {
$sphinx->SetFilter('fldSiteTypeUID_attr', $typeFilterArr);
}
// if we're doing a boundary search, skip the search string
if (COUNT($rads) > 0) {
$originalSearchString = '';
if ($showFavourites === false) {
//$sphinx->SetFilterFloatRange('lat_radians', min($rads['minLat'], $rads['maxLat']), max($rads['minLat'], $rads['maxLat']));
//$sphinx->SetFilterFloatRange('long_radians', min($rads['minLon'], $rads['maxLon']), max($rads['minLon'], $rads['maxLon']));
if ($rads['minLat'] > $rads['maxLat']) {
$rads['minLat'] = $rads['minLat'] - 360;
}
if ($rads['minLon'] > $rads['maxLon']) {
$rads['minLon'] = $rads['minLon'] - 180;
}
$sphinx->SetFilterFloatRange('lat_radians', $rads['minLat'], $rads['maxLat']);
$sphinx->SetFilterFloatRange('long_radians', $rads['minLon'], $rads['maxLon']);
}
}
// order by centre point
if (COUNT($centre) > 0) {
// otherwise start in the centre
// $sphinx->SetGeoAnchor('lat_radians', 'long_radians', (float) $centre['centreLat'], (float) $centre['centreLon']);
$centreLat = (float) $centre['centreLat'];
$centreLon = (float) $centre['centreLon'];
$sphinx->SetSelect("GEODIST(lat_radians, long_radians, $centreLat, $centreLon) AS geodist");
$lintDistanceLimit = 999999999.0; // everything
if ($showFavourites === false && isset($rads['maxLat'])) {
$radiusMiles = $this->get('geolocation_helper')->getSeparation(
rad2deg($rads['maxLat']),
rad2deg($rads['minLon']),
rad2deg($rads['minLat']),
rad2deg($rads['maxLon']),
"M"
);
$lintDistanceLimit = $radiusMiles * 1609; // miles to meters...
}
$sphinx->SetFilterFloatRange('geodist', 0.0, (float)$lintDistanceLimit);
$sphinx->SetSortMode(SPH_SORT_EXTENDED, 'geodist ASC');
} else {
// apply search weights
$sphinx->SetFieldWeights(array('fldTown_str' => 100, 'fldAddress1_str' => 30, 'fldSiteName_str' => 20));
}
// if we should be limiting to only favourites, pickup the selected
// favourites from cookies
if ($showFavourites === true) {
$request = $this->container->get('request_stack')->getCurrentRequest();
$favourites = explode(',', $request->cookies->get('HSF_favlist'));
if (count($favourites)) {
foreach ($favourites as $k => $favourite) {
$favourites[$k] = (int)$favourite;
}
$sphinx->SetFilter('fldUID_attr', $favourites);
}
}
$rs = $sphinx->Query($originalSearchString, $this->container->getParameter('sphinx_index'));
echo json_encode($sphinx);
$rsArr['results'] = array();
if (isset($rs['matches']) && count($rs['matches'])) {
// update the search text to what we actually searched for, this
// is needed in case we've updated/set $rsArr['searchText']
// after a geolookup
$rsArr['searchText'] = $textSearch;
// clear any previous bounds set by the geolookup, we don't want this
// if we have direct text match results
$rsArr['geobounds'] = array();
if (isset($rs['matches']) && count($rs['matches'])) {
foreach ($rs['matches'] as $k => $match) {
$rsArr['results'][$k] = $this->_remapSphinxData($k, $match);
}
}
// sort the results by distance
usort($rsArr['results'], function ($a, $b) {
return $a['fldDistance'] - $b['fldDistance'];
});
}
}
// add on the total record count
$rsArr['total'] = (int) COUNT($rsArr['results']);
return $rsArr;
}
This gives me back results however they look like this:
{"_host":"sphinx","_port":36307,"_path":"","_socket":false,"_offset":0,"_limit":250,"_mode":0,"_weights":[],"_sort":4,"_sortby":"geodist ASC","_min_id":0,"_max_id":0,"_filters":[{"type":2,"attr":"geodist","exclude":false,"min":0,"max":999999999}],"_groupby":"","_groupfunc":0,"_groupsort":"#group desc","_groupdistinct":"","_maxmatches":"250","_cutoff":0,"_retrycount":0,"_retrydelay":0,"_anchor":[],"_indexweights":[],"_ranker":0,"_rankexpr":"","_maxquerytime":0,"_fieldweights":[],"_overrides":[],"_select":"GEODIST(lat_radians, long_radians, 0.93008595838778, -2.0943951023932) AS geodist","_error":"","_warning":"","_connerror":false,"_reqs":[],"_mbenc":"","_arrayresult":false,"_timeout":0}{"results":[[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,34362776,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,38279990,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7963188,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7971966,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,31790051,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7972301,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,33589292,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,33589642,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7962913,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,31789941,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,7962178,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,49484181,null,""],[null,null,null,null,null,null,null,"Other","http:\/\/localhost:8080\/themes\/docker\/images\/Site-Type-Other.png",null,31795436,null,""],
.....
My searchd config looks like this:
searchd
{
listen = 36307
listen = 9306:mysql41
log = /opt/sphinx/searchd.log
query_log = /opt/sphinx/query.log
read_timeout = 5
max_children = 30
pid_file = /opt/sphinx/searchd.pid
seamless_rotate = 1
preopen_indexes = 1
unlink_old = 1
binlog_path = /opt/sphinx/
}
I am new tp Sphinx and need help correcting this query. Any thoughts?
Edit: This is sphinx version 3.4.1
So after hours on this over the past few days, I have found the answer...:
I was missing the * in the statement:
$sphinx->SetSelect("*, GEODIST($centreLat, $centreLon, lat_radians, long_radians) as geodist");
I hope this helps anyone who has this issue in the future

How to redirect to you tube using PHP

i have a site it running on a platform called "photo store" its a PHP site. there is image i want some one click that image redirect to my you tube channel but problem is all pages loading from template.so i did some coding and add a few line with if statement first i did only echo that works but when i try to redirect to YouTube it wand load 500 error coming can anyone help me??
this is a code
if(strpos($_SERVER['HTTP_REFERER'],'cart.php') or strpos($_SERVER['HTTP_REFERER'],'index.php')) // Clear the crumbs if coming from the cart or index
unset($_SESSION['crumbsSession']);
try
{
//$useGalleryID = $galleryID; // Original untouched gallery ID
$useMediaID = $mediaID; // Original untouched media ID
if(!$mediaID) // Make sure a media ID was passed
$smarty->assign('noAccess',1);
else
{
if($config['EncryptIDs']) // Decrypt IDs
{
$mediaID = k_decrypt($mediaID);
$useGalleryID = k_encrypt($_SESSION['id']);
}
else
$useGalleryID = $_SESSION['id'];
//echo $mediaID;
idCheck($mediaID); // Make sure ID is numeric
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM {$dbinfo[pre]}media WHERE media_id = '{$mediaID}'";
$mediaInfo = new mediaList($sql);
if($mediaInfo->getRows())
{
if($mediaID==985){
echo $mediaID;
window.location.replace("http://www.youtube.com");
}
else{
$media = $mediaInfo->getSingleMediaDetails('preview');
$galleryIDArray = $mediaInfo->getMediaGalleryIDs(); // Get an array of galleries this media is in
if(#!in_array($mediaID,$_SESSION['viewedMedia'])) // See if media has already been viewed
{
$newMediaViews = $media['views']+1;
mysqli_query($db,"UPDATE {$dbinfo[pre]}media SET views='{$newMediaViews}' WHERE media_id = '{$mediaID}'"); // Update views
$media['views'] = $newMediaViews; // Update the array so the count shown is the new count
$_SESSION['viewedMedia'][] = $mediaID;
}
//print_r($media); exit;
/*
if(!$_SESSION['crumbsSession']) // Get a crumb trail - doesn't work for contibutors yet
{
#$galleryInfo = mysqli_fetch_assoc(mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_galleries WHERE gmedia_id = '{$mediaID}' ORDER BY mg_id LIMIT 1"));
if($galleryInfo['gallery_id'])
{
$galleriesMainPageLink['page'] = "gallery.php?mode=gallery";
$_SESSION['galleriesData'][0]['linkto'] = linkto($galleriesMainPageLink); // Check for SEO
$_SESSION['galleriesData'][0]['name'] = $lang['galleries']; //
$_SESSION['crumbsSession'] = galleryCrumbsFull($galleryInfo['gallery_id']);
}
}
*/
// Check for video sample
$mediaInfo2 = new mediaTools($mediaID);
if($media['dsp_type'] == 'video') // Make sure the DSP type is set to video
{
if($video = $mediaInfo2->getVidSampleInfoFromDB()) // Make sure video file exists
{
$videoCheck = $mediaInfo2->verifyVidSampleExists();
if($videoCheck['status']) { // Make sure the video exists
//print_k($videoCheck); exit;
if($videoCheck['url'] and $config['passVideoThroughPHP'] === false)
$video['url'] = $videoCheck['url']; // Use URL method
else
$video['url'] = $config['settings']['site_url'].'/video.php?mediaID='.$media['encryptedID']; // Use PHP pass-through
//echo $video['url']; exit;
//print_k($video);
$media['videoStatus'] = 1;
$media['videoInfo'] = $video;
} else {
$media['videoStatus'] = 0;
}
}
else
$media['videoStatus'] = 0;
}
else
{
/*
* Get an estimated preview width and height
*/
$sample = $mediaInfo2->getSampleInfoFromDB();
$sampleSize = getScaledSizeNoSource($sample['sample_width'],$sample['sample_height'],$config['settings']['preview_size'],$crop=0);
$media['previewWidth'] = $sampleSize[0];
$media['previewHeight'] = $sampleSize[1];
}
$mediaPrice = getMediaPrice($media); // Get the media price based on the license
$mediaCredits = getMediaCredits($media); // Get the media credits based on the license
// Get category ID - Make sure member has access to category - maybe add this later
$galleryIDArrayFlat = ($galleryIDArray) ? implode(",",$galleryIDArray) : 0;
/*
* Prints *****************************************************************************************************************************
*/
$galleryPrintsResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}prints
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}prints.print_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'prints'
AND ({$dbinfo[pre]}prints.attachment = 'media' OR {$dbinfo[pre]}prints.attachment = 'both')
"
); // Find out which prints are assigned to galleries this photo is in
$galleryPrintsRows = mysqli_num_rows($galleryPrintsResult);
while($galleryPrint = mysqli_fetch_array($galleryPrintsResult))
$printIDArray[] = $galleryPrint['item_id'];
$mediaPrintsResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_prints WHERE media_id = '{$mediaID}'"); // Find what prints have been directly assigned to this photo // GROUP BY print_id
$mediaPrintsRows = mysqli_num_rows($mediaPrintsResult);
//echo $mediaPrintsRows; exit; // Testing
while($mediaPrint = mysqli_fetch_array($mediaPrintsResult))
{
if($mediaPrint['printgrp_id']) // Is a group assignment
{
// Select print groups
$mediaPrintsGroupsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}prints
LEFT JOIN {$dbinfo[pre]}groupids
ON {$dbinfo[pre]}prints.print_id = {$dbinfo[pre]}groupids.item_id
WHERE {$dbinfo[pre]}groupids.group_id = '{$mediaPrint[printgrp_id]}'
AND {$dbinfo[pre]}prints.active = 1
AND {$dbinfo[pre]}prints.deleted = 0
AND {$dbinfo[pre]}groupids.mgrarea = 'prints'
"
);
//$pgRows = mysqli_num_rows($mediaPrintsGroupsResult); // Testing
//echo $pgRows;
while($mediaPrintsGroup = mysqli_fetch_array($mediaPrintsGroupsResult))
$printIDArray[] = $mediaPrintsGroup['print_id'];
}
else
{
$printIDArray[] = $mediaPrint['print_id'];
if($mediaPrint['customized'])
{
$printCustomizedIDs[] = $mediaPrint['print_id']; // Add this ID to the custom array list
$customPrint[$mediaPrint['print_id']] = $mediaPrint; // Get the actual values for the custom item
}
}
}
if($printIDArray)
$printsIDArrayFlat = implode(",",$printIDArray);
else
$printsIDArrayFlat = 0;
// Now that we have the print ID array select the prints that the customer has access to and assign them to smarty
$printsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}prints
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}prints.print_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'prints')
WHERE ({$dbinfo[pre]}prints.print_id IN ({$printsIDArrayFlat}) OR {$dbinfo[pre]}prints.all_galleries = 1)
AND {$dbinfo[pre]}prints.active = 1
AND {$dbinfo[pre]}prints.deleted = 0
AND ({$dbinfo[pre]}prints.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
ORDER BY {$dbinfo[pre]}prints.sortorder
"
);
if($returnRows = mysqli_num_rows($printsResult))
{
while($print = mysqli_fetch_assoc($printsResult))
{
$print['price'] = defaultPrice($print['price']); // Make sure to assign a default price if needed
$print['credits'] = defaultCredits($print['credits']); // Make sure to assign default credits if needed
/*
* Custom Pricing calculations
*/
if(#in_array($print['print_id'],$printCustomizedIDs))
{
$print['price_calc'] = $customPrint[$print['print_id']]['price_calc'];
$print['price'] = defaultPrice($customPrint[$print['print_id']]['price']);
$print['credits'] = defaultCredits($customPrint[$print['print_id']]['credits']);
$print['credits_calc'] = $customPrint[$print['print_id']]['credits_calc'];
$print['quantity'] = $customPrint[$print['print_id']]['quantity'];
}
/*
* Advanced Pricing calculations
*/
switch($print['price_calc'])
{
case 'add':
$print['price'] = $mediaPrice + $print['price'];
break;
case 'sub':
$print['price'] = $mediaPrice - $print['price'];
break;
case 'mult':
$print['price'] = $mediaPrice * $print['price'];
break;
}
switch($print['credits_calc'])
{
case 'add':
$print['credits'] = $mediaCredits + $print['credits'];
break;
case 'sub':
$print['credits'] = $mediaCredits - $print['credits'];
break;
case 'mult':
$print['credits'] = $mediaCredits * $print['credits'];
break;
}
//echo $mediaCredits.'-'.$print['credits'].'-'.$print['credits_calc']."/";
if($print['quantity'] != '0') // Make sure the quantity is other than 0
{
$printsArray[$print['print_id']] = printsList($print,$mediaID);
$optionsResult = mysqli_query($db,"SELECT og_id FROM {$dbinfo[pre]}option_grp WHERE parent_type = 'prints' AND parent_id = '{$print[print_id]}' AND deleted = 0"); // See if there are any options for this item
if(mysqli_num_rows($optionsResult))
{
$printsArray[$print['print_id']]['addToCartLink'] = $printsArray[$print['print_id']]['linkto']; // Workbox popup
$printsArray[$print['print_id']]['directToCart'] = false; // Workbox popup
}
else
{
if($config['EncryptIDs'])
$printsArray[$print['print_id']]['addToCartLink'] = "{$siteURL}/cart.php?mode=add&type=print&id=".$printsArray[$print['print_id']]['encryptedID']."&mediaID={$media[encryptedID]}"; // Direct to cart
else
$printsArray[$print['print_id']]['addToCartLink'] = "{$siteURL}/cart.php?mode=add&type=print&id={$print[print_id]}&mediaID={$media[media_id]}"; // Direct to cart
$printsArray[$print['print_id']]['directToCart'] = true; // Direct to cart
}
}
}
$smarty->assign('printRows',$returnRows);
$smarty->assign('prints',$printsArray);
}
/*
* Digital Files *****************************************************************************************************************************
*/
require_once 'media.details.inc.php';
/*
* Products *****************************************************************************************************************************
*/
$galleryProductsResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}products
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}products.prod_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'products'
AND ({$dbinfo[pre]}products.attachment = 'media' OR {$dbinfo[pre]}products.attachment = 'both')
"
); // Find out which products are assigned to galleries this photo is in
$galleryProductsRows = mysqli_num_rows($galleryProductsResult);
while($galleryProduct = mysqli_fetch_array($galleryProductsResult))
$productIDsArray[] = $galleryProduct['item_id'];
$mediaProductsResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_products WHERE media_id = '{$mediaID}'"); // Find what products have been directly assigned to this photo // GROUP BY prod_id
$mediaProductsRows = mysqli_num_rows($mediaProductsResult);
while($mediaProduct = mysqli_fetch_array($mediaProductsResult))
{
if($mediaProduct['prodgrp_id']) // Is a group assignment
{
// Select product groups
$mediaProductsGroupsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}products
LEFT JOIN {$dbinfo[pre]}groupids
ON {$dbinfo[pre]}products.prod_id = {$dbinfo[pre]}groupids.item_id
WHERE {$dbinfo[pre]}groupids.group_id = '{$mediaProduct[prodgrp_id]}'
AND {$dbinfo[pre]}products.active = 1
AND {$dbinfo[pre]}products.deleted = 0
AND {$dbinfo[pre]}groupids.mgrarea = 'products'
"
);
while($mediaProductsGroup = mysqli_fetch_array($mediaProductsGroupsResult))
$productIDsArray[] = $mediaProductsGroup['prod_id'];
}
else
{
$productIDsArray[] = $mediaProduct['prod_id'];
if($mediaProduct['customized'])
{
$productCustomizedIDs[] = $mediaProduct['prod_id']; // Add this ID to the custom array list
$customProduct[$mediaProduct['prod_id']] = $mediaProduct; // Get the actual values for the custom item
}
}
}
if($productIDsArray)
$productIDsArrayFlat = implode(",",$productIDsArray);
else
$productIDsArrayFlat = 0;
//print_r($productCustomizedIDs); exit;
// Now that we have the product ID array select the products that the customer has access to and assign them to smarty
$productsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}products
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}products.prod_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'products')
WHERE ({$dbinfo[pre]}products.prod_id IN ({$productIDsArrayFlat}) OR {$dbinfo[pre]}products.all_galleries = 1)
AND {$dbinfo[pre]}products.active = 1
AND {$dbinfo[pre]}products.deleted = 0
AND ({$dbinfo[pre]}products.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
ORDER BY {$dbinfo[pre]}products.sortorder
"
);
if($returnRows = mysqli_num_rows($productsResult))
{
while($product = mysqli_fetch_array($productsResult))
{
$product['price'] = defaultPrice($product['price']); // Make sure to assign a default price if needed
$product['credits'] = defaultCredits($product['credits']); // Make sure to assign default credits if needed
/*
* Custom Pricing calculations
*/
if(#in_array($product['prod_id'],$productCustomizedIDs))
{
$product['price_calc'] = $customProduct[$product['prod_id']]['price_calc'];
$product['price'] = defaultPrice($customProduct[$product['prod_id']]['price']);
$product['credits'] = defaultCredits($customProduct[$product['prod_id']]['credits']);
$product['credits_calc'] = $customProduct[$product['prod_id']]['credits_calc'];
$product['quantity'] = $customProduct[$product['prod_id']]['quantity'];
}
/*
* Advanced Pricing calculations
*/
switch($product['price_calc'])
{
case 'add':
$product['price'] = $mediaPrice + $product['price'];
break;
case 'sub':
$product['price'] = $mediaPrice - $product['price'];
break;
case 'mult':
$product['price'] = $mediaPrice * $product['price'];
break;
}
switch($product['credits_calc'])
{
case 'add':
$product['credits'] = $mediaCredits + $product['credits'];
break;
case 'sub':
$product['credits'] = $mediaCredits - $product['credits'];
break;
case 'mult':
$product['credits'] = $mediaCredits * $product['credits'];
break;
}
if($product['quantity'] != '0') // Make sure the quantity is other than 0
{
if($product['product_type'] == '1') // Check if this is a media based product
$productsArray[$product['prod_id']] = productsList($product,$mediaID); // Media based
else
$productsArray[$product['prod_id']] = productsList($product,false); // Stand Alone
$optionsResult = mysqli_query($db,"SELECT og_id FROM {$dbinfo[pre]}option_grp WHERE parent_type = 'products' AND parent_id = '{$product[prod_id]}' AND deleted = 0"); // See if there are any options for this item
if(mysqli_num_rows($optionsResult))
{
$productsArray[$product['prod_id']]['addToCartLink'] = $productsArray[$product['prod_id']]['linkto']; // Workbox popup
$productsArray[$product['prod_id']]['directToCart'] = false; // Workbox popup
}
else
{
if($config['EncryptIDs'])
{
$cartLink = "{$siteURL}/cart.php?mode=add&type=product&id=".$productsArray[$product['prod_id']]['encryptedID'];
if($product['product_type'] == '1') $cartLink .= "&mediaID={$media[encryptedID]}";
$productsArray[$product['prod_id']]['addToCartLink'] = $cartLink; // Direct to cart
}
else
{
$cartLink = "{$siteURL}/cart.php?mode=add&type=product&id={$product[prod_id]}";
if($product['product_type'] == '1') $cartLink .= "&mediaID={$media[media_id]}";
$productsArray[$product['prod_id']]['addToCartLink'] = $cartLink; // Direct to cart
}
$productsArray[$product['prod_id']]['directToCart'] = true; // Direct to cart
}
}
}
$smarty->assign('productRows',$returnRows);
$smarty->assign('products',$productsArray);
}
/*
* Collections *****************************************************************************************************************************
*/
$galleryCollectionsResult = mysqli_query($db,"SELECT item_id FROM {$dbinfo[pre]}item_galleries WHERE mgrarea = 'collections' AND gallery_id IN ({$galleryIDArrayFlat})"); // Find collections from galleries
$galleryCollectionsRows = mysqli_num_rows($galleryCollectionsResult);
if($galleryCollectionsRows)
{
while($galleryCollection = mysqli_fetch_array($galleryCollectionsResult))
$collectionIDs[] = $galleryCollection['item_id'];
}
$mediaCollectionsResult = mysqli_query($db,"SELECT coll_id FROM {$dbinfo[pre]}media_collections WHERE cmedia_id = '{$mediaID}'"); // Find collections this item is directly in
$mediaCollectionsRows = mysqli_num_rows($mediaCollectionsResult);
if($mediaCollectionsRows)
{
while($mediaCollection = mysqli_fetch_array($mediaCollectionsResult))
$collectionIDs[] = $mediaCollection['coll_id'];
}
if($collectionIDs) // Only do if some were found
{
$collectionIDsFlat = implode(',',$collectionIDs);
$collectionsResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}collections
LEFT JOIN {$dbinfo[pre]}perms
ON ({$dbinfo[pre]}collections.coll_id = {$dbinfo[pre]}perms.item_id AND {$dbinfo[pre]}perms.perm_area = 'collections')
WHERE {$dbinfo[pre]}collections.active = 1
AND {$dbinfo[pre]}collections.deleted = 0
AND ({$dbinfo[pre]}collections.everyone = 1 OR {$dbinfo[pre]}perms.perm_value IN ({$memberPermissionsForDB}))
AND ({$dbinfo[pre]}collections.quantity = '' OR {$dbinfo[pre]}collections.quantity > '0')
AND {$dbinfo[pre]}collections.coll_id IN ({$collectionIDsFlat})
ORDER BY {$dbinfo[pre]}collections.sortorder
"
); // Select collections that member has access to
if($returnRows = mysqli_num_rows($collectionsResult))
{
while($collections = mysqli_fetch_array($collectionsResult))
{
$collectionsArray[$collections['coll_id']] = collectionsList($collections);
$collectionsWithAccess[] = $collections['coll_id'];
}
$smarty->assign('collectionRows',$returnRows);
$smarty->assign('collections',$collectionsArray);
}
}
/*
* Packages *****************************************************************************************************************************
*/
/*
$galleryPackagesResult = mysqli_query($db,
"
SELECT *
FROM {$dbinfo[pre]}packages
WHERE all_galleries = 1
AND (attachment = 'media' OR attachment = 'both')
"
); // Find packages that are assigned to all galleries and are attached to media or both
$galleryPackagesRows = mysqli_num_rows($galleryPackagesResult);
while($galleryPackage = mysqli_fetch_array($galleryPackagesResult))
$packageIDsArray[] = $galleryPackage['pack_id'];
*/
$galleryPackagesResult = mysqli_query($db,
"
SELECT DISTINCT(item_id)
FROM {$dbinfo[pre]}item_galleries
LEFT JOIN {$dbinfo[pre]}packages
ON {$dbinfo[pre]}item_galleries.item_id = {$dbinfo[pre]}packages.pack_id
WHERE {$dbinfo[pre]}item_galleries.gallery_id IN ({$galleryIDArrayFlat})
AND {$dbinfo[pre]}item_galleries.mgrarea = 'packages'
AND ({$dbinfo[pre]}packages.attachment = 'media' OR {$dbinfo[pre]}packages.attachment = 'both')
"
); // Find out which packages are assigned to galleries this photo is in or all galleries and attached to media or both
$galleryPackagesRows = mysqli_num_rows($galleryPackagesResult);
while($galleryPackage = mysqli_fetch_array($galleryPackagesResult))
$packageIDsArray[] = $galleryPackage['item_id'];
//print_r($packageIDsArray); // Testing
$mediaPackagesResult = mysqli_query($db,"SELECT * FROM {$dbinfo[pre]}media_packages
window.location.replace("http://www.youtube.com"); is wrong
use thins:
header("Location: http://www.youtube.com");
exit;
Remember that this must be called before any actual output is sent

Exclude Currency Country from Script

I need to tweak our script slightly. What would be the modification to get the INR currency below to NOT get divided by 1.2 and NOT have the rounding occur, like the other currencies (except GBP) as per below?
<?php
require_once "tools.php";
function GetRate($curCode)
{
if ($curCode=="GBP")
return 1;
if ($curCode=="USD")
return 1.5399;
if ($curCode=="AUD")
return 1.9838;
if ($curCode=="CAD")
return 1.9168;
if ($curCode=="INR")
return 1;
/* $url = "http://rate-exchange.appspot.com/currency?from=GBP&to=".$curCode;
$s = ReadPageCURL($url);
if ($ar = GetStringBetweenTags('rate":',',',$s))
return floatval(trim($ar[0]));*/
else
return 1;
}
function Convert($s,$curCode)
{
$path = "/home2/busi6292/public_html/orders/convertcurrency/automatic/";
if ($curCode=="GBP")
{
$resFile=$path."bigcommerce_uk.xml";
$addURL="?setCurrencyId=1";
}
else
if ($curCode=="USD")
{
$resFile=$path."bigcommerce_usa.xml";
$addURL="?setCurrencyId=3";
}
else
if ($curCode=="INR")
{
$resFile=$path."bigcommerce_uk_revised2.xml";
$addURL="?setCurrencyId=1";
}
else
if ($curCode=="CAD")
{
$addURL="?setCurrencyId=6";
$resFile=$path."bigcommerce_canada.xml";
}
else
if ($curCode=="AUD")
{
$addURL="?setCurrencyId=4";
$resFile=$path."bigcommerce_australia.xml";
}
$curRate = GetRate($curCode);
echo ("<br>$curCode<br>$curRate<br>$resFile<Br><br>");
$eTag=' GBP';
$eTagLen=strlen($eTag);
$res=$s;
if ($curCode!="GBP")
{
$res=str_replace(".html]]></link>",".html".$addURL."]]></link>",$res);
$res=str_replace("/]]></link>","/".$addURL."]]></link>",$res);
while (($ep=strpos($res,$eTag,0))!==false)
{
if (#file_exists("stop.txt")) { #unlink("stop.txt"); die ("<br>stopped"); }
$sp=$ep-1;
while ($sp>=0)
{
if (substr($res,$sp,1)=="[")
{
$sp++;
$lastPos=$ep+$eTagLen;
$s1=substr($res,$sp,$lastPos-$sp);
//pre-divide the s1 force to float and apply pre-rounding
$preDivide = round((floatval($s1)/1.2), 2);
//old line before pre-divison and rounding change
//$newPrice=sprintf("%1.4f",(floatval($s1)/1.2*floatval($curRate)))." ".$curCode;
$newPrice=sprintf("%1.4f",($preDivide*floatval($curRate)))." ".$curCode;
//double checks the round and forces only 2 decimal places
$roundPrice = number_format((float)$newPrice, 2, '.', '');
//old line before pre-division and rounding change
// $res=str_replace("[".$s1."]","[".$newPrice."]",$res);
$res=str_replace("[".$s1."]","[".$roundPrice."]",$res);
file_put_contents($resFile,$res);
$FileSize2 = filesize($resFile);
//WriteToLog("log_".$curCode.".txt","1. sp=$sp, ep=$ep, lastPos=$lastPos, old price = $s1, newPrice = $newPrice. x1=".sprintf("%1.4f",floatval($s1)/1.2)." x0=".sprintf("%1.4f",$s1));
//die ("s1=$s1, newPrice=$newPrice");
break;
}
$sp--;
}
//WriteToLog("log_".$curCode.".txt","2. sp=$sp, ep=$ep, lastPos=$lastPos, old price = $s1, newPrice = $newPrice. x1=".sprintf("%1.4f",floatval($s1)/1.2)." x0=".sprintf("%1.4f",$s1));
}
file_put_contents($resFile,$res);
$FileSize1 = filesize($resFile);
if($FileSize1 == '0' || $FileSize2 == '0')
{
$t=#microtime(true);
$url = "http://www.MYDOMAIN.co.uk/xml.php?GSF=88d6badb/GB";
$s = ReadPageCURL($url);
file_put_contents("original.xml",$s);
Convert($s,"GBP");
Convert($s,"USD");
Convert($s,"CAD");
Convert($s,"AUD");
Convert($s,"INR");
$t=#microtime(true)-$t;
echo "<br>Cron finished, elapsed time = ".sprintf("%1.3f",$t);
}
// if ($curCode!="GBP")die ("<br>abort");
} // replace prices
}
$t=#microtime(true);
$url = "http://www.MYDOMAIN.co.uk/xml.php?GSF=88d6badb/GB";
$s = ReadPageCURL($url);
file_put_contents("original.xml",$s);
Convert($s,"GBP");
Convert($s,"USD");
Convert($s,"CAD");
Convert($s,"AUD");
Convert($s,"INR");
$t=#microtime(true)-$t;
echo "<br>Cron finished, elapsed time = ".sprintf("%1.3f",$t);
?>
Just Check for INR before executing the line.
if($curCode != "INR")
{
$preDivide = round((floatval($s1)/1.2), 2);
}
else
{
$preDivide = floatval($s1);//or whatever treatment you want to give to INR
}

How to change value of a variable from a file?

I need to replace a line in a file.php.
I need to replace a value of a variable of a file.php, yet I can get the desired line, take the value of the variable but do not know how to replace the whole line.
Example:
<?php
$archive = file('Library/config/PaymentConfig.php'); // transforms the content into an array where each line is a position
$valueLine = $archive[10]; // $environment = 'production';
function getEnvironment($valueLine){
$removecharacters = array('$environment = ', "'", ';');
return str_replace($removecharacters, '', urldecode($valueLine)); // returns only the value of the variable
}
if (getEnvironment($valueLine) == $myValue) { // $myValue = production or sandbox
// Here I need to replace the line
// For $environment = 'production'; or $environment = 'sandbox';
}
?>
As per my comment, i would suggest editing file.php to get the value from a txtfile/database.
Using a text file:
//file.php
$environment = file_get_contents('environment.txt');
Then in your code, you can change the value in the text file:
$environment = 'production';
file_put_contents('environment.txt', $environment);
Correct answer
if (getEnvironment($valueLine) == $myValue) { // $myValue = production or sandbox
$archive[10] = '$environment = "sandbox";' . "\n";
file_put_contents('Library/config/PaymentConfig.php', implode("", $archive));
}
Correct answer 2
<?php
$archive = "Library/config/PaymentConfig.php";
$search = "PaymentConfig['environment']";
$arrayArchive = file($archive);
$position = 0;
for($i = 0; $i < sizeof($arrayArchive); $i++){
if(strpos($arrayArchive[$i],$search) && (strpos($arrayArchive[$i],'production') || strpos($arrayArchive[$i],'sandbox'))){
$fullLine = $arrayArchive[$i]; // $PaymentConfig['environment'] = "production"; // production, sandbox
$position = $i;
if(strpos($fullLine, '"production"') == true){
$environment = '"production"';
} else if(strpos($fullLine, '"sandbox"') == true){
$environment = '"sandbox"';
}
}
}
echo $environment; // current environment
$newEnvironment = '"sandbox"'; // or $newEnvironment = '"production"';
if ($environment == $myValue) { // $myValue = production or sandbox
$arrayArchive[$position] = str_replace($environment, $newEnvironment, $fullLine);
file_put_contents($archive, implode("", $arrayArchive));
}
?>

PHP: How to use the Twitter API's data to convert URLs, mentions, and hastags in tweets to links?

I'm really stumped on how Twitter expects users of its API to convert the plaintext tweets it sends to properly linked HTML.
Here's the deal: Twitter's JSON API sends this set of information back when you request the detailed data for a tweet:
{
"created_at":"Wed Jul 18 01:03:31 +0000 2012",
"id":225395341250412544,
"id_str":"225395341250412544",
"text":"This is a test tweet. #boring #nbc http://t.co/LUfDreY6 #skronk #crux http://t.co/VpuMlaDs #twitter",
"source":"web",
"truncated":false,
"in_reply_to_status_id":null,
"in_reply_to_status_id_str":null,
"in_reply_to_user_id":null,
"in_reply_to_user_id_str":null,
"in_reply_to_screen_name":null,
"user": <REDACTED>,
"geo":null,
"coordinates":null,
"place":null,
"contributors":null,
"retweet_count":0,
"entities":{
"hashtags":[
{
"text":"boring",
"indices":[22,29]
},
{
"text":"skronk",
"indices":[56,63]
}
],
"urls":[
{
"url":"http://t.co/LUfDreY6",
"expanded_url":"http://www.twitter.com",
"display_url":"twitter.com",
"indices":[35,55]
},
{
"url":"http://t.co/VpuMlaDs",
"expanded_url":"http://www.example.com",
"display_url":"example.com",
"indices":[70,90]
}
],
"user_mentions":[
{
"screen_name":"nbc",
"name":"NBC",
"id":26585095,
"id_str":"26585095",
"indices":[30,34]
},
{
"screen_name":"crux",
"name":"Z. D. Smith",
"id":407213,
"id_str":"407213",
"indices":[64,69]
},
{
"screen_name":"twitter",
"name":"Twitter",
"id":783214,
"id_str":"783214",
"indices":[91,99]
}
]
},
"favorited":false,
"retweeted":false,
"possibly_sensitive":false
}
The interesting parts, for this question, are the text element and the entries in the hashtags, user_mentions, and urls arrays. Twitter is telling us where in the text element the hastags, mentions, and urls appear with the indices arrays... so here's the crux of the question:
How do you use those indices arrays?
You can't just use them straight up by looping over each link element with something like substr_replace, since replacing the first link element in the text will invalidate all the index values for subsequent link elements. You also can't use substr_replace's array functionality, since it only works when you give it an array of strings for the first arg, rather than a single string (I've tested this. The results are... strange).
Is there some function that can simultaneously replace multiple index-delimited substrings in a single string with different replacement strings?
All you have to do to use the indices twitter provides straight up with a simple replace is collect the replacements you want to make and then sort them backwards. You can probably find a more clever way to build $entities, I wanted them optional anyway, so I KISS as far as that went.
Either way, my point here was just to show that you don't need to explode the string and character count and whatnot. Regardless of how you do it, all you need to to is start at the end and work to the beginning of the string, and the index twitter has is still valid.
<?php
function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true)
{
$return = $tweet->text;
$entities = array();
if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/".$e->screen_name."' target='_blank'>#".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = "<a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}
usort($entities, function($a,$b){return($b["start"]-$a["start"]);});
foreach($entities as $item)
{
$return = substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}
return($return);
}
?>
Ok so I needed to do exactly this and I solved it. Here is the function I wrote. https://gist.github.com/3337428
function parse_message( &$tweet ) {
if ( !empty($tweet['entities']) ) {
$replace_index = array();
$append = array();
$text = $tweet['text'];
foreach ($tweet['entities'] as $area => $items) {
$prefix = false;
$display = false;
switch ( $area ) {
case 'hashtags':
$find = 'text';
$prefix = '#';
$url = 'https://twitter.com/search/?src=hash&q=%23';
break;
case 'user_mentions':
$find = 'screen_name';
$prefix = '#';
$url = 'https://twitter.com/';
break;
case 'media':
$display = 'media_url_https';
$href = 'media_url_https';
$size = 'small';
break;
case 'urls':
$find = 'url';
$display = 'display_url';
$url = "expanded_url";
break;
default: break;
}
foreach ($items as $item) {
if ( $area == 'media' ) {
// We can display images at the end of the tweet but sizing needs to added all the way to the top.
// $append[$item->$display] = "<img src=\"{$item->$href}:$size\" />";
}else{
$msg = $display ? $prefix.$item->$display : $prefix.$item->$find;
$replace = $prefix.$item->$find;
$href = isset($item->$url) ? $item->$url : $url;
if (!(strpos($href, 'http') === 0)) $href = "http://".$href;
if ( $prefix ) $href .= $item->$find;
$with = "$msg";
$replace_index[$replace] = $with;
}
}
}
foreach ($replace_index as $replace => $with) $tweet['text'] = str_replace($replace,$with,$tweet['text']);
foreach ($append as $add) $tweet['text'] .= $add;
}
}
It's an edge case but the use of str_replace() in Styledev's answer could cause issues if one entity is contained within another. For example, "I'm a genius! #me #mensa" could become "I'm a genius! #me #mensa" if the shorter entity is substituted first.
This solution avoids that problem:
<?php
/**
* Hyperlinks hashtags, twitter names, and urls within the text of a tweet
*
* #param object $apiResponseTweetObject A json_decoded() one of these: https://dev.twitter.com/docs/platform-objects/tweets
* #return string The tweet's text with hyperlinks added
*/
function linkEntitiesWithinText($apiResponseTweetObject) {
// Convert tweet text to array of one-character strings
// $characters = str_split($apiResponseTweetObject->text);
$characters = preg_split('//u', $apiResponseTweetObject->text, null, PREG_SPLIT_NO_EMPTY);
// Insert starting and closing link tags at indices...
// ... for #user_mentions
foreach ($apiResponseTweetObject->entities->user_mentions as $entity) {
$link = "https://twitter.com/" . $entity->screen_name;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for #hashtags
foreach ($apiResponseTweetObject->entities->hashtags as $entity) {
$link = "https://twitter.com/search?q=%23" . $entity->text;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for http://urls
foreach ($apiResponseTweetObject->entities->urls as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// ... for media
foreach ($apiResponseTweetObject->entities->media as $entity) {
$link = $entity->expanded_url;
$characters[$entity->indices[0]] = "<a href=\"$link\">" . $characters[$entity->indices[0]];
$characters[$entity->indices[1] - 1] .= "</a>";
}
// Convert array back to string
return implode('', $characters);
}
?>
Jeff's solution worked well with English text but it got broken when the tweet contained non-ASCII characters. This solution avoids that problem:
mb_internal_encoding("UTF-8");
// Return hyperlinked tweet text from json_decoded status object:
function MakeStatusLinks($status)
{$TextLength=mb_strlen($status['text']); // Number of UTF-8 characters in plain tweet.
for ($i=0;$i<$TextLength;$i++)
{$ch=mb_substr($status['text'],$i,1); if ($ch<>"\n") $ChAr[]=$ch; else $ChAr[]="\n<br/>"; // Keep new lines in HTML tweet.
}
if (isset($status['entities']['user_mentions']))
foreach ($status['entities']['user_mentions'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='https://twitter.com/".$entity['screen_name']."'>".$ChAr[$entity['indices'][0]];
$ChAr[$entity['indices'][1]-1].="</a>";
}
if (isset($status['entities']['hashtags']))
foreach ($status['entities']['hashtags'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='https://twitter.com/search?q=%23".$entity['text']."'>".$ChAr[$entity['indices'][0]];
$ChAr[$entity['indices'][1]-1] .= "</a>";
}
if (isset($status['entities']['urls']))
foreach ($status['entities']['urls'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='".$entity['expanded_url']."'>".$entity['display_url']."</a>";
for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]='';
}
if (isset($status['entities']['media']))
foreach ($status['entities']['media'] as $entity)
{$ChAr[$entity['indices'][0]] = "<a href='".$entity['expanded_url']."'>".$entity['display_url']."</a>";
for ($i=$entity['indices'][0]+1;$i<$entity['indices'][1];$i++) $ChAr[$i]='';
}
return implode('', $ChAr); // HTML tweet.
}
Here is an updated answer that works with Twitter's new Extended Mode. It combines the answer by #vita10gy and the comment by #Hugo (to make it utf8 compatible), with a few minor tweaks to work with the new api values.
function utf8_substr_replace($original, $replacement, $position, $length) {
$startString = mb_substr($original, 0, $position, "UTF-8");
$endString = mb_substr($original, $position + $length, mb_strlen($original), "UTF-8");
$out = $startString . $replacement . $endString;
return $out;
}
function json_tweet_text_to_HTML($tweet, $links=true, $users=true, $hashtags=true) {
// Media urls can show up on the end of the full_text tweet, but twitter doesn't index that url.
// The display_text_range indexes show the actual tweet text length.
// Cut the string off at the end to get rid of this unindexed url.
$return = mb_substr($tweet->full_text, $tweet->display_text_range[0],$tweet->display_text_range[1]);
$entities = array();
if($links && is_array($tweet->entities->urls))
{
foreach($tweet->entities->urls as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='".$e->expanded_url."' target='_blank'>".$e->display_url."</a>";
$entities[] = $temp;
}
}
if($users && is_array($tweet->entities->user_mentions))
{
foreach($tweet->entities->user_mentions as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='https://twitter.com/".$e->screen_name."' target='_blank'>#".$e->screen_name."</a>";
$entities[] = $temp;
}
}
if($hashtags && is_array($tweet->entities->hashtags))
{
foreach($tweet->entities->hashtags as $e)
{
$temp["start"] = $e->indices[0];
$temp["end"] = $e->indices[1];
$temp["replacement"] = " <a href='https://twitter.com/hashtag/".$e->text."?src=hash' target='_blank'>#".$e->text."</a>";
$entities[] = $temp;
}
}
usort($entities, function($a,$b){return($b["start"]-$a["start"]);});
foreach($entities as $item)
{
$return = utf8_substr_replace($return, $item["replacement"], $item["start"], $item["end"] - $item["start"]);
}
return($return);
}
Here is a JavaScript version (using jQuery) of vita10gy's solution
function tweetTextToHtml(tweet, links, users, hashtags) {
if (typeof(links)==='undefined') { links = true; }
if (typeof(users)==='undefined') { users = true; }
if (typeof(hashtags)==='undefined') { hashtags = true; }
var returnStr = tweet.text;
var entitiesArray = [];
if(links && tweet.entities.urls.length > 0) {
jQuery.each(tweet.entities.urls, function() {
var temp1 = {};
temp1.start = this.indices[0];
temp1.end = this.indices[1];
temp1.replacement = '' + this.display_url + '';
entitiesArray.push(temp1);
});
}
if(users && tweet.entities.user_mentions.length > 0) {
jQuery.each(tweet.entities.user_mentions, function() {
var temp2 = {};
temp2.start = this.indices[0];
temp2.end = this.indices[1];
temp2.replacement = '#' + this.screen_name + '';
entitiesArray.push(temp2);
});
}
if(hashtags && tweet.entities.hashtags.length > 0) {
jQuery.each(tweet.entities.hashtags, function() {
var temp3 = {};
temp3.start = this.indices[0];
temp3.end = this.indices[1];
temp3.replacement = '#' + this.text + '';
entitiesArray.push(temp3);
});
}
entitiesArray.sort(function(a, b) {return b.start - a.start;});
jQuery.each(entitiesArray, function() {
returnStr = substrReplace(returnStr, this.replacement, this.start, this.end - this.start);
});
return returnStr;
}
You can then use this function like so ...
for(var i in tweetsJsonObj) {
var tweet = tweetsJsonObj[i];
var htmlTweetText = tweetTextToHtml(tweet);
// Do something with the formatted tweet here ...
}
Regarding vita10gy's helpful json_tweet_text_to_HTML(), I found a tweet that it could not format correctly: 626125868247552000.
This tweet has a nonbreaking space in it. My solution was to replace the first line of the function with the following:
$return = str_replace("\xC2\xA0", ' ', $tweet->text);
Performing a str_replace() on is covered here.

Categories