Show all my active WordPress plugins

ript>

Recently, I needed to get a list of every plugin that I’ve activated on all of my WordPress local-hosted blogs.
So, instead of going to every blog’s dashboard and noting down the list of every active plugin, I decided to write a quick (and dirty, i.e. not optimized) script.


<?php
// initialize variables [you have to change them to their proper values]
$dbhost = "localhost";
$dbuser = "dbuser";
$dbpass = "dbpassword";

// connect to MySQL and get all database names
$db = mysql_connect( $dbhost, $dbuser, $dbpass)
      or die( "MySQL connection problem: " . mysql_error());

mysql_set_charset( "utf8");
mysql_select_db( "information_schema", $db) or die( mysql_error());
$sql = "SELECT SCHEMA_NAME FROM SCHEMATA";
$u0 = mysql_query( $sql, $db) or die( mysql_error());
$alldb = array();
while ($u1 = mysql_fetch_row( $u0)) { $alldb[] = $u1[ 0]; }

// select each database found and check for active plugins
foreach( $alldb as $adb) {
    $conn = mysql_select_db( $adb, $db);

    // get *_options table name
    $sql = "SHOW TABLES FROM $adb LIKE '%_options'";
    $u0 = mysql_query( $sql, $db); // or continue;
    while ($u1 = mysql_fetch_row( $u0)) {
        if ($opt = $u1[0]) {
            // get active plugins list
            $sql = "SELECT * FROM $opt WHERE option_name='active_plugins'";
            $u00 = mysql_query( $sql, $db);
            if ($u01 = mysql_fetch_array( $u00)) {
                $apj = $u01[ 'option_value'];
                if ($apj) {
                    $ap = unserialize( $apj);
                    foreach( $ap as $apv)
                        echo "Database: $adb >>> $apvn";
                }
            }
        }
    }
}

mysql_close( $db);
?>

The output of this script is a list of all active plugins, one for each line, so it can be used in a shell script, for example one can find out how many of them are active:

php show_all_active_plugins.php | wc -l

or find out which blogs are using a certain plugin:

php show_all_active_plugins.php | grep akismet

Disclaimer: as usual, this script works for my setup and, for this reason, I'm sharing it here for everyone interested. I hope it will work for anyone else who tries it, but I cannot guarantee it for every possible situation.


Visit The Light of the LAMP blog for more…

PHP: print a calendar fast

Say you need to fill a file or a sheet of paper (if you print the output) with a range of consecutive dates (or dates with equal space between them). Then, the following PHP one-liner might be handy some day:

for ($i=1; $i<=365; $i++) echo date( “Y-m-d”, mktime( 0, 0, 0, 1, $i)). “\n”;

The above snippet prints each day of current year on its own line. If you want one day per week, then you can change accordingly the values of for-loop variable, for example:

for ($i=4; $i<=365; $i+=7) […]

 Or, for next year’s calendar:

for ($i=1; $i<=365; $i++) echo date( “Y-m-d”, mktime( 0, 0, 0, 1, $i, 1+date(“Y”))). “\n”;

Don’t forget to change 365 with 366 for a leap year.


Visit The Light of the LAMP blog for more…

Change photo extensions by content

Recently I had an interesting problem.  I had a lot of files in a directory, all photos, with their filenames messed up, especially their extensions.  So, in order to clear them and keep only the good ones, I had first to rename them in a more consistent manner (the JPEG photos ending with .jpeg, the PNGs with .png and so on).

I guess there is probably a plethora of appropriate tools, but I had no time to search in the chaotic internet, so I wrote a small PHP script (with a little help from the shell: command ‘file‘) and run it from the command line.

The script just parses the output of the file command and renames each file accordingly.

I’m putting this here, just in case it will be useful to someone else also:

#!/usr/bin/php
<?php

$res = array();
exec( "file *", $res);

foreach( $res as $f) {
list( $fn, $ft) = split( ':', $f);
if (strpos( $ft, "JPEG") !== false) {
rename( $fn, $fn .".jpeg");
} else if (strpos( $ft, "PNG") !== false) {
rename( $fn, $fn .".png");
} else
echo "cannot rename $fnn";
}
?>

I’m actually testing only for JPEG & PNG files since I know that I have only these two types.
Don’t forget to make this file executable if you want to run it from the command line.


Visit The Light of the LAMP blog for more…

Formatting human readable numbers with PHP

One of my former colleagues, Athanassios Bakalidis, in his latest blog post “Java: Formatting a Number Using a Custom Format“, has written about number formatting in Java language. This post made me think about the ways we ‘re using to print numbers from PHP to HTML output.

When we ‘re dealing with integers, usually it’s sufficient to add a

style=”text-align: right;”

to right-align the numbers in a column.

Floating point numbers, on the other hand, may require the use of number_format() function to properly format them, for example to have the same number of decimals (added to the obvious round(), floor() and ceil() functions).

