wp functions not being recognized in cron job - php

Setting:
I have a wordpress site but disabled wp_cron to have the full control of cron.
define('DISABLE_WP_CRON', true);
In crontab -e, I have following cron job:
*/2 * * * * /usr/bin/php /var/www/cron/mycron.php init >> /var/log/error.log 2>&1
The mycron.php has a simple function
if (!empty($argv[1])) {
switch ($argv[1]){
case 'init':
cron_test();
break;
}
}
function cron_test() {
$time = date(DATE_RFC822, time());
write_log("Start:" . $time); //outputs debug to my own log file
};
function write_log($log){
if ( true === WP_DEBUG ) {
if ( is_array( $log ) || is_object( $log ) ) {
write_log( print_r( $log, true ) );
} else {
write_log( $log );
}
}
};
Note that I declared the mycron.php in functions.php for wp:
require_once('parts/mycron.php');
Error log:
In my error.log for the cron, I have the following error:
PHP Warning: Use of undefined constant WP_DEBUG - assumed 'WP_DEBUG'
So, I am guessing there is some sort of disconnection between cron and wp, which is my best guess.
What I am trying to do:
The mycron.php will have many wordpress functions that I would need. How do I make the cron to recognize the wp function such as WP_DEBUG?
Any help will be much appreciated.
Thanks!

You need to load Wordpress functions manually, to use them in a custom script.
require_once("../../../../wp-load.php");
Also answered in depth here,
How to include Wordpress functions in custom .php file?

Related

Error in WordPress with plugin reactpress

