2011/11/17

How to install GD Extension on EC2

If you're using Amazon EC2 with Amazon Linux AMI, you my find GD Extension is not installed by default. The following are steps to get it installed.
  • check if PHP GD is installed or not by 'rpm -qa | grep php', if you see 'php-gd-5.3.8-3.20.amzn1.i686" or similar, then you are fine and can stop here.
  • If not, then run command, 'sudo yum install php-gd'
  • And restrat apache by 'sudo /etc/init.d/httpd restart'
  • Cheer!

2011/11/07

Set Magic Quotes Runtime is deprecated

I see a lot of error in logs regarding set magic quotes runtime is deprecated on one of my wordpress site running the nginx server. The error is like the following,
2011/11/07 12:02:48 [error] 15798#0: *130087 FastCGI sent in stderr: \"PHP Deprecated:  Function set_magic_quotes_runtime() is deprecated in /var/www/example/content/wp-settings.php on line 32\" while reading response header from upstream, client: 173.13.114.113, server: www.example.com, request: \"GET /news/ HTTP/1.1\", upstream: \"fastcgi://unix:/var/run/www/php.sock:\", host: \"www.example.com\", referrer: \"http://www.example.com/\"
I already turn off Deprecated error in php.ini, but Not sure why it does not stop. The bad thing is that a lot of deprecated errors make the important error message hidden, so I got the fix this. Finally, the solution is edit wp-settings.php on line 32 to
//set_magic_quotes_runtime( 0 );
//110711 - Since this function is depracted as of PHP 5.3, use ini_set('magic_quotes_runtime', 0); instead.
@ini_set( 'magic_quotes_runtime', 0);

Ref: http://php.net/manual/en/function.set-magic-quotes-runtime.php


2011/11/01

How to disable autosave and wp post revisions

Just a short note.
define('WP_POST_REVISIONS', false);

function disable_autosave() {
wp_deregister_script('autosave');
}
add_action( 'wp_print_scripts', 'disable_autosave' );

2011/10/27

HTML entities in Textarea tag

Maybe this is obvious, but I just leaned it. See the example below,
<textarea>
techrecorder&reg;
</textarea>
I expected to see the '&reg;' but it gives me '®' So when the value of textara tag is presented by convering all of html entities code to the code result, for exmaple, '&lt;' to '<' and '&quot;' to '"'. So if you wanted to show html entities code in textarea, you have to escape &, for example,
<textarea>
techrecorder&amp;reg;
</textarea>

selectall_arrayref vs. selectall_hashref

