I am having an issue with the twig template system - php

I have opencart 3 installed on my dev box and have suddenly started getting the following error:
Fatal error: Class Twig_Loader_Filesystem contains 2 abstract methods
and must therefore be declared abstract or implement the remaining
methods (Twig_LoaderInterface::isFresh,
Twig_ExistsLoaderInterface::exists) in
/mnt/c/wsl/server/opencart/system/library/template/Twig/Loader/Filesystem.php
on line 17
I have been working on a custom template and all was going fine until I changed something in the controller of the footer. Changing it back did not resolve the issue. I have also manually cleared the cache in the OC folder and the twig folder. I also did not have the cache setting set to off so I manually made this change in the db as I get the same error trying to get into the admin.
I am at a loss. I would love any help I could get.
Call Stack
{main}( )
start( )
require_once( '/mnt/c/wsl/server/opencart/system/framework.php' )
Router->dispatch( )
Router->execute( )
Action->execute( )
ControllerStartupRouter->index( )
Action->execute( )
ControllerCommonHome->index( )
Loader->controller( )
Action->execute( )
ControllerCommonColumnLeft->index( )
Loader->view( )
Template->render( )
Template\Twig->render( )
spl_autoload_call ( )
Twig_Autoloader::autoload( )
require( '/mnt/c/wsl/server/opencart/system/library/template/Twig/Loader/Filesystem.php'
)
Location
.../index.php:0
.../index.php:19
.../startup.php:104
.../framework.php:165
.../router.php:56
.../router.php:67
.../action.php:79
.../router.php:25
.../action.php:79
.../home.php:12
.../loader.php:48
.../action.php:79
.../column_left.php:72
.../loader.php:125
.../template.php:51
.../twig.php:20
.../twig.php:20
.../Autoloader.php:51
class Twig_Loader_Filesystem implements Twig_LoaderInterface, Twig_ExistsLoaderInterface
{
/** Identifier of the main namespace. */
const MAIN_NAMESPACE = '__main__';
protected $paths = array();
protected $cache = array();
protected $errorCache = array();
/**
* Constructor.
*
* #param string|array $paths A path or an array of paths where to look for templates
*/
public function __construct($paths = array())
{
if ($paths) {
$this->setPaths($paths);
}
}
/**
* Returns the paths to the templates.
*
* #param string $namespace A path namespace
*
* #return array The array of paths where to look for templates
*/
public function getPaths($namespace = self::MAIN_NAMESPACE)
{
return isset($this->paths[$namespace]) ? $this->paths[$namespace] : array();
}
/**
* Returns the path namespaces.
*
* The main namespace is always defined.
*
* #return array The array of defined namespaces
*/
public function getNamespaces()
{
return array_keys($this->paths);
}
/**
* Sets the paths where templates are stored.
*
* #param string|array $paths A path or an array of paths where to look for templates
* #param string $namespace A path namespace
*/
public function setPaths($paths, $namespace = self::MAIN_NAMESPACE)
{
if (!is_array($paths)) {
$paths = array($paths);
}
$this->paths[$namespace] = array();
foreach ($paths as $path) {
$this->addPath($path, $namespace);
}
}
/**
* Adds a path where templates are stored.
*
* #param string $path A path where to look for templates
* #param string $namespace A path name
*
* #throws Twig_Error_Loader
*/
public function addPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = array();
if (!is_dir($path)) {
throw new Twig_Error_Loader(sprintf('The "%s" directory does not exist.', $path));
}
$this->paths[$namespace][] = rtrim($path, '/\\');
}
/**
* Prepends a path where templates are stored.
*
* #param string $path A path where to look for templates
* #param string $namespace A path name
*
* #throws Twig_Error_Loader
*/
public function prependPath($path, $namespace = self::MAIN_NAMESPACE)
{
// invalidate the cache
$this->cache = $this->errorCache = array();
if (!is_dir($path)) {
throw new Twig_Error_Loader(sprintf('The "%s" directory does not exist.', $path));
}
$path = rtrim($path, '/\\');
if (!isset($this->paths[$namespace])) {
$this->paths[$namespace][] = $path;
} else {
array_unshift($this->paths[$namespace], $path);
}
}
/**
* {#inheritdoc}
*/
public function getSource($name)
{
return file_get_contents($this->findTemplate($name));
}
/**
* {#inheritdoc}
*/
public function getCacheKey($name)
{
return $this->findTemplate($name);
}
/**
* {#inheritdoc}
*/
public function exists($name)
{
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return true;
}
try {
return false !== $this->findTemplate($name, false);
} catch (Twig_Error_Loader $exception) {
return false;
}
}
/**
* {#inheritdoc}
*/
public function isFresh($name, $time)
{
return filemtime($this->findTemplate($name)) <= $time;
}
protected function findTemplate($name)
{
$throw = func_num_args() > 1 ? func_get_arg(1) : true;
$name = $this->normalizeName($name);
if (isset($this->cache[$name])) {
return $this->cache[$name];
}
if (isset($this->errorCache[$name])) {
if (!$throw) {
return false;
}
throw new Twig_Error_Loader($this->errorCache[$name]);
}
$this->validateName($name);
list($namespace, $shortname) = $this->parseName($name);
if (!isset($this->paths[$namespace])) {
$this->errorCache[$name] = sprintf('There are no registered paths for namespace "%s".', $namespace);
if (!$throw) {
return false;
}
throw new Twig_Error_Loader($this->errorCache[$name]);
}
foreach ($this->paths[$namespace] as $path) {
if (is_file($path.'/'.$shortname)) {
if (false !== $realpath = realpath($path.'/'.$shortname)) {
return $this->cache[$name] = $realpath;
}
return $this->cache[$name] = $path.'/'.$shortname;
}
}
$this->errorCache[$name] = sprintf('Unable to find template "%s" (looked into: %s).', $name, implode(', ', $this->paths[$namespace]));
if (!$throw) {
return false;
}
throw new Twig_Error_Loader($this->errorCache[$name]);
}
protected function parseName($name, $default = self::MAIN_NAMESPACE)
{
if (isset($name[0]) && '#' == $name[0]) {
if (false === $pos = strpos($name, '/')) {
throw new Twig_Error_Loader(sprintf('Malformed namespaced template name "%s" (expecting "#namespace/template_name").', $name));
}
$namespace = substr($name, 1, $pos - 1);
$shortname = substr($name, $pos + 1);
return array($namespace, $shortname);
}
return array($default, $name);
}
protected function normalizeName($name)
{
return preg_replace('#/{2,}#', '/', str_replace('\\', '/', (string) $name));
}
protected function validateName($name)
{
if (false !== strpos($name, "\0")) {
throw new Twig_Error_Loader('A template name cannot contain NUL bytes.');
}
$name = ltrim($name, '/');
$parts = explode('/', $name);
$level = 0;
foreach ($parts as $part) {
if ('..' === $part) {
--$level;
} elseif ('.' !== $part) {
++$level;
}
if ($level < 0) {
throw new Twig_Error_Loader(sprintf('Looks like you try to load a template outside configured directories (%s).', $name));
}
}
}
}

