Need help converting deprecated Function create_function() in PHP 7.2 - deprecated

Would anyone be able to update this deprecated piece of code for PHP 7.2. I have found many similar questions and answers, but can't figure out how to convert this particular piece of code.
array_walk($_REQUEST['categories'], create_function('&$c', '$c = "-" . $c;'));

You can use an anonymous function.
array_walk($_REQUEST['categories'], function(&$c) { $c = "-" . $c; });
Example
$array = ['a','b','c'];
array_walk($array, function(&$c) { $c = "-" . $c; });
print_r($array);
Will produce
Array
(
[0] => -a
[1] => -b
[2] => -c
)

Related

Error by read the file size PHP

I want to get the file size of an attachment of my wordpress post.
But when I run the site, I get this error ...
Can anyone help me?
"Warning: filesize(): stat failed for http://XXX.de/webdev/wp-content/uploads/2013/03/example.zip in C:\Users\XXX\Desktop\XAMPP\htdocs\webdev\wp-content\themes\web dev-theme\modul-page.php on line 27"
<?php
$a = filesize($img['url']);
echo$a;
?>
Thanks!
First check and see if the files/dirs are read/writeable.
I would do this inside of a file exist just for best practices. It is hard to determine what is wrong because you have not specified what line 27 is.
if ( file_exists($img['url']) ) {
$the_file_size = filesize($img['url']);
if ( $the_file_size >= 0 ) {
echo $the_file_size . ' bytes';
} else {
echo "File size could not be determined";
}
}

Install WordPress using bash shell without visiting /wp-admin/install.php?

