Twitter usertimeline code not working - php

I have created this test script to get data from the twitter usertimeline which I'm sure was previously working however now it returns nothing. Is there something I am missing here? (To test simply amend the constants at the top)
define('CONSUMER_KEY', '');
define('CONSUMER_SECRET', '');
define('OAUTH_TOKEN','');
define('OAUTH_SECRET','');
define('USER_ID','');
function generateSignature($oauth,$fullurl,$http_method){
// Take params from url
$main_url = explode('?',$fullurl);
$urls = explode('&',$main_url[1]);
foreach ($urls as $param){
$bits = explode('=',$param);
if (strlen($bits[0])){
$oauth[$bits[0]] = rawurlencode($bits[1]);
}
}
ksort($oauth);
$string = http_build_query($oauth);
$new_string = strtoupper($http_method).'&'.urlencode($main_url[0]).'&'.urlencode(urldecode($string));
$sign_str = CONSUMER_SECRET.'&'.OAUTH_SECRET;
return urlencode(base64_encode(hash_hmac('sha1',$new_string,$sign_str,true)));
}
function random($len,$use_chars = false,$numU = false){
$num = range(0,9);
$letu = range('A','Z');
$letl = range('a','z');
$chars = array("!","*","£","$","^","(",")","_","+");
if ($use_chars){
$arr = array_merge($num,$letu,$letl,$chars);
} else {
$arr = array_merge($num,$letu,$letl);
}
// Shuffling - new addition 11/9 to make order actually random!
shuffle($arr);
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
return implode('',$out);
}
$method = 'GET';
// Twitter still uses Oauth1 (which is a pain)
$oauth = array(
'oauth_consumer_key'=>CONSUMER_KEY,
'oauth_nonce'=>random(32),
'oauth_signature_method'=>'HMAC-SHA1',
'oauth_timestamp'=>time(),
'oauth_token'=>OAUTH_TOKEN,
'oauth_version'=>'1.0',
);
$url = "https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=".USER_ID;
$oauth['oauth_signature'] = generateSignature($oauth,$url,$method,'');
ksort($oauth);
foreach ($oauth as $k=>$v){
$auths[] = $k.'="'.$v.'"';
}
$stream = array('http' =>
array(
'method' => $method,
// ignore_errors should be true
'ignore_errors'=>true, // http://php.net/manual/en/context.http.php - otherwise browser returns error not error content
'follow_location'=>false,
'max_redirects'=>0,
'header'=> array(
'Authorization: OAuth '.implode(', ',$auths),
'Connection: close'
)
)
);
echo $url;
$response = file_get_contents($url, false, stream_context_create($stream));
print'<pre>';print_r($stream);print'</pre>';
print'<pre>[';print_r($reponse);print']</pre>';

