My category order not working after WordPress upgrade

Description

You just upgraded WordPress and “My Category Order” (widget and functions) do not display any categories.
I hate to be you! But wait…

Solution

This is normal and you can fix it very easily by visiting the “My Category Order” page. When you visit the plugin page the first time after a WordPress upgrade, it will show this message:

File /home/advokata/public_html/wp-includes/taxonomy.php has been patched successfully

That’s it…

This is the solution Andrew (plugin author) pointed out by email after I commented on the “My Category Order” plugin page.

setAttribute/getAttribute(“style”) crossbrowser alternative

The JavaScript methods setAttribute and getAttribute are very handy when you are designing dynamic effects for your website, but those methods have a lot of bugs in IE (6 an 7 at least), I use these two crossbrowser functions as alternatives instead of using directly setAttribute() and getAttribute(), I’ve been using them for quite a long time and have had excellent results (crossbrowser compatibility):

/* setStyle function */
function setStyle(element, styleText){
	if(element.style.setAttribute)
		element.style.setAttribute("cssText", styleText );
	else
		element.setAttribute("style", styleText );
}
/* getStyle function */
function getStyle(element){
 	var styleText = element.getAttribute('style');
 	if(styleText == null)
		return "";
	if (typeof styleText == 'string') // !IE
		return styleText;
	else  // IE
		return styleText.cssText;
}

Now use the setStyle function whenever you need to change the style attribite of a HTML element

Demonstration

Roll over this trigger:

setStyle and getStyle Test (using border and padding)

Explanation

On the demonstration we define two style for the div, the default one and one that we will swith to once we “mouseover” the div.

<script type="text/javascript">
/* <![CDATA[ */
/* Test */
var my_element = document.getElementById("test_div");
var my_trigger = document.getElementById("trigger");
var initial_style = getStyle(my_element);
var alternative_style = "border:solid 6px green;padding:6px";
my_trigger.onmouseover = my_element.onload = function (){
	setStyle(my_element, alternative_style);
};
my_trigger.onmouseout = function (){
	setStyle(my_element, initial_style)
};
/* ]]> */
</script>
Roll over this <a id="trigger" href="#" onclick="return false;" >trigger</a>:
<div id="test_div" style="border:solid 2px green;padding:10px">
  setStyle and getStyle Test (using border and padding)
</div>

<div style="display:n

//

How to upgrade Ubuntu from 8.10 to 9.04 using the command line and the Internet?

You can upgrade your linux system using the package manager APT which is available on debian based distributions:

First we have to update all the packages installed:

$ sudo apt-get update
$ sudo apt-get upgrade

Now we make sure that we have the update-manager-core package installed with:

sudo apt-get install update-manager-core

Then we start the upgrade

sudo do-release-upgrade

How to check a file type efficiently in PHP?

The Problem

Do you know a method in PHP to check the type of an uploaded file
without relying on extension or Mime-type because these two can be faked?

Verifying the file type in PHP

Relying on the Mime-type of a file submitted by a user is a bad practice, using the extension is even worse!
Some people use functions of the php fileinfo extension, these functions do not rely on file extensions but do rely on bytes sections of the file that can be easily faked.

You can retrieve the mime type with finfo_file() like this:

<?php
$filename = "test.gif"

$finfo = finfo_open(FILEINFO_MIME_TYPE);
$file_mime_type = finfo_file($finfo, $filename);
finfo_close($finfo);

echo $file_mime_type; // Expected ouput: image/gif
?>

So you can use the php fileinfo functions to determine if the file is what it claims to be, I mean that the file extension matches the result of finfo_file(), if it doesn’t, there is no need to go further, the file should be rejected from being stored on your server and from beig served to your website visitors.

If the extension matches the MIME type we will have to go further and check if the files is really a GIF/JPEG/ZIP file or a fake file with malicious code.

For that we need to have a set of functions for the MIME types we are interested in, for images for example (TIFF, PNG, GIF, JPEG…), there is a good function that uses the identify linux command, modify it to suit your needs

