Joomla Call to a member function get() on null - php

I have very little php knowledge. I know I'm doing something wrong, but what?
I'm adding the sass compiler from Joomla Master Bootstrap template into my own Joomla template. It works, but not as it should. I can't turn it on or off in the backend.
The code in Masterbootstrap is this:
include 'includes/params.php';
if ($params->get('compile_sass', '0') === '1') {
require_once "includes/sass.php";
}
In my template I don't have params.php, but /functions/tpl-init.php. I added the variable $compile_sass there. My code looks like this:
require_once __DIR__ . '/functions/tpl-init.php';
if ($params->get('compile_sass', '0') === '1') {
require_once "includes/html/sass.php";
}
Doesn't work. I get the error: Call to a member function get() on null
So I changed this into:
require_once __DIR__ . '/functions/tpl-init.php';
require_once "includes/html/sass.php";
That works, but now the compiler is permanently on.
What should I do to correct this?

To get template params from outside the template you need to do this
Template parameters from outside a template
$app = JFactory::getApplication('site');
$temp = $app->getTemplate(true);
$param = $temp->params->get('compile_sass', '0');
Remember the Masterbootstrap template should be active.
To get any template param you need to do this
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query ->select('params')
->from('#__template_styles')
->where('`template` = ' . $db->q('masterbootstrap')) // Check Spelling of template
->where('client_id = 0'); // client_id = 0 for Site and client_id = 1 for Admin
$db->setQuery($query);
$params = json_decode($db->loadResult());
echo $params->compile_sass;
Better is to create a similar param in your own template using your templateDetails.xml file rather than depending on the external template.

I got help from a friend. He solved it in a minute. It's so simple... it usually is, after you found the solution:
require_once __DIR__ . '/functions/tpl-init.php';
if ($compile_sass === '1')
{
require_once "includes/html/sass.php";
}

Related

Error in php - Call to a member function get_results() on a non-object

I have wordpress blog and I have massive comments under some post. I found recently that some comments are duplicated two or three times. I want to use php code that removes duplicate elements from table wp_comments from mysql database of Wordpress (by opening php file on server). I used this code:
<?php
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
global $wpdb;
$comments = $wpdb->get_results("SELECT * FROM ".$wpdb->prefix."_comments"
." ORDER BY comment_post_ID, comment_content");
$prev = NULL;
foreach($comments as $comment) {
if ($prev && $prev->comment_content == $comment->comment_content
&& $prev->comment_post_ID == $comment->comment_post_ID ) {
$wpdb->query("DELETE FROM ".$wpdb->prefix."_comments WHERE comment_ID == ".$comment->comment_ID);
}
else
$prev = $comment;
}
?>
and I got this error:
*> Fatal error: Call to a member function get_results() on a non-object in .../commentsremoving.php on line 5*
UPDATE:
Thanks to Sheikh Heera I have now no error message, but my code doesn't work - no duplicated comments were deleted. Any ideas why?
Whenever you want to use WordPress' functionality outside of WordPress you can use
include_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php' );
Then you can use WordPress's functionality. Check This. If you want to just access the database functions then
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php' );
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-includes/wp-db.php' );
if (!$wpdb) {
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
} else {
global $wpdb;
}
Stick the following in your code after line 5. Does the script show any errors in the page now?
$wpdb->print_error();
My guess is you're not requiring the wp-load.php at the top of this file. To load up WordPress so you can use its global variables and functions, this file is required. Try putting this at the top of your file before the global variable:
require( '/path/to/wp-load.php' );

Undefined variable error on a variable inside an included file