But, what if I wanted to sort an array having two arithmetic columns?
Then, I’d use the sprintf() function to zero-pad numeric values, like this (certain sections are omitted):

$u0 = mysql_query( $sql, $db) or die( mysql_error());
$aa = array();
while ($u1 = mysql_fetch_row( $u0)) {
    $id = $u1[0];
    $c1 = $u1[1];
    $aa[$id] = number_format($u1[2]/$c1,4) .":". sprintf("%06d", $c1);
}
arsort( $aa); reset( $aa);
while (list($k, $v) = each($aa)) {
    list( $v1, $c1) = explode( ":", $v);
    $c1 = intval( $c1);
    $v1 = round( $v1, 2);
    [......]
}

With this technique, one can sort numeric values properly as numbers (although by internally converting them to strings).


Visit The Light of the LAMP blog for more…

Twit from PHP with cURL

There are cases you need to update a special Twitter feed to inform your visitors about something that has happened to your site. Then, this PHP function might be very useful if you add it in your functions arsenal:

/* inform twitter about something */
function twit( $msg = "")
{
 $username = "twitter-username";
 $password = "twitter-password";
 $ch = curl_init();
 curl_setopt( $ch, CURLOPT_URL, "http://twitter.com/statuses/update.xml");
 curl_setopt( $ch, CURLOPT_RETURNTRANSFER, TRUE); // change to FALSE for not reporting XML output
 curl_setopt( $ch, CURLOPT_POST, 1);
 curl_setopt( $ch, CURLOPT_POSTFIELDS, "status=" . urlencode( $msg));
 curl_setopt( $ch, CURLOPT_USERPWD, "$username:$password");
 ob_start();
 $response = curl_exec( $ch);
 ob_end_clean();
 curl_close( $ch);
 return $response;
}

As you can see, it only takes a string argument; the message you want to send. It returns also a string, which is either a true/false value or an XML-formatted response, depending on the value of CURLOPT_RETURNTRANSFER.

In order to use this function, you need to have installed the cURL extension of PHP. You can check if it’s installed quickly with the following command:

$ php -i | grep -i curl

If cURL is installed, you can expect an output like this:

additional .ini files parsed => /etc/php5/cli/conf.d/curl.ini,
curl
cURL support => enabled
cURL Information => libcurl/7.16.4 OpenSSL/0.9.8e zlib/1.2.3.3 libidn/1.0

If not, the package you need to install is php5-curl.


Visit The Light of the LAMP blog for more…

Command-line PHP

Working with the command-line version of PHP can be very enlightening some times. For example, consider the following situations:

  • Instead of having a test page with only phpinfo() in it, just to view PHP’s current settings, you can issue:

    php -i

  • Suppose you want to check your PHP code quickly for any errors. Executing

    php -l filename.php

    can easily reveal any pitfalls.

  • If you want to employ your code in a production environment, your don’t need any textual redundancies, so you can strip all the comments and whitespace by using

    php -w filename.php > ../production_directory/filename.php

  • Finally, suppose you’ve just added/enabled a new module and you want to know if you did everything correctly. Then

    php -m | grep “modulename”

    will answer this question.

For more information, read the manual page of php!

Of course, to be able to do all the above, you have to install the CLI of PHP. For a system that uses the apt-get family of scripts, this is as easy as running:

sudo apt-get install php5-cli

For other systems, I believe that commands like

yum install php5-cli

or

rpm -Uhv php5-cli

will work the same. Check your system’s documentation about the correct command and syntax.

Being able to run PHP scripts from the shell is a very powerful capability, especially if one doesn’t feel comfortable with shell scripts or other interpreted languages, such as PERL or Python.


Visit The Light of the LAMP blog for more…

PHP web-based resources

For a PHP programmer, I can recommend two web-based resources, full of useful information.

  • PHP Classes has a vast amount of useful PHP packages in source code with examples.
  • Chris Shiflett is a blogger who writes on advanced topics about PHP programming.

Both sites have RSS feeds and are updated frequently with new stuff.


Visit The Light of the LAMP blog for more…

PHP: function is_me()

A very useful function to determine first if the visitor is the developer or not and then act accordingly.

Code:

/* check if client is me */
function is_me()
{
$ip=$_SERVER["REMOTE_ADDR"];
$br=$_SERVER["HTTP_USER_AGENT"];
if (($ip=="127.0.0.1") and (strstr( $br, "Firefox")))
return true;
return false;
}

Explanation:
If the visitor’s IP is 127.0.0.1 (=localhost) and the browser is “Firefox” then the visitor is me!

Usage example:

if (is_me()) { error_reporting( E_ALL); } else { error_reporting( 0); }

With the above snippet, one developer can check for errors and warnings in a running system without the casual visitor noticing a thing. It is very easy also to view the web-page with another browser to check what the visitor actually sees.


Visit The Light of the LAMP blog for more…