I'm using WordPress version 5.7.2 and when I upgrade it to php version 7.4.19 I get these errors:
Failed opening 'default' for inclusion (include_path='.:/usr/lib/php7.4') wp-includes/template-loader.php on line 106
Warning: include(default): failed to open stream: No such file or directory in /homepages/1/d229455270/htdocs/clickandbuilds/WordPress/DaseCMS/wp-includes/template-loader.php on line 106
This happens when I activate the plugin reactpress. This is the piece of code where the error occurs:
/**
* Filters the path of the current template before including it.
*
* #since 3.0.0
*
* #param string $template The path of the template to include.
*/
$template = apply_filters( 'template_include', $template );
if ( $template ) {
include $template; //Error in this line
} elseif ( current_user_can( 'switch_themes' ) ) {
$theme = wp_get_theme();
if ( $theme->errors() ) {
wp_die( $theme->errors() );
}
Why is this happening? How can I fix it? I see that is compatible with my WordPress version...
And with my php version...
Thank you in advance
Why is this happening?
Because there's a mistake in the Reactpress_Public::repr_change_page_template() method (see line 99 in wp-content/plugins/reactpress/public/class-reactpress-public.php) which is hooked onto template_include.
The author should check if the value of the _wp_page_template metadata (which stores the path of a custom page template) is not default (which is the default value) and only if so, then should the $template value be set to the metadata value.
And if one doesn't do that check, then we'd end up with include 'default' which then emits the error/warning in question ("Failed opening 'default' for inclusion").
How can I fix it?
Please contact the plugin support and ask them to fix the issue ASAP, but for the time being, you may just change the conditional here to: (* change the entire "if")
if (!empty($meta['_wp_page_template'][0]) && $meta['_wp_page_template'][0] != $template && // wrapped
'default' !== $meta['_wp_page_template'][0] // check if the value is NOT "default"
) {
$template = $meta['_wp_page_template'][0];
}
Yes, you shouldn't modify core plugin files; but this is a special case, because the plugin needs a fix, which hopefully will come in the plugin's next release.
Alternate solution without modifying the plugin files
.. is by overriding the template using the same hook:
// Add to the theme functions.php file:
add_filter( 'template_include', 'my_fix_template_include', 100 );
function my_fix_template_include( $template ) {
if ( 'default' === $template && is_page() ) { // * the plugin uses is_page()
$template = get_page_template();
}
return $template;
}

Async php function to backup database

I am using a PHP page to backup my database and it works just perfectly.
My problem (my future problem, Id better say) is that my cron job in my hosting allows working function only if a response is returned by 5 seconds, otherwise it fails.
My DB so far is quite small and I am not sure how much time it takes but surely less than 5 seconds since it is working.
But when my db will grow up, I reckon issues will start.
How can I make my function working also after 5 seconds?
With an async function will I solve?
hm, do you have shell access?
i made my index.php and its called master class to detect cli mode. like so:
if( php_sapi_name() === 'fpm-fcgi') {
define( 'WEB_MODE', true );
define( 'CLI_MODE', false );
} else if (php_sapi_name() === 'cli') {
define( 'WEB_MODE', false );
define( 'CLI_MODE', true );
} else {
define( 'WEB_MODE', true );
define( 'CLI_MODE', false );
}
then in my script which is executed by http request i do it like so:
$this->asyncShellExecution('/usr/bin/php ' . ROOT_PATH .'/php/index.php -m houseKeeping' );
private function asyncShellExecution(string $str)
{
exec($str . " > /dev/null 2>/dev/null &");
}
in cli mode i call new asyncHouseKeeping()
class asyncHouseKeeping
{
function __construct()
{
$args=getopt("m:t:i:o:l:s:f:");
if($args['m'] == 'houseKeeping') {
$this->doHouseKeeping();
} else {
exit;
}
}
}
that way i am getting the cpu and time critical image optimization process after uploading images by xhr out of the blocking code and it runs it stuff afterwards.

Load WordPress Environment with Plugins from CLI

I'd like to run a php script from cli which will access a WP plugin's class.
I've seen plenty ways of loading WP environment from cli, most common which I also use is
if( php_sapi_name() !== 'cli' ) {
die("Meant to be run from command line");
}
function find_wordpress_base_path() {
$dir = dirname(__FILE__);
do {
//it is possible to check for other files here
if( file_exists($dir."/wp-config.php") ) {
return $dir;
}
} while( $dir = realpath("$dir/..") );
return null;
}
define( 'BASE_PATH', find_wordpress_base_path()."/" );
define('WP_USE_THEMES', false);
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header;
require(BASE_PATH . 'wp-load.php');
However the above code will not load the plugins and if I try to access a plugin's class i get the error "Call to undefined method". I've also
tried running it from wp-cli using eval-file command, but again with no luck.
any ideas on how to load wordpress environment with plugins from cli ?

phpMyAdmin Fatal error: Call to undefined function __()

Server running RHEL 7 and PHP 5.4.16. When I try to open /phpMyAdmin in my browser, I'm given the error:
Fatal error: Call to undefined function __() in /usr/share/phpMyAdmin/libraries/core.lib.php on line 242
Call Stack
# Time Memory Function Location
1 0.0008 348000 {main}( ) ../index.php:0
2 0.0018 503144 require_once( '/usr/share/phpMyAdmin/libraries/common.inc.php' ) ../index.php:12
3 0.0252 4224464 PMA_Config->__construct( ) ../common.inc.php:304
4 0.0252 4224712 PMA_Config->load( ) ../Config.class.php:100
5 0.0265 4309888 PMA_Config->checkConfigSource( ) ../Config.class.php:849
6 0.0265 4311088 PMA_fatalError( ) ../Config.class.php:1169
I believe I've installed all required libraries and that apache has the proper permissions for the session.save_path directory, which were the issues previous times that this question had been asked. See: Call to undefined function __() error - phpMyAdmin
Can someone give me a hint based on that call stack?
Here are the functions from the lines that the stack trace references, with the relevant line written in the left margin:
core.lib.php at line 242:
/**
* displays the given error message on phpMyAdmin error page in foreign language,
* ends script execution and closes session
*
* loads language file if not loaded already
*
* #param string $error_message the error message or named error message
* #param string|array $message_args arguments applied to $error_message
* #param boolean $delete_session whether to delete session cookie
*
* #return void
*/
function PMA_fatalError(
$error_message, $message_args = null, $delete_session = true
) {
/* Use format string if applicable */
if (is_string($message_args)) {
$error_message = sprintf($error_message, $message_args);
} elseif (is_array($message_args)) {
$error_message = vsprintf($error_message, $message_args);
}
if ($GLOBALS['is_ajax_request']) {
$response = PMA_Response::getInstance();
$response->isSuccess(false);
$response->addJSON('message', PMA_Message::error($error_message));
} else {
$error_message = strtr($error_message, array('<br />' => '[br]'));
/* Load gettext for fatal errors */
if (!function_exists('__')) {
// It is possible that PMA_fatalError() is called before including
// vendor_config.php which defines GETTEXT_INC. See bug #4557
if (defined(GETTEXT_INC)) {
include_once GETTEXT_INC;
} else {
include_once './libraries/php-gettext/gettext.inc';
}
}
// these variables are used in the included file libraries/error.inc.php
242 $error_header = __('Error');
$lang = $GLOBALS['available_languages'][$GLOBALS['lang']][1];
$dir = $GLOBALS['text_dir'];
// on fatal errors it cannot hurt to always delete the current session
if ($delete_session
&& isset($GLOBALS['session_name'])
&& isset($_COOKIE[$GLOBALS['session_name']])
) {
$GLOBALS['PMA_Config']->removeCookie($GLOBALS['session_name']);
}
// Displays the error message
include './libraries/error.inc.php';
}
if (! defined('TESTSUITE')) {
exit;
}
}
common.inc.php at line 304:
304 $GLOBALS['PMA_Config'] = new PMA_Config(CONFIG_FILE);
if (!defined('PMA_MINIMUM_COMMON')) {
$GLOBALS['PMA_Config']->checkPmaAbsoluteUri();
}
Config.class.php at line 100:
/**
* constructor
*
* #param string $source source to read config from
*/
function __construct($source = null)
{
$this->settings = array();
// functions need to refresh in case of config file changed goes in
// PMA_Config::load()
100 $this->load($source);
// other settings, independent from config file, comes in
$this->checkSystem();
$this->isHttps();
$this->base_settings = $this->settings;
}
Config.class.php at line 849:
/**
* loads configuration from $source, usually the config file
* should be called on object creation
*
* #param string $source config file
*
* #return bool
*/
function load($source = null)
{
$this->loadDefaults();
if (null !== $source) {
$this->setSource($source);
}
/**
* We check and set the font size at this point, to make the font size
* selector work also for users without a config.inc.php
*/
$this->checkFontsize();
if (! $this->checkConfigSource()) {
849 return false;
}
Config.class.php at line 1169:
/**
* check config source
*
* #return boolean whether source is valid or not
*/
function checkConfigSource()
{
if (! $this->getSource()) {
// no configuration file set at all
return false;
}
if (! file_exists($this->getSource())) {
$this->source_mtime = 0;
return false;
}
if (! is_readable($this->getSource())) {
// manually check if file is readable
// might be bug #3059806 Supporting running from CIFS/Samba shares
$contents = false;
$handle = #fopen($this->getSource(), 'r');
if ($handle !== false) {
$contents = #fread($handle, 1); // reading 1 byte is enough to test
#fclose($handle);
}
if ($contents === false) {
$this->source_mtime = 0;
PMA_fatalError(
sprintf(
function_exists('__')
? __('Existing configuration file (%s) is not readable.')
: 'Existing configuration file (%s) is not readable.',
$this->getSource()
)
1169 );
return false;
}
}
return true;
}
The problem was the wrong permissions for the /etc/phpMyAdmin directory. The web server user, apache, had proper permissions for the session.save_path directory, but apache couldn't read from my config.inc.php file. Changing the owner of /etc/phpMyAdmin to the apache user and changing the permissions to 755 solved the problem.
Looking at the checkConfigSource() function in Config.class.php led me to believe that if the problem was with accessing the configuration file then I would have received the error 'Existing configuration file (%s) is not readable.' instead of Call to undefined function __() Does anyone know why that wasn't the case?
This was a pretty basic problem/solution, but unless someone suggests otherwise I think I'll leave it up since this exact problem/solution isn't addressed in other discussions of the Fatal error: Call to undefined function __() in /usr/share/phpMyAdmin/libraries/core.lib.php error when trying to start phpMyAdmin after installation.
Had the same Error message from phpMyAdmin ::
FastCGI sent in stderr: "PHP message: PHP Fatal error: Call to undefined function __() in /usr/share/phpMyAdmin/libraries/core.lib.php on line 245" while reading response header from upstream, client:
Solution that worked on my Fedora 22 server x86_64 using nginx :
changing the owner and the group identifier from root:apache on the file /var/lib/php/session
to root:nginx
using the command sudo chown -Rfv root:nginx /var/lib/php/session.
If phpmyadmin was working fine and then suddenly stops working for no reason with a bizarre and useless error message, you might try deleting your php sessions.
rm -rf /var/lib/php/sessions/*
The exact location may very depending on OS and version, and this will delete all active sessions, not just yours, but it can fix some "suddenly stopped working" issues when you haven't changed anything and it was working fine before.
For me it was different issue. I had given 777 permissions to phpMyAdmin forlder. When I changed it to 755, it worked fine.
Hope this will help someone.
Error "The connection was reset" File:
/usr/share/phpmyadmin/libraries/common.inc.php
search:
$GLOBALS['PMA_Config'] = new PMA_Config(CONFIG_FILE);<br>
replace with:
$GLOBALS['PMA_Config'] = new PMA_Config();

MediaWiki upgrade (1.19.6 to 1.22.2) breaks - fetchContent() error

Just upgraded Mediawiki 1.19.6 to the most current, 1.22.2.
Used update.php, which worked just fine. The front page loads, as do SOME of the articles if you enter their exact URL. However, following any of the links produces:
Catchable fatal error: Argument 1 passed to
ContentHandler::getContentText() must implement interface Content,
boolean given, called in <wiki path>/includes/Article.php on line 389
and defined in <wiki path>/includes/content/ContentHandler.php on line
95.
I've looked up the call to getContentText() in Article.php, and it's in a function called fetchContent(), with a comment about it being crufty and a note that the ContentHandler method within is deprecated.
I can't figure out how to fix what's gone wrong, and web searches are only turning up bug reports that are marked fixed... any ideas? Thanks very much.
getContentText() is depreciated.
Use WikiPage::getContent()
https://doc.wikimedia.org/mediawiki-core/master/php/html/classArticle.html#affd3b52d2544cc334d7805ae9e5aba98
We had the same problem. Our ICT guy handled it by adapting the Article.php file placed in the includes directory of your mediawiki. Only 1 function was adapted (line 377 function function fetchContent()). I do not know the exact working principle but the MediaWiki returned to normal.
Also I believe you need to run the mediawiki update routine by visiting:
'HostAdress'/MediaWiki/mw-config/
Original function in Article.php:
function fetchContent() { #BC cruft!
ContentHandler::deprecated( __METHOD__, '1.21' );
if ( $this->mContentLoaded && $this->mContent ) {
return $this->mContent;
}
wfProfileIn( __METHOD__ );
$content = $this->fetchContentObject();
// #todo Get rid of mContent everywhere!
$this->mContent = ContentHandler::getContentText( $content );
ContentHandler::runLegacyHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
wfProfileOut( __METHOD__ );
return $this->mContent;
}
New function in Article.php:
function fetchContent() { #BC cruft!
ContentHandler::deprecated( __METHOD__, '1.21' );
if ( $this->mContentLoaded && $this->mContent ) {
return $this->mContent;
}
wfProfileIn( __METHOD__ );
$content = $this->fetchContentObject();
if ( !$content ) {
wfProfileOut( __METHOD__ );
return false;
}
// #todo Get rid of mContent everywhere!
$this->mContent = ContentHandler::getContentText( $content );
ContentHandler::runLegacyHooks( 'ArticleAfterFetchContent', array( &$this, &$this->mContent ) );
wfProfileOut( __METHOD__ );
return $this->mContent;
}

Categories