Installing git on CentOS 6.4 with cPanel

So, I ran into an issue installing git on a box that had CentOS 6.4 on it… I kept pulling out my hair… Turns out…

Per http://serverfault.com/questions/337399/cant-install-git-on-a-centos-6-0-x64 — to install git on a machine with CentOS 6.4 and cPanel you can install git using:

yum install git --disableexcludes=main --skip-broken

Have fun out there!


Getting the Taxonomy and Term from within archive.php

This one just takes advantage of get_query_var, see below:

$taxonomy_name = get_taxonomy( get_query_var( 'taxonomy' ) )->labels->name;
$term_name = get_term_by( 'slug',$term, get_query_var('taxonomy') )->name;


Use archive.php as the search results page

This one is easy too…
add_action( 'template_redirect', function(){
if (is_search()) {
include("archive.php");
die();
}
});

It’s important to note this uses an anonymous function which requires PHP 5.3+.


Automatically Include All Class Files in Subdirectory (e.g. inc/ or class/)

Easy as pie!

Here’s an example to include all PHP files in a subdirectory named class.

N.B. Make sure you are one level below the class folder.

 

foreach (glob(plugin_dir_path(__FILE__) . "class/*.php") as $filename) include $filename;

Ignoring Files Locally in Git

I wanted to keep some WordPress plugins on my local installation of WordPress that did not end up on my live server: mostly debugging tools (for example: 1, 2 and 3). I could have essentially added them to git ignore, but that would get pushed upstream, so I essentially needed to locally exclude these files/directories. Luckily there’s a fairly painless way to do so on a local machine (this is written from the vantage of a Linux terminal):

  1. cd into your .git directory typically resides your base directory (note dotfiles may be hidden).
  2. From your .git directory cd into the info directory.
  3. Use the text editor of your choosing to edit the file “exclude” in the info directory.
  4. Add the specific paths that you wish to exclude.
  5. Here’s what my exclude file looks like for the aforelinked plugins to be excluded:
# git ls-files --others --exclude-from=.git/info/exclude
# Lines that start with '#' are comments.
# For a project mostly in C, the following would be a good set of
# exclude patterns (uncomment them if you want to use them):
# *.[oa]
# *~
plugins/debug-bar
plugins/debug-objects
plugins/debug-queries

 

 

 


Permenant Alias in OS X Terminal

I use MAMP on my local as part of my development environment. When dropping to terminal to perform an action (e.g. git commit/checkout/etc.) I was getting tired of manually changing my directory to the default MAMP root (cd /Applications/MAMP/htdocs/wp-content) so I figured that I’d add an alias using the following:

echo 'alias mamp="cd /Applications/MAMP/htdocs/wp-content"' >> ~/.bashrc && source ~/.bashrc

This seemed to work but much to my chagrin the next time I rebooted or opened a new terminal the alias appeared to be gone, bringing me back to step one. I finally figured out how to get this to work permanently …

  1. issue nano ~/.bash_profile to edit your bash profile
  2. add in alias mamp="cd /Applications/MAMP/htdocs/wp-content" and close and save

voila!


Simple Add a Class to the Body Tag in WordPress

This is something that is extremely easy once you realize that the hook body_class exists. It is important to pass an variable argument (it can be anything, just has to be there), the hook will pass the current array of classes to that argument. Simple usage of this hook is as follows:

function add_body_class ($classes) {
    $classes[] = 'myclass';
    return $classes;
}

add_filter('body_class', 'add_body_class');

What this does is add the class “myclass” to the <body> class.

Here’s an example of adding a specific class to the homepage, add this to your functions.php (for a theme) or your plugin functions page (for a plugin):

function add_home_class ($classes) {
   if (is_home()) $classes[] = 'myclass';
    return $classes;
}

add_filter('body_class', 'add_home_class');

This can be adapted in any way shape or form, just change the logic in the if statement that wraps around the filter.

Have fun!