I'm including this file to collect one of its variables. File path is correct and i don't get file include errors. But when i try to print a variable inside that file it gives undefined variable error. Following is the code.
include_once($path . "folder/file.php");
echo($code);
There is a php class. inside the class there is a login function . Within that function I'm including another file assume it's funtions.php.
functions.php has above code in it.
Inside functions.php file i include this file which contains the variable i'm looking for (assume it's test.php).
test.php looks like this (inside php tags)
$code="something";
$another_variable="something else";
so now like i said before when i include this inside functions.php and print $code it why does it gives an undefined error?
Full code
function log($user, $pass) {
global $config;
$this->get_available_accounts();
if (isset($this->Users_obj[$user])) {
if ($this->Users_obj[$user]->userName == $user && $this->Users_obj[$user]->passWord == $pass) {
delete_cache_full();
$_SESSION['username'] = $user;
$_SESSION['log'] = true;
$_SESSION['usergroup']=$this->Users_obj[$user]->level;
$this->set_permission_session($_SESSION['usergroup']);
include_once $config->path . 'config.php';
$newUpdate2=showUpdates2();
if(!empty($newUpdate2)){
$_SESSION['updateremindlater']=$newUpdate2['date'];
}
//file
include_once $config->path . 'functions.php';
$func = new UserFuncs();
$func->validate();
include_once $config->path . 'view/ViewDashboard.php';
return true;
}
}
thats the function im including this file into. include_once $config->$path . 'functions.php'; includes functions.php file
functions.php looks like this
include_once($path. "folder/config.php");
echo($code);
and config.php looks like
$code = "ERGERW2342HV3453WERWEER";
$host_name = "SERV345WERFDGDDFGDGF";
$return_code = "DFGDFSDGFS";
$vurl = "YUIYUJHGJ";
$next_val ="AWERFDFVDV";
$val_exp = "NMGHJGJGH";
Help much appreciated!
Just guessing that you've included config.php somewhere else before, and that it's not being included again due to include_once. Therefore the variables are not created in the scope you're including it in the second time.
This could be a problem with variable scope, where you are trying t access the variable from somewhere (e.g. a function) where it is not available to that particular object (you did mention that you included the file within a class).
I agree with deceze and hakre, it's very hard to answer this question without seeing your code.

Manual wp_install() difficulties

I am trying to automatically install a WordPress distribution in PHP with the following code:
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
When I manually run wp_install() [/wp-admin/includes/upgrade.php], I get this error:
Fatal error: Call to a member function flush_rules() on a non object in /home/username/public_html/wp-admin/includes/upgrade.php on line 85
After looking at the WordPress source code, it appears that $wp_rewrite is trying to call flush_rules() when $wp_rewrite itself doesn't exist.
Another strange twist is that this is virtually the same code as wordpress-cli-installer. My wp-config.php file is automatically generated and ready.
How come wordpress-cli-installer's code works but mine does not?
EDIT:
After a lot of trial and error, I found out that my code was not working because it was defined and executed in a function. After I separated the code from the function and executed it, it worked. However, that raises another question. Is it even possible to execute the above code inside of a function? I have tried using the $GLOBALS += get_defined_vars(); hack after the require_once statements, but that doesn't seem to do anything. In other words:
<?php
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
// ^ This works.
// v This won't work.
function run(){
$base_dir = '/home/username/wordpress_location';
chdir($base_dir);
define('WP_SITEURL', 'http://www.domain.com/');
define('WP_INSTALLING', true);
require_once 'wp-load.php';
require_once 'wp-admin/includes/upgrade.php';
require_once 'wp-includes/wp-db.php';
$result = wp_install($title, $username, $email, true, null, $password);
}
run();
?>
How do I use the require_once inside of a function while still being able to access and manage the globals?
That idea is wrong in general. You can make global only required variables (which might change from version to version). But the 'dirty' way is
function make_global()
{
$test_var = "I'm local";
$GLOBALS += get_defined_vars();
}
var_dump(isset($test_var));
make_global();
var_dump(isset($test_var));

Getting WordPress database name/username/password with PHP

I'm writing a WordPress plug-in and need to read the database name, username, and password (In order to do a sql dump). Is this possible?
Thanks-
Yes, they are defined in wp-config.php
Database Name: DB_NAME
Database User: DB_USER
Database password: DB_PASSWORD
Database Host: DB_HOST
They are define. See you wp-config.php in the root directory of Wordpress
Wordpress has some fairly goofy stuff going on throughout its OO code, this isn't the first one I've encountered as we dig deeper into the internals with each successive project at Moxune. See WP_User::__set doesn't persist custom fields as it claims.
The goofiness I refer to here of course is that something like the table prefix, aka wpdb::prefix is a public member variable, however things like dbname, dbpassword, and dbhost are protected and there are no public accessor methods.
I'm sure one of the Wordpress core devs will try to argue some rationale for it, but in the meantime may as well use some good 'ol OO to cope. My suggestion, a decorator.
class SaneDb
{
private $_oDb;
public function __construct(wpdb $oDb)
{
$this->_oDb = $oDb;
}
public function __get($sField)
{
if($sField != '_oDb')
return $this->_oDb->$sField;
}
public function __set($sField, $mValue)
{
if($sField != '_oDb')
$this->_oDb->$sField = $mValue;
}
public function __call($sMethod, array $aArgs)
{
return call_user_func_array(array($this->_oDb, $sMethod), $aArgs);
}
public function getDbName() { return $this->_oDb->dbname; }
public function getDbPass() { return $this->_oDb->dbpassword; }
public function getDbHost() { return $this->_oDb->dbhost; }
}
Then atop your plugin code (functions.php) setup a global in similar vein to wpdb.
global $sanedb;
$sanedb = new SaneDb($wpdb);
From there, just use $sanedb within your plugin instead of $wpdb.
Lastly, getting ahold of the database name et al.
$sanedb->getDbName();
This is super simple now. You can create a PHP file and use the following code.
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-config.php';
include_once $path . '/wp-load.php';
include_once $path . '/wp-includes/wp-db.php';
include_once $path . '/wp-includes/pluggable.php';
// We need the WordPress Database Credentials
global $wpdb;
$user = $wpdb->dbuser;
$pass = $wpdb->dbpassword;
$name = $wpdb->dbname;
If you need other data just do a print_r on the wpdb variable and you'll see everything inside of there.

How to call WordPress functions in a custom PHP script

I have a PHP script I want to use for creating a new blog in WPMU. I am having trouble calling WordPress functions like wpmu_create_user and wpmu_create_blog.
My hope is to get this script running as a cron job from the command line and pick up new blog creation requests from an external db, create a new blog using the WordPress functions and update the database with the new blog information.
include wp-load.php file (in the root of your wordpress installation) in your php script file like so,
require_once("/path/to/wordpress/wp-load.php");
you will have to provide the abspath of the wp-load file,
now you can use all the functions of wordpress in your php script
I've got a universal solution that will work in any PHP file inside the wp-content folder without any adjustments or needing to know what is mysterious 'path/to/wordpress'
require_once(explode("wp-content", __FILE__)[0] . "wp-load.php");
It just automatically goes up to root of WordPress and loads wp-load.php.
You can just paste it anywhere, no matter if it's a plugin or theme file, and it will work.
I think stuff like ../../../.. looks extremely bad and when you modify the structure of your folders of a theme or plugin you can get crazy.
Note: This solution assumes you didn't rename your wp-content folder.
For wordpress 3.1, I had to specify the host/domain because wp-includes/ms-settings.php:100 needs it or it dies. So my script looks something like (note I am using it for a network/multiblog site):
#!/usr/bin/php -q
<?php
#for multi-blog only
$blog_id = 1;
#specify host or domain (needed for wp-includes/ms-settings.php:100)
$_SERVER[ 'HTTP_HOST' ] = 'localhost';
#location of wp-load.php so we have access to database and $wpdb object
$wp_load_loc = "/path/to/wordpress/wp-load.php";
require_once($wp_load_loc);
#for multi-blog only
switch_to_blog($blog_id);
#test to make sure we can access database
echo $wpdb->prefix;
?>
This should work:
require_once($_SERVER['DOCUMENT_ROOT'].'/wp-load.php');
i.e. When the php script is on the same server and WP is installed on the root. As most cases are.
Following is the code I am using:
<?PHP
require_once ('/path/to/wordpress/wp-load.php');
require_once ('/path/to/wordpress/wp-blog-header.php');
require_once ('/path/to/wordpress/wp-includes/registration.php');
do_action('wpmuadminedit', '');
//Code to Connect and Select the external database
//Code to Connect to the external DB and get the new order details:
NewBlogName=$name and AdminEmail=$email
if ( !email_exists($email) )
{
// email does exist, create a new user
$name = create_name_from_email($email);
$password = "use a default password";
$user_id=wpmu_create_user($name, $password, $email);
create_blog($email, $title, $user_id, $password);
}
else
{
// user exists, create new blog
$user_id=email_exists($email);
$password = "use existing wordpress password";
create_blog($email, $title, $user_id, $password);
}
function create_name_from_email ($email) {
preg_match('/[^#]+)#/',$email,$matches);
$name = $matches[1];
return $name;
}
//Creates a new blog, expects user to already exist.
function create_blog($email, $title, $user_id, $password)
{
//Code to Update external DB that the order is in process
$public = array("public" => 1);
if (constant('VHOST') == 'yes')
{
$newdomain = $domain . "." . $current_site->domain;
$path = $base;
}
else
{
$newdomain = $current_site->domain; $path = $base . $domain . '/';
}
$domain = strtolower($domain);
$newdomain = strtolower($newdomain);
$path = strtolower($path);
$meta = apply_filters('signup_create_blog_meta', array('lang_id' => 1, $public));
$meta = apply_filters("add_singup_meta", $meta);
wpmu_create_blog($newdomain, $path, $title, $user_id , $meta, $current_site->id);
do_action('wpmu_activate_blog', $blog_id, $user_id, $password, $title, $meta);
// Update external DB with BlogUrl, NewBlogName, AdminPassword,
OrderStatus=Complete.
mysql_close($con);
?>
require_once('../../../wp-load.php');
I think you have to add this line before any usage of wordpress function in your custom file. and make sure i have add ../ 3 times as per my wordpress installation structure.It's depends on your structure checks manually.
ex. if your custom file is inside your themes/yourtheme/custom.php then above code will works perfectly and if not then add ../ or remove one or more ../ as per your path.
WordPress uses a phpass function.
This worked for me as I had a password, and the hash in a table (migrated WordPress users) and had to find a way to check login details.
Grab this download here - https://github.com/sunnysingh/phpass-starter
All you need is this basic function to check a text password to a WordPress hash:
<?php
require_once("PasswordHash.php");
$hasher = new PasswordHash(8, false);
// Check that the password is correct
$check = $hasher->CheckPassword($password, $stored_hash);
if ($check) {
// Password good
} else {
// Password wrong
}
?>
All credits to Sunny Singh!

Categories