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....
Related
This question already has answers here:
PHP parse/syntax errors; and how to solve them
(20 answers)
Closed 1 year ago.
on this site I use magento and theme :
http://www.herbalheaven.co.uk
Everything works good but when you go on categories I got the same error for all of them :
http://www.herbalheaven.co.uk/herbal-ayurveda.html
Parse error: syntax error, unexpected '' (T_NS_SEPARATOR), expecting function (T_FUNCTION) or const (T_CONST) in /home/herbalheaven/public_html/app/code/MageBig/AjaxFilter/Plugin/Catalog/Product/ProductList/Toolbar.php on line 16
And here is the code :
<?php
/**
* Copyright © www.magebig.com - All rights reserved.
* See LICENSE.txt for license details.
*/
namespace MageBig\AjaxFilter\Plugin\Catalog\Product\ProductList;
use MageBig\AjaxFilter\Model\Layer\Filter\Rating;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;
use Magento\Store\Model\ScopeInterface;
class Toolbar
{
private \Magento\Catalog\Model\Product\ProductList\Toolbar $toolbarModel;
private RequestInterface $request;
private Registry $coreRegistry;
private ScopeConfigInterface $scopeConfig;
public function __construct(
\Magento\Catalog\Model\Product\ProductList\Toolbar $toolbarModel,
ScopeConfigInterface $scopeConfig,
Registry $coreRegistry
)
{
$this->toolbarModel = $toolbarModel;
$this->scopeConfig = $scopeConfig;
$this->coreRegistry = $coreRegistry;
}
public function aroundSetCollection(
\Magento\Catalog\Block\Product\ProductList\Toolbar $subject,
\Closure $proceed,
$collection
) {
if (!$this->coreRegistry->registry('product_filter_collection')) {
$c1 = clone $collection;
$c1->setOrder('price', 'desc')->getFirstItem();
$this->coreRegistry->register('product_filter_collection', $c1);
}
$order = $subject->getCurrentOrder();
$result = $proceed($collection);
$ratingCode = Rating::RATING_CODE;
if ($ratingCode && ($order == $ratingCode)) {
$direction = $subject->getCurrentDirection();
$searchEngine = $this->scopeConfig->getValue('catalog/search/engine', ScopeInterface::SCOPE_STORE);
if ($searchEngine == 'mysql') {
$collection->setOrder('rating_summary', $direction);
} else {
$collection->setOrder('rating', $direction);
}
}
return $result;
}
/**
* #param $subject
* #param $dir
* #return string
*/
public function afterGetCurrentDirection($subject, $dir)
{
$defaultDir = $subject->getCurrentOrder() == 'rating' ? 'desc' : $dir;
$subject->setDefaultDirection($defaultDir);
if (!$this->toolbarModel->getDirection()) {
$dir = $defaultDir;
}
return $dir;
}
}
Please use below code
<?php
/**
* Copyright © www.magebig.com - All rights reserved.
* See LICENSE.txt for license details.
*/
namespace MageBig\AjaxFilter\Plugin\Catalog\Product\ProductList;
use MageBig\AjaxFilter\Model\Layer\Filter\Rating;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Registry;
use Magento\Store\Model\ScopeInterface;
use Magento\Catalog\Model\Product\ProductList\Toolbar as defaultToolbar;
class Toolbar
{
private defaultToolbar $toolbarModel;
private RequestInterface $request;
private Registry $coreRegistry;
private ScopeConfigInterface $scopeConfig;
public function __construct(
defaultToolbar $toolbarModel,
ScopeConfigInterface $scopeConfig,
Registry $coreRegistry
)
{
$this->toolbarModel = $toolbarModel;
$this->scopeConfig = $scopeConfig;
$this->coreRegistry = $coreRegistry;
}
public function aroundSetCollection(
defaultToolbar $subject,
\Closure $proceed,
$collection
) {
if (!$this->coreRegistry->registry('product_filter_collection')) {
$c1 = clone $collection;
$c1->setOrder('price', 'desc')->getFirstItem();
$this->coreRegistry->register('product_filter_collection', $c1);
}
$order = $subject->getCurrentOrder();
$result = $proceed($collection);
$ratingCode = Rating::RATING_CODE;
if ($ratingCode && ($order == $ratingCode)) {
$direction = $subject->getCurrentDirection();
$searchEngine = $this->scopeConfig->getValue('catalog/search/engine', ScopeInterface::SCOPE_STORE);
if ($searchEngine == 'mysql') {
$collection->setOrder('rating_summary', $direction);
} else {
$collection->setOrder('rating', $direction);
}
}
return $result;
}
/**
* #param $subject
* #param $dir
* #return string
*/
public function afterGetCurrentDirection($subject, $dir)
{
$defaultDir = $subject->getCurrentOrder() == 'rating' ? 'desc' : $dir;
$subject->setDefaultDirection($defaultDir);
if (!$this->toolbarModel->getDirection()) {
$dir = $defaultDir;
}
return $dir;
}
}
If this code work, I have explain how its work
Error: In your code you have added extra \ slashed in line on 16.
Step 1: First I have include default Toolbar Class with the alias of defaultToolbar.
use Magento\Catalog\Model\Product\ProductList\Toolbar as defaultToolbar;
Step 2: I have replace all manual path with the alias name.
Thanks
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));
}
}
}
}
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.
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');
}
}
I have error, while trying to include this file. I have a error
Fatal error: Namespace declaration statement has to be the very first statement in the script in /var/www/html/phpinstagram/phpinstagram/Instagram.php on line 2
Code:
<?php
namespace phpinstagram;
class Instagram {
/*
* #var array
*/
protected $_commands = array();
/*
* #var \phpinstagram\Instagram\Client\Communication
*/
protected $_communication;
/*
* #var \phpinstagram\Instagram\Api\Feed
*/
public $feed;
/*
* #var \phpinstagram\Instagram\Api\Auth
*/
public $auth;
public function __construct() {
$this->feed = new \phpinstagram\Instagram\Api\Feed();
$this->feed->setInstagram($this);
$this->auth = new \phpinstagram\Instagram\Api\Auth();
$this->auth->setInstagram($this);
$this->_communication = new \phpinstagram\Instagram\Client\Communication();
}
public function addCommand(\phpinstagram\Instagram\Command\ICommand $cmd) {
$this->_commands[] = $cmd;
}
public function run() {
$executed = array();
//$cookieJar = null;
foreach ($this->_commands as $utcmd) {
if ($utcmd instanceof \phpinstagram\Instagram\Command\ICommand) {
/*
* #var \phpinstagram\Instagram\Command\ICommand
*/
$cmd = $utcmd;
//if (!is_null($cookieJar))
// $this->_communication->getClient()->setCookieJar($cookieJar);
foreach ($cmd->dependsOn() as $dependency) {
foreach ($executed as $previous) {
if (get_class($previous) == '\Instagram\Command\\' . $dependency) {
break 2;
}
}
throw new \phpinstagram\Instagram\Command\DependencyException(
'Command ' . get_class($cmd) . " depends on $dependency but it never was executed!\n\n"
);
}
$cmd->setCommunication($this->_communication);
$cmd->validate();
//echo get_class($cmd)." is valid. executing...\n\n";
$cmd->exec();
$executed[] = $cmd;
// reset parameters
$this->_communication->getClient()->resetParameters();
//$cookieJar = $this->_communication->getClient()->getCookieJar();
}
}
// reset commands
$this->_commands = array();
}
}
You probably use UTF-8 encoding with Byte Order Mark (see https://en.wikipedia.org/wiki/Byte_order_mark). Try to convert your files to "UTF-8 without BOM".