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");