Class & Object Scope for Variable Variables in PHP - php

Question 1) Why is the Variable/variable $this->$template not visible to parse_and_return(), lines 42-50, but visible to $this->fetch, lines 456-472. I thought parse_and_return and $this->fetch belong to the same object, therefore $this->$template should be visible to both functions.
Question 2) Where is $this->$template initialized?
bar.tpl & foo.tpl are separate files
<!-- bar.tpl -->
<HTML>
<HEAD><TITLE>Feature world - {PAGETITLE}</TITLE></HEAD>
<BODY BGCOLOR=BLACK TEXT=WHITE>
<H1>{PAGETITLE}</H1>
{PAGECONTENT}
</BODY>
</HTML>
-->
<!--
foo.tpl
This does not do anything obvious. Please look at {NAME}.
demo.php3
-->
index.php file
<?php
include "FastTemplate.php";
$tpl = new FastTemplate(".");
$tpl->define(array(foo => "foo.tpl", bar => "bar.tpl"));
$tpl->assign(NAME, "me");
$tpl->assign(PAGETITLE, "Welcome!");
$tpl->parse(PAGECONTENT, "foo");
echo $tpl->parse_and_return("bar");
?>
The FastTemplate Class / FastTemplate.php file
<?php
class FastTemplate {
var $start;
var $ERROR = "";
var $LAST = "";
var $ROOT = "";
var $FILELIST = array ( );
var $PARSEVARS = array ( );
var $LOADED = array ( );
var $HANDLE = array ( );
var $UPDT_TIME = '60';
var $COMMENTS_START = "{*";
var $COMMENTS_END = "*}";
var $PATTERN_VARS_VARIABLE = array ( );
var $PATTERN_VARS_DEFINE = array ( );
FUNCTION FastTemplate($pathToTemplates = "") {
if (! empty ( $pathToTemplates )) {
$this->set_root ( $pathToTemplates );
}
$this->start = $this->utime ();
}
FUNCTION parse_and_return($tpl_name) {
$HREF = 'TPL';
$this->parse ( $HREF, $tpl_name );
$result = trim ( $this->fetch ( $HREF ) );
$this->clear_href ( $HREF );
RETURN $result;
}
FUNCTION set_root($root) {
$trailer = substr ( $root, - 1 );
if ((ord ( $trailer )) != 47) {
$root = "$root" . chr ( 47 );
}
if (is_dir ( $root )) {
$this->ROOT = $root;
} else {
$this->ROOT = "";
$this->error ( "dir [$root] is not a directory" );
}
}
FUNCTION get_root() {
RETURN $this->ROOT;
}
FUNCTION utime() {
$time = explode ( " ", microtime () );
$usec = ( double ) $time [0];
$sec = ( double ) $time [1];
RETURN $sec + $usec;
}
FUNCTION get_template($template) {
if (empty ( $this->ROOT )) {
$this->error ( "Root not valid.", 1 );
RETURN FALSE;
}
if (empty ( $template )) {
$this->error ( "Template name is empty.", 1 );
RETURN FALSE;
};
$filename = "$this->ROOT" . "$template";
$contents = ((function_exists ( 'file_get_contents' ))) ? file_get_contents ( $filename ) : implode ( "\n", file ( $filename ) );
RETURN trim ( $contents );
}
FUNCTION parseParamString($string) {
$matches=array();
if (preg_match_all ( '/\{([a-z0-9_]+)\}/i', $string, $matches )) {
FOR($i = 0; $i < count ( $matches [0] ); $i ++) {
$string = str_replace ( $matches [0] [$i], $this->PARSEVARS [$matches [1] [$i]], $string );
}
}
RETURN $string;
}
FUNCTION value_defined($value, $field = '', $params = '') {
$var = $this->PARSEVARS [$value];
if ($field {0} == '.') {
$field = substr ( $field, 1 );
}
# echo "$value, $field, $params <BR>";
if (is_object ( $var )) {
if (method_exists ( $var, $field )) {
eval ( '$return = $var->' . $field . '(' . $this->parseParamString ( $params ) . ');' );
RETURN ((! empty ( $return )) || ($return === TRUE));
} ELSEif ((strcasecmp ( $field, 'id' ) != 0) && method_exists ( $var, 'get' )) {
$result = $var->get ( $field );
RETURN (! empty ( $result ) || $result === TRUE);
} ELSEif ((strcasecmp ( $field, 'id' ) == 0) && method_exists ( $var, 'getId' )) {
$result = $var->getId ();
RETURN (! empty ( $result ) || $result === TRUE);
}
} else {
RETURN (! empty ( $var ) || $var === TRUE);
}
}
FUNCTION parse_defined($template) {
$lines = split ( "\n", $template );
$newTemplate = "";
$ifdefs = FALSE;
$depth = 0;
$needparsedef [$depth] ["defs"] = FALSE;
$needparsedef [$depth] ["parse"] = TRUE;
WHILE ( list ( $num, $line ) = each ( $lines ) ) {
if (((! $needparsedef [$depth] ["defs"]) || ($needparsedef [$depth] ["parse"])) && (strpos ( $line, "IFDEF:" ) === FALSE) && (strpos ( $line, "IFNDEF:" ) === FALSE) && (strpos ( $line, "ELSE" ) === FALSE) && (strpos ( $line, "ENDIF" ) === FALSE)) {
$newTemplate .= trim ( $line ) . "\n";
}
if (preg_match ( "/<!--\s*IFDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->/i", $line, $regs )) {
$depth ++;
$needparsedef [$depth] ["defs"] = TRUE;
if ($this->value_defined ( $regs [1], $regs [3], $regs [4] )){
$needparsedef [$depth] ["parse"] = $needparsedef [$depth - 1] ["parse"];
}else{
$needparsedef [$depth] ["parse"] = FALSE;
}
}
if (preg_match ( "/<!--\s*IFNDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->/i", $line, $regs )) {
$depth ++;
$needparsedef [$depth] ["defs"] = TRUE;
}
if (! $this->value_defined ( $regs [1], $regs [3], $regs [4] )){
$needparsedef [$depth] ["parse"] = $needparsedef [$depth - 1] ["parse"];
}else{
$needparsedef [$depth] ["parse"] = FALSE;}
}
// ELSE block
if (preg_match ( "/<!--\s*ELSE\s*-->/i", $line )) {
if ($needparsedef [$depth] ["defs"]){
$needparsedef [$depth] ["parse"] = (! ($needparsedef [$depth] ["parse"]) & $needparsedef [$depth - 1] ["parse"]);
}
if (preg_match ( "/<!--\s*ENDIF\s*-->/i", $line )) {
$needparsedef [$depth] ["defs"] = FALSE;
$depth --;
}
}
if ($depth){
$this->error ( 'Some nonclosed IDEFS blocks', 0 );
}
RETURN $newTemplate;
}
FUNCTION parse_template($template, $ft_array) {
$matches=array();
if (preg_match_all ( '/\{([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)([a-zA-Z_][a-zA-Z0-9_]+)\(?(\s*\,?\".*?\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\}/i', $template, $matches )) {
FOR($i = 0; $i < count ( $matches [0] ); ++ $i) {
$obj = $ft_array [$matches [1] [$i]];
if ((is_object ( $obj ) && method_exists ( $obj, $matches [3] [$i] ))) {
eval ( '$return = $obj->' . $matches [3] [$i] . '(' . $this->parseParamString ( $matches [4] [$i] ) . ');' );
$template = str_replace ( $matches [0] [$i], $return, $template );
} else if (is_object ( $obj ) && ($matches [3] [$i] == 'id') && method_exists ( $obj, 'getId' )){
$template = str_replace ( $matches [0] [$i], $obj->getId (), $template );
}else if (is_object ( $obj ) && method_exists ( $obj, 'get' )){
$template = str_replace ( $matches [0] [$i], $obj->get ( $matches [3] [$i] ), $template ); }else if (! is_object ( $obj )){
$template = str_replace ( $matches [0] [$i], '', $template );
}
} //end for loop
} //end if
if (preg_match_all ( '/<\!\-\-\s*#include\s+file="([\{\}a-zA-Z0-9_\.\-\/]+)"\s*\\-\->/i', $template, $matches )) {
FOR($i = 0; $i < count ( $matches [0] ); $i ++) {
$file_path = $matches [1] [$i];
FOREACH ( $ft_array as $key => $value ) {
if (! empty ( $key )) {
$key = '{' . "$key" . '}';
$file_path = str_replace ( "$key", "$value", "$file_path" );
}
} //foreach
$content = '';
if (! isset ( $ft_array [$file_path] )) {
if (! file_exists ( $file_path )){
$file_path = $this->ROOT . $file_path;
}
if (! file_exists ( $file_path )){
$file_path = $this->ROOT . basename ( $file_path );
}
if (file_exists ( $file_path )) {
$content = ((function_exists ( 'file_get_contents' ))) ? file_get_contents ( $file_path ) : implode ( "\n", file ( $file_path ) );
} else {
$content = '';
}
} else {
$content = $ft_array [$file_path];
$template = str_replace ( $matches [0] [$i], $content, $template );
}
} //for
} //end preg_match_all
reset ( $ft_array );
WHILE ( list ( $key, $val ) = each ( $ft_array ) ) {
if (! (empty ( $key ))) {
if (gettype ( $val ) != "string") {
settype ( $val, "string" );
}
$key = '{' . "$key" . '}';
$template = str_replace ( "$key", "$val", "$template" );
}
}
$template = ereg_replace ( "{([A-Za-z0-9_\.]+)}", "", $template );
$template = preg_replace ( "/(<!--\s*IFDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*?\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->)/i", "\n$0\n", $template );
$template = preg_replace ( "/(<!--\s*IFNDEF:\s*([a-zA-Z_][a-zA-Z0-9_]+)(\.|\-\>)?([a-zA-Z_][a-zA-Z0-9_]+)?\(?(\s*\,?\".*?\"\s*\,?|\s*\,?[a-z0-9\_]*\s*\,?)\)?\s*-->)/i", "\n$0\n", $template );
$template = preg_replace ( "/(<!--\s*ELSE\s*-->)/i", "\n\\0\n", $template );
$template = preg_replace ( "/(<!--\s*ENDIF\s*-->)/i", "\n\\0\n", $template );
WHILE ( list ( $num, $line ) = each ( $lines ) ) {
if (! $inside_block) {
$template .= "$line\n";
}
}
$template = $this->parse_defined ( $template );
RETURN $template;
}
FUNCTION parse($ReturnVar, $FileTags) {
FOREACH ( $this->PATTERN_VARS_DEFINE as $value ){
$this->multiple_assign_define ( "$value" );
}
FOREACH ( $this->PATTERN_VARS_VARIABLE as $value ){
$this->multiple_assign ( "$value" );
}
$append = FALSE;
$this->LAST = $ReturnVar;
$this->HANDLE [$ReturnVar] = 1;
if (gettype ( $FileTags ) == "array") {
unset ( $this->$ReturnVar );
WHILE ( list ( $key, $val ) = each ( $FileTags ) ) {
if ((! isset ( $this->$val )) || (empty ( $this->$val ))) {
$this->LOADED ["$val"] = 1;
$fileName = $this->FILELIST ["$val"];
$this->$val = $this->get_template ( $fileName );
}
$this->$ReturnVar = $this->parse_template ( $this->$val, $this->PARSEVARS );
// For recursive calls.
$this->assign ( array ($ReturnVar => $this->$ReturnVar ) );
}
} else {
$val = $FileTags;
if ((substr ( $val, 0, 1 )) == '.') {
$append = TRUE;
$val = substr ( $val, 1 );
}
if ((! isset ( $this->$val )) || (empty ( $this->$val ))) {
$this->LOADED ["$val"] = 1;
$fileName = $this->FILELIST ["$val"];
$this->$val = $this->get_template ( $fileName );
}
if ($append) {
if (isset ( $this->$ReturnVar )) {
$this->$ReturnVar .= $this->parse_template ( $this->$val, $this->PARSEVARS );
} else {
$this->$ReturnVar = $this->parse_template ( $this->$val, $this->PARSEVARS );
}
} else {
$this->$ReturnVar = $this->parse_template ( $this->$val, $this->PARSEVARS );
}
$this->assign ( array ($ReturnVar => $this->$ReturnVar ) );
}
RETURN;
}
FUNCTION getfast($template = "") {
if (empty ( $template )) {
$template = $this->LAST;
}
// "$this->$template" not initialize here!
if ((! (isset ( $this->$template ))) || (empty ( $this->$template ))) {
$this->error ( "Nothing parsed, nothing printed", 0 );
RETURN;
} else {
if (! get_magic_quotes_gpc ()){
$this->$template = stripslashes ( $this->$template );
}
RETURN $this->$template;
}
}
FUNCTION fetch($template = "") {
if (empty ( $template )) {
$template = $this->LAST;
}
if ((! (isset ( $this->$template ))) || (empty ( $this->$template ))) {
$this->error ( "Nothing parsed, nothing printed", 0 );
RETURN "";
}
RETURN ($this->$template);
}
FUNCTION define($fileList, $value = null) {
if ((gettype ( $fileList ) != "array") && ! is_null ( $value )){
$fileList = array ($fileList => $value );
}
WHILE ( list ( $FileTag, $FileName ) = each ( $fileList ) ) {
$this->FILELIST ["$FileTag"] = $FileName;
}
RETURN TRUE;
}
FUNCTION clear_href($href) {
if (! empty ( $href )) {
if ((gettype ( $href )) != "array") {
unset ( $this->PARSEVARS [$href] );
RETURN;
} else {
FOREACH ( $href as $value ){
unset ( $this->PARSEVARS [$value] );
RETURN;
}
}
} else {
// Empty - clear them all
$this->clear_assign ();
}
RETURN;
}
FUNCTION clear_assign() {
if (! (empty ( $this->PARSEVARS ))) {
WHILE ( list ( $Ref, $Val ) = each ( $this->PARSEVARS ) ) {
unset ( $this->PARSEVARS ["$Ref"] );
}
}
}
FUNCTION assign_from_array($Arr, $Keys) {
if (gettype ( $Arr ) == "array") {
foreach ( $Keys as $k ){
if (! empty ( $k )){
$this->PARSEVARS [strtoupper ( $k )] = str_replace ( '&#', '&#', $Arr [$k] );
}
}
}
}
FUNCTION assign($ft_array, $trailer = "") {
if (gettype ( $ft_array ) == "array") {
WHILE ( list ( $key, $val ) = each ( $ft_array ) ) {
if (! (empty ( $key ))) {
if (! is_object ( $val )){
$this->PARSEVARS ["$key"] = str_replace ( '&#', '&#', $val );
} else{
$this->PARSEVARS ["$key"] = $val;
}
}
}
} else {
if (! empty ( $ft_array )) {
if (! is_object ( $trailer )){
$this->PARSEVARS ["$ft_array"] = str_replace ( '&#', '&#', $trailer );
}else{
$this->PARSEVARS ["$ft_array"] = $trailer;
}
}
}
}
FUNCTION get_assigned($ft_name = "") {
if (empty ( $ft_name )) {
RETURN FALSE;
}
if (isset ( $this->PARSEVARS ["$ft_name"] )) {
RETURN ($this->PARSEVARS ["$ft_name"]);
} else {
RETURN FALSE;
}
}
FUNCTION error($errorMsg, $die = 0) {
$this->ERROR = $errorMsg;
echo "ERROR: $this->ERROR <BR> \n";
if ($die == 1) {
exit ();
}
RETURN;
}
FUNCTION multiple_assign($pattern) {
WHILE ( list ( $key, $value ) = each ( $GLOBALS ) ) {
if (substr ( $key, 0, strlen ( $pattern ) ) == $pattern) {
$this->assign ( strtoupper ( $key ), $value );
}
}
reset ( $GLOBALS );
}
FUNCTION multiple_assign_define($pattern) {
$ar = get_defined_constants ();
FOREACH ( $ar as $key => $def ){
if (substr ( $key, 0, strlen ( $pattern ) ) == $pattern){
$this->assign ( strtoupper ( $key ), $def );
}
}
}
} // End Class
?>