I found this:
// Create a number only random string
if ($numU){ $arr = $num; }
$rand = array_rand($arr,$len);
foreach ($rand as $num){
$out[] = $arr[$num];
}
I am not completly sure, but i think there shouldn't be a } after if ($numU){ $arr = $num;
I think it should be a open bracket. {
I found one more thing:
print'<pre>[';print_r($reponse);print']</pre>';
Here at the bottom of the code, you wrote "$reponse" instead of "$response"
I hope it helped! If it did, give it a upvote and choose as best answer!

Related

GET & DELETE using file_get_contents() very slow

I use the file_get_contents() from server M to get the response from server X. The result was success but it take too long.
$url = "http://10.20.30.40";
$opts = array('http' =>
array(
'method' => 'GET',
'header' => 'Connection: close\r\n'
)
);
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
$result = json_decode($result);
$response = parse_http_response_header($http_response_header);
print_r($result);
print_r($response);
/////// below is just function to parse the response ///////
function parse_http_response_header(array $headers)
{
$responses = array();
$buffer = NULL;
foreach ($headers as $header)
{
if ('HTTP/' === substr($header, 0, 5))
{
// add buffer on top of all responses
if ($buffer) array_unshift($responses, $buffer);
$buffer = array();
list($version, $code, $phrase) = explode(' ', $header, 3) + array('', FALSE, '');
$buffer['status'] = array(
'line' => $header,
'version' => $version,
'code' => (int) $code,
'phrase' => $phrase
);
$fields = &$buffer['fields'];
$fields = array();
continue;
}
list($name, $value) = explode(': ', $header, 2) + array('', '');
// header-names are case insensitive
$name = strtoupper($name);
// values of multiple fields with the same name are normalized into
// a comma separated list (HTTP/1.0+1.1)
if (isset($fields[$name]))
{
$value = $fields[$name].','.$value;
}
$fields[$name] = $value;
}
unset($fields); // remove reference
array_unshift($responses, $buffer);
return $responses;
}
Is there any suggestion or function option to get the response (the content and the response code) faster?
(NOTE: I am not allowed to install cURL, so please gimme other option)

is there any way i can extract first n comments from this piece of code?

$facebook = new Facebook(array(
'appId'=>'','secret'=>''
));
$post = "10152390205162139";
$comments = array();
$done = false;
$options = array();
$path = "/".$post.'/comments';
while(!$done){
try{
$data = $facebook->api($path,'GET',$options);
}catch(FacebookApiException $e){
echo $e->getMessage();
$data = null;
$done = true;
}
if(!is_null($data)){
$comments = array_merge($comments, $data['data']);
if(isset($data['paging']['next']) && !empty($data['paging']['next'])){
$parts = parse_url($data['paging']['next']);
$path = $parts['path'];
parse_str($parts['query'], $options);
} else {
$done = true;
}
}
}
what i'm trying to do is, extract list of comments from the particular post made by a page, now i want to limit the number of comments like 100 or 200, since some of the post's have comments more than 50k, it kills my script :\
There is a limit option, so you probably only have to change:
$options = array();
to:
$options = array('limit' => 100);
You could try limiting the while clause in your script, something like:
while (!$done || count($comments) <= 200) {
...
}

PHP Reconstruct array Paypal TransactionSearch Function

I am making a call to Paypals API TransactionSearch and I am getting back a flat array of data. I am needing to reconstruct this array. Here is the structure that I get back from paypal:
array(36){
[
"L_TIMESTAMP0"
]=>string(28)"2012%2d09%2d18T22%3a10%3a13Z"[
"L_TIMESTAMP1"
]=>string(28)"2012%2d09%2d18T19%3a55%3a41Z"[
"L_TIMESTAMP2"
]=>string(28)"2012%2d09%2d18T19%3a55%3a41Z"[
"L_TIMEZONE0"
]=>string(3)"GMT"[
"L_TIMEZONE1"
]=>string(3)"GMT"[
"L_TIMEZONE2"
]=>string(3)"GMT"[
"L_TYPE0"
]=>string(7)"Payment"[
"L_TYPE1"
]=>string(7)"Payment"[
"L_TYPE2"
]=>string(7)"Payment"[
"L_EMAIL0"
]=>string(26)"XXXXX%40hotmail%2ecom"[
"L_EMAIL1"
]=>string(31)"XXXX%40lvcoxmail%2ecom"[
"L_EMAIL2"
]=>string(23)"XXXXt%2ecom"[
"L_TRANSACTIONID0"
]=>string(17)"13E586955G649992Y"[
"L_TRANSACTIONID1"
]=>string(17)"8LH96897T3119113R"[
"L_TRANSACTIONID2"
]=>string(17)"87U867057E085230E"[
"L_STATUS0"
]=>string(9)"Completed"[
"L_STATUS1"
]=>string(9)"Completed"[
"L_STATUS2"
]=>string(9)"Completed"[
"L_AMT0"
]=>string(7)"85%2e00"[
"L_AMT1"
]=>string(7)"85%2e00"[
"L_AMT2"
]=>string(7)"85%2e00"[
"L_CURRENCYCODE0"
]=>string(3)"USD"[
"L_CURRENCYCODE1"
]=>string(3)"USD"[
"L_CURRENCYCODE2"
]=>string(3)"USD"[
"L_FEEAMT0"
]=>string(9)"%2d2%2e17"[
"L_FEEAMT1"
]=>string(9)"%2d2%2e17"[
"L_FEEAMT2"
]=>string(9)"%2d2%2e17"[
"L_NETAMT0"
]=>string(7)"82%2e83"[
"L_NETAMT1"
]=>string(7)"82%2e83"[
"L_NETAMT2"
]=>string(7)"82%2e83"[
"TIMESTAMP"
]=>string(28)"2012%2d11%2d08T14%3a24%3a30Z"[
"CORRELATIONID"
]=>string(13)"52c22d68648cd"[
"ACK"
]=>string(7)"Success"[
"VERSION"
]=>string(6)"51%2e0"[
"BUILD"
]=>string(7)"4137385"
}
I need to reset the array to just the following:
["L_STATUSn"]=>string(9)"Completed"
["L_TRANSACTIONIDn"]=>string(17)"8LH96897T3119113R"
with 'n' being the number, being the array key number that paypal returns.
Here is the code I am using, and it is borked.
$i = 0;
$c = 0;
foreach ($comparison AS $aKey => $v) {
$findme1 = 'L_TIMESTAMP'.$i++;
$findme2 = 'L_STATUS'.$c++;
$txid = $myarray[$findme1];
$status = $myarray[$findme2];
$TXid = array_search('$findme1', $aKey);
$Status = array_search('$findme2', $aKey);
$TxID[] = array('Status' => $aStatus, 'TransactionID' => $aTransactionID);
}
appreciate abetter way to reconstruct this array, the method I am trying to use doesnt appear to be too efficient.
Somewhat late, but maybe others have this request too. So here goes:
function process_response($str)
{
$data = array();
$x = explode("&", $str);
foreach($x as $val)
{
$y = explode("=", $val);
preg_match_all('/^([^\d]+)(\d+)/', $y[0], $match);
if (isset($match[1][0]))
{
$text = $match[1][0];
$num = $match[2][0];
$data[$num][$text] = urldecode($y[1]);
}
else
{
$text = $y[0];
// $data[$text] = urldecode($y[1]);
}
}
return $data;
}
Just feed the result from your curl call into this and take the result as a formatted array.
Note the commented out line, there are some fields that are global, such as version, if you want these, uncomment, but then you may have to adjust some formatting code down stream.
if you want to feed this into PHPExcel object, you could do so like so:
$index = 1;
foreach($data as $row)
{
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A'.$index, $row['L_TIMESTAMP'])
->setCellValue('B'.$index, $row['L_TIMEZONE'])
->setCellValue('C'.$index, $row['L_TYPE'])
->setCellValue('D'.$index, $row['L_EMAIL'])
->setCellValue('E'.$index, $row['L_NAME'])
->setCellValue('F'.$index, $row['L_TRANSACTIONID'])
->setCellValue('G'.$index, $row['L_STATUS'])
->setCellValue('H'.$index, $row['L_AMT'])
->setCellValue('I'.$index, $row['L_CURRENCYCODE'])
->setCellValue('J'.$index, $row['L_FEEAMT'])
->setCellValue('K'.$index, $row['L_NETAMT']);
$index++;
}

Display correct data from .json file

I apologise in advance if this is vague, I have battled with this for nigh on 10 hours now and have got nowhere...
My client has been screwed over by their SEO company and I am trying to help to save their business. One major problem we have is that theirs websites content is dependant on a data feed hosted on their SEO companys website. The content for different areas around their main town is auto generated by this script. Part of the script is hosted on the clients server and this communicates with the feed.
I have found a JSON file with all the data that the feed uses, but am struggling to get the script to read off of this file instead.
There appears to be 2 functions I should be interested in generateContentFromFeed and generateTextFromFile. Currently it appears to be using generateContentFromFeed (but may be using generateTextFromFile elsehwere, but I'm quite sure it isnt. I believe this function is there if you dont want to get the data externally).
I have tried swapping the functions around, and changing the source of the feed in the config file, but with no joy. All this achieved was outputting the entire contents of the json file.
Files are below:
content.class.php
<?php
/**
* This class manipulates content from files / JSON into an array
* Also includes helpful functions for formatting content
*/
class Content {
public $links = array();
public $replacements = array();
private function stripslashes_gpc($string) {
if (get_magic_quotes_gpc()) {
return stripslashes($string);
} else {
return $string;
}
}
private function sourceContentToArray($source) {
// array
if (is_array($source)) {
$array = $source;
// json
} elseif (json_decode($source) != FALSE || json_decode($source) != NULL) {
$array = json_decode($source, 1);
// file
} elseif (file_exists($source)) {
if (!$array = json_decode(file_get_contents($source), 1)) {
echo "File empty or corrupt";
return false;
}
} else {
echo 'Source content not recognised';
return false;
}
return $array;
}
public function generateContent($source, $type="paragraph", $label="", $subject, $num=0, $randomize_order=false) {
if (!$array = $this->sourceContentToArray($source))
return false;
$array = empty($this->links) ? $this->loadLinks($array, $subject) : $array;
$this->loadGlobalReplacements($array, $subject);
$ca = array();
foreach ($array['content'] as $c) {
if ($c['type'] == $type) {
if (empty($label) || (!empty($label) && $c['label'] == $label)) {
$ca[] = $c;
}
}
}
$rc = array();
foreach ($ca as $k => $a) {
$rc[] = $this->randomizeContent($a, $subject.$k);
}
if ((!is_array($num) && $num >= 1) || (is_array($num) && $num[0] >= 1)) {
$rc = $this->arraySliceByInteger($rc, $subject, $num);
} else if ((!is_array($num) && $num > 0 && $num < 1) || (is_array($num) && $num[0] > 0 && $num[0] < 1)) {
$rc = $this->arraySliceByPercentage($rc, $subject, $num);
} else {
if ($randomize_order == true)
$rc = $this->arraySliceByPercentage($rc, $subject, 1);
}
return $rc;
}
public function formatContent($source, $type, $subject, $find_replace=array()) {
$c = "";
foreach ($source as $k => $s) {
$text = "";
if ($type == "list" || $type == "paragraph") {
$text .= "<h3>";
foreach ($s['title'] as $t) {
$text .= $t." ";
}
$text .= "</h3>";
}
if ($type == "list") {
$text .= "<ul>";
} else if ($type == "paragraph") {
$text .= "<p>";
}
foreach ($s['parts'] as $b) {
if ($type == "list")
$text .= "<li>";
$text .= $b." ";
if ($type == "list")
$text .= "</li>";
}
if ($type == "list") {
$text .= "</ul>";
} else if ($type == "paragraph") {
$text .= "</p>";
}
$text = $this->findReplace($s['replacements'], $text, $subject.$k."1");
$text = $this->injectLinks($this->links, $text, $subject.$k."2");
$text = $this->findReplace($this->replacements, $text, $subject.$k."3");
$text = $this->findReplace($find_replace, $text, $subject.$k."4");
$text = $this->aAnReplacement($text);
$text = $this->capitaliseFirstLetterOfSentences($text);
$c .= $this->stripslashes_gpc($text);
}
return $c;
}
public function injectLinks($links, $text, $subject) {
global $randomizer;
if (empty($links))
return $text;
foreach ($links as $k => $link) {
$_link = array();
if (preg_match("/\{L".($k+1)."\}/", $text)) {
preg_match_all("/\{L".($k+1)."\}/", $text, $vars);
foreach ($vars[0] as $vark => $varv) {
$_link['link'] = empty($_link['link']) ? $this->links[$k]['link'] : $_link['link'];
$l_link = $randomizer->fetchEncryptedRandomPhrase($_link['link'], 1, $subject.$k.$vark);
unset($_link['link'][array_search($l_link, $_link['link'])]);
$_link['link'] = array_values($_link['link']);
$_link['text'] = empty($_link['text']) ? $this->links[$k]['text'] : $_link['text'];
$l_text = $randomizer->fetchEncryptedRandomPhrase($_link['text'], 2, $subject.$k.$vark);
unset($_link['text'][array_search($l_text, $_link['text'])]);
$_link['text'] = array_values($_link['text']);
$link_html = empty($l_link) ? $l_text : "".$l_text."";
$text = preg_replace("/\{L".($k+1)."\}/", $link_html, $text, 1);
$this->removeUsedLinksFromPool($l_link);
}
}
}
return $text;
}
private function loadLinks($source, $subject) {
global $randomizer;
if (!empty($source['links'])) {
foreach ($source['links'] as $k => $l) {
$source['links'][$k]['link'] = preg_split("/\r?\n/", trim($l['link']));
$source['links'][$k]['text'] = preg_split("/\r?\n/", trim($l['text']));
}
$this->links = $source['links'];
}
return $source;
}
private function loadGlobalReplacements($source, $subject) {
global $randomizer;
$source['replacements'] = $this->removeEmptyIndexes($source['replacements']);
foreach ($source['replacements'] as $k => $l) {
$source['replacements'][$k] = preg_split("/\r?\n/", trim($l));
}
$this->replacements = $source['replacements'];
return $source;
}
private function removeUsedLinksFromPool($link) {
foreach ($this->links as $key => $links) {
foreach ($links['link'] as $k => $l) {
if ($l == $link) {
unset($this->links[$key]['link'][$k]);
}
}
}
}
private function randomizeContent($source, $subject) {
global $randomizer;
$source['title'] = $this->removeEmptyIndexes($source['title']);
foreach ($source['title'] as $k => $t) {
$source['title'][$k] = trim($randomizer->fetchEncryptedRandomPhrase(preg_split("/\r?\n/", trim($t)), 1, $subject.$k));
}
$source['parts'] = $this->removeEmptyIndexes($source['parts']);
foreach ($source['parts'] as $k => $b) {
$source['parts'][$k] = trim($randomizer->fetchEncryptedRandomPhrase(preg_split("/\r?\n/", trim($b)), 2, $subject.$k));
}
$source['structure'] = trim($source['structure']);
if ($source['type'] == "list") {
$source['parts'] = array_values($source['parts']);
$source['parts'] = $randomizer->randomShuffle($source['parts'], $subject."9");
} else if ($source['structure'] != "") {
$source['structure'] = $randomizer->fetchEncryptedRandomPhrase(preg_split("/\r?\n/", $source['structure']), 3, $subject);
preg_match_all("/(\{[0-9]{1,2}\})/", $source['structure'], $matches);
$sc = array();
foreach ($matches[0] as $match) {
$sc[] = str_replace(array("{", "}"), "", $match);
}
$bs = array();
foreach ($sc as $s) {
$bs[] = $source['parts'][$s];
}
$source['parts'] = $bs;
}
$source['replacements'] = $this->removeEmptyIndexes($source['replacements']);
foreach ($source['replacements'] as $k => $r) {
$source['replacements'][$k] = preg_split("/\r?\n/", trim($r));
}
return $source;
}
private function removeEmptyIndexes($array, $reset_keys=false) {
foreach($array as $key => $value) {
if ($value == "") {
unset($array[$key]);
}
}
if (!empty($reset_keys))
$array = array_values($array);
return $array;
}
private function arraySliceByPercentage($array, $subject, $decimal=0.6) {
global $randomizer;
$array = $randomizer->randomShuffle($array, $subject);
if (is_array($decimal))
$decimal = $randomizer->fetchEncryptedRandomPhrase(range($decimal[0], $decimal[1], 0.1), 1, $subject);
$ac = count($array);
$n = ceil($ac * $decimal);
$new_array = array_slice($array, 0, $n);
return $new_array;
}
private function arraySliceByInteger($array, $subject, $number=10) {
global $randomizer;
$array = $randomizer->randomShuffle($array, $subject);
if (is_array($number))
$number = $randomizer->fetchEncryptedRandomPhrase(range($number[0], $number[1]), 1, $subject);
$new_array = array_slice($array, 0, $number);
return $new_array;
}
private function aAnReplacement($text) {
$irregular = array(
"hour" => "an",
"europe" => "a",
"unique" => "a",
"honest" => "an",
"one" => "a"
);
$text = preg_replace("/(^|\W)([aA])n ([^aAeEiIoOuU])/", "$1$2"." "."$3", $text);
$text = preg_replace("/(^|\W)([aA]) ([aAeEiIoOuU])/", "$1$2"."n "."$3", $text);
foreach ($irregular as $k => $v) {
if (preg_match("/(^|\W)an? ".$k."/i", $text)) {
$text = preg_replace("/(^|\W)an? (".$k.")/i", "$1".$v." "."$2", $text);
}
}
return $text;
}
private function capitaliseFirstLetterOfSentences($text) {
$text = preg_replace("/(<p>|<li>|^|[\n\t]|[\.\?\!]+\s)(<a.*?>)?(?!%)([a-z]{1})/se", "'$1$2'.strtoupper('$3')", $text);
return $text;
}
public function findReplace($find_replace, $input, $subject) {
global $randomizer;
if (!empty($find_replace)) {
foreach ($find_replace as $key => $val) {
if (is_array($val)) {
$fr = $val;
$pattern = "/".preg_quote($key)."/i";
preg_match_all($pattern, $input, $vars);
foreach ($vars[0] as $vark => $varv) {
$fr = empty($fr) ? $val : $fr;
$new_val = $randomizer->fetchEncryptedRandomPhrase($fr, 1, $subject.$key.$vark);
unset($fr[array_search($new_val, $fr)]);
$fr = array_values($fr);
$input = preg_replace($pattern, $new_val, $input, 1);
}
} else {
$pattern = "/".preg_quote($key)."/i";
$input = preg_replace($pattern, $val, $input);
}
}
}
return $input;
}
public function generateTextFromFile($file, $subject, $find_replace=array()) {
global $randomizer;
$content = trim(file_get_contents($file));
$lines = preg_split("/\r?\n/s", $content);
$text = $randomizer->fetchEncryptedRandomPhrase($lines, 4, $subject);
$text = $this->findReplace($find_replace, $text, $subject);
return $text;
}
public function generateContentFromFeed($file, $type, $label="", $subject, $num=0, $find_replace=array()) {
global $cfg;
$vars = array ( "api_key" => $cfg['feed']['api_key'],
"subject" => $subject,
"file" => $file,
"type" => $type,
"label" => $label,
"num" => $num,
"find_replace" => json_encode($find_replace));
$encoded_vars = http_build_query($vars);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"http://feeds.redsauce.com/example/index.php");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded_vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
}
?>
config.php
<?php
// LOCAL SERVER
// Paths
$cfg['basedir'] = "public_html/directory/"; // change this for inlcudes and requires.
$cfg['baseurl'] = "/directory/"; // change this for relative links and linking to images, media etc.
$cfg['fullbaseurl'] = "http://customerssite.com/directory/"; // change this for absolute links and linking to pages
/*
// Database - local
$cfg['database']['host'] = "127.0.0.1";
$cfg['database']['name'] = "username";
$cfg['database']['user'] = 'root'; // change this to the database user
$cfg['database']['password'] = ''; // change this to the database password
*/
// Database - web
$cfg['database']['host'] = "localhost";
$cfg['database']['name'] = "db";
$cfg['database']['user'] = 'user'; // change this to the database user
$cfg['database']['password'] = 'pass'; // change this to the database password
// Errors
$cfg['errors']['display'] = 1; // change this to display errors on or off (on for testing, off for production)
$cfg['errors']['log'] = 0; // change this to log errors to /log/error.log
// Caching
$cfg['caching']['status'] = 0; // determines whether the cache is enabled. 1 for enabled, 0 for disabled
$cfg['caching']['expiry_time'] = 604800; // determines expiry time of cached items (604800 = 14 days)
$cfg['caching']['directory'] = $cfg['basedir']."public_html/_cache/"; // directory in which cached files are stored
// Analytics
$cfg['analytics']['status'] = 1;
$cfg['analytics']['tracking_id'] = "UA-21030138-1";
// Javascript
$cfg['maps']['status'] = 0; // load google maps javascript
$cfg['jquery_ui']['status'] = 0; // load jquery ui javascript + css
// Site defaults
$cfg['site_name'] = "Customer"; // change this to the site name
$cfg['default']['page_title'] = "Customer"; // change this to the default title of all pages
$cfg['default']['page_description'] = "Customer"; // change this to the default meta-description of all pages
$cfg['default']['email'] = "Customer"; // change this to the administrators email for receiving messages when users signup etc
$cfg['default']['category']['id'] = 130;
// Email
$cfg['email']['address'] = "Customer"; // change this to the administrators email for receiving messages when users signup etc
$cfg['email']['from'] = $cfg['site_name']." <Customer>"; // email will appear to have come from this address
$cfg['email']['subject'] = "Enquiry from ".$cfg['site_name']; // subject of the email
$cfg['email']['success_message'] = "Thank you for your enquiry. Someone will be in touch with you shortly."; // message to display if the email is sent successfully
$cfg['email']['failure_message'] = "There was an error processing your enquiry. Please try again."; // message to display if the email is not sent successfully
// Content feed
$cfg['feed']['api_key'] = "Customer"; // enter the unique content feed api key here
$cfg['feed']['url'] = "http://feeds.customersseocompany.com/customer/index.php"; // URL to connect to to pull the content feed
// Dates
date_default_timezone_set('Europe/London');
$cfg['default']['date_format'] = "d/m/Y H:i:s";
// Options
$cfg['listings']['type'] = "ajax"; // options are none (to display no listings), page (to display the listings on the page) or ajax (to load the listings via AJAX)
$cfg['listings']['num_per_page'] = 10; // maximum number of listings to show per page
// Routing
$cfg['routes'] = array(
'category' => array(
"(?P<category>.+?)-category",
"_pages/category.php"
),
't1' => array(
"(?P<category>.+?)-in-(?P<t1_name>.+?)_(?P<county>.+)",
"_pages/tier1.php"
),
't1_map' => array(
"t1-map-data-(?P<t1_name>.+)-(?P<page_num>[0-9]+)",
"_ajax/map-data.php"
),
't2_map' => array(
"t2-map-data-(?P<t2_name>.+)-(?P<t1_name>.+)-(?P<page_num>[0-9]+)",
"_ajax/map-data.php"
),
'ajax_listings' => array(
"ajax-listings-(?P<category>.+?)-(?P<t2_id>.+)-(?P<page_num>[0-9]+)",
"_ajax/listings.php"
),
'search' => array(
"^search\/?$",
"_pages/search.php"
),
'single' => array(
".*?-(?P<listing_id>[0-9]+)",
"_pages/single.php"
)
);
// Site specific
// Encoding
header('Content-type: text/html; charset=UTF-8');
?>
part of the code used in tier1.php (file used to generate each location and keywords page) which generates the paragraph text :
<?php
$randParas = array(1, 2, 3);
$numParas = $randomizer -> fetchEncryptedRandomPhrase($randParas, 1, $_SERVER['REQUEST_URI']);
$content = $content->generateContentFromFeed(
// file
"categories/".$category[0]['category_slug']."/paragraphs",
// type
"paragraph",
// label
"",
// subject
$_SERVER['REQUEST_URI']."7",
// num
$numParas,
// find_ replace
array(
"XX" => $t1_location[0]['definitive_name'],
"YY" => $cfg['site_name']
)
);
?>
A snippet from one of the json files (I am aware the code I have pasted terminates early, I just wanted to put a part of it here as the file is huge!):
{"filename":" xx keywords","content":[{"title":{"1":"xx example\r\nexample in xx\r\nexample in the xx region\r\nexample in the xx area","2":"","3":"","4":""},"type":"paragraph","label":"","structure":"","parts":{"1":"Stylish and practical, a xx keyword \r\nPractical and stylish, a xx keyword \r\nUseful and pragmatic, a xx keyword \r\nPragmatic and useful, a xx keyword \r\nModern and convenient, a xx keyword ",
If you need any more info, please tell me what you need. I really appreciate the help in advance, as I really want to help this client out. They are great people who do not deserve to be hit by a negative SEO company.
What would be the most helpful is if somebody knows what this script is! I can then buy/download it and generate my own feed using the data.
If you can help with either the code to generate the feed, or how I should go about getting the data out of the json files and filter it correctly, that would be great!
Many thanks,
Kevin
ps. Sorry for all the code, I have been told off before for not posting enough!
EDIT : Here is the code I am now using after the suggestion below:
<?php
$randParas = array(1, 2, 3);
$numParas = $randomizer -> fetchEncryptedRandomPhrase($randParas, 1, $_SERVER['REQUEST_URI']);
$content = $content->generateContent(
// file
"content/categories/".$category[0]['category_slug']."/paragraphs.json",
// type
"paragraph",
// label
"",
// subject
$_SERVER['REQUEST_URI']."7",
// num
$numParas,
// find_ replace
array(
"XX" => $t1_location[0]['definitive_name'],
"YY" => $cfg['site_name']
)
);
?>
<?php
if($numParas == '3'){
$divClass = 'vertiCol';
}
elseif($numParas == '2'){
$divClass = 'vertiColDub';
}
else {
$divClass = 'horizCol';
}
$randImages = glob('_images/categories/'.$category[0]['category_slug'].'/*.jpg');
$randImages = $randomizer->randomShuffle($randImages, $_SERVER['REQUEST_URI']);
$fc = preg_replace("/<h3>.*?<\/h3>/", "$0", $content);
$fc = preg_replace("/<h3>.*?<\/h3><p>.*?<\/p>/", "<div class=\"contCol ".$divClass."\">$0$1</div>", $content);
$fca = preg_split("/(\.|\?|\!)/", $fc, -1, PREG_SPLIT_DELIM_CAPTURE);
$prStr = '';
foreach ($fca as $fck => $fcv) {
if ($fck % 3 == 0 && $fck != 0 && !in_array($fcv, array(".", "?", "!")))
$prStr .= "</p>\n<p>";
$prStr .= $fcv;
}
preg_match_all('/<div class="contCol '.$divClass.'"><h3>.*?<\/h3>.*?<\/div>/s', $prStr, $matches);
$randAlign = array(
array('topleft'),
array('topright'),
#array('bottomleft'),
# array('bottomright')
);
$i=0;
$randSelectAlign = $randomizer->fetchEncryptedRandomPhrase($randAlign, 0, $_SERVER['REQUEST_URI']);
$randSelectAlign = $randSelectAlign[0];
foreach($matches[0] as $newPar){
$i++;
if($randSelectAlign=='topleft'){
echo str_replace('</h3><p>', '</h3><p><span class="imgWrap" style="float:left"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span>', $newPar);
}
elseif($randSelectAlign=='topright'){
echo str_replace('</h3><p>', '</h3><p><span class="imgWrap" style="float:right"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span>', $newPar);
}
elseif($randSelectAlign=='bottomleft'){
echo str_replace('</p></div>', '<span class="imgWrap" style="float:left"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span></div>', $newPar);
}
elseif($randSelectAlign=='bottomright'){
echo str_replace('</p></div>', '<span class="imgWrap" style="float:right"><img src="'.$cfg['baseurl'].$randImages[$i].'" width="170" /></span></div>', $newPar);
}
else {
}
//randomly from float array based on server uri!
//randomly select a way to display the images here etc
#
}
?>
Which is giving me the following error messages:
Notice: Array to string conversion in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 230
Notice: Array to string conversion in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 231
Warning: preg_split() expects parameter 2 to be string, array given in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 233
Warning: Invalid argument supplied for foreach() in /home/account/public_html/subdomain/directory/_pages/tier1.php on line 237
These lines of code are :
230 $fc = preg_replace("/<h3>.*?<\/h3>/", "$0", $content);
231 $fc = preg_replace("/<h3>.*?<\/h3><p>.*?<\/p>/", "<div class=\"contCol ".$divClass."\">$0$1</div>", $content);
233 $fca = preg_split("/(\.|\?|\!)/", $fc, -1, PREG_SPLIT_DELIM_CAPTURE);
235 $prStr = '';
237 foreach ($fca as $fck => $fcv) {
if ($fck % 3 == 0 && $fck != 0 && !in_array($fcv, array(".", "?", "!")))
$prStr .= "</p>\n<p>";
$prStr .= $fcv;
}
I presume this is because its spitting the content out as an array? Is there anything in particular I need to do to the data to make it output correctly?
Many thanks,
Kevin
Having glanced over the code, I think I have some idea what it's supposed to do, though I'm still confused about the randomizer stuff ;-)
You can pass your JSON data as a string into the generateContent() method as the first parameter ($source).
The generateContent() returns an array, so you will have to run it through formatContent() (I think).

custom images using Yahoo Weather feed

I'm retrieving data from Yahoo Weather currently and able to display the elements I need so far. I'm stumped on how to use the Condition Codes (i think i need to turn the number into an integer) to have a string such that I can display my own custom icons. As the weather in the region I am tracking is fairly mild I want to assign only a small number of icons but have each cover a string of Condition Codes. So far this is my code that is working–
function bm_getWeather ($code = '', $temp = 'c') {
$file = 'http://weather.yahooapis.com/forecastrss?w=' . $code . '&u=' . $temp;
$request = new WP_Http;
$result = $request->request($file);
if (isset($result->errors)) {
return FALSE;
}
$data = $result['body'];
$output = array (
'temperature' => bm_getWeatherProperties('temp', $data),
'weather_code' => bm_getWeatherProperties('code', $data),
'class' => bm_getWeatherProperties('code', $data),
'weather' => bm_getWeatherProperties('text', $data),
);
return $output;
}
function weather_icon() {
$data = bm_getWeather($code = '', $temp = 'c');
// Error is here
$nums = (int)$data['weather_code']; // Needs to be cast as an integer
$severe = array(12, 13, 14, 16, 19);
$rain = array(3200);
// Therefore the maths is wrong
switch($nums) {
case (in_array($nums, $severe)):
$cat = 'severe';
break;
case (in_array($nums,$rain)):
$cat = 'snow';
break;
default:
$cat = 'happy';
break;
}
return $cat;
}
function bm_getWeatherProperties ($needle, $data) {
$regex = '<yweather:condition.*' . $needle . '="(.*?)".*/>';
preg_match($regex, $data, $matches);
return (string)$matches[1];
}
Any help would be much appreciated as my php skills are less than adequate right now.

Categories