Related

How to add auto complete to classes instantiated with custom function?

I instantiate my classes through custom functions.
The classes are in app/code/core/ e.g.
app/code/core/Property/Helper/Property.php
require_once("Core/Helper.php");
class Property_Helper_Property extends Core\Helper
{
public function __construct($con)
{
parent::__construct($con);
}
public function test()
{
return "hello";
}
}
app/code/core/Core/Helper.php
<?php
namespace Core;
abstract class Helper
{
protected $con;
public function __construct($con)
{
$this->con = $con;
}
}
I can call the method test() of the class Property_Helper_Property from any file like this:
require_once 'app/Main.php'; // always needed
Main::getHelper("Property/Property")->test();
app/Main.php
This file contains the final class "Main" which has the static method getHelper
if (!defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if (!defined('PS')) define('PS', PATH_SEPARATOR);
if (!defined('BP')) define('BP', dirname(dirname(__FILE__)));
/**
* Set include path
*/
Main::register('original_include_path', get_include_path());
$paths = array();
$paths[] = Main::CORE_PATH;
$paths[] = Main::LOCAL_PATH;
$paths[] = BP . DS . 'lib';
$paths[] = BP . DS . 'inc';
$appPath = implode(PS, $paths);
set_include_path($appPath . PS . Main::registry('original_include_path'));
final class Main
{
const CORE_PATH = BP . DS . 'app' . DS . 'code' . DS . 'core';
const LOCAL_PATH = BP . DS . 'app' . DS . 'code' . DS . 'local';
/**
* Registry collection
*
* #var array
*/
static private $_registry = array();
public static function getDbConnection()
{
return self::registry("db_connection");
}
/**
* Register a new variable
*
* #param string $key
* #param mixed $value
* #param bool $graceful
*/
public static function register($key, $value, $graceful = false)
{
if (isset(self::$_registry[$key])) {
if ($graceful) {
return;
}
self::throwException('Main registry key "'.$key.'" already exists');
}
self::$_registry[$key] = $value;
}
/**
* Unregister a variable from register by key
*
* #param string $key
*/
public static function unregister($key)
{
if (isset(self::$_registry[$key])) {
if (is_object(self::$_registry[$key]) && (method_exists(self::$_registry[$key], '__destruct'))) {
self::$_registry[$key]->__destruct();
}
unset(self::$_registry[$key]);
}
}
/**
* Retrieve a value from registry by a key
*
* #param string $key
* #return mixed
*/
public static function registry($key)
{
if (isset(self::$_registry[$key])) {
return self::$_registry[$key];
}
return null;
}
public static function getHelper($name)
{
$classPath = self::getClassPath($name, "Helper");
if (!$classPath) { return false; }
$fullClassPath = self::getFullClassPath($classPath);
if (!$fullClassPath) { return false; }
$obj = self::getClassInstance($fullClassPath, $classPath);
if (!$obj) { return false; }
return $obj;
}
public static function getModel($name)
{
$classPath = self::getClassPath($name, "Model");
if (!$classPath) { return false; }
$fullClassPath = self::getFullClassPath($classPath);
if (!$fullClassPath) { return false; }
$obj = self::getClassInstance($fullClassPath, $classPath);
if (!$obj) { return false; }
return $obj;
}
private function getClassInstance($fullClassPath, $classPath)
{
if (!$classPath) { return false; }
require_once($fullClassPath);
$className = str_replace("/", "_", $classPath);
if (class_exists($className)) {
return new $className(self::getDbConnection());
} else {
return false;
}
}
private function getFullClassPath($classPath)
{
$modulPaths = [self::CORE_PATH, self::LOCAL_PATH];
return self::checkIfFileExistInModule($modulPaths, $classPath);
}
private function getClassPath($modelName, $identifier="Model")
{
if (strpos($modelName, '/') === false) { return false; }
if (substr_count($modelName, "/") == 1) {
$exp = explode("/", $modelName);
return $exp[0] . "/$identifier/" . $exp[1];
} else {
return false;
}
}
private function checkIfFileExistInModule($modulPaths, $modelname)
{
foreach($modulPaths as $path) {
$path = $path . DS . $modelname . ".php";
if (file_exists($path)) {
return $path;
}
}
return "0";
}
}
This works just fine... now the actual question.
If I am writing...
$obj = Main::getHelper("Property/Property");
$obj->
...then my IDE (NetBeans) does not auto suggest the public methods/properties which I can use.
Is there a way to "teach" my logic to add auto suggestion / auto completion so that it automatically shows all public methods/properties available in the object?
You need to use phpdoc blocks. Pretty sure they are supported by NetBeans:
/** #var Property_Helper_Property $obj */
$obj = Main::getHelper("Property/Property");
From that point forward auto-completion and static analysis will work, since it will be understood that $obj will be an instance of Property_Helper_Property.

Call to a member function publish()

i have created a joomla component and when i click on publish and unpublish button in admin then i am getting such error.
Fatal error: Call to a member function publish() on boolean in ...\libraries\legacy\controller\admin.php on line 209
Please help
UPDATE
my View.html.php
require_once JPATH_COMPONENT . '/helpers/lab.php';
class labViewStructurelist extends JViewLegacy
{
protected $structurelist;
protected $pagination;
public $filterForm;
public $activeFilters;public $state;
public function display($tpl = null)
{
$this->structurelist = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
//print_r($this->pagination->pagesTotal);die();
$this->filterForm = $this->get('FilterForm');
$this->activeFilters = $this->get('ActiveFilters');
$this->addToolBar();
$this->sidebar = JHtmlSidebar::render();
if (count($errors = $this->get('Errors')))
{
JError::raiseError(500, implode('<br />', $errors));
return false;
}
return parent::display($tpl);
}
protected function addToolBar() {
JToolBarHelper::title( JText::_('COM_LAB_LAB_DDDD'), 'generic.png' );
JToolBarHelper::publish('Structurelist.publish');
JToolBarHelper::unpublish('Structurelist.unpublish');
JToolBarHelper::deleteList('', 'patients.delete', 'JTOOLBAR_DELETE');
JToolBarHelper::preferences('com_lab');
}
}
Controller/stricturelist.php
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
// import Joomla controller library
jimport('joomla.application.component.controlleradmin');
class LabControllerStructurelist extends JControllerAdmin
{
public function getModel($name='Structurelist',$prefix='ssModel',$config=array('ignore_request'=>true))
{
$model=parent::getModel($name,$prefix,$config);
return $model;
}
}
models\structurelist.php
defined('_JEXEC') or die;
jimport('joomla.application.component.modellist');
JFormHelper::loadFieldClass('list');
class LabModelStructurelist extends JModelList{
public function __construct($config = array())
{
if (empty($config['filter_fields']))
{
$config['filter_fields'] = array(
'id', 'a.id',
'fullname', 'a.fullname',
);
$assoc = JLanguageAssociations::isEnabled();
if ($assoc)
{
$config['filter_fields'][] = 'association';
}
}
parent::__construct($config);
}
public function getListQuery()
{
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('*');
$query->from('#__ss_structure_tmp');
$search = $this->getState('filter.search');
$limit = $this->getState('filter.limit');
if (!empty($search)) {
$query->where('fullname LIKE "%' . $search .'%" ' );
}
if (!empty($limit)) {
$query->setLimit($limit);
}
return $query;
}
protected function populateState($ordering = 'a.fullname', $direction = 'asc')
{
$app = JFactory::getApplication();
if ($layout = $app->input->get('layout'))
{
$this->context .= '.' . $layout;
}
$search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');
$this->setState('filter.search', $search);
parent::populateState();
}
}
You need to provide the model to your controller using the getModel() method. Look in the articles controller of the com_content for example.
You need to add a table file with the publish function within:
defined('_JEXEC') or die;
use Joomla\Utilities\ArrayHelper;
class labTableStructurelist extends JTable
{
/**
* Constructor
*
* #param JDatabase &$db A database connector object
*/
public function __construct(&$db)
{
parent::__construct('#__ss_structure_tmp', 'id', $db);
}
/**
* Overloaded bind function to pre-process the params.
*
* #param array $array Named array
* #param mixed $ignore Optional array or list of parameters to ignore
*
* #return null|string null is operation was satisfactory, otherwise returns an error
*
* #see JTable:bind
* #since 1.5
*/
public function bind($array, $ignore = '')
{
$input = JFactory::getApplication()->input;
$task = $input->getString('task', '');
if (($task == 'save' || $task == 'apply') && (!JFactory::getUser()->authorise('core.edit.state', 'com_lab.structurelist.'.$array['id']) && $array['state'] == 1))
{
$array['state'] = 0;
}
if ($array['id'] == 0)
{
$array['created_by'] = JFactory::getUser()->id;
}
if (isset($array['params']) && is_array($array['params']))
{
$registry = new JRegistry;
$registry->loadArray($array['params']);
$array['params'] = (string) $registry;
}
if (isset($array['metadata']) && is_array($array['metadata']))
{
$registry = new JRegistry;
$registry->loadArray($array['metadata']);
$array['metadata'] = (string) $registry;
}
if (!JFactory::getUser()->authorise('core.admin', 'com_lab.structurelist.' . $array['id']))
{
$actions = JAccess::getActionsFromFile(
JPATH_ADMINISTRATOR . '/components/com_lab/access.xml',
"/access/section[#name='user']/"
);
$default_actions = JAccess::getAssetRules('com_lab.structurelist.' . $array['id'])->getData();
$array_jaccess = array();
foreach ($actions as $action)
{
$array_jaccess[$action->name] = $default_actions[$action->name];
}
$array['rules'] = $this->JAccessRulestoArray($array_jaccess);
}
// Bind the rules for ACL where supported.
if (isset($array['rules']) && is_array($array['rules']))
{
$this->setRules($array['rules']);
}
return parent::bind($array, $ignore);
}
/**
* This function convert an array of JAccessRule objects into an rules array.
*
* #param array $jaccessrules An array of JAccessRule objects.
*
* #return array
*/
private function JAccessRulestoArray($jaccessrules)
{
$rules = array();
foreach ($jaccessrules as $action => $jaccess)
{
$actions = array();
foreach ($jaccess->getData() as $group => $allow)
{
$actions[$group] = ((bool) $allow);
}
$rules[$action] = $actions;
}
return $rules;
}
/**
* Overloaded check function
*
* #return bool
*/
public function check()
{
// If there is an ordering column and this is a new row then get the next ordering value
if (property_exists($this, 'ordering') && $this->id == 0)
{
$this->ordering = self::getNextOrder();
}
return parent::check();
}
/**
* Method to set the publishing state for a row or list of rows in the database
* table. The method respects checked out rows by other users and will attempt
* to checkin rows that it can after adjustments are made.
*
* #param mixed $pks An optional array of primary key values to update. If not
* set the instance property value is used.
* #param integer $state The publishing state. eg. [0 = unpublished, 1 = published]
* #param integer $userId The user id of the user performing the operation.
*
* #return boolean True on success.
*
* #since 1.0.4
*
* #throws Exception
*/
public function publish($pks = null, $state = 1, $userId = 0)
{
// Initialise variables.
$k = $this->_tbl_key;
// Sanitize input.
ArrayHelper::toInteger($pks);
$userId = (int) $userId;
$state = (int) $state;
// If there are no primary keys set check to see if the instance key is set.
if (empty($pks))
{
if ($this->$k)
{
$pks = array($this->$k);
}
// Nothing to set publishing state on, return false.
else
{
throw new Exception(500, JText::_('JLIB_DATABASE_ERROR_NO_ROWS_SELECTED'));
}
}
// Build the WHERE clause for the primary keys.
$where = $k . '=' . implode(' OR ' . $k . '=', $pks);
// Determine if there is checkin support for the table.
if (!property_exists($this, 'checked_out') || !property_exists($this, 'checked_out_time'))
{
$checkin = '';
}
else
{
$checkin = ' AND (checked_out = 0 OR checked_out = ' . (int) $userId . ')';
}
// Update the publishing state for rows with the given primary keys.
$this->_db->setQuery(
'UPDATE `' . $this->_tbl . '`' .
' SET `state` = ' . (int) $state .
' WHERE (' . $where . ')' .
$checkin
);
$this->_db->execute();
// If checkin is supported and all rows were adjusted, check them in.
if ($checkin && (count($pks) == $this->_db->getAffectedRows()))
{
// Checkin each row.
foreach ($pks as $pk)
{
$this->checkin($pk);
}
}
// If the JTable instance value is in the list of primary keys that were set, set the instance.
if (in_array($this->$k, $pks))
{
$this->state = $state;
}
return true;
}
/**
* Define a namespaced asset name for inclusion in the #__assets table
*
* #return string The asset name
*
* #see JTable::_getAssetName
*/
protected function _getAssetName()
{
$k = $this->_tbl_key;
return 'com_lab.structurelist.' . (int) $this->$k;
}
/**
* Returns the parent asset's id. If you have a tree structure, retrieve the parent's id using the external key field
*
* #param JTable $table Table name
* #param integer $id Id
*
* #see JTable::_getAssetParentId
*
* #return mixed The id on success, false on failure.
*/
protected function _getAssetParentId(JTable $table = null, $id = null)
{
// We will retrieve the parent-asset from the Asset-table
$assetParent = JTable::getInstance('Asset');
// Default: if no asset-parent can be found we take the global asset
$assetParentId = $assetParent->getRootId();
// The item has the component as asset-parent
$assetParent->loadByName('com_lab');
// Return the found asset-parent-id
if ($assetParent->id)
{
$assetParentId = $assetParent->id;
}
return $assetParentId;
}
/**
* Delete a record by id
*
* #param mixed $pk Primary key value to delete. Optional
*
* #return bool
*/
public function delete($pk = null)
{
$this->load($pk);
$result = parent::delete($pk);
return $result;
}
}
Please note, that this is just an example of a table file, I can't guarantee that this would work just by copy&paste. Please check com_content/table for another example.
Also add a getTable() to your List single item model:
public function getTable($type = 'view_name', $prefix = 'labTable', $config = array())
{
return JTable::getInstance($type, $prefix, $config);
}
Please check if file structure is correct:
List View
structurelist**s** -> list view with multiple items
|-> controller/structurelists.php
|-> models/structurelists.php
|-> view/structurelists/
Single View / List View (publish() for example)
structurelist -> single item view (edit view)
|-> models/structurelist.php (this is important for the publish() in the list view)
|-> models/forms/structurelist.xml
|-> tables/structurelist.php (this is important for the publish() in the list view)
|-> view/structurelist/
Feel free to comment if you need more help.

Failed to load function

i tried to generate URL with load another class
the error messages is :
Notice: Undefined variable: user in
/var/www/html/lab/system/core/Router.php on line 260
Warning: call_user_func_array() expects parameter 1 to be a valid
callback, first array member is not a valid class name or object in
/var/www/html/lab/system/core/Router.php on line 260
Router.php :
<?php
require_once 'class.php';
class AltoRouter {
/**
* #var array Array of all routes (incl. named routes).
*/
protected $routes = array();
/**
* #var array Array of all named routes.
*/
protected $namedRoutes = array();
/**
* #var string Can be used to ignore leading part of the Request URL (if main file lives in subdirectory of host)
*/
protected $basePath = '';
/**
* #var array Array of default match types (regex helpers)
*/
protected $matchTypes = array(
'i' => '[0-9]++',
'a' => '[0-9A-Za-z]++',
'h' => '[0-9A-Fa-f]++',
'*' => '.+?',
'**' => '.++',
'' => '[^/\.]++'
);
/**
* Create router in one call from config.
*
* #param array $routes
* #param string $basePath
* #param array $matchTypes
*/
public function __construct( $routes = array(), $basePath = '', $matchTypes = array() ) {
$this->addRoutes($routes);
$this->setBasePath($basePath);
$this->addMatchTypes($matchTypes);
}
/**
* Retrieves all routes.
* Useful if you want to process or display routes.
* #return array All routes.
*/
public function getRoutes() {
return $this->routes;
}
/**
* Add multiple routes at once from array in the following format:
*
* $routes = array(
* array($method, $route, $target, $name)
* );
*
* #param array $routes
* #return void
* #author Koen Punt
* #throws Exception
*/
public function addRoutes($routes){
if(!is_array($routes) && !$routes instanceof Traversable) {
throw new \Exception('Routes should be an array or an instance of Traversable');
}
foreach($routes as $route) {
call_user_func_array(array($this, 'map'), $route);
}
}
/**
* Set the base path.
* Useful if you are running your application from a subdirectory.
*/
public function setBasePath($basePath) {
$this->basePath = $basePath;
}
/**
* Add named match types. It uses array_merge so keys can be overwritten.
*
* #param array $matchTypes The key is the name and the value is the regex.
*/
public function addMatchTypes($matchTypes) {
$this->matchTypes = array_merge($this->matchTypes, $matchTypes);
}
/**
* Map a route to a target
*
* #param string $method One of 5 HTTP Methods, or a pipe-separated list of multiple HTTP Methods (GET|POST|PATCH|PUT|DELETE)
* #param string $route The route regex, custom regex must start with an #. You can use multiple pre-set regex filters, like [i:id]
* #param mixed $target The target where this route should point to. Can be anything.
* #param string $name Optional name of this route. Supply if you want to reverse route this url in your application.
* #throws Exception
*/
public function map($method, $route, $target, $name = null) {
$this->routes[] = array($method, $route, $target, $name);
if($name) {
if(isset($this->namedRoutes[$name])) {
throw new \Exception("Can not redeclare route '{$name}'");
} else {
$this->namedRoutes[$name] = $route;
}
}
return;
}
/**
* Reversed routing
*
* Generate the URL for a named route. Replace regexes with supplied parameters
*
* #param string $routeName The name of the route.
* #param array #params Associative array of parameters to replace placeholders with.
* #return string The URL of the route with named parameters in place.
* #throws Exception
*/
public function generate($routeName, array $params = array()) {
// Check if named route exists
if(!isset($this->namedRoutes[$routeName])) {
throw new \Exception("Route '{$routeName}' does not exist.");
}
// Replace named parameters
$route = $this->namedRoutes[$routeName];
// prepend base path to route url again
$url = $this->basePath . $route;
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if ($pre) {
$block = substr($block, 1);
}
if(isset($params[$param])) {
$url = str_replace($block, $params[$param], $url);
} elseif ($optional) {
$url = str_replace($pre . $block, '', $url);
}
}
}
return $url;
}
/**
* Match a given Request Url against stored routes
* #param string $requestUrl
* #param string $requestMethod
* #return array|boolean Array with route information on success, false on failure (no match).
*/
public function match($requestUrl = null, $requestMethod = null) {
$params = array();
$match = false;
// set Request Url if it isn't passed as parameter
if($requestUrl === null) {
$requestUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
}
// strip base path from request url
$requestUrl = substr($requestUrl, strlen($this->basePath));
// Strip query string (?a=b) from Request Url
if (($strpos = strpos($requestUrl, '?')) !== false) {
$requestUrl = substr($requestUrl, 0, $strpos);
}
// set Request Method if it isn't passed as a parameter
if($requestMethod === null) {
$requestMethod = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET';
}
foreach($this->routes as $handler) {
list($method, $_route, $target, $name) = $handler;
$methods = explode('|', $method);
$method_match = false;
// Check if request method matches. If not, abandon early. (CHEAP)
foreach($methods as $method) {
if (strcasecmp($requestMethod, $method) === 0) {
$method_match = true;
break;
}
}
// Method did not match, continue to next route.
if(!$method_match) continue;
// Check for a wildcard (matches all)
if ($_route === '*') {
$match = true;
} elseif (isset($_route[0]) && $_route[0] === '#') {
$pattern = '`' . substr($_route, 1) . '`u';
$match = preg_match($pattern, $requestUrl, $params);
} else {
$route = null;
$regex = false;
$j = 0;
$n = isset($_route[0]) ? $_route[0] : null;
$i = 0;
// Find the longest non-regex substring and match it against the URI
while (true) {
if (!isset($_route[$i])) {
break;
} elseif (false === $regex) {
$c = $n;
$regex = $c === '[' || $c === '(' || $c === '.';
if (false === $regex && false !== isset($_route[$i+1])) {
$n = $_route[$i + 1];
$regex = $n === '?' || $n === '+' || $n === '*' || $n === '{';
}
if (false === $regex && $c !== '/' && (!isset($requestUrl[$j]) || $c !== $requestUrl[$j])) {
continue 2;
}
$j++;
}
$route .= $_route[$i++];
}
$regex = $this->compileRoute($route);
$match = preg_match($regex, $requestUrl, $params);
}
if(($match == true || $match > 0)) {
if($params) {
foreach($params as $key => $value) {
if(is_numeric($key)) unset($params[$key]);
}
}
return array(
'target' => $target,
'params' => $params,
'name' => $name
);
}
}
return false;
}
/**
* Compile the regex for a given route (EXPENSIVE)
*/
private function compileRoute($route) {
if (preg_match_all('`(/|\.|)\[([^:\]]*+)(?::([^:\]]*+))?\](\?|)`', $route, $matches, PREG_SET_ORDER)) {
$matchTypes = $this->matchTypes;
foreach($matches as $match) {
list($block, $pre, $type, $param, $optional) = $match;
if (isset($matchTypes[$type])) {
$type = $matchTypes[$type];
}
if ($pre === '.') {
$pre = '\.';
}
//Older versions of PCRE require the 'P' in (?P<named>)
$pattern = '(?:'
. ($pre !== '' ? $pre : null)
. '('
. ($param !== '' ? "?P<$param>" : null)
. $type
. '))'
. ($optional !== '' ? '?' : null);
$route = str_replace($block, $pattern, $route);
}
}
return "`^$route$`u";
}
}
$router = new AltoRouter();
$user = new Users();
$router->setBasePath('/lab/system/core/Router.php');
############################################################
$router->map('GET', '/home', function()
{
echo 'Home page';
}, 'home');
$router->map('GET', '/user', function()
{
call_user_func_array(array($user, 'user'), array());
}, 'user');
############################################################
$match = $router->match();
if($match && is_callable($match['target']))
{
call_user_func_array($match['target'], $match['params']);
}
else
{
echo "404 Not Found";
}
?>
class.php
<?php
class Users
{
function user()
{
echo "User page";
}
}
?>
anyone can explain it? thanks
did you try this ?
$router->map('GET', '/user', function($user)
{
call_user_func_array(array($user, 'user'), array());
}, 'user');