Answer to my first question:
There are two reasons why the variable “$this->$template” is not visible to the parse_and_return();
Reason 1: The “$this->$template” variable points to an instance variable $TPL of the FastTemplate class that does not exist until parse() is called. The parse() function parses the bar.tpl file and resolves this file's FastTemplate {VARS}. An instance variable $TPL is created in a FastTemplate object and assigned the bar.tpl file’s contents. The $TPL variable will not be visible to any member function until it is created.
Reason 2: $template is a local variable and $this->$template is a local variable variable; local only to the fetch() function. Because the scope of these variables are local they will generate and error if you try to use them in other member functions. However, once the $TPL instance variable is created you can access its data value from any member function by simply using $this->TPL.
Answer to my second question:
As stated above, “$this->$template” is a local variable variable and refers to the instance variable $TPL that is initialized with the value of the bar.tpl file’s contents. This $TPL variable is initialized near or on lines 382-388, inside the parse() function. The following expression was used to initialize $TPL: “$this->$ReturnVar = $this->parse_template ($this->$val, $this->PARSEVARS )”.
The $ReturnVar variable was the first parameter in parse() function's definition, e.g. FUNCTION parse($ReturnVar, $FileTags). The $ReturnVar variable was passed an argument with a string value of “TPL”. You can now use a variable variable to access a variable’s address, in this case the address of the string “TPL” by using $$ReturnVar. Because “TPL” is an instance variable of a FastTemplate object you must use the pseudo variable “$this->” to access it. Therefore the variable variable is structured as $this->$ReturnVar. This will create the $TPL variable and access its address and assign the address the contents of the bar.tpl file.
Coincidentally in this this example the object is named $tpl but any name could have been used.
Closing comment - It will be my objective to simplify this code by excluding all the variable variables and using a more direct coding approach. It is my opinion that the over use of variable variables (pointers) makes your code convoluted and hard to follow.