I wrote this little BASH script that creates a folder,unzips Wordpress and creates a database for a site.
The final step is actually installing Wordpress, which usually involves pointing your browser to install.php and filling out a form in the GUI.
I want to do this from the BASH shell, but can't figure out how to invoke wp_install() and pass it the parameters it needs:
-admin_email
-admin_password
-weblog_title
-user_name
(line 85 in install.php)
Here's a similar question, but in python
#!/bin/bash
#ask for the site name
echo "Site Name:"
read name
# make site directory under splogs
mkdir /var/www/splogs/$name
dirname="/var/www/splogs/$name"
#import wordpress from dropbox
cp -r ~/Dropbox/Web/Resources/Wordpress/Core $dirname
cd $dirname
#unwrap the double wrap
mv Core/* ./
rm -r Core
mv wp-config-sample.php wp-config.php
sed -i 's/database_name_here/'$name'/g' ./wp-config.php
sed -i 's/username_here/root/g' ./wp-config.php
sed -i 's/password_here/mypassword/g' ./wp-config.php
cp -r ~/Dropbox/Web/Resources/Wordpress/Themes/responsive $dirname/wp-content/t$
cd $dirname
CMD="create database $name"
mysql -uroot -pmypass -e "$CMD"
How do I alter the script to automatically run the installer without the need to open a browser?
Check out wp-cli, based on Drush for Drupal.
wp core install --url=url --title=site-title [--admin_name=username] --admin_email=email --admin_password=password
All commands:
wp core [download|config|install|install_network|version|update|update_db]
wp db [create|drop|optimize|repair|connect|cli|query|export|import]
wp eval-file
wp eval
wp export [validate_arguments]
wp generate [posts|users]
wp home
wp option [add|update|delete|get]
wp plugin [activate|deactivate|toggle|path|update|uninstall|delete|status|install]
wp post-meta [get|delete|add|update]
wp post [create|update|delete]
wp theme [activate|path|delete|status|install|update]
wp transient [get|set|delete|type]
wp user-meta [get|delete|add|update]
wp user [list|delete|create|update]
I was having the same problem as you are. I tried Victor's method and it didn't quite work.
I made a few edits and it works now!
You have to add php tags inside of the script to make the code work, otherwise it just echoes to the terminal.
My script directly calls the wp_install function of upgrade.php, bypassing install.php completely (no edits to other files required).
I made my script named script.sh, made it executable, dropped it in the wp-admin directory, and ran it from the terminal.
#!/usr/bin/php
<?php
function get_args()
{
$args = array();
for ($i=1; $i<count($_SERVER['argv']); $i++)
{
$arg = $_SERVER['argv'][$i];
if ($arg{0} == '-' && $arg{1} != '-')
{
for ($j=1; $j < strlen($arg); $j++)
{
$key = $arg{$j};
$value = $_SERVER['argv'][$i+1]{0} != '-' ? preg_replace(array('/^["\']/', '/["\']$/'), '', $_SERVER['argv'][++$i]) : true;
$args[$key] = $value;
}
}
else
$args[] = $arg;
}
return $args;
}
// read commandline arguments
$opt = get_args();
define( 'WP_INSTALLING', true );
/** Load WordPress Bootstrap */
require_once( dirname( dirname( __FILE__ ) ) . '/wp-load.php' );
/** Load WordPress Administration Upgrade API */
require_once( dirname( __FILE__ ) . '/includes/upgrade.php' );
/** Load wpdb */
require_once(dirname(dirname(__FILE__)) . '/wp-includes/wp-db.php');
$result = wp_install($opt[0], $opt[1], $opt[2], false, '', $opt[3]);
?>
I called the file like this: # ./script.sh SiteName UserName email#address.com Password
Maybe you need to modify the Wordpress original installer a bit.
First, create a wrapper php CLI script, let's say its name is wrapper.sh:
#!/usr/bin/php -qC
function get_args()
{
$args = array();
for ($i=1; $i<count($_SERVER['argv']); $i++)
{
$arg = $_SERVER['argv'][$i];
if ($arg{0} == '-' && $arg{1} != '-')
{
for ($j=1; $j < strlen($arg); $j++)
{
$key = $arg{$j};
$value = $_SERVER['argv'][$i+1]{0} != '-' ? preg_replace(array('/^["\']/', '/["\']$/'), '', $_SERVER['argv'][++$i]) : true;
$args[$key] = $value;
}
}
else
$args[] = $arg;
}
return $args;
}
// read commandline arguments
$opt = get_args();
require "install.php";
This will allow you to invoke the script from the command line, and pass arguments to it directly into the $opt numeric array.
You can then pass the needed vars in a strict order you define, for instance:
./wrapper.sh <admin_email> <admin_password> <weblog_title> <user_name>
In the install.php you need to change the definition of the before mentioned vars, as it follows:
global $opt;
$admin_email = $opt[0];
$admin_password = $opt[1];
$weblog_title = $opt[2];
$user_name = $opt[3];
Then let the install script do its job.
This is an untested method, and also very open to any modifications you need. It's mainly a guideline for using a wrapper php/cli script to define the needed variable w/out having to send them via a HTTP REQUEST / query string. Maybe it's rather a weird way to get things done, so please, feel free to give any constructive/destructive feedback :-)
It's incredible how little discussion there is on this topic. I think it's awesome that WP-CLI was released and now acquired by Automattic, which should help to keep the project going long-term.
But relying on another dependency is not ideal, esp. when dealing with automated deployment...
This is what we came up with for SlickStack...
First, we save a MySQL "test" query and grep for e.g. wp_options as variables:
QUERY_PRODUCTION_WP_OPTIONS_EXIST=$(mysql --execute "SHOW TABLES FROM ${DB_NAME} WHERE Tables_in_${DB_NAME} LIKE '${DB_PREFIX}options';")
GREP_WP_OPTIONS_STRING_PRODUCTION=$(echo "${QUERY_PRODUCTION_WP_OPTIONS_EXIST}" | grep --no-messages "${DB_PREFIX}"options)
...doing it this way helps to avoid false positives like when queries/grep might spit out warnings etc.
And the if statement that will populate the WordPress database conditionally:
## populate database if wp_options not exists ##
if [[ -z "${GREP_WP_OPTIONS_STRING_PRODUCTION}" ]]; then
/usr/bin/php -qCr "include '/var/www/html/wp-admin/install.php'; wp_install('SlickStack', '\"${SFTP_USER}\"', '\"${SFTP_USER}\"#\"${SITE_DOMAIN_EXCLUDING_WWW}\"', 1, '', \"${SFTP_PASSWORD}\");"
fi
The -q keeps it quiet to avoid parsing conflicts and the -r tells it to execute the following code. I'm pretty sure we don't really need the -C flag here, but I added it anyways just in case.
Note: I had to play around with the if statement a few times, because the wp_install array is sensitive and I found that wrapping the password variable in single quotes resulted in a broken MD5 hash code, so if any issues try adding/removing quotation marks...