PHP - Linking to html files is wrong in Pdf-to-html

I have installed Poppler Utils for windows in addition to https://github.com/mgufrone/pdf-to-html
It works perfectly and it converts PDF files to HTML, by making a single HTML file contains 2 iframes, one for pages navigation and the other for the actual text.
The problem is when the HTML files are generated, the linking for iframe src gives a false linking.
For Example:
Test.html
Pages.html
Page_1.html
All these files exist in the same folder named "Output".
Test.html contains 2 iframes linking to Pages.html and Page_1.html
Here's the problem in Test.html:
<frameset cols="100,*">
<frame name="links" src="output/Pages.html"/>
<frame name="contents" src="output/Pages_1.html"/>
</frameset>
Should be:
<frameset cols="100,*">
<frame name="links" src="Pages.html"/>
<frame name="contents" src="Pages_1.html"/>
</frameset>
PDF.php
<?php namespace Gufy\PdfToHtml;
class Pdf
{
protected $file, $info;
// protected $info_bin = '/usr/bin/pdfinfo';
public function __construct($file, $options=array())
{
$this->file = $file;
$class = $this;
array_walk($options, function($item, $key) use($class){
$class->$key = $item;
});
return $this;
}
public function getInfo()
{
if($this->info == null)
$this->info($this->file);
return $this->info;
}
protected function info()
{
$content = shell_exec($this->bin().' '.$this->file);
// print_r($info);
$options = explode("\n", $content);
$info = array();
foreach($options as &$item)
{
if(!empty($item))
{
list($key, $value) = explode(":", $item);
$info[str_replace(array(" "),array("_"),strtolower($key))] = trim($value);
}
}
// print_r($info);
$this->info = $info;
return $this;
// return $content;
}
public function html()
{
if($this->info == null)
$this->info($this->file);
return new Html($this->file);
}
public function getPages()
{
if($this->info == null)
$this->info($this->file);
return $this->info['pages'];
}
public function bin()
{
return Config::get('pdfinfo.bin', '/usr/bin/pdfinfo');
}
}
Base.php
<?php
namespace Gufy\PdfToHtml;
class Base
{
private $options=array(
'singlePage'=>false,
'imageJpeg'=>false,
'ignoreImages'=>false,
'zoom'=>1.5,
'noFrames'=>true,
);
public $outputDir;
private $bin="/usr/bin/pdftohtml";
private $file;
public function __construct($pdfFile='', $options=array())
{
if(empty($pdfFile))
return $this;
$pdf = $this;
if(!empty($options))
array_walk($options, function($value, $key) use($pdf){
$pdf->setOptions($key, $value);
});
return $this->open($pdfFile);
}
public function open($pdfFile)
{
$this->file = $pdfFile;
$this->setOutputDirectory(dirname($pdfFile));
return $this;
}
public function html()
{
$this->generate();
$file_output = $this->outputDir."/".preg_replace("/\.pdf$/","",basename($this->file)).".html";
$content = file_get_contents($file_output);
unlink($file_output);
return $content;
}
/**
* generating html files using pdftohtml software.
* #return $this current object
*/
public function generate(){
$output = $this->outputDir."/".preg_replace("/\.pdf$/","",basename($this->file)).".html";
$options = $this->generateOptions();
$command = $this->bin()." ".$options." ".$this->file." ".$output;
$result = exec($command);
return $this;
}
/**
* generate options based on the preserved options
* #return string options that will be passed on running the command
*/
public function generateOptions()
{
$generated = array();
array_walk($this->options, function($value, $key) use(&$generated){
$result = "";
switch($key)
{
case "singlePage":
$result = $value?"-c":"-s";
break;
case "imageJpeg":
$result = "-fmt ".($value?"jpg":"png");
break;
case "zoom":
$result = "-zoom ".$value;
break;
case "ignoreImages":
$result = $value?"-i":"";
break;
case 'noFrames':
$result = $value?'-noframes':'';
break;
}
$generated[] = $result;
});
return implode(" ", $generated);
}
/**
* change value of preserved configuration
* #param string $key key of option you want to change
* #param mixed $value value of option you want to change
* #return $this current object
*/
public function setOptions($key, $value)
{
if(isset($this->options[$key]))
$this->options[$key] = $value;
return $this;
}
/**
* open pdf file that will be converted. make sure it is exists
* #param string $pdfFile path to pdf file
* #return $this current object
*/
public function setOutputDirectory($dir)
{
$this->outputDir=$dir;
return $this;
}
/**
* clear the whole files that has been generated by pdftohtml. Make sure directory ONLY contain generated files from pdftohtml
* because it remove the whole contents under preserved output directory
* #return $this current object
*/
public function clearOutputDirectory()
{
$files = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->outputDir, \FilesystemIterator::SKIP_DOTS));
foreach($files as $file)
{
$path = (string)$file;
$basename = basename($path);
if($basename != '..')
{
if(is_file($path) && file_exists($path))
unlink($path);
elseif(is_dir($path) && file_exists($path))
rmdir($path);
}
}
return $this;
}
public function bin()
{
return Config::get('pdftohtml.bin', '/usr/bin/pdftohtml');
}
}