<?php
function is_jpg($fullpathtoimage){
  exec("/usr/bin/identify -format %m $fullpathtoimage",$out);
  //using system() echos STDOUT automatically
  if(!empty($out)){
    //identify returns an empty result if the file is not an image
    if($out === 'JPEG')
      return true;
    return false;
  }
}
?>

Original code written by Ryan Day

Since I do not use file uploads, I can not provide functions for other file types, but I will search for them and edit my post if I find any.

There’s another solution that should work for all types but I’m not sure about it, it uses the linux file command:

<?php
function file_mime_type($fullpathtoimage){
 exec("/usr/bin/file -bi $fullpathtoimage",$out);
 $mime_type = array_shift(explode(';',$out[0]));
 return $mime_type;
}

// Test
print_r(file_mime_type(__FILE__)); // Outputs: text/x-c++ which is ok
?>

SMF mod: Add Posts Navigation

preview

Description and Features:

Enhance your website accessibility and add posts navigation arrows within posts to let you and your visitors navigate very easily between posts and pages:

  • Place top and down arrow within posts
  • Topmost arrow or downmost arrow take you to the previous or next page
  • No additional images loaded
  • No JavaScript
  • Unlike all other similar mods, this one is not broken when a post is deleted from the topic
  • Unlike all other similar mods, No useless arrows are shown (when there is no next or previous post or page)

Requirement(s):

Works on the default theme only

Demo:

See image

Download:

Link to download SMF mod: Add Posts Navigation

Print HTML code from JavaScript variable

This also was about to drive me crazy so I will not let it go without writing about it..

Let’s say you have some long HTML code contained on a PHP variable, something like this

<?php
$some_div = '
<div id="box">
  <h1>Title</h1>
  <p>Article contents + comments</p>
<div>';
?>

Now you want to use this HTML code as a JavaScript variable instead of printing it directly, you will tell me you’ll do this:

<script type="text/javascript">
/* <![CDATA[ */
  var some_div = '<?php echo $some_div; ?>';
/* ]]> */
</script>

JavaScript doesn’t like unescaped new lines and special characters (mainly “, <  and >) too much, so the previous code won’t work, my quick solution for that is to do the following:

  • Encode the html code in PHP using urlencode
  • Decode it within JavaScript

When using PHP’s urlencode function, all whitespace characters will be replaced by + signs, so we’d better deal with those characters before encoding them, otherwise, we won’t make a difference between spaces and real + signs, please read the comment on the PHP code below to understand:

<?php

// replace consecutive white space characters with a single space
$some_div_2 = preg_replace('/s+/',' ',$some_div);

// Explode (cut the string on the white space and put the resulting part on an array)
$some_div_2 = explode(' ', $some_div_2);

// Encode the text contained on the array cells
foreach($some_div_2 as $index => $content)
  $some_div_2[$index] = urlencode($content);

// Implode (reassemble) the array to a string again
$some_div_2 = implode(' ', $some_div_2);

?>

<script type="text/javascript">
/* <![CDATA[ */

  // Import the variable from PHP
  var some_div = <?php echo $some_div_2; ?>

  // Decode it
  some_div_2 = unescape(decodeURI(some_div));

  // Display it
  document.writeln(some_div_2);

/* ]]> */
</script>

A note on JavaScript arrays creation & initialization

I use PHP a lot in my projects and it happens that sometimes I combine PHP with another language and write completely useless code.

PHP arrays can be created and initialized with like this:

<?php
  $cities[] = "mecca";
  $cities[] = "medina";
?>

I thought that the same would apply to javascript… Yes, it can work, but only if the array already exists, otherwise you will get an error, Your browser will tell you that it can’t find that array, pretty simple… maybe…

var cities = []// we create the array first
  cities[0] = "mecca";
  cities[1] = "medina";

Note that JavaScript doesn’t automatically assign table indexes, you have to set them automatically. +1 for PHP (on most other languages)

Get file extension on PHP