last n elements of an array

I'm trying to write a function that will print out the last 3 elements of $PWD, with a '...' beforehand if there are more than 3 elements.
e.g.
/home/nornagon/src --> ~/src
/home/nornagon/src/foo/bar/baz --> ...foo/bar/baz
This is my code so far, but $foo[-3,-1] doesn't work if the array has too few elements in it.
function custom_pwd() {
d=${PWD/#$HOME/\~}
d=(${(s:/:)d})
echo $d[-4,-1]
}
The zsh already has some nifty prompt processing available with print's -P option. This should do the trick:
custom_pwd() {
d=$(print -P '%3~')
case $d in
('~'*|/*) echo "$d";;
(*) echo "...$d"
esac
}
See man zshmisc, section "EXPANSION OF PROMPT SEQUENCES" for the gory details.
Here's what I came up with, though it's not terribly elegant:
function custom_pwd() {
local d slash
d=${PWD/#$HOME/\~}
case $d in
/*) slash=/ ;;
*) slash= ;;
esac
d=(${(s:/:)d})
d[1]=$slash$d[1]
num=$#d
ellipsis=
if (( num > 3 )); then num=3; ellipsis='…'; fi
echo $ellipsis${(j./.)d[-$num,-1]}
}

wordpress _e function

it shows"-- Debug: Undefined variable: wordscut on line 168 of /wp-content/theme"
function cutstr($string, $length) {
$string =strip_tags($string);
preg_match_all("/[x01-x7f]|[xc2-xdf][x80-xbf]|xe0[xa0-xbf][x80-xbf]|
[xe1-xef][x80-xbf][x80-xbf]|xf0[x90-xbf][x80-xbf][x80-xbf]|[xf1-xf7][x80-xbf][x80-xbf][x80-xbf]/", $string, $info);
for($i=0; $i<count($info[0]); $i++) {
$wordscut.= $info[0][$i];
$j= ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
if ($j > $length - 3) {
return $wordscut." ...";
}
}
return join('', $info[0]);
}
the above is my function. i know in php, it's right if a variable doesn't be declared before it is used.why it shows"Undefined variable: wordscut, j..... thank you.
2,* REQUIRED: Non-printable characters were found in the '''functions.php''' file. You may want to check this file for errors.
what is Non-printable characters .how to correct it? thank you.
This is one one classic bug.
When PHP started your script, $wordscut is not defined. When you run
$wordscut .= "sometext";
The code actually do
$wordscut = $wordscut . "sometext";
At this point, $wordscut is not available, thus Undefined Variable error occurred.
To fix it, add
$wordscut = '';
before
for($i=0; $i<count($info[0]); $i++) {

crontab report of what runs in a specified start and end datetime

Are there any tools or reports out there that given a crontab file can output which jobs run within a specified time-frame.
Our crontab file has become very large and our system administrators struggle to find out which jobs need to be rerun when we have scheduled downtime on the server. We're trying to figure out which jobs we need to run.
I was planning on writing my own script but wondering if there was something out there already
One thing you can do is:
Get Perl module Schedule::Cron
Modify it to sleep only optionally (create "fast-forward" mode and where it does sleep($sleep) change to do nothing when fast-forwarding. This will also require changing $now = time; call to do $now++.
Modify it to be able indicate start and end times for emulation.
Create a Perl one-liner which takes the output of crontab -l and converts it into similar contab but one which replaces command cmd1 arg1 arg2 with a perl subroutine sub { print "Execution: cmd1 arg1 arg2\n"}
Run the scheduler in the fast-forward mode, as indicated in the POD.
It will read in your modified crontab, and emulate the execution.
There is a fine and clean solution for a 'simulation mode' of Schedule::Cron (and for any other module using sleep,time,alarm internally without modifying Schedule::Cron itself. You can use Time::Mock for throtteling, e.g. with
perl -MTime::Mock=throttle,600 schedule.pl
one can speedup your 'time machine' by a factor 600 (so, instead of sleeping for 10 minutes it will only sleep a second). Please refer to the manpage of Time::Mock for more details.
For using a crontab file directly with Schedule::Cron you should be able to take the example from the README directly:
use Schedule::Cron;
my $cron = new Schedule::Cron(sub { system(shift) },
file => "/var/spool/crontab.perl");
$cron->run();
The trick here is to use a default dispatcher method which calls system() with the stored parameters. Please let me know, whether this will work for you or whether it will need to be fixed. Instead of system, you could use print as well, of course.
Here's a similar approach to DVK's but using Perl module Schedule::Cron::Events.
This is very much a "caveat user" posting - a starting point. Given this crontab file a_crontab.txt:
59 21 * * 1-5 ls >> $HOME/work/stack_overflow/cron_ls.txt
# A comment
18 09 * * 1-5 echo "wibble"
The below script cron.pl, run as follows, gives:
$ perl cron.pl a_crontab.txt "2009/11/09 00:00:00" "2009/11/12 00:00:00"
2009/11/09 09:18:00 "echo "wibble""
2009/11/09 21:59:00 "ls >> $HOME/work/stack_overflow/cron_ls.txt"
2009/11/10 09:18:00 "echo "wibble""
2009/11/10 21:59:00 "ls >> $HOME/work/stack_overflow/cron_ls.txt"
2009/11/11 09:18:00 "echo "wibble""
2009/11/11 21:59:00 "ls >> $HOME/work/stack_overflow/cron_ls.txt"
2009/11/12 09:18:00 "echo "wibble""
2009/11/12 21:59:00 "ls >> $HOME/work/stack_overflow/cron_ls.txt"
Prototype (!) script:
use strict;
use warnings;
use Schedule::Cron::Events;
my $crontab_file = shift || die "! Must provide crontab file name";
my $start_time = shift || die "! Must provide start time YYYY/MM/DD HH:MM:SS";
my $stop_time = shift || die "! Must provide stop time YYYY/MM/DD HH:MM:SS";
open my $fh, '<', $crontab_file or die "! Could not open file $crontab_file for reading: $!";
my $table = [];
while ( <$fh> ) {
next if /^\s*$/;
next if /^\s*#/;
chomp;
push #$table, new Schedule::Cron::Events( $_, Date => [ smhdmy_from_iso( $start_time ) ] );
}
close $fh;
my $events = [];
for my $cron ( #$table ) {
my $event_time = $stop_time;
while ( $event_time le $stop_time ) {
my ( $sec, $min, $hour, $day, $month, $year ) = $cron->nextEvent;
$event_time = sprintf q{%4d/%02d/%02d %02d:%02d:%02d}, 1900 + $year, 1 + $month, $day, $hour, $min, $sec;
push #$events, qq{$event_time "} . $cron->commandLine . q{"};
}
}
print join( qq{\n}, sort #$events ) . qq{\n};
sub smhdmy_from_iso {
my $input = shift;
my ( $y, $m, $d, $H, $M, $S ) = ( $input =~ m=(\d{4})/(\d\d)/(\d\d) (\d\d):(\d\d):(\d\d)= );
( $S, $M, $H, $d, --$m, $y - 1900 );
}
Hope you can adapt to your needs.

Resources