Related

Place ads between two text-only paragraphs

I am using the following code to place ads between text-only paragraphs. However, the problem is it inserts only 2 ads in the content even if the post is lengthy.
So, I want to display the ad in every nth paragraph (keeping the first ad). So, if n=4, the ad will display after the 4th paragraph but only if the 5th paragraph have text.
add_filter( 'the_content', 'so_25888630_ad_between_paragraphs' );
function so_25888630_ad_between_paragraphs($content){
if( in_the_loop() ){
$closing_p = '</p>';
$paragraphs = explode( $closing_p, wptexturize($content) );
$count = count( $paragraphs );
if( 4 >= $count ) {
$totals = array( $paragraphs );
}else{
$midpoint = floor($count / 2);
$first = array_slice($paragraphs, 0, $midpoint );
if( $count%2 == 1 ) {
$second = array_slice( $paragraphs, $midpoint, $midpoint, true );
}else{
$second = array_slice( $paragraphs, $midpoint, $midpoint-1, true );
}
$totals = array( $first, $second );
}
$new_paras = array();
foreach ( $totals as $key_total=>$total ) {
$p = array();
foreach ( $total as $key_paras=>$paragraph ) {
$word_count = count(explode(' ', $paragraph));
if( preg_match( '~<(?:img|ul|li)[ >]~', $paragraph ) || $word_count < 10 ) {
$p[$key_paras] = 0;
}else{
$p[$key_paras] = 1;
}
}
$m = array();
foreach ( $p as $key=>$value ) {
if( 1 === $value && array_key_exists( $key-1, $p ) && $p[$key] === $p[$key-1] && !$m){
$m[] = $key;
}elseif( !array_key_exists( $key+1, $p ) && !$m ) {
$m[] = 'no-ad';
}
}
if( $key_total == 0 ){
$ad = array( 'ad1' => '<p>PLACE YOUR ADD NO 1 HERE</p>' );
}else{
$ad = array( 'ad2' => '<p>PLACE YOUR ADD NO 2 HERE</p>' );
}
foreach ( $total as $key_para=>$para ) {
if( !in_array( 'no_ad', $m ) && $key_para === $m[0] ){
$new_paras[key($ad)] = $ad[key($ad)];
$new_paras[$key_para] = $para;
}else{
$new_paras[$key_para] = $para;
}
}
}
$content = implode( ' ', $new_paras );
}
return $content;
}

