Been pulling my hair for 2 hours on this Smarty 2.6 to Smarty 3.1 upgrade task for that old website. The reason is that the host is now PHP 7 only. No more PHP 5. I thought it would be a 1 hour deal, but it's quickly turning into a nightmare. I remember using Smarty back in 2005 and I've never used it ever again, but today, nearly 15 years later, this monstrosity of a template engine is haunting me back!
Here's the init PHP file's contents:
<?php
#Load Smarty library
#require_once("php/Smarty-2.6.26/libs/Smarty.class.php");
#require_once("php/smarty-3.1.34/libs/Smarty.class.php");
require_once("php/smarty-3.1.34/libs/SmartyBC.class.php");
require_once("php/smarty-3.1.34/libs/sysplugins/smarty_security.php");
class class_init extends SmartyBC {
function __construct(){
#Init
parent::__construct();
#Directories
$this->template_dir = "skin/".SKIN."/public/";
$this->compile_dir = "skin/".SKIN."/compile/";
$this->config_dir = "skin/".SKIN."/config/";
$this->cache_dir = "skin/".SKIN."/cache/";
#Caching
$this->caching = (boolean)SMARTY_CACHING;
$this->cache_lifetime = (int)SMARTY_CACHE_LIFETIME;
$this->debugging = true;
}
function is_cached($str_tpl, $cache_id = NULL, $compile_id = NULL){
return $this->isCached($str_tpl, $cache_id, $compile_id);
}
}
class MySecurity extends SmartySecurity {
public $secure_dir = array('/home/lesclownsducarro/public_html/');
public function __construct(Smarty $smarty){
parent::__construct($smarty);
}
}
?>
Here's the controller file's contents:
require_once("./php/class/init.php");
$_ENV['class_init'] = new class_init();
$securityPolicy = new Smarty_Security($_ENV['class_init']);
$securityPolicy->php_handling = \Smarty::PHP_ALLOW;
$_ENV['class_init']->enableSecurity($securityPolicy);
Getting a completely blank page and the error_log simply states:
[30-Dec-2019 22:22:40 UTC] PHP Fatal error: Class 'SmartySecurity' not found in /home/xxxxx/public_html/php/class/init.php on line 32
FOR BACKWARDS COMPATIBILITY, I need to use SmartyBC because the template is including PHP files all over the place. inb4 yes I know, and this is not my website.
Any ideas ?
DOH. Welp, I'm just too tired, it seems.
It should obviously be: $securityPolicy = new Smarty_Security($_ENV['class_init']);
...with the underscore. I don't know, I copy/pasted the example from smarty.net without paying any attention at all. "new SmartySecurity" as seen here: https://www.smarty.net/forums/viewtopic.php?p=72741
JFC.
Related
I am trying to implement a logging library which would fetch the current debug level from the environment the application runs in:
23 $level = $_SERVER['DEBUG_LEVEL'];
24 $handler = new StreamHandler('/var/log/php/php.log', Logger::${$level});
When I do this, the code fails with the error:
A valid variable name starts with a letter or underscore,followed by any number of letters, numbers, or underscores at line 24.
How would I use a specific Logger:: level in this way?
UPDATE:
I have tried having $level = "INFO" and changing ${$level} to $$level. None of these changes helped.
However, replacing the line 24 with $handler = new StreamHandler('/var/log/php/php.log', Logger::INFO); and the code compiles and runs as expected.
The variable itself is declared here
PHP Version => 5.6.99-hhvm
So the answer was to use a function for a constant lookup:
$handler = new StreamHandler('/var/log/php/php.log', constant("Monolog\Logger::" . $level));
<?php
class Logger {
const MY = 1;
}
$lookingfor = 'MY';
// approach 1
$value1 = (new ReflectionClass('Logger'))->getConstants()[$lookingfor];
// approach 2
$value2 = constant("Logger::" . $lookingfor);
echo "$value1|$value2";
?>
Result: "1|1"
I get the following error:
Catchable fatal error: Argument 1 passed to CorenlpAdapter::getOutput() must be an instance of string, string given, called in /Library/WebServer/Documents/website/php-stanford-corenlp-adapter/index.php on line 22 and defined in /Library/WebServer/Documents/website/php-stanford-corenlp-adapter/src/CoreNLP/CorenlpAdapter.php on line 95
index.php 21 and 22 contain:
$text1 = 'I will meet Mary in New York at 10pm';
$coreNLP->getOutput($text1);
corenlpAdapter.php lines 95 and onwards contain:
public function getOutput(string $text){
if(ONLINE_API){
// run the text through the public API
$this->getServerOutputOnline($text);
} else{
// run the text through Java CoreNLP
$this->getServerOutput($text);
}
// cache result
$this->serverMemory[] = $this->serverOutput;
if(empty($this->serverOutput)){
echo '** ERROR: No output from the CoreNLP Server **<br />
- Check if the CoreNLP server is running. Start the CoreNLP server if necessary<br />
- Check if the port you are using (probably port 9000) is not blocked by another program<br />';
die;
}
/**
* create trees
*/
$sentences = $this->serverOutput['sentences'];
foreach($this->serverOutput['sentences'] as $sentence){
$tree = $this->getTreeWithTokens($sentence); // gets one tree
$this->trees[] = $tree; // collect all trees
}
/**
* add OpenIE data
*/
$this->addOpenIE();
// to get the trees just call $coreNLP->trees in the main program
return;
}
Why exactly am I getting this error when text1 is a string?
I am the original author of this class. As you can see, the function getOutput looks like this:
public function getOutput(string $text){
...
}
Change that to:
public function getOutput($text){
...
}
The function tries to enforce that the input is string. The original code should work. However, it seems that in your case, PHP thinks "string" is not actually a string. Maybe the coding environment (the IDE) you are using uses the wrong character set? Or maybe you copy-pasted the code from HTML into the IDE or something like that. Thus whilst it says "string" on the screen, it's not actually a string to PHP.
If you are sure the input is a string, you can safely change the code like above. The class should then work normally.
public function getOutput($text){
.
.
.
}
I am trying to use the output from a php file in a TemplaVoila FCE.
According to the articles, etc, I have found on the subject, I seem to be doing it right. But it does not work.
I have reduced my implementation to a very simple test, and I hope that someone here can tell me what I am doing wrong.
The php code is in fileadmin/php/test.php
The file contains this code:
<?php
function getBeechgroveTest($content, $conf)
{
return 'B';
}
//echo getBeechgroveTest(0,0);
?>
In the main template (template module - not TemplaVoila) I have added this line:
includeLibs.beechgroveTest = fileadmin/php/test.php
I have tried to put it at the root level and inside a PAGE object. Both gave the same result.
If I uncomment the 'echo' line I get a 'B' at the top of my HTML page, so the php must be read at some point.
My FCE has one field of type 'None (TypoScript only)' and contains this code:
10 = TEXT
10 {
value = A
}
20 = USER
20 {
userFunc = getBeechgroveTest
}
30 = TEXT
30 {
value = C
}
I was expecting the FCE to output 'ABC', but I only get 'AC'.
What am I doing wrong?
I use TYPO3 version 4.5.30 and TemplVoila 1.8.0
It must by problem in cache, try use USER_INT instead USER. If you create this object as USER_INT, it will be rendered non-cached, outside the main page-rendering.
20 = USER_INT
20 {
userFunc = getBeechgroveTest
}
I have slapped together a test PHP script. It would output some remote connection's geo ip based data. Nothing fancy, just a quick prototype.
But I am seeing an odd behavior, so I am asking here if somebody had any clues about it.
PHP is version 5.5.12 on Ubuntu 64 bit.
Here's some code from the geoip_test.php calling script:
require_once ('geoip_utils.php');
$server_geoip_record = geoip_record_by_name('php.net');
echo '<pre>PHP.net web server location: ' . print_r($server_geoip_record, 1);
echo '<br />PHP.net web server local time: ' . \df_library\getUserTime($server_geoip_record)->format('Y-m-d H:i:s');
Nothing fancy at all, isn't it?
Now the simple geoip_utils.php code:
<?php
namespace df_library;
require_once('timezone.php');
// Given an IP address, returns the language code (i.e. en)
function getLanguageCodeFromIP($input_ip)
{
};
// Given a geo_ip_record, it returns the local time for the location indicated
// by it. In case of errors, it will return the optionally provided fall back value
function getUserTime($geoip_record, $fall_back_time_zone = 'America/Los_Angeles') {
//Calculate the timezone and local time
try
{
//Create timezone
$timezone = #get_time_zone($geoip_record['country_code'], ($geoip_record['region'] != '') ? $geoip_record['region'] : 0);
if (!isset($timezone)) {
$timezone = $fall_back_time_zone;
}
$user_timezone = new \DateTimeZone($timezone);
//Create local time
$user_localtime = new \DateTime("now", $user_timezone);
}
//Timezone and/or local time detection failed
catch(Exception $e)
{
$user_localtime = new \DateTime("now");
}
return $user_localtime;
}
?>
When I run the calling script I get:
PHP Fatal error: Call to undefined function df_library\getUserTime() in /var/www/apps/res/geoip_test.php on line 5
The funny part is: if I add this debug code:
$x = get_defined_functions();
print_r($x["user"]);
I get this output:
Array
(
[0] => df_library\getlanguagecodefromip
[1] => df_library\gettimezone
[2] => df_library\getutcdatetime
[3] => df_library\getlocalizedtime
[4] => df_library\getutcdatetimeaslocalizeddatetime
[5] => df_library\getlocalizeddatetimeasutcdatetime
[6] => get_time_zone
)
First of all, I don't understand why the function names are converted to lower case.
But most of all, notice how index 0 shows the empty function function getLanguageCodeFromIP($input_ip) being defined, and that function is right above the one that the interpreter complains about as not being defined!
Why does PHP see the other function in that file but not the one I want to use?
Any ideas are welcome!
There is an extra semi-colon ; after the close bracket of function getLanguageCodeFromIP which causes PHP parser somehow unable to recognize the functions after getLanguageCodeFromIP.
As proven in OP's comment, removing the ; solved the problem.
First let me say sorry for the amount of code I'm posting below I'm going to try and keep it as short as possible but this is built on top of my MVC (lightweight-mvc)
Ok So my Problem is that for some reason php is throwing a fatal error on code that should not be being used in my current code,
So how this works I have my MVC witch used the first 2 parts of the url to know what its loading, the problem is I'm building a Moulder CMS into my MVC so it's boot strapping twice,
So here is my Problem,
http://{domain}/admin/control/addon/uploader/method/uploadCheck/
I'm using the above now let me explain a little into that the /admin/control are for the main MVC System it auto-loads the Admin controller then fires the controlAction method from the controller much the same as most MVC's,
The next part are URL paramters that build an array the same as GET or POST would
array('addon'=>'uploader', 'method'=>'uploadCheck')
So from that my control action will auto load as is the code below
public function controlAction(){
global $_URL;
if(cleanData::URL("addon")){
$addonName = "addon_".cleanData::URL("addon");
$methodName = (cleanData::URL("method"))? cleanData::URL("method")."Action" : "indexAction";
echo $methodName;
$addon = new $addonName();
$addon->$methodName();
return;
}else{
$this->loadView("CMS/controll");
}
}
cleanData::URL is an abstract method that just returns the value of the key provided though addSlashes()
So as you can see from the code below it will then use the autoloader to load the module(AKA addon)
Just so you can follow the auto loader works in a simpler version of the Zend Frame work autoloader _ so you have class name addon_admin that would be inside file admin.php that is in the folder addon so the autoloader will load addon/admin.php
So As above with my URL and controlAction it's loading addon/uploader.php and as such this is the contents
<?php
class addon_uploader extends Addons{
public function uploadCheckAction(){
echo 0;
}
public function uploaderAction(){
if (!empty($_FILES)) {
$tmpFile = $_FILES['Filedata']["tmp_name"];
$newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']);
move_uploaded_file($tmpFileName, $newLock);
$POSTback = array(
'name' => $_FILES['Filedata']['name'],
'type' => $_FILES['Filedata']['type'],
'tmp_name' => $newLock,
'error' => $_FILES['Filedata']['error'],
'size' => $_FILES['Filedata']['size']
);
echo json_enocde($POSTback);
}
}
}
?>
But as you can see from my URL its using the uploadCheckAction method witch for debugging i have set so it always says false (AKA 0),
But i seem to get this error:
Fatal error: Only variables can be passed by reference in C:\xampp\htdocs\FallenFate\addon\uploader.php on line 11
But line 11 is $newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']); witch should not be being used could any one provide any help into why this would occur and how i could fix it
end() PHP Manual needs an expression of a single variable (more precisely an array), but not a function return value or any other type of expression.
I think that's basically the cause of your error, more specifically with your code:
$newLock = "../uploads/".end(explode('/', $tmpFile).$_FILES['Filedata']['name']);
you're even driving this far beyond any level of treatment PHP can cope with:
you concatenate an array with a string (which results in a string).
you run end() on that string - not on a variable, not even an array.
I have no clue what you try to do with the code, but I can try:
$filename = $_FILES['Filedata']['name'];
$parts = explode('/', $tmpFile);
$last = end($parts);
$newLock = "../uploads/". $last . $filename;
Or probably even only this:
$filename = $_FILES['Filedata']['name'];
$newLock = "../uploads/". $filename;