There are many ways to retrieve files extension with PHP, but we will have to choose one that feets our needs and gives more reliable results.
When dealing with file extension you should know that a file extension is not always 3 characters long (ex:  foto.jpeg, index.html) and that it doesn’t start after the last dot (.) in the file name (ex: program.tar.gz, config.php.inc).

Let’s write the filename_details function that we will use to retrieve the extension of the file module.tar.bz or any file you have:

<?php
function filename_details($filename, $dots){
  $filename_no_ext = $filename;
  while($dots--){
    $temp_arr = explode('.', $filename_no_ext);
    $extension = '.'.array_pop($temp_arr).$extension;
    $filename_no_ext = implode('.', $temp_arr);
  }
  $extension = substr($extension, 1);
  return array($filename_no_ext, $extension);
}
print_r(filename_details('module.tar.bz',2));

/*
Output: 
Array
(
  [0] => module
  [1] => tar.bz
)
//*/

?>

Install PHP 5.2.6 on CentOs 5.x

Oddly enough, PHP 5.2.6 is still not available on the default CentOS repositories ([base], [updates], [addons], and [extras]), the latest PHP version available in those repos is PHP 5.1.6!

In order to install PHP 5.2.6 you can add the CentOS testing repository and enable it then install or update PHP.

To add the CentOS testing directory, create a file /etc/yum.repos.d/centos-test.repo and add this line:

[c5-testing]
name=CentOS-5 Testing
baseurl=http://dev.centos.org/centos/5/testing/$basearch/
enabled=1
gpgcheck=1
gpgkey=http://dev.centos.org/centos/RPM-GPG-KEY-CentOS-testing

Then install or update PHP:

[root@server ~]# yum install php

or

[root@server ~]# yum update php

Then you can disable the testing repo by editing the file and setting the option “enabled” to “0”

[c5-testing]
name=CentOS-5 Testing
baseurl=http://dev.centos.org/centos/5/testing/$basearch/
enabled=0
gpgcheck=1
gpgkey=http://dev.centos.org/centos/RPM-GPG-KEY-CentOS-testing

MySQL script files how-to

What is a MySQL script file?.. Why use it?

A MySQL script file (aka MySQL batch file) is a regular text file containing MySQL statements separeted by terminantors, statements in a MySQL script file can be run from the MySQL client, this is very useful, many PHP script available online come with MySQL script files that need to be run as part of the PHP script installation process, Continue reading “MySQL script files how-to”

How to read .chm files in Ubuntu

This tutorial assumes that you are a sudoer running Gnome

What is .chm

Wikipedia says:

Microsoft Compiled HTML Help is a proprietary format for online help files, developed by Microsoft and first released in 1997 as a successor to the Microsoft WinHelp format. It was first introduced with the release of Windows 98, and is still supported and distributed through Windows XP and Vista platforms.

Install Xchm

The default installation of Ubuntu doesn’t include any reader for CHM help files, but you can add one easily. Continue reading “How to read .chm files in Ubuntu”

Generate a negative random number using JavaScript

Maths

Ok, so you already know how to generate positive rondom numbers but let’s do it again:

To generate a random number varying from 0 to 9 we will use this code:

var randomN = Math.floor(Math.random()*10)

This expression on the right of the “=”

  1. produces a random number from 0 to 1 (excluding 1, say 0.917) with Math.random()
  2. multiplies it by 10 (9.71)
  3. removes decimals (9) with Math.floor

For negative values from -9 to 0 we will  simply subtract 9 from the previous result:

var negativeRandomN = Math.floor(Math.random()*10) - 9

Now what if you wanted a rondom integer from -10 to 20… ?
Yes you guessed it right! we will generate a random number from 0 to 30 then substact 10 from it

var randomN = Math.floor(Math.random()*31) - 10

So the rule is:
To generate a random integer from m to n, here is the code

var randomN = Math.floor(Math.random() * (n-m+1)) + m

Examples

# Random integer from 1 to 10
var randomN = Math.floor(Math.random() * 10) + 1

# Random integer from -100 to 100
var randomN = Math.floor(Math.random() * 201) -100

# Random integer from 0 to 255
var randomN = Math.floor(Math.random() * 256)