PHP: Warning: array_map(): Argument #2 should be an array

I have a script that works perfect in ubuntu, recently I copied the exact same script to centos6 server
and I'm getting the following error:
PHP Warning: array_map(): Argument #2 should be an array in /copy_scripts/classes/Vserver.class.php on line 245
the code
/**
* Get an array of open files
* #param array $aExt
* #return array of arrays ['views','size','path']
*/
public function getOpenFiles($aExt=array()) {
$aOpenFiles = self::GetList(self::$sLogOpenFiles);
$aOpenFiles = array_map( create_function('$v', '
$v = trim($v);
$aFile = preg_split("#[\t\s]+#",$v);
$oFile = new VserverFile($aFile[2]);
$oFile->setViews($aFile[0]);
return $oFile;'),
$aOpenFiles
);
//echo "<pre>";
//print_r($aOpenFiles);
return $aOpenFiles;
}
Can it be the difference between php versions?
centos:
PHP 5.3.3 (cli) (built: Jul 3 2012 16:53:21)
ubuntu
PHP 5.3.10-2 (cli) (built: Feb 20 2012 19:39:00)
Copyright (c) 1997-2012 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2012 Zend Technologies
what I've tried so far:
changing setting in php.ini a restarting php.
the complete code:
<?php
/**
*
* Global Video Server class
* Singleton class
* Has methods to manipulate files
* #author kpoxas
*
*/
class Vserver {
static protected $oInstance=null;
static protected $iTimeStart, $iTimeEnd;
const FILE_NOEXIST = -2;
const FILE_ZEROSIZE = -4;
const FILE_DIFF = -8;
/*
* Path /var/www/HDD_PATH/
*/
static public $sHDDPath = null;
/*
* Path /var/www/SSD_PATH/
*/
static public $sSSDPath = null;
/*
* Folder same on every RAID.../FOLDER/...
*/
static public $sHTTPFolder = null;
/*
* Open Files Log
*/
static public $sLogOpenFiles = null;
/*
* Limit of Free space on SSD in percents
*/
static public $iSSDUsage = 90;
/*
* Limit of Free space on SSD in percents (not delete below)
*/
static public $iSSDDeleteUsage = 80;
/*
* Limit of Free space on SSD in bytes (not delete below)
*/
static public $iSSDDeleteUsageAbsolute = 5368709120;
/*
* Min views count of file to copy
*/
static public $iMinViews = 2;
/*
* Search within files older than $iDaysToDelete days
*/
static public $iDaysToDelete = 1;
/*
* Test Mode
* File manipulations aren't executed
* Only log mode
*/
static public $bTest = false;
/*
* Store openfiles.txt log
*/
static protected $sOpenFiles = null;
/**
* Äåñêðèïòîð áëîêèðóþùåãî ôàéëà
*
* #var string
*/
protected $oLockFile=null;
/**
* Singleton Object implementation
*
* #return VSERVER
*/
static public function getInstance() {
if (isset(self::$oInstance) and (self::$oInstance instanceof self)) {
return self::$oInstance;
} else {
self::$oInstance= new self();
return self::$oInstance;
}
}
/**
* Get Log content
* #param string $sLogPath
* #return string
*/
static public function GetLog($sLogPath) {
if ($s = #file_get_contents($sLogPath)) {
$s = trim($s);
if (!empty($s)) {
return $s;
}
}
return false;
}
/**
* Get Log content in list mode divided by EOL
* #param string $sLogPath
* #return array
*/
static public function GetList($sLogPath) {
if ($sList = self::GetLog($sLogPath)) {
return explode(PHP_EOL,trim($sList));
}
}
/**
* Check if directory exists and chmod 775
* #param $directory
*/
static public function CheckDirectory($directory) {
$directory = rtrim($directory, '/\\');
if (is_dir($directory)) #chmod($directory, 0775);
else {
if (!mkdir($directory, 0755, true)) {
//self::AddError ('Directory does not exist', $directory);
return false;
}
}
}
/**
* Check if file exist
* Check if file has zero size
* #param string $filename
*/
static public function CheckFile($filename) {
if (file_exists($filename) && !is_file($filename)) {
self::log("NO VALID FILEPATH: {$filename}");
return false;
} else if(!file_exists($filename)) {
self::log("FILE DOESN'T EXIST: {$filename}");
return self::FILE_NOEXIST;
} else if(!filesize($filename)) {
self::log("FILE ZEROSIZE: {$filename}");
return self::FILE_ZEROSIZE;
}
else return true;
}
/**
* Check if file1 is identical to file2
* #param string $filename1
* #param string $filename2
*/
static public function CheckIdentity($filename1, $filename2) {
if (self::CheckFile($filename1)>0 && self::CheckFile($filename2)>0) {
if (filesize($filename1)===filesize($filename2)) {
self::log("FILES: {$filename1} AND {$filename2} ARE IDENTICAL");
return true;
}
self::log("FILES: {$filename1} AND {$filename2} ARE DIFFERENT");
return false;
}
}
/**
* Copy file from $source to $dest
* Make www-data owner
* Make perms 755
*/
static public function Copy($source, $dest = null) {
self::log("COPY {$source} TO {$dest}");
if (self::$bTest) return true;
self::CheckDirectory(dirname($dest));
// copy
$sCmd = "cp -f '{$source}' '{$dest}'";
self::exec($sCmd);
// chown
$sCmdChown = "chown www-data:www-data '{$dest}'";
self::exec($sCmdChown);
// chmod
$sCmdChmod = "chmod 775 '{$dest}'";
self::exec($sCmdChmod);
return true;
}
/**
* Delete file
*/
static public function Delete($source) {
self::log("DELETE {$source}");
if (self::$bTest) return true;
// chmod
$sCmdChmod = "rm '{$source}'";
self::exec($sCmdChmod);
}
/**
* Get free space of catalog or storage in bytes
* #param string $sDir
*/
static public function GetFreeSpace($sDir = '') {
return disk_free_space($sDir);
}
/**
* Get total space of catalog or storage in bytes
* #param string $sDir
*/
static public function GetTotalSpace($sDir = '') {
return disk_total_space($sDir);
}
/**
* Get used space of catalog or storage in percents
* #param string $sDir
*/
static public function GetUsage($sDir = '') {
//$sCmd = "df -k {$sDir} | grep -Eo '[0-9]+%'";
//return intval(self::exec($sCmd));
return round(1-self::GetFreeSpace($sDir)/self::GetTotalSpace($sDir),4)*100;
}
/**
* Exec command wrapper
*/
static public function exec($sCmd = null, &$aVar=null) {
if (empty($sCmd)) {
return;
}
self::log($sCmd);
return exec($sCmd, $aVar);
}
static public function log($sStr) {
echo "{$sStr}<br>\n";
}
/**
* Get open files log
* #return string
*/
static public function getOpenFilesContent() {
if (self::$sOpenFiles === null) {
self::$sOpenFiles = self::GetLog(self::$sLogOpenFiles);
}
return self::$sOpenFiles;
}
/**
* Get an array of open files
* #param array $aExt
* #return array of arrays ['views','size','path']
*/
public function getOpenFiles($aExt=array()) {
$aOpenFiles = self::GetList(self::$sLogOpenFiles);
$aOpenFiles = array_map( create_function('$v', '
$v = trim($v);
$aFile = preg_split("#[\t\s]+#",$v);
$oFile = new VserverFile($aFile[2]);
$oFile->setViews($aFile[0]);
return $oFile;'),
$aOpenFiles
);
//echo "<pre>";
//print_r($aOpenFiles);
return $aOpenFiles;
}
public function getFileList($sDir=null, $aExt=array('flv','mp4'), $sGrep='') {
if (!$sDir || empty($aExt)) return;
$aCmdExt = "\( -name '*."
.implode("' -o -name '*.",$aExt)
."' \)";
$sCmd = "find {$sDir} {$aCmdExt} -mmin +".self::$iDaysToDelete."";
// sort by date
//$sCmd = "find {$sDir} {$aCmdExt} -printf '%T# %p\n'| sort -k 1n | cut -d' ' -f2-";
if (!empty($sGrep)) {
$sCmd.= " | {$sGrep}";
}
self::exec($sCmd,$aFiles);
return $aFiles;
}
/**
*
* Get list of storages
*/
public function getStorages() {
$sCmd = "df -k | grep -Eo 'storage[0-9]+$'";
self::exec($sCmd,$aStorages);
return $aStorages;
}
/**
*
* Get list of megastorages
*/
public function getMegaStorages() {
$sCmd = "df -k | sort -k5 -r | grep -Eo 'megastorage[0-9]+$'";
self::exec($sCmd,$aStorages);
return $aStorages;
}
/**
* Copy opened files to SSD
*/
public function copyToSSD() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$iCopied = 0;
$iIgnored = 0;
$aOpenedFiles = $this->GetOpenFiles();
foreach ($aOpenedFiles as $oFile) {
if (self::GetUsage(self::$sSSDPath) < self::$iSSDUsage) {
if ($oFile->getViews() >=self::$iMinViews && $oFile->synchronize()) $iCopied++;
else $iIgnored++;
} else {
break;
}
}
self::log("COPIED: {$iCopied}");
self::log("IGNORED: {$iIgnored}");
self::log("SSD USAGE: ".self::GetUsage(self::$sSSDPath)."%");
}
/**
* DELETE FROM SSD
*/
public function deleteFromSSD() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$iDeleted = 0;
$iIgnored = 0;
/*
* Get megastorages sorted by usage desc,
*/
$aMegaStorages = $this->getMegaStorages();
foreach ($aMegaStorages as &$sMegaStorage) {
/*
* Get files in current megastorage
*/
$aFileList = $this->getFileList('/'.$sMegaStorage);
if (empty($aFileList)) {
self::log("NO FILES FOUND in {$sMegaStorage}");
continue;
}
$aFileList = array_map(
create_function('$v', '
$oFile = new VserverFile(trim($v));
return $oFile;
'),
$aFileList
);
/*
* Delete files until appropriate usage
*/
$iFreeSpace = self::GetFreeSpace('/'.$sMegaStorage);
$iTotalSpace = self::GetTotalSpace('/'.$sMegaStorage);
foreach ($aFileList as &$oFile) {
$iUsageCurrent = round(1-$iFreeSpace/$iTotalSpace,4)*100;
self::Log($sMegaStorage." ".$iUsageCurrent."%");
if ($iUsageCurrent > self::$iSSDDeleteUsage) {
if (!$oFile->isOpened()) {
$iFreeSpace += $oFile->getSize();
$oFile->synchronize();
$oFile->deleteFromSSD();
$iDeleted++;
} else $iIgnored++;
} else {
break;
}
}
}
/*
$aFileList = $this->getFileList(self::$sSSDPath);
if (empty($aFileList)) {
self::log("NO FILES FOUND");
return;
}
$aFileList = array_map(
create_function('$v', '
$oFile = new VserverFile(trim($v));
return $oFile;
'),
$aFileList
);
foreach ($aFileList as $oFile) {
if (self::GetUsage(self::$sSSDPath) > self::$iSSDDeleteUsage) {
if (!$oFile->isOpened()) {
$oFile->synchronize();
$oFile->deleteFromSSD();
$iDeleted++;
} else $iIgnored++;
} else {
break;
}
}
*/
self::log("DELETED: {$iDeleted}");
self::log("IGNORED: {$iIgnored}");
self::log("SSD USAGE: ".self::GetUsage(self::$sSSDPath)."%");
}
/**
* DELETE FROM SSD
* USING ABSOLUTE VALUE of $iSSDDeleteUsageAbsolute
*/
public function deleteFromSSDAbsolute() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$iDeleted = 0;
$iIgnored = 0;
/*
* Get megastorages sorted by usage desc,
*/
$aMegaStorages = $this->getMegaStorages();
foreach ($aMegaStorages as &$sMegaStorage) {
/*
* Get files in current megastorage
*/
$aFileList = $this->getFileList('/'.$sMegaStorage);
if (empty($aFileList)) {
self::log("NO FILES FOUND in {$sMegaStorage}");
continue;
}
$aFileList = array_map(
create_function('$v', '
$oFile = new VserverFile(trim($v));
return $oFile;
'),
$aFileList
);
/*
* Delete files until appropriate usage
*/
$iFreeSpace = self::GetFreeSpace('/'.$sMegaStorage);
foreach ($aFileList as &$oFile) {
self::Log($sMegaStorage." ".(round($iFreeSpace/1024/1024/1024,2))." G");
if ($iFreeSpace < self::$iSSDDeleteUsageAbsolute) {
if (!$oFile->isOpened()) {
$iFreeSpace += $oFile->getSize();
$oFile->synchronize();
$oFile->deleteFromSSD();
$iDeleted++;
} else $iIgnored++;
} else {
break;
}
}
}
self::log("DELETED: {$iDeleted}");
self::log("IGNORED: {$iIgnored}");
self::log("FREE SPACE: ".(round($iFreeSpace/1024/1024/1024,2))." G");
}
/**
*
* Get Identical files on storages
*/
public function getIdentical() {
$this->setLock(__FUNCTION__.'.lock');
if($this->isLock()) {
self::log("Process has already started.");
return;
}
$aStorages = $this->getStorages();
foreach ($aStorages as &$sStorage) {
$sDir = "/{$sStorage}/".self::$sHTTPFolder;
$aList[$sStorage] = $this->getFileList($sDir,array('flv'), "grep -Eo '".self::$sHTTPFolder.".*$'");
}
$iStorages = sizeof($aList);
for ($i=0; $i<$iStorages; $i++) {
reset($aList);
$sPrimaryStorage = key($aList);
$aPrimaryFiles = array_shift($aList);
foreach($aList as $sSecondaryStorage=>&$aSecondaryFiles) {
self::log("{$sPrimaryStorage} <-- {$sSecondaryStorage}");
//array of identical files
$aIdentical = array_intersect($aPrimaryFiles, $aSecondaryFiles);
if (!empty($aIdentical)) {
// get sizes
foreach ($aIdentical as $sFile) {
$iPrimaryPath = "/{$sPrimaryStorage}/".$sFile;
$iPrimarySize = filesize($iPrimaryPath);
$iSecondaryPath = "/{$sSecondaryStorage}/".$sFile;
$iSecondarySize = filesize($iSecondaryPath);
self::log("| {$iPrimaryPath} <-- {$iPrimarySize}");
self::log("| {$iSecondaryPath} <-- {$iSecondarySize}");
// delete if sizes are identical
if ($iPrimarySize == $iSecondarySize) self::Delete($iSecondaryPath);
// if any have null size
else if ($iPrimarySize * $iSecondarySize) continue;
else if (filectime($iPrimarySize)>filectime($iSecondaryPath)) self::Delete($iSecondaryPath);
else if (filectime($iSecondaryPath)>filectime($iPrimarySize)) self::Delete($iPrimarySize);
}
}
}
}
//echo "<pre>";
//print_r(array_intersect($aPrimaryFiles, $aSecondaryFiles));
//echo "</pre>";
}
/**
* Ñîçäàåò áëîêèðîâêó íà ïðîöåññ
*/
public function setLock($sLockFile=null) {
if(!empty($sLockFile)) {
$this->oLockFile=fopen($sLockFile,'a');
}
}
/**
* Ïðîâåðÿåò óíèêàëüíîñòü ñîçäàâàåìîãî ïðîöåññà
*/
public function isLock() {
return ($this->oLockFile && !flock($this->oLockFile, LOCK_EX|LOCK_NB));
}
/**
* Ñíèìàåò áëîêèðîâêó íà ïîâòîðíûé ïðîöåññ
*/
public function unsetLock() {
return ($this->oLockFile && #flock($this->oLockFile, LOCK_UN));
}
public function __construct() {
self::$iTimeStart = microtime(true);
}
public function __destruct() {
self::$iTimeEnd = microtime(true);
$iTimeExecution = round(self::$iTimeEnd - self::$iTimeStart,3);
$iUsageMem = memory_get_usage(true)/1024/1024; //Mb
$iUsageMemPeak = memory_get_peak_usage(true)/1024/1024; //Mb
self::log("Execution time: {$iTimeExecution} s");
self::log("Memory Usage: {$iUsageMem} Mb");
self::log("Memory Peak Usage: {$iUsageMemPeak} Mb");
$this->unsetLock();
}
/**
* Class autoloader
*
* #param unknown_type $sClassName
*/
public static function autoload($sClassName) {
require_once("{$sClassName}.class.php");
}
}
spl_autoload_register(array('Vserver','autoload'));
?>
Since array_map complains about $aOpenFiles not being an array you might want to take a look at that variable.
public function getOpenFiles($aExt=array()) {
$aOpenFiles = self::GetList(self::$sLogOpenFiles);
if ( !is_array($aOpenFiles) ) {
var_dump($aOpenFiles);
die('not an array');
}
$aOpenFiles = array_map( ...
quote:
static public function GetList($sLogPath) {
if ($sList = self::GetLog($sLogPath)) {
return explode(PHP_EOL,trim($sList));
}
}
... and if $sList evaluates to false (which may very well happen, since GetLog returns false on some conditions) this function returns nothing.
You have to check for that condition somewhere. Where depends on how you want the script to react on what condition. e.g.
static public function GetList($sLogPath) {
if ($sList = self::GetLog($sLogPath)) {
return explode(PHP_EOL,trim($sList));
}
return array();
}
would "fix" the error, but if that's feasible is another question; it may only "hide" a symptom - not the underlying problem. Must there be a log file? Must GetList(GetLog()) return a (non-empty) array? and so on and on....

Categories