Php script into WordPress as page template - php

I am trying to integrate bought php script (yougrabber) into WordPress as page template.
Script works fine as standalone website. But when I try to insert it as a page template and open it I get the following error:
Warning: require_once(application/config/routes.php): failed to open
stream: No such file or directory in
/opt/lampp/htdocs/wordpress/wordpress/wp-content/themes/twentyseventeen/yougrabber/core/router.php
on line 55
Fatal error: require_once(): Failed opening required
'application/config/routes.php' (include_path='.:/opt/lampp/lib/php')
in
/opt/lampp/htdocs/wordpress/wordpress/wp-content/themes/twentyseventeen/yougrabber/core/router.php
on line 55
I think that script is expected to be loaded in root directory.
And this is how scripts index.php looks when I put it in theme directory and tell wp it is a page template.
<?php
/*
Template Name: TESTIRANJE
*/
?>
<?php
//error_reporting(E_ALL); //uncomment for development server
define("BASE_PATH", str_replace("\\", NULL, dirname($_SERVER["SCRIPT_NAME"]) == "/" ? NULL : dirname($_SERVER["SCRIPT_NAME"])) . '/');
require_once "core/router.php";
Router::init();
function __autoload($class) { Router::autoload($class); }
Router::route();
?>
Any help is appreciated. Thank you.
Edit:
router.php
<?php
class Router
{
private static $current_page;
private static $page_struct;
private static $is_router_loaded;
private function __construct()
{
self::$current_page = self::getPage();
self::$page_struct = explode("/", self::$current_page);
self::$page_struct = array_values(array_filter(self::$page_struct, 'strlen'));
}
public static function init()
{
if(self::$is_router_loaded instanceof Router) return self::$is_router_loaded;
else return self::$is_router_loaded = new Router;
}
public static function route()
{
self::loadAutoload();
if(!self::getController())
{
try {
self::loadDefaultPage();
}
catch(ConfigException $e) { return self::error404(); }
}
self::loadRewrites();
self::loadPostedPage();
}
private static function loadDefaultPage()
{
require('application/config/routes.php');
if(!is_array($routes["default_page"])) throw new ConfigException();
else
{
$controller_cname = 'application\\Controllers\\'.$routes['default_page'][0];
$controller_obj = new $controller_cname;
$controller_obj->$routes['default_page'][1]();
}
exit;
}
private static function loadAutoload()
{
require_once("application/config/routes.php");
require_once("/application/config/autoload.php");
$loader =\core\Loader::getInstance(true);
foreach($autoload['libraries'] as $library)
{
$loader->library($library);
}
foreach(array_unique($autoload['controllers']) as $controller)
{
if((strtolower(self::getController()) != strtolower($controller)) && (self::getController() != null && $routes['default_page'][0] == 'users')) $loader->controller($controller);
}
}
private static function loadRewrites()
{
require("application/config/routes.php");
foreach ($routes as $rewrittenPage => $realPage)
{
if(is_array($realPage)) continue;
if($rewrittenPage == str_replace(BASE_PATH, NULL, $_SERVER["REQUEST_URI"])) self::setPage($realPage);
else if(preg_match_all('#\[(.*)\]#U', $rewrittenPage, $param_names))
{
$getRegex = preg_replace("#\[.*\]#U", "(.*)", $rewrittenPage);
preg_match_all("#^\/?".$getRegex."$#", self::$current_page, $param_values); unset($param_values[0]);
if(in_array(null, $param_values)) continue;
else
{
$i = 0;
foreach($param_values as $p_value)
{
$realPage = str_replace('['.$param_names[1][$i].']', $param_names[1][$i].':'.$p_value[0], $realPage);
$i++;
}
self::setPage($realPage);
}
}
}
}
private static function loadPostedPage()
{
if(self::getController() != null && $controller = self::getController())
{
$controller = "application\\Controllers\\".$controller;
$controller = new $controller;
if(!self::getMethod())
{
if(method_exists($controller, 'index'))
{
$controller->index();
}
}
else
{
$method = self::getMethod();
if(!method_exists($controller, $method)) return self::error404();
$method_data = new ReflectionMethod($controller, $method);
if($method_data->isPublic() == true)
{
if(!self::getParameters())
{
if($method_data->getNumberOfRequiredParameters() == 0) $controller->$method(); else self::error404();
}
else
{
$parametersToSet = self::getParameters();
$sortParams = array();
foreach($method_data->getParameters() as $params)
{
if(!$params->isOptional() && !isset($parametersToSet[$params->getName()])) return self::error404 ();
if($params->isOptional() && !isset($parametersToSet[$params->getName()])) $sortParams[] = $params->getDefaultValue();
else $sortParams[] = $parametersToSet[$params->getName()];
}
$method_data->invokeArgs($controller, $sortParams);
}
} else return self::error404();
}
}
}
public static function error404()
{
header("HTTP/1.0 404 Not Found");
die(file_get_contents('application/errors/404.html'));
exit;
}
public static function autoload($className)
{
if(class_exists($className)) return true;
else
{
$className = strtolower(str_replace('\\', '/', $className));
if(!file_exists($className.'.php')) return self::error404();;
require_once $className .'.php';
}
}
private static function getController()
{
if(isset(self::$page_struct[0]))
return self::$page_struct[0];
}
private static function getMethod()
{
if(isset(self::$page_struct[1]))
return self::$page_struct[1];
}
private static function getParameters()
{
$parameters = array();
foreach(self::$page_struct as $place => $args)
{
if($place > 1 && strstr($args, ':'))
{
$parameter = explode(":", $args);
$parameters[$parameter[0]] = $parameter[1];
$_GET[$parameter[0]] = $parameter[1];
}
}
return $parameters;
}
public static function getPage()
{
$rpath = BASE_PATH == "/" ? NULL : BASE_PATH;
if(self::$current_page == null) self::$current_page = (
str_replace('?'.$_SERVER["QUERY_STRING"], NULL,
str_replace($rpath, NULL, $_SERVER["REQUEST_URI"])));
return self::$current_page;
}
private static function setPage($page)
{
self::$current_page = $page;
self::$page_struct = explode("/", self::$current_page);
self::$page_struct = array_filter(self::$page_struct, 'strlen');
}
}
class ConfigException Extends Exception {}
?>
After trying what #ArsalanMithani sugested, now getting:
Warning: require_once(): http:// wrapper is disabled in the server
configuration by allow_url_include=0 in
/opt/lampp/htdocs/wordpress/wordpress/wp-content/themes/twentyseventeen/core/router.php
on line 55
Warning:
require_once(http://localhost/wordpress/wordpress/wp-content/themes/twentyseventeen/application/config/routes.php):
failed to open stream: no suitable wrapper could be found in
/opt/lampp/htdocs/wordpress/wordpress/wp-content/themes/twentyseventeen/core/router.php
on line 55
Fatal error: require_once(): Failed opening required
'http://localhost/wordpress/wordpress/wp-content/themes/twentyseventeen/application/config/routes.php'
(include_path='.:/opt/lampp/lib/php') in
/opt/lampp/htdocs/wordpress/wordpress/wp-content/themes/twentyseventeen/core/router.php
on line 55

That's seems path issue, you are using it in WordPress so you have to define relevant paths in WordPress way.
Use get_template_directory_uri() to get the theme path and if you are using child theme then use get_stylesheet_directory_uri().
require( get_template_directory_uri() . '/directorypathtoscriptfiles');
if you have put your script like wp-content/yourtheme/yourscriptdir then your path should be :
require( get_template_directory_uri() . '/yourscriptdir/core/router.php');
EDIT
The warning is generated because a full URL has been used for the file that you are including, you are getting some HTML may be, this is the reason i was asking for your dir structure, although it will work if you change allow_url_include to 1 in php.ini file, but what would you do on live server? to tackle this now add ../ in your require instead of full url like below & see if that works:
do this in router.php
require( '../application/config/routes.php');

Related

I have Error in my php auto loader file at the time of excel upload

My code is working in local but when I upload my same code in live it gives me
Type: Error
Message: Class 'PHPExcel_Shared_String' not found
Filename: /home/u451055217/domains/barque.online/public_html/demo/application/libraries/PHPExcel/Autoloader.php
Line Number: 11
my auto load file:
<?php
PHPExcel_Autoloader::register();
if (ini_get('mbstring.func_overload') & 2) {
throw new PHPExcel_Exception('Multibyte function overloading in PHP must be disabled for string functions (2).');
}
PHPExcel_Shared_String::buildCharacterSets();
class PHPExcel_Autoloader
{
public static function register()
{
if (function_exists('__autoload')) {
spl_autoload_register('__autoload');
}
if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'), true, true);
} else {
return spl_autoload_register(array('PHPExcel_Autoloader', 'load'));
}
}
public static function load($pClassName)
{
if ((class_exists($pClassName, false)) || (strpos($pClassName, 'PHPExcel') !== 0)) {
return false;
}
$pClassFilePath = PHPEXCEL_ROOT .
str_replace('_', DIRECTORY_SEPARATOR, $pClassName) .
'.php';
if ((file_exists($pClassFilePath) === false) || (is_readable($pClassFilePath) === false)) {
return false;
}
require($pClassFilePath);
}
}
I do not know where I am wrong in my code.
I uploaded the same code of my local.