Error on unserialize()

I'm trying to fix a PHP error on unserialize(). I know we can suppress it with # but can it be possible to fix that error without suppressing.
Here is the table & my code:
TABLE: 'config'
id c_key c_value
1 facebook a:1:{i:0;s:8:"Newsfeed";}
2 mg_notification_msv to.aaaa.org
public function db_get_config($key, $default = null)
{
if (!empty($key)) {
// $record = $this->db_get_record($this->tables['config'], array('c_key' => $key));
$record = $this->db->from($this->tables['config'])->where(array('c_key' => $key))->limit(1)->get()->row_array();
if (!empty($record)) {
$value = unserialize($record['c_value']); // Message: unserialize(): Error at offset 0 of 15 bytes
if ($value === false) {
$value = $record['c_value'];
}
return $value;
}
}
return $default;
}
When passing $key as facebook or mg_notification_msv, the function returns array(1) { [0]=> string(8) "Newsfeed" } or string(15) "to.aaaa.org" on var_dump().
This returns the error:
A PHP Error was encountered
Severity: Notice Message: unserialize(): Error at offset 0 of 15 bytes
Filename: models/common_model.php
Line Number: xxxx
Is there any way to fix this PHP error?
Use of strlen() on $record['c_value'] doesn't help me.
It's probably throwing that error because when you try to unserialize the value of mg_notification_msv it's trying to unserialize a string that wasn't serialized before (to.aaaa.org is not a serialized string)
You can try to unserialize only if the string is unserializable:
if (#unserialize($record['c_value']) !== false ) {
$value = unserialize($record['c_value']);
} else {
$value = $record['c_value'];
}
I tried with WP is_serialized() & possible resolved my issue.
<?php
public function db_get_config($key, $default = null)
{
if (!empty($key)) {
// $record = $this->db_get_record($this->tables['config'], array('c_key' => $key));
$record = $this->db->from($this->tables['config'])->where(array('c_key' => $key))->limit(1)->get()->row_array();
if (!empty($record)) {
$e = $this->is_serialized($record['c_value']); // WP support function
if ($e === true) {
$value = unserialize($record['c_value']);
if ($value === false) {
$value = $record['c_value'];
}
} else {
$value = $record['c_value'];
}
return $value;
}
}
return $default;
}
private function is_serialized( $data, $strict = true )
{
// if it isn't a string, it isn't serialized.
if ( ! is_string( $data ) ) {
return false;
}
$data = trim( $data );
if ( 'N;' == $data ) {
return true;
}
if ( strlen( $data ) < 4 ) {
return false;
}
if ( ':' !== $data[1] ) {
return false;
}
if ( $strict ) {
$lastc = substr( $data, -1 );
if ( ';' !== $lastc && '}' !== $lastc ) {
return false;
}
} else {
$semicolon = strpos( $data, ';' );
$brace = strpos( $data, '}' );
// Either ; or } must exist.
if ( false === $semicolon && false === $brace )
return false;
// But neither must be in the first X characters.
if ( false !== $semicolon && $semicolon < 3 )
return false;
if ( false !== $brace && $brace < 4 )
return false;
}
$token = $data[0];
switch ( $token ) {
case 's' :
if ( $strict ) {
if ( '"' !== substr( $data, -2, 1 ) ) {
return false;
}
} elseif ( false === strpos( $data, '"' ) ) {
return false;
}
// or else fall through
case 'a' :
case 'O' :
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b' :
case 'i' :
case 'd' :
$end = $strict ? '$' : '';
return (bool) preg_match( "/^{$token}:[0-9.E-]+;$end/", $data );
}
return false;
}
?>