Set up LAMP Environment and WordPress

What Are We Doing?

It’s best to start with a fresh Linux install. For this guide I am using RHEL (RedHat Enterprise Linux) as my distro and YUM (short for, Yellowdog Updater, Modified) as my package manager. YMMV depending on the distro you use, but it should be fairly similar. After we install the packages from the RPM (RPM Package Manager) we will install phpMyAdmin and WordPress. Lastly we’ll do some Apache Tuning (which will be detailed in a separate article).

YUM Package Installation

From the Linux command prompt, sudo to root and issue the following installation commands:

yum install httpd
yum install php
yum install mysql
yum install mysql-server
yum install php-mysql
yum install mysql-devel

The reason I did not combine them into one command (i.e. yum install httpd, php, mysql…) is, for a novice, you can spot errors easier in installations this way. If you wish to save time feel free to do so. You should add a directory to your machine and make a quick update to httpd.conf, especially if you plan on serving multiple sites, make sure you sudo to root before doing the following:

  • Navigate to /var/www/ and issue “mkdir sites”
  • Navigate to /var/www/sites/ and issue “mkdir myapp” (fill out whatever you want, I will use myapp for this article.
  • Edit httpd configuration file with nano by issuing “nano /etc/httpd/conf/httpd.conf” (feel free to use vi)
  • In httpd.conf update any references to DocumentRoot to our new DocumentRoot (DocumentRoot “/var/www/sites/myapp”)
Once you have updated httpd.conf let’s restart httpd by issuing “service httpd restart” at the command prompt.

We still need to install phpMyAdmin and WordPress, which is explained below.

Set up MySQL

Run the following command (assuming mysql installed to /usr/bin which it should have):

/usr/bin/mysql_secure_installation

Follow the instructions to a tee. Some advice, though if you have an operations team to consult with, run these through them for optimal setup:

  • set root password to something very secure and make sure to write it down and only share with those who need it
  • do not allow “anonymous user”
  • disallow root login remotely (especially if production!!)
  • remove test database (especially if production!!)
  • reload the privileges table

phpMyAdmin

Install phpMyAdmin

  • Go to phpmyadmin.net and get the URL for the latest phpMyAdmin tarball. At the time of this writing the URL is http://sourceforge.net/projects/phpmyadmin/files/phpMyAdmin/3.5.1/phpMyAdmin-3.5.1-all-languages.tar.gz
  • Navigate to myapp (/var/www/sites/myapp) and issue “wget URL_TO_TARBALL”
  • Issue “tar -zxvf phpMyAdmin_TAR_FILE”
  • For sanity sake rename the newly created “phpMyAdmin_TAR_FILE/” directory to phpmyadmin by issuing: “mv phpMyAdmin_TAR_FILE/ phpmyadmin”
  • Delete the tar file.

Configure phpMyAdmin

Let’s create a config file for phpMyAdmin.

  • Navigate to /phpmyadmin directory and issue:
    • mkdir config
    • chmod o+rw config
  • Navigate in a web browser to http://IPADDRESS/phpmyadmin/setup and follow all of the steps (make sure to set a blowfish password, located under Features/Security)
  • Make sure to click “Save” or config file will not be generated.
  • Once completed issue the following commands from the phpmyadmin directory:
    • mv config/config.inc.php .   (Note the “.”)
    • chmod o-rw config.inc.php
    • rm -rf config

Create PMA User to Admin PMA (phpMyAdmin)

  • issue “mysql -u root -p < /path/to/phpmyadmin/examples/create_tables.sql” (e.g. “mysql -u root -p < /var/www/html/phpmyadmin/examples/create_tables.sql”
  • enter the password for root
  • this will create a user pma user
  • navigate back to the phpmyadmin path and issue the following command “mysql -u root -p”
    • Enter in root’s password
    • This will log you into mysql as root at the “mysql>” prompt paste the following (replace PMAPASSWORD with something secure):
      GRANT USAGE ON mysql.* TO 'pma'@'localhost' IDENTIFIED BY 'PMAPASSWORD';
      GRANT SELECT (
      Host, User, Select_priv, Insert_priv, Update_priv, Delete_priv,
      Create_priv, Drop_priv, Reload_priv, Shutdown_priv, Process_priv,
      File_priv, Grant_priv, References_priv, Index_priv, Alter_priv,
      Show_db_priv, Super_priv, Create_tmp_table_priv, Lock_tables_priv,
      Execute_priv, Repl_slave_priv, Repl_client_priv
      ) ON mysql.user TO 'pma'@'localhost';
      GRANT SELECT ON mysql.db TO 'pma'@'localhost';
      GRANT SELECT ON mysql.host TO 'pma'@'localhost';
      GRANT SELECT (Host, Db, User, Table_name, Table_priv, Column_priv)
      ON mysql.tables_priv TO 'pma'@'localhost';
  • navigate back to the phpmyadmin directory (you might already be there)
  • issue “ls config*.php”
  • if “config.inc.php” does not exist but “config.sample.inc.php” does issue the following command “cp config.sample.inc.php config.inc.php”
  • issue the following commands:
  • “chmod 777 config.inc.php”
  • “nano config.inc.php”
  • in the editor make sure to uncomment out all lines similar to:
    // $cfg['Servers'][$i]['controluser'] = 'pma';
    // $cfg['Servers'][$i]['controlpass'] = 'pmapass';
    // $cfg['Servers'][$i]['pmadb'] = 'phpmyadmin';
    // $cfg['Servers'][$i]['bookmarktable'] = 'pma_bookmark';
    // $cfg['Servers'][$i]['relation'] = 'pma_relation';
    // $cfg['Servers'][$i]['table_info'] = 'pma_table_info';
    // $cfg['Servers'][$i]['table_coords'] = 'pma_table_coords';
    // $cfg['Servers'][$i]['pdf_pages'] = 'pma_pdf_pages';
    // $cfg['Servers'][$i]['column_info'] = 'pma_column_info';
    // $cfg['Servers'][$i]['history'] = 'pma_history';
    // $cfg['Servers'][$i]['tracking'] = 'pma_tracking';
    // $cfg['Servers'][$i]['designer_coords'] = 'pma_designer_coords';
    // $cfg['Servers'][$i]['userconfig'] = 'pma_userconfig';
    // $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';
  • save and exit
  • issue “chmod 555 config.inc.php”
  • IMPORTANT – go to your web browser and clear your browser’s cache
  • Navigate to the phpMyAdmin URL
  • Log in with root and root’s password
  • You should not see any errors on the bottom of phpmyadmin’s home screen

Create a Database for WordPress

  • Log into phpMyAdmin
  • Click “Privileges” and then on the Privileges screen click “Add a New User”
  • Fill out all of the information, this will be the WordPress database. Set a username such as “myapp”, have phpMyAdmin generate a password, set “localhost” as the host. Make sure to note the database name/username and password. (Database name and username should be the same thing)
  • Select “Create database with the same name and grant all privileges.”
  • Click “Create User”

WordPress

  • Navigate to your web application’s directory (e.g. /var/www/sites/myapp)
  • Issue “wget http://wordpress.org/latest.tar.gz” (verbatim)
  • Issue “tar -xzvf latest.tar.gz”
  • Issue “mv wordpress/ .”
  • Fire up your web browser and navigate to http://YOUR_IP/
  • Fill out the information including the database, username and password created in the last section
  • All done :) Pat yourself on the back!

Some Notes:

  • Remove phpMyAdmin on production sites for security sake
  • Use secure passwords!
  • Note the passwords somewhere safe, in case you forget them
  • Leave me a comment if you have any questions! Thanks!

Casting a string to boolean in PHP

So it’s been some time, but I finally came across an issue that I have faced, which hopefully means you have too. Either way this will serve as a great reference for myself, since I come across this on a semi-regular basis.

So say you are given data in the type of String, either from some sort of XML, JSON, or from user input that you need to convert to boolean. Using some quick logic you would think it was as easy as:

<?php
$string="false";
$string_boolean=(bool)$string;

right? Let’s try this one out:

<?php
$string="false";
$string_boolean=(bool)$string;
// note: you could use (bool) or (boolean) they do the same thing.
if ($string_boolean) {
    echo $string . " is true";
} else {
    echo $string . " is false";
}

If we run this script it returns, almost comically:

false is true

So what can we do here? Give up and change our career? Maybe. But let’s first do 2 things and then rethink our career-change:

  1. Why does this happen?
  2. What can we do about it?

Let’s examine PHP.net’s documentation regarding casting booleans.

From PHP.net:

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. 
However, in most cases the cast is unnecessary, since a value will be 
automatically converted if an operator, function or control structure requires 
a boolean argument.

When converting to boolean, the following values are considered FALSE:

   -    the boolean FALSE itself
   -    the integer 0 (zero)
   -    the float 0.0 (zero)
   -    the empty string, and the string "0"
   -    an array with zero elements
   -    an object with zero member variables (PHP 4 only)
   -    the special type NULL (including unset variables)
   -    SimpleXML objects created from empty tags

Every other value is considered TRUE (including any resource).

So, since both the string “true” and the string “false” do not meet any of the bullets, it will evaluate to true. OK, makes sense (sort of). So what are we to do now? Well we can create a function to mitigate our scenario. The function can be called string_boolean and what it can do is evaluate a string and if it’s value is “false” return false, otherwise return true. There is one gotchas that we need to mitigate, well it’s actually two: we need to treat “TRUE” , “TRue” ” TRUE”, ” True “, “    TRUE”, etc. all as true and likewise we need to treat “FALSE”, “FALSe”, “FALSE  “, “False”, etc. all the same. We can make use of our two good function friends mb_strtoupper  (technically we could also use strtoupper) and trim.

So, let’s talk our way through this function. It’s signature would be function string_boolean ($string) and it’s body would basically clean up $string and evaluate it against the actual word “true” – if it equals true return TRUE (the boolean) otherwise return FALSE. This puts the onus on false, think of this as analogous to the concept of innocent until proven guilty. The value is false until it is proven in a trial (i.e. the function we create) to be true. This is a safer way to handle this in my estimation. We could use an if … then scheme, but I’d rather use our good old friend the ternary for the sake of brevity.

Let’s construct this baby (note I am purposely making this longer than it needs to be, for education’s sake. Don’t believe me, I’ll write the function’s body in one line before I’m done, that’ll teach you to go against me (just kidding)!):

function string_boolean($string){
	$string      = trim($string); // let's make sure we get rid of any junk whitespace surrounding our input.
	$string      = mb_strtoupper($string); // let's convert our input to uppercase, which will make our comparison easier.
	$true_string = mb_strtoupper("TRUE"); // just because I'm paranoid;
	return $string === $true_string ? TRUE : FALSE; //if processed input equals "TRUE" return true otherwise return false.
}

One quick note: I use === instead of == to be strict in my comparison. Since PHP is a weak typed language the === is a way to enforce testing both the TYPE and VALUE of $string. That is, === checks if the value of $string is equal to “TRUE” AND that both $string and “TRUE” are the same type (string). Hope that makes some semblance of sense.

Here is the function in one line!

function string_boolean($string){
	return ( mb_strtoupper( trim( $string)) === mb_strtoupper ("true")) ? TRUE : FALSE;
}

Enjoy!


WordPress Power Tools

Just a quick note announcing that I have created documentation for WordPress Power Tools for the latest version (1.3.1) which can be found here.

Remember you can download WordPress Power Tools from the WordPress directory plugin here or by searching “WordPress Power Tools” in the plugin repository.