Widget in CodeIgniter 3

For a dashboard-app, I want to create a widget-component in my CI3-project. I found a similar question: How to create a widget system in Codeigniter, but it seems that this is either outdated or just not usable for CI3. Even the link with the "more information" results in a 404.
I googled that of course, but didn't find anything useful. One post was from 2013, which showed that example von the CI2 base.
However, maybe this plugin still works and I have an error in my setup.
I placed a file "Widget.php" in
/application/third_party/
with the following content:
class Widget
{
public $module_path;
function run($file) {
$args = func_get_args();
$module = '';
/* is module in filename? */
if (($pos = strrpos($file, '/')) !== FALSE) {
$module = substr($file, 0, $pos);
$file = substr($file, $pos + 1);
}
list($path, $file) = Modules::find($file, $module, 'widgets/');
if ($path === FALSE) {
$path = APPPATH.'widgets/';
}
Modules::load_file($file, $path);
$file = ucfirst($file);
$widget = new $file();
$widget->module_path = $path;
return call_user_func_array(array($widget, 'run'), array_slice($args, 1));
}
function render($view, $data = array()) {
extract($data);
include $this->module_path.'views/'.$view.EXT;
}
function load($object) {
$this->$object = load_class(ucfirst($object));
}
function __get($var) {
global $CI;
return $CI->$var;
}
}
In my application/widgets-folder, I have a file called News.php.
<?php
class News extends Widget
{
function run() {
die('here');
}
}
In application/libraries/ I placed a file widgetlib.php :
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class widgetlib {
function __construct() {
include(APPPATH . '/third_party/Widget.php');
}
}
and finally, in my view:
<?php widget::run("News"); ?>
Then I checked my autoloader-class in application/config/autoload.php:
$autoload['libraries'] =
'session',
'database',
'widgetlib'
);
This results in:
A PHP Error was encountered
Severity: Error
Message: Class 'Modules' not found
Filename: third_party/Widget.php
Line Number: 20
and
Severity: Runtime Notice
Message: Non-static method Widget::run() should not be called statically, assuming $this from incompatible context
Filename: views/index.php

Class constructor error on validation

I am developing a file uploaded class, and trying to perform few validation before other codes, but its returning all vars instead of false, check following code....
class FileUploader
{
private $filePath;
function __construct($file_path) {
if(file_exists($file_path)) {
$this->filePath = $file_path;
}
else return false;
}
}
When I am using this class like following....
$file_path = getcwd().'\img.pn'; //invalid path
$file_uploader = new FileUploader($file_path);
if($file_uploader) {
//process
}
else {
echo 'Invalid File Path!';
}
But it doesn't echo Invalid File Path as expected, when i tried var_dump, it returned following output...
object(FileUploader)[1]
private 'filePath' => null
Please help to fix this. thanks.
You might consider using an exception in the constructor as constructors should no return anything. (Have a look at this question).
Otherwise you may create a function to check the file_path :
class FileUploader
{
private $filePath;
function __construct($file_path) {
$this->filePath = $file_path;
}
function isValidFilePath() {
return file_exists($this->file_path);
}
}
and then :
$file_path = getcwd().'\img.pn'; //invalid path
$file_uploader = new FileUploader($file_path);
if($file_uploader->isValidFilePath()) {
//process
}
else {
echo 'Invalid File Path!';
}

Error When Calling Function

I searched forever trying to find an answer, but was ultimately stumped. I've been writing code to allow multiple bots to connect to a chat box. I wrote all the main code and checked it over to make sure it was all okay. Then when I got to calling the function needed to make it work, it gave me an error saying:
Notice: Undefined variable: ip in C:\wamp\www\BotRaid.php on line 40
And also an error saying:
Fatal Error: Cannot access empty property in C:\wamp\www\BotRaid.php
on line 40
( Also a screenshot here: http://prntscr.com/ckz55 )
<?php
date_default_timezone_set("UCT");
declare(ticks=1);
set_time_limit(0);
class BotRaid
{
public $ip="174.36.242.26";
public $port=10038;
public $soc = null;
public $packet = array();
##############################
# You can edit below this #
##############################
public $roomid="155470742";
public $userid = "606657406";
public $k = "2485599605";
public $name="";
public $avatar=;
public $homepage="";
##############################
# Stop editing #
##############################
public function retry()
{
$this->connect($this->$ip,$this->$port); //Line 40, where I'm getting the error now.
$this->join($this->$roomid);
while($this->read()!="DIED");
}
public function connect($ip, $port)
{
if($this->$soc!=null) socket_close($this->$soc);
$soc = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if(!$this->$soc)$this->port();
if(!socket_connect($this->$soc,$this->$ip,$this->$port))$this->port();
}
public function port()
{
$this->$port++;
if($this->$port>10038) $this->$port=10038;
$this->retry();
}
public function join($roomid)
{
$this->send('<y m="1" />');
$this->read();
$this->send('<j2 q="1" y="'.$this->$packet['y']['i'].'" k="'.$this->$k.'" k3="0" z="12" p="0" c"'.$roomid.'" f="0" u="'.$this->$userid.'" d0="0" n="'.$this->$name.'" a="'.$this->$avatar.'" h="'.$this->$homepage.'" v="0" />');
$this->port();
$this->$roomid;
}
public function send($msg)
{
echo "\n Successfully connected.";
socket_write($this->$soc, $this->$msg."\0", strlen($this->$msg)+1);
}
public function read($parse=true)
{
$res = rtrim(socket_read($this->$soc, 4096));
echo "\nSuccessfully connected.";
if(strpos(strtolower($res), "Failed"))$this->port();
if(!$res) return "DIED";
$this->lastPacket = $res;
if($res{strlen($res)-1}!='>') {$res.=$this->read(false);}
if($parse)$this->parse($res);
return $res;
}
public function parse($packer)
{
$packet=str_replace('+','#più#',str_replace(' ="',' #=#"',$packet));
if(substr_count($packet,'>')>1) $packet = explode('/>',$packet);
foreach((Array)$packet as $p) {
$p = trim($p);
if(strlen($p)<5) return;
$type = trim(strtolower(substr($p,1,strpos($p.' ',' '))));
$p = trim(str_replace("<$type",'',str_replace('/>','',$p)));
parse_str(str_replace('"','',str_replace('" ','&',str_replace('="','=',str_replace('&','__38',$p)))),$this->packet[$type]);
foreach($this->packet[$type] as $k=>$v) {
$this->packet[$type][$k] = str_replace('#più#','+',str_replace('#=#','=',str_replace('__38','&',$v)));
}
}
}
}
$bot = new BotRaid; //This is where I had the error originally
$bot->retry();
?>
Line 40 is below the "Stop Editing" line. Anyone have any suggestions? Or perhaps need me to clear some things up?
You are accessing the properties of the class incorrectly.
The line:
$this->connect($this->$ip,$this->$port);
Should be:
$this->connect($this->ip, $this->port);
Since there was no local variable called $ip, your expression was evaluating to $this-> when trying to access the property since PHP lets you access properties and functions using variables.
For example, this would work:
$ip = 'ip';
$theIp = $this->$ip; // evaluates to $this->ip
// or a function call
$method = 'someFunction';
$value = $this->$method(); // evaluates to $this->someFunction();
You will have to change all the occurrences of $this->$foo with $this->foo since you used that notation throughout the class.
As noted in the comment by #Aatch, see the docs on variable variables for further explanation. But that is what you were running into accidentally.

PHP including external files which use class fields from base file

Let's say I have a class...
class A {
private $action;
private $includes;
public function __construct($action, $file) {
//assign fields
}
public function includeFile()
include_once($this->file);
}
$a = new A('foo.process.php', 'somefile.php');
$a->includeFile();
As you can see, includeFile() calls the include from within the function, therefore once the external file is included, it should technically be inside of the function from my understanding.
After I've done that, let's look at the file included, which is somefile.php, which calls the field like so.
<form action=<?=$this->action;?> method="post" name="someForm">
<!--moar markup here-->
</form>
When I try to do this, I receive an error. Yet, in a CMS like Joomla I see this accomplished all the time. How is this possible?
Update
Here's the error I get.
Fatal error: Using $this when not in object context in /var/www/form/form.process.php on line 8
Update 2
Here's my code:
class EditForm implements ISave{
private $formName;
private $adData;
private $photoData;
private $urlData;
private $includes;
public function __construct(AdData $adData, PhotoData $photoData, UrlData $urlData, $includes) {
$this->formName = 'pageOne';
$this->adData = $adData;
$this->photoData = $photoData;
$this->urlData = $urlData;
$this->includes = $includes;
}
public function saveData() {
$this->adData->saveData();
$this->photoData->saveData();
}
public function includeFiles() {
if (is_array($this->includes)) {
foreach($this->includes as $file) {
include_once($file);
}
} else {
include_once($this->includes);
}
}
public function populateCategories($parent) {
$categories = $this->getCategories($parent);
$this->printCategories($categories);
}
public function populateCountries() {
$countries = $this->getCountries();
$this->printCountries($countries);
}
public function populateSubCategories() {
//TODO
}
private function getCategories($parent) {
$db = patentionConnect();
$query =
"SELECT * FROM `jos_adsmanager_categories`
WHERE `parent` = :parent";
$result = $db->fetchAll(
$query,
array(
new PQO(':parent', $parent)
)
);
return $result;
}
private function getCountries() {
$db = patentionConnect();
$query =
"SELECT `fieldtitle` FROM `jos_adsmanager_field_values`
WHERE fieldid = :id";
$result = $db->fetchAll(
$query,
array(
new PQO(':id', 29)
)
);
return $result;
}
private function printCountries(array $countries) {
foreach($countries as $row) {
?>
<option value=<?=$row['fieldtitle'];?> >
<?=$row['fieldtitle'];?>
</option>
<?php
}
}
private function printCategories(array $categories) {
foreach($categories as $key => $row){
?>
<option value=<?=$row['id'];?>>
<?=$row['name'];?>
</option>
<?php
}
}
}
And the include call (which exists in the same file):
$template = new EditForm(
new AdData(),
new PhotoData(),
new UrlData($Itemid),
array(
'form.php',
'form.process.php'
)
);
$template->includeFiles();
And the main file which is included...
if ($this->formName == "pageOne") {
$this->adData->addData('category', $_POST['category']);
$this->adData->addData('subcategory', $_POST['subcategory']);
} else if ($this->formName == "pageTwo") {
$this->adData->addData('ad_Website', $_POST['ad_Website']);
$this->adData->addData('ad_Patent', $_POST['ad_Patent']);
$this->adData->addData('ad_Address', $_POST['ad_Address']);
$this->adData->addData('email', $_POST['email']);
$this->adData->addData('hide_email', $_POST['hide_email']);
$this->adData->addData('ad_phone', $_POST['ad_phone']);
$this->adData->addData('ad_Protection', $_POST['ad_Protection']);
$this->adData->addData('ad_Number', $_POST['ad_Number']);
$this->adData->addData('ad_Country', $_POST['ad_Country']);
$this->adData->addData('ad_issuedate', $_POST['issuedate'] . '/' . $_POST['issuemonth'] . '/' . $_POST['issueyear']);
} else if ($this->formName == "pageThree") {
$this->adData->addData('name', $_POST['name']);
$this->adData->addData('ad_Background', $_POST['ad_Background']);
$this->adData->addData('ad_opeartion', $_POST['ad_operation']);
$this->adData->addData('ad_advlimit', $_POST['ad_advlimit']);
$this->adData->addData('ad_status', $_POST['ad_status']);
$this->adData->addData('ad_addinfo', $_POST['ad_addinfo']);
$this->adData->addData('ad_description', $_POST['ad_description']);
$this->adData->addData('tags', $_POST['tags']);
$this->adData->addData('videolink', $_POST['videolink']);
} else if ($this->formName == "pageFour") {
foreach($_POST['jos_photos'] as $photo) {
$this->photoData->addData(
array(
'title' => $photo['title'],
'url' => $photo['url'],
'ad_id' => $this->photoData->__get('ad_id'),
'userid' => $this->photoData->__get('userid')
)
);
}
}
Update
Strange: while the error itself hadn't been quite related to what the problem was, I found that it was simply an undefined field which I hadn't implemented.
Consider this thread solved. To those who replied, I certainly appreciate it regardless.
This should work. Are you sure you're doing the include from a non-static method that's part of the class (class A in your example)? Can you post the exact code you're using?
Edit: As general advice for problems like this, see if you can trim down the code so the problem is reproducible in a short, simple example that anyone could easily copy/paste to reproduce the exact error. The majority of the time, you'll figure out the answer yourself in the process of trying to simplify. And if you don't, it will make it much easier for others to help you debug.

Categories