Both selectall_arrayref and selectall_hashref are method that combines "prepare", "execute" and "fetchall_arrayref" into a single call. The former returns a reference to an array containing a reference to an array (or hash, see below) for each row of data fetched. And the latter returns a reference to a hash containing one entry, at most, for each row, as returned by fetchall_hashref(). Note that selectall_hashref return the ordered list of result as statement intented to, for example,
$sql = \"select ename from employee order by ename\"; 
$hash_ref = $dbh->selectall_hashref($statement, \"ename\");
The %$hash_ref does not contant the ordered list of ename, because it's hash. So the get the ordered list, you need to sort the hash. like
sort(%$hash_ref);
In some case, the statement has "order by" multiple fields, it's not easy to sort hash to having the same order as statement trying to, so you may just use selectall_arrayref, which can also return a reference to a hash, for example,
$sql = \"select ename, eage from employee order by ename, eage\";
my $emps = $dbh->selectall_arrayref(
      $sql,
      { Slice => {} }
  );
  foreach my $emp ( @$emps ) {
      print \"Employee: $emp->{ename}\n\";
  }
For more perl dbi usage, click here http://search.cpan.org/~timb/DBI/DBI.pm

2011/10/13

Restore Slave When it broke

When something goes wrong, slave throws error, one symptom will be that a lot of mysqld-relay-bin.xxxx files are accumulated in /var/lib/mysql/. So you try to restart slave, but got error,
ERROR 1201 (HY000): Could not initialize master info structure; more error messages can be found in the MySQL error log
And you check mysql error log (usually at /var/log/mysqld.log), it says "111014 3:30:47 [ERROR] Error reading slave log configuration". How to do? The simple solution is that,
  • Stop slave, by "slave stop;" at mysql command line.
  • Remove all mysqld-relay-bin.xxxx.
  • Remove master.info and relay-log.info
  • Then start slave by "slave start"
That should work, but you may lost some positions. And if you wanted to start slave at current replcate log file, then you can run one more command before starting slave.
CHANGE MASTER TO MASTER_LOG_FILE='your_current_replog.000693', MASTER_LOG_POS=certain_pos (I used 4);
Good luck!

2011/10/04

Three Steps to Setup SMTP Mail in Debian

Step one

Install Pear (PHP Extension and Application Repository) by the following command,
apt-get install php-pear

Step two

Install Pear Mail Package by the following command,
pear install Mail-1.2.0
Note: the latest version of Mail package at the time I am writing is 1.2.0, check this page for the current version.

Setp three

Install Net_SMTP, which is required to send SMTP mail. You can use the following command to install it.
pear install Net_SMTP

Done!

The following is the script you can use to test,
<?php
include(\"Mail.php\");

function sendmail_smtp($to, $subject, $body){

   $from = \"you@gmail.com\";

   $host = \"ssl://smtp.gmail.com\";
   $port = \"465\";
   $username = \"you@gmail.com\";
   $password = \"yourpass\";

   $headers = array ('From' => $from,
     'To' => $to,
     'Subject' => $subject);
   $smtp = Mail::factory('smtp',
     array ('host' => $host,
       'port' => $port,
       'auth' => true,
       'username' => $username,
       'password' => $password));

   $mail = $smtp->send($to, $headers, $body);

   if (PEAR::isError($mail)) {
      echo(\"<p>\" . $mail->getMessage() . \"</p>\");
   } else {
      echo(\"<p>Message successfully sent!</p>\");
   }

}
?>
Now, you can use Pear SMPT to send mail on any server even your home server without seting up a mail server. Is it cool?

2011/09/30

PHP mail does not work

The OS is linux, and the webserver is apache, and in php.ini file the mail is set as 'sendmail_path = /usr/sbin/sendmail -t -i'. The problem is that php mail() function does not work, although it returns 1 like it's successful. In this case you will not find any help by looking into apache error log. The debugging should start from maillog, which is located at /var/log/ if you are not specify the different loction in the php.ini. I saw the errors like,
delay=00:00:06, xdelay=00:00:02, mailer=relay, pri=120481, relay=*****, dsn=4.5.0, stat=Operating system error
sendmail[24572]: ruleset=try_tls, arg1=mail.***.com, relay=mail.***.com, reject=451 4.3.0 Temporary system failure. Please try again later.
which is actually hard to tell what's going on. I actually tested it mail function thru command line. Accidentally I found if I am root, I was able to send the mail. And I dig more into mail log, I found some useful error logs (note that those logs were generated by the test through url, not command line), like
sendmail[24572]: p8S0pDSY024569: SYSERR(apache): db_map_open: cannot pre-open database /etc/mail/access.db: Permission denied
So then the issue is clear. I checked the /etc/mail/access.db, the mod was 640, so changed to 644, and it sloved the problem.

2011/09/16

Just some note I wrote yesterday

My client wanted to update a webpage with a monthly image, and image extension could be gif, png, jpg, etc. What I need to do is to dynamic check the image in the monthly_tips folder, if there is current month's image, then use it, if not, use the previous month's image, if not, then use a default image.

//get current month, ex: 201109
$ym = date("Ym");

//get last month, ex: 201108
$last_ym = date("Ym",strtotime("-1 months"));

//check if current month's image exists, note that image name like YYYYMM.png, YYYYMM.jpg, etc.
$img = glob("monthly_tips/" . $ym . ".*");
if(count($img) && 0)
  $safty_img = $img[0];
else{//if not found, then check the last month
  $cpath = dirname(__FILE__);
  $img = glob("monthly_tips/" . $last_ym . ".*");
  $default = null;
  //if found the last month's img, then copy it to last.png
  if(count($img)){
    $lastimg = $cpath . "/" . $img[0];
    $path_parts = pathinfo($lastimg);
    $default = 'last.' . $path_parts['extension'];
    $default_path = $cpath . "/monthly_tips/" . $default;
    copy($lastimg, $default_path);
  }
  else{
    $img = glob("monthly_tips/last.*");
    if(count($img))
    $default = $img[0];
  } 
  if($default && file_exists($cpath . "/monthly_tips/" . $default))
    $safty_img = "monthly_tips/" . $default;
  else
    $safty_img = "monthly_tips/default.png"; //worst case;
}

echo $safty_img;


OK, I actually made this way to complicate, and you may not understand what I tried to do here. And my final solution is actually quite simple. The idea is just to use the latest update image in that folder by the following code.

function glob_rsort_latest( $patt ) {
    $rtn = array();
    if ( ( $files = @glob($patt) ) === false ) {
        return $rtn;
    }
    if ( !count($files) ) {
        return $rtn;
    }

    foreach ( $files as $filename ) {
        $rtn[$filename] = filemtime($filename);
    }
    arsort($rtn);
    reset($rtn);
    return $rtn;
}

$files = glob_rsort_latest( 'monthly_tips/*.*' ) ;
if(count($files)){
    $imgs = array_keys($files);
    $safy_img = $imgs[0];
}

2011/07/27

Headache of ISO-8859-1 to UTF8

In Perl, you can use encode ('UTF-8', $iso-text-str) to convert ISO-8859-1 encoded string to UTF-8 encoded string. And in PHP, you can use utf8_encode($iso-text-str) to do the converting.
However, you may be out of luck, for after being converted, some characters could be funky and not what you wanted to see. I think this is because, some characters in UTF8 are invisible, like x80 - x9f (see the following ISO-8859-1 characters list images)





Because I  only care of those regular characters, like \x20-\x7F or \xA9 or \xAE or \x99,  I strip other characters before applying encoding function.
In Perl
$content =~ s/[^(\x20-\x7F|\xA9|\xAE|\x99)]+//g;
$content = encode('utf8', $content);

In PHP
$content = preg_replace('/[^(\x20-\x7F|\xA9|\xAE|\x99|\n)]+/', "", $content);
$content = utf8_encode($content);

UPDATE: Actually, I found that in Perl, encode function cannot correctly convert \x99 to ™. Finally my solution is the following,
open (FILE,  ">$your_file") || die "couldn't write to epcmf file\n";
   binmode(FILE, ":UTF-8");

   $title =~ s/[^(\x20-\x7F|\xA9|\xAE|\x99)]+//g;
   $title =~ s/\x99/™/g;
   $title =~ s/\xAE/®/g;
   $title =~ s/\xA9/©/g;
   print FILE $title;

Note:

  1. You should edit your script in UTF-8, for example, in PUTTY, you can change your character set to UTF-8 at Configuration > Windows > Translation
  2. UTF-8 is different to utf8, so in make sure you write it as binmode(FILE, ":UTF-8");

2011/07/25

Reset Chrome Profiles - Ubuntu 11.04

If your chrome browser is messed up, such as icon of bookmark and/or plugin is missing, cannot load your profile, etc. You may want to reset your profiles. If you use Chrome Sync, then it's very safe to just rename profiles folder, and restart chrome, and then set up Chrome Sync using your existing sync account, after that everything should be back to normal.
The chrome profile folder is under ~/.config/chromium/Default.

2011/07/18

How to center dynamic ul

A UL is a block element, it'll take up the whole width of its container. If you remove float:left and set a width to it, then margin:0 auto will work, but only the ul will center and not the li, unless you know exactly what the width of the UL should be. If you do not know what the ul width should be(e.g. dynamic list menu), then you need to float:left the UL and li, put it in a div, and use this trick to center http://pmob.co.uk/pob/centred-float.htm

2011/07/02

Connect to VPN via Sonicwall NetExtender

I was trying to connect to company's VPN via Sonicwall NetExtender. The version of NetExtender that I can get from my company is 3.5.629, which works fine in my Windows7 desktop, but it does not work in my Ubuntu 11.04. After doing Access Authentication, I was able to connect to server, but eventually I was logout, and the following are some error message I got.
Using SSL Encryption Cipher 'DHE-RSA-AES256-SHA'
Using new PPP frame encoding mechanism
pppd: no device specified and stdin is not a tty
SSL_read ZERO RETURN
SSL-VPN logging out...
SSL-VPN connection is terminated.
Exiting NetExtender client
Connection interrupted.  Reconnecting... 
I spent sometime Googling, and finally I found out the solution. In short, I need a newer version of NetExtender, which you can download it at  Sonicwall demo page,
https://sslvpn.demo.sonicwall.com/cgi-bin/welcome
(note that you need to use "demo" as username and "password" as password to login, and then click NetExtender to download it. I did that in Firefox, and it should popup the download link, and then you can use Active Manager to extract it.

Here are some note:
1. Before you install the newer version, you must uninstall the old version, if you already installed it. (Go to netExtenderClient folder, and run "sudo ./uninstall")
2. You need root to run netExtender (or, sudo ./netExtender)
3. You can also run sudo ./netExtenderGui (the one has user interface), but it may require java.

Hope this helps for someone who has the same problem.

2011/06/24

phpmyadmin cannot import - ubuntu 11.04

"No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. See FAQ 1.16."

Most of time when you see this error, you can just follow the instruction in FAQ1.16 to make some changes in php.ini, such as file_uploads, upload_max_filesize, memory_limit, upload_tmp_dir, max_input_time and post_max_size.
If all of these does not work for you, then it could be the file/directory permission problem. Check the files under /var/lib/phpmyadmin, there are two files, config.inc.php, blowfish_secret.inc.php, and one folder, tmp. Make sure tmp is writeable by APACHE RUN USER, which can be set at /var/apache2/envvars.

Good luck!

2011/06/23

how to install two firefoxs in ubuntu 11.04

Firefox 5 is out now. My ubuntu has updated Firefox Browser to 5, and it works fine, and I do feel it's faster, but the problem is that some add-ons does not work in the new Firefox. If this is a case for you too, or you just like to have old Firefox in your machine, here is how I did it. 1. Go to Mozilla Old download page at http://www.mozilla.com/en-US/firefox/all-older.html, and pick one and download it. 2. Unzip the file and save it to somewhere, says, /home/adam/firefox. 3. Close the existing firefox, and at your command line, change directory to firefox folder, and then enter the following command
./firefox &

Note that you have close exiting Firefox, otherwise, it will trigger the Firefox 5 not Firefox 3. And you can click the file named firefox to open it, but you have to select RUN, not open it in the text editor.

2011/06/17

Order of ClassPath

You can define multiple ClassPath, like

CLASSPATH=$CLASSPATH:/usr/local/apache/lucene/lucene-core-2.0.0.jar:/usr/local/apache/lucene/src/:/usr/local/apache/lucene/src/lucene-classes.jar:.
export CLASSPATH


But the order of ClassPath is important. Basically it is first come first server, if Java Interpreter find the class in the first class path, then it will ignore the the one in the later class path. See the detail from Oracle java doc

The order in which you specify multiple class path entries is important. The Java interpreter will look for classes in the directories in the order they appear in the class path variable. In the example above, the Java interpreter will first look for a needed class in the directory C:\java\MyClasses. Only if it doesn't find a class with the proper name in that directory will the interpreter look in the C:\java\OtherClasses directory.

2011/06/10

remotely connect from Windows - ubuntu 11.04

Here I would like to introduce two ways to connect to Ubuntu from Windows PC.

1. Remote desktop connection.
You need to enable Remote Desktop in Ubuntu, just open application named "Remote Desktop" and change some preference, which is straight forward. And then you need install a VNC viewer software in your windows pc. I use TightVNC and it works just fine.

2. SSH
You need to install ssh server in Ubuntu by running the following command,

sudo apt-get install ssh

And then you can use putty in Windows PC.

2011/06/03

Change archive date format - wordpress 3.1.2

Cannot believe it, but I could not find it in the dashboard to change archive date format. The wordpress I have installed is English version 3.1.2, and date format of archive is "mY", like "June 2011". If you like to show it as 2011 June, beside writing your own get archive function, only thing you can do I think is change source code. I know it is very bad idea, but anyway, if you have to change the formate, here is the solution, Go to "/wp-include/general-template.php", find this line,
$text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
And change it to
$text = sprintf(__('%2$d %1$s'), $wp_locale->get_month($arcresult->month), $arcresult->year);
 
If you also want to change the date formate on archive page title, then find this line,
$result = $prefix . $my_month . $prefix . $my_year;
And change it to
$result = $prefix . $my_year . $prefix . $my_month;

2011/05/27

Change allowed uploading file size - Ubuntu 11.04

When you import a large table using phpmyadmin, you may see the error of, No data was received to import. Either no file name was submitted, or the file size exceeded the maximum size permitted by your PHP configuration. To increase allowed uploading file size, you can need change two values at php.ini file. At command line, type in, sudo vim /etc/php5/apache2/php.ini And then, change values of post_max_size and upload_max_filesize to whatever you want, the default is 8M and 2M separately. ; Maximum size of POST data that PHP will accept. ; http://php.net/post-max-size post_max_size = 80M ; Maximum allowed size for uploaded files. ; http://php.net/upload-max-filesize upload_max_filesize = 20M

How to insall curl php - Ubuntu 11.04

I need curl all the time. Here is how to install it in Ubuntu 11.04 sudo apt-get install php5-curl And then restart apache, how? sudo /etc/init.d/apache2 restart

How to install phpmyadmin - ubuntu 11.04

After installing LAMP server, phpmyadmin is not installed. phpMyAdmin make life easier at least I like it. Here is how to install it in ubuntu 11.04,
 sudo apt-get install libapache2-mod-auth-mysql phpmyadmin
 It's staightforward, although you need to provide some information, like server type, (Choose Apache), Database root password, phpMyAdmin Root password, etc.
And them restart apache by,
 sudo /etc/init.d/apache2 restart
 And try http://localhost/phpmyadmin/, If it does not work, then try the following,
Copy the content of apache configuration file at /etc/phpmyadmin/apache.conf into /var/apache2/http.conf (http.conf was empty in my case) and then restart the apache. OK, then the link, http://localhost/phpmyadmin/ should work.

How to enable .htaccess - Ubuntu 11.04

After you install LAMP, mode rewrite is not enabled. So in order to use .htaccess, you can do the following,

turn on RewriteEngine module

sudo a2enmod rewrite

allow directory to be overridden

Go to /etc/apache2/sites-available and edited the file "default" Change AllowOverride to All from none in Directory /var/www/.
NameVirtualHost *
<VirtualHost *>
        ServerAdmin admin@site.com

        DocumentRoot /var/www/
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                # This directive allows us to have apache2's default start page
                # in /apache2-default/, but still have / go to the right place
                # Commented out for Ubuntu
                #RedirectMatch ^/$ /apache2-default/
        </Directory>
Restart Apache by sudo /etc/init.d/apache2 restart You should be all set.

2011/05/26

How to install LAMP + Zend Ubuntu 11.04

It's super easy to install LAMP server in Ubuntu 11.04, just need to run the follow command,
sudo apt-get install lamp-server^
You may be asked to set up root password for mysql during the installation, other than that, everything is automatically.

To restart apache, run the following command,
sudo /etc/init.d/apache2 restart
OK, install Zend is also easy,
sudo apt-get install zend-framework
After that you have to make sure zend library path is included. Go to php.ini (@/etc/php5/apache2/), edit the following line,

; UNIX: "/path1:/path2" 
include_path = ".:/usr/share/php:/usr/share/php/libzend-framework-php" 
I also found, after added include_path in the php.ini, the Zend library is still not found if I run the php script in the command line. Not sure why, but the solution I found is uncomment the line at /etc/php5/conf.d/zend-framework.ini,
[Zend] include_path=${include_path} ":/usr/share/php/libzend-framework-php"
Happy ubuntu!

2011/05/25

How to show desktop - Ubuntu 11.04

<Super> key + d (In most PC keyboard, super key is the key between Ctr and Alt having Windows icon in there)
And you can customize it using Keybindings.

Where is Keybidings? here you go.
You can set this up through CompizConfig Settings Manager. (You can always search Apps by clicking the top-left Ubuntu Icon or hit <Super> key) This option is under General Options -> Keybindings.

2011/05/24

How to mount windows drive - Ubuntu 11.04

If you have both Ubuntu and Windows installed in your computer, you
may want to access Windows Drive from Ubuntu, here is how,

1. create a folder under media,

<code>sudo mkdir -p /media/c</code>

2. sudo fdisk -l
You will see something like the following,

Disk /dev/sda: 80.0 GB, 80026361856 bytes
255 heads, 63 sectors/track, 9729 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x9c879c87

Device Boot Start End Blocks Id System
/dev/sda1 * 1 8421 67641651 7 HPFS/NTFS
/dev/sda2 8423 9728 10490445 7 HPFS/NTFS

3. mount it

sudo mount -t ntfs -o nls=utf8,umask=0222 /dev/sda1 /media/c

Note that /dev/sda1 is my Device, yours may be different!!!

How to keep launcher on the top - Ubuntu 11.04

By default Launcher is auto hide, but my screen is wide enough, so I
like it's open all the time to easy access. I thought there should be
an option for us to do change its behaviors when you right click on
the Launcher, but I was wrong, maybe in next release.

So here is how,
http://askubuntu.com/questions/9865/how-can-i-configure-unitys-launcher-auto-hide-behavior/31418#31418

Happy Ubuntu!

2011/05/18

Multiple Preg replace in PHP

You can do multiple preg replace with one function call, for example,

PHP, using GeSHi 1.0.8.8
  1. $subject = "{hello}";
  2. $patterns = array("/{/", "/}/");
  3. $replaces = array("{ldelim}", "{rdelim}");
  4. echo preg_replace($patterns, $replaces, $subject); 

Guess what your get? you get,

{ldelim{rdelim}hello{rdelim}

The reason you get this is that perg_replace executes multiple patterns one by one, so ‘{‘ is replaced by ‘{ldelim}’, and then ‘{ldelim}’ is replaced by ‘ {ldelim{rdelim}’.

I believe this is not what you wanted to get. You only want one ‘pattern’ is replaced once. So you can do this,

PHP (brief), using GeSHi 1.0.8.8
  1. $title = "{abdcd}";
  2. $patterns = array("/{/", "/}/");
  3. $replaces = array("LC", "RC");
  4. $title = preg_replace($patterns, $replaces, $title);
  5.  
  6. $patterns = array("/LC/", "/RC/");
  7. $replaces = array("{ldelim}", "{rdelim}");
  8. echo preg_replace($patterns, $replaces, $title);

Finally, you get,

{ldelim}hello{rdelim}

Note that in smarty template, to keep brace, you have to change ‘{ ‘or ‘} ‘to ‘{ldelim}’ or ‘{rdelim}’, or add {literal} and {/literal} around the code that you don’t want smarty engine to interpret it.