index.php returning a blank web page on openshift host

I have a website I am trying to maintain for a project:
http://uomtwittersearch-jbon0041.rhcloud.com/
The user connects to Twitter through the application and authenticates by using the twitteroauth library (by abraham). The process works fine up until it lands on index.php (calling index.inc as the respective HTML page) where it gives me a blank page. On localhost it works perfectly fine so I am not sure what could be causing this. Other pages such as connect.php initialize as required.
Visiting the website as it is will give an error and I am assuming that is because it cannot find index.php directly and it lies in the folder twitteroauth-master. I will fix this when I manage to at least make the contents of index.php appear but for now I am visiting:
http://uomtwittersearch-jbon0041.rhcloud.com/twitteroauth-master/connect.php
first, and this also goes to anyone who would like to visit it. If you have twitter log on with your details, this will move you to index.php which will be blank. Other than that one can simply replace 'connect' with 'index'.
What could be causing the blank page for index.php?
This is only my first ever web development project so I am not sure if this is something obvious. Moreover, I am using OpenShift for hosting.
EDIT --------------------
This is my index.php script. Again the script works fine without any problems on localhost.
<?php
//session_save_path(home/users/web/b2940/ipg.uomtwittersearchnet/cgi-bin/tmp);
ini_set('display_errors',1);
error_reporting(E_ALL);
session_start ();
require_once ('twitteroauth/twitteroauth.php');
require_once ('config.php');
include ('nlp/stop_words.php');
include ('nlp/acronyms.php');
set_time_limit ( 300 );
//////////////////////// TWITTEROAUTH /////////////////////////////////////
/* If access tokens are not available redirect to connect page. */
if (empty ( $_SESSION ['access_token'] ) || empty ( $_SESSION ['access_token'] ['oauth_token'] ) || empty ( $_SESSION ['access_token'] ['oauth_token_secret'] )) {
header ( 'Location: ./clearsessions.php' );
}
/* Get user access tokens out of the session. */
$access_token = $_SESSION ['access_token'];
/* Create a TwitterOauth object with consumer/user tokens. */
$connection = new TwitterOAuth ( CONSUMER_KEY, CONSUMER_SECRET, $access_token ['oauth_token'], $access_token ['oauth_token_secret'] );
///////////////////////////////////////////////////////////////////////////
///// UNCOMMENT BELOW TO AUTOMATICALLY SPECIFY CURRENTLY LOGGED IN USER
//$user = $connection->get('account/verify_credentials');
//$user_handle = $user->screen_name;
$user_handle = 'AngeloDalli';
$timeline = getContent ( $connection, $user_handle, 1 );
$latest_id = $timeline [0]->id_str;
$most_recent = getMostRecentTweet ();
if ($latest_id > $most_recent) {
$t_start = microtime(true); // start indexing
$timeline = getContent ( $connection, $user_handle, 200 );
$json_index = decodeIndex ();
$json_index = updateIndex ( $timeline, $connection, $user_handle, $json_index, $most_recent );
$json_index = sortIndex ( $json_index );
$json = encodeIndex ( $json_index );
updateMostRecentTweet ( $latest_id );
$_SESSION ['index_size'] = countIndex ( $json_index );
$t_end = microtime(true); // finish indexing
$content = 'New tweets indexed! Number of tweets in index: ' . $_SESSION ['index_size'];
// total indexing time
$time = 'Total time of indexing: ' . ($t_end - $t_start)/60 . ' seconds';
} else {
$content = 'No new tweets indexed!';
$time = '';
}
/////////////////////// FUNCTIONS //////////////////////////////////////////////
function getContent($connection, $user_handle, $n) {
$content = $connection->get ( 'statuses/user_timeline', array (
'screen_name' => $user_handle,
'count' => $n
) );
return $content;
}
function decodeIndex() {
$string = file_get_contents ( INDEX_PATH );
if ($string) {
$json_index = json_decode ( $string, true );
} else {
$json_index = [ ];
}
return $json_index;
}
function updateIndex($timeline, $connection, $user_handle, $json_index, $most_recent) {
// URL arrays for uClassify API calls
$urls = [ ];
$urls_id = [ ];
// halt if no more new tweets are found
$halt = false;
// set to 1 to skip first tweet after 1st batch
$j = 0;
// count number of new tweets indexed
$count = 0;
while ( (count ( $timeline ) != 1 || $j == 0) && $halt == false ) {
$no_of_tweets_in_batch = 0;
$n = $j;
while ( ($n < count ( $timeline )) && $halt == false ) {
$tweet_id = $timeline [$n]->id_str;
if ($tweet_id > $most_recent) {
$text = $timeline [$n]->text;
$tokens = parseTweet ( $text );
$coord = extractLocation ( $timeline, $n );
addSentimentURL ( $text, $tweet_id, $urls, $urls_id );
$keywords = makeEntry ( $tokens, $tweet_id, $coord, $text );
foreach ( $keywords as $type ) {
$json_index [] = $type;
}
$n ++;
$no_of_tweets_in_batch ++;
} else {
$halt = true;
}
}
if ($halt == false) {
$tweet_id = $timeline [$n - 1]->id_str;
$timeline = $connection->get ( 'statuses/user_timeline', array (
'screen_name' => $user_handle,
'count' => 200,
'max_id' => $tweet_id
) );
// skip 1st tweet after 1st batch
$j = 1;
}
$count += $no_of_tweets_in_batch;
}
$json_index = extractSentiments ( $urls, $urls_id, $json_index );
echo 'Number of tweets indexed: ' . ($count);
return $json_index;
}
function parseTweet($tweet) {
// find urls in tweet and remove (HTTP ONLY CURRENTLY)
$tweet = preg_replace ( '/(http:\/\/[^\s]+)/', "", $tweet );
// split tweet into tokens and clean
$words = preg_split ( "/[^A-Za-z0-9]+/", $tweet );
// /[\s,:.##?!()-$%&^*;+=]+/ ------ Alternative regex
$expansion = expandAcronyms ( $words );
$tokens = removeStopWords ( $expansion );
// convert to type-frequency array
$tokens = array_filter ( $tokens );
$tokens = array_count_values ( $tokens );
return $tokens;
}
function expandAcronyms($terms) {
$words = [ ];
$acrok = array_keys ( $GLOBALS ['acronyms'] );
$acrov = array_values ( $GLOBALS ['acronyms'] );
for($i = 0; $i < count ( $terms ); $i ++) {
$j = 0;
$is_acronym = false;
while ( $is_acronym == false && $j != count ( $acrok ) ) {
if (strcasecmp ( $terms [$i], $acrok [$j] ) == 0) {
$is_acronym = true;
$expansion = $acrov [$j];
}
$j ++;
}
if ($is_acronym) {
$expansion = preg_split ( "/[^A-Za-z0-9]+/", $expansion );
foreach ( $expansion as $term ) {
$words [] = $term;
}
} else {
$words [] = $terms [$i];
}
}
return $words;
}
function removeStopWords($words) {
$tokens = [ ];
for($i = 0; $i < count ( $words ); $i ++) {
$is_stopword = false;
$j = 0;
while ( $is_stopword == false && $j != count ( $GLOBALS ['stop_words'] ) ) {
if (strcasecmp ( $words [$i], $GLOBALS ['stop_words'] [$j] ) == 0) {
$is_stopword = true;
} else
$j ++;
}
if (! $is_stopword) {
$tokens [] = $words [$i];
}
}
return $tokens;
}
function extractLocation($timeline, $n) {
$geo = $timeline [$n]->place;
if (! empty ( $geo )) {
$place = $geo->full_name;
$long = $geo->bounding_box->coordinates [0] [1] [0];
$lat = $geo->bounding_box->coordinates [0] [1] [1];
$coord = array (
'place' => $place,
'latitude' => $lat,
'longitude' => $long
);
} else {
$coord = [ ];
}
return $coord;
}
function addSentimentURL($text, $tweet_id, &$urls, &$urls_id) {
$urls_id [] = $tweet_id;
$url = makeURLForAPICall ( $text );
$urls [] = $url;
}
function makeURLForAPICall($tweet) {
$tweet = str_replace ( ' ', '+', $tweet );
$prefix = 'http://uclassify.com/browse/uClassify/Sentiment/ClassifyText?';
$key = 'readkey=' . CLASSIFY_KEY . '&';
$text = 'text=' . $tweet . '&';
$version = 'version=1.01';
$url = $prefix . $key . $text . $version;
return $url;
}
function makeEntry($tokens, $tweet_id, $coord, $text) {
$types = array ();
while ( current ( $tokens ) ) {
$key = key ( $tokens );
array_push ( $types, array (
'type' => $key,
'frequency' => $tokens [$key],
'tweet_id' => $tweet_id,
'location' => $coord,
'text' => $text
) );
next ( $tokens );
}
return $types;
}
function extractSentiments($urls, $urls_id, &$json_index) {
$responses = multiHandle ( $urls );
// add sentiments to all index entries
foreach ( $json_index as $i => $term ) {
$tweet_id = $term ['tweet_id'];
foreach ( $urls_id as $j => $id ) {
if ($tweet_id == $id) {
$sentiment = parseSentiment ( $responses [$j] );
$json_index [$i] ['sentiment'] = $sentiment;
}
}
}
return $json_index;
}
// - Without sentiment, indexing is performed at reasonable speed
// - With sentiment, very frequent API calls greatly reduce indexing speed
// - filegetcontents() for Sentiment API calls is too slow, therefore considered cURL
// - cURL is still too slow and indexing performance is still not good enough
// - therefore considered using multi cURL which is much faster than by just using cURL
// on its own and significantly improved sentiment extraction which in turn greatly
// improved indexing with sentiment
function multiHandle($urls) {
// curl handles
$curls = array ();
// results returned in xml
$xml = array ();
// init multi handle
$mh = curl_multi_init ();
foreach ( $urls as $i => $d ) {
// init curl handle
$curls [$i] = curl_init ();
$url = (is_array ( $d ) && ! empty ( $d ['url'] )) ? $d ['url'] : $d;
// set url to curl handle
curl_setopt ( $curls [$i], CURLOPT_URL, $url );
// on success, return actual result rather than true
curl_setopt ( $curls [$i], CURLOPT_RETURNTRANSFER, 1 );
// add curl handle to multi handle
curl_multi_add_handle ( $mh, $curls [$i] );
}
// execute the handles
$active = null;
do {
curl_multi_exec ( $mh, $active );
} while ( $active > 0 );
// get xml and flush handles
foreach ( $curls as $i => $ch ) {
$xml [$i] = curl_multi_getcontent ( $ch );
curl_multi_remove_handle ( $mh, $ch );
}
// close multi handle
curl_multi_close ( $mh );
return $xml;
}
// SENTIMENT VALUES ON INDEX.JSON FOR THIS ASSIGNMENT ARE NOT CORRECT SINCE THE
// NUMBER OF API CALLS EXCEEDED 5000 ON THE DAY OF HANDING IN. ONCE THE API CALLS
// ARE ALLOWED AGAIN IT CLASSIFIES AS REQUIRED
function parseSentiment($xml) {
$p = xml_parser_create ();
xml_parse_into_struct ( $p, $xml, $vals, $index );
xml_parser_free ( $p );
$positivity = $vals [8] ['attributes'] ['P'];
$negativity = 1 - $positivity;
$sentiment = array (
'pos' => $positivity,
'neg' => $negativity
);
return $sentiment;
}
function sortIndex($json_index) {
$type = array ();
$freq = array ();
$id = array ();
foreach ( $json_index as $key => $row ) {
$type [$key] = $row ['type'];
$freq [$key] = $row ['frequency'];
$id [$key] = $row ['tweet_id'];
}
array_multisort ( $type, SORT_ASC | SORT_NATURAL | SORT_FLAG_CASE,
$freq, SORT_DESC,
$id, SORT_ASC,
$json_index );
return $json_index;
}
function encodeIndex($json_index) {
$json = json_encode ( $json_index, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT );
$index = fopen ( INDEX_PATH, 'w' );
fwrite ( $index, $json );
fclose ( $index );
return $json;
}
function countIndex($json_index) {
$tweets = [ ];
$count = 0;
for($i = 0; $i < count ( $json_index ); $i ++) {
$id = $json_index [$i] ['tweet_id'];
if (in_array ( $id, $tweets )) {
} else {
$tweets [] = $id;
$count ++;
}
}
return $count;
}
function lookup($array, $key, $val) {
foreach ( $array as $item ) {
if (isset ( $item [$key] ) && $item [$key] == $val) {
return true;
} else {
return false;
}
}
}
function getMostRecentTweet() {
$file = fopen ( 'latest.txt', 'r' );
$most_recent = fgets ( $file );
if (! $most_recent) {
$most_recent = 0;
}
fclose ( $file );
return $most_recent;
}
function updateMostRecentTweet($latest_id) {
$file = fopen ( 'latest.txt', 'w' );
fwrite ( $file, $latest_id . PHP_EOL );
fclose ( $file );
}
include ('index.inc');
?>
I have fixed the problem. When creating my application on OpenShift using the application wizard, I was specifying PHP 5.3 as the cartridge and not PHP 5.4 (note the way I'm specifying certain empty arrays).
The true lesson to take from this is: always be sure about the version of the language you're developing with
Thank you for any help given and I hope this may come of use to someone else in the future!

Folder Tree in array using PHP

I am trying to display a folder tree. Its working all good. Below is the code.
$fileData = fillArrayWithFileNodes( new DirectoryIterator( $dir ) );
function fillArrayWithFileNodes( DirectoryIterator $dir )
{
$data = array();
foreach ( $dir as $node )
{
if ( $node->isDir() && !$node->isDot() )
{
$data[$node->getFilename()] = fillArrayWithFileNodes( new DirectoryIterator( $node->getPathname() ) );
}
else if ( $node->isFile() )
{
$data[] = $node->getFilename();
}
}
return $data;
}
But i have a new requirement. I want to have it in a class, so that i can use it this way.
$tree = new folderTree();
$structure = $tree->display('testdir',2); //2 is the level of subfolders
So i have wrapped everything in a class in the below way.
class folderTree {
function display($dir,$level='') {
$fileData = fillArrayWithFileNodes( new DirectoryIterator( $dir ) );
function fillArrayWithFileNodes( DirectoryIterator $dir )
{
$data = array();
foreach ( $dir as $node )
{
if ( $node->isDir() && !$node->isDot() )
{
$data[$node->getFilename()] = fillArrayWithFileNodes( new DirectoryIterator( $node->getPathname() ) );
}
else if ( $node->isFile() )
{
$data[] = $node->getFilename();
}
}
return $data;
}
}
}
But i am really stuck in how to use the level.
What is level ?
-folder
-childfolder (level1)
file1
file2
-subchildfolder (level2)
file1
file2
You can copy the logic from below code:
<?php
function getFiles(RecursiveDirectoryIterator $rdi, $depth=0) {
if (!is_object($rdi))
return;
for ($rdi->rewind();$rdi->valid();$rdi->next()) {
if ($rdi->isDot())
continue;
if ($rdi->isDir() || $rdi->isFile()) {
for ($i = 0; $i<=$depth;++$i)
echo ' ';
echo $rdi->current().'<br />';
if ($rdi->hasChildren())
getFiles($rdi->getChildren(),1+$depth);
}
}
}
$depth = 2;
getFiles(new RecursiveDirectoryIterator('.'), $depth);
?>

wordpress memory size fetal error on functions.php

I making a plugin for wordpress, but i have problem with allowed memory size on my server, it is 128, they dont allow me to increase memory at run time.
my plugin have function to export user datas to csv and email to user. i getting fetal error on this wordpress, functions.php line 252
is there efficient way to optimize this below function to prevent getting error
thank you
function is_serialized( $data ) {
// if it isn't a string, it isn't serialized
if ( ! is_string( $data ) )
return false;
$data = trim( $data );
if ( 'N;' == $data )
return true;
$length = strlen( $data );
if ( $length < 4 )
return false;
if ( ':' !== $data[1] )
return false;
$lastc = $data[$length-1];
if ( ';' !== $lastc && '}' !== $lastc )
return false;
$token = $data[0];
switch ( $token ) {
case 's' :
if ( '"' !== $data[$length-2] )
return false;
case 'a' :
case 'O' :
return (bool) preg_match( "/^{$token}:[0-9]+:/s", $data );
case 'b' :
case 'i' :
case 'd' :
return (bool) preg_match( "/^{$token}:[0-9.E-]+;\$/", $data );
}
return false;
}
my function - fileds are dynamic getting from admin panel
$outFile = '';
$blogusers = get_users();
// retrieve the current options
$spueIntervall = get_option('spue_intervall');
//fileds are dynamic
$spueSeperator = get_option('spue_seperator');
$spueFields = get_option('spue_fields');
// Check if the functions is already loaded
if (!function_exists('get_userdata'))
require_once (ABSPATH . 'wp-includes/pluggable.php');
// Setup the top-line of the file
foreach ($spueFields AS $fieldKey => $fieldValue)
{
if ($fieldValue == 1)
{
$outFile .= $fieldKey . $spueSeperator;
}
}
$outFile .= "\n";
// Loop to all users
foreach ($blogusers as $user)
{
// Get the userdate
$user_info = get_userdata($user->ID);
// Only output the needed data
foreach ($spueFields AS $fieldKey => $fieldValue)
{
if ($fieldValue == 1)
{
$outFile .= '"' . $user_info->{$fieldKey} . '"' . $spueSeperator;
}
}
$outFile .= "\n";
}
// Save
file_put_contents( dirname(__FILE__) . '\spue-export.csv', utf8_encode($outFile));
got it
foreach ( $blogusers as $user ) {
$data = array();
foreach ($spueFields AS $fieldKey => $fieldValue) {
if ($fieldValue == 1)
{
$value = isset( $user->{$fieldKey} ) ? $user->{$fieldKey} : '';
$value = is_array( $value ) ? serialize( $value ) : $value;
$data[] = '"' . str_replace( '"', '""', $value ) . '"';
$outFile.=implode( ',', $data ) . "\n";
}

Categories