Tuesday, November 2, 2010

jQuery autocomplete with caching and custom value selection

Download jQuery library from jQuery site and its ui plugin for autocomplete from this link http://jqueryui.com/home

Define below function in any your js file. (ex: common.js) and then include it in your page.

/**
* Set autocomplete property
*/
function setAutoComplete(element_id, ajax_url, listener, cache_name, term_length)
{
if (element_id === undefined || ajax_url === undefined) return false;
if (listener === undefined) listener = 'itemselected';
if (term_length === undefined) term_length = 1;
if (cache_name === undefined) cache_name = 'itosa_ac_cache';

var cache = [];
cache[cache_name] = [];

$("#"+element_id).autocomplete({
source: function( request, response ) {
var term = request.term;
if ( term in cache[cache_name] ) {
response( cache[cache_name][ term ] );
return;
}
$(this).addClass('ui-autocomplete-loading');
lastXhr = $.getJSON( ajax_url, request, function( data, status, xhr ) {
cache[cache_name][ term ] = data;
if ( data != null && xhr === lastXhr ) {
response( data );
}
});
},
minLength: term_length,
select: function(event, ui){$('body').trigger(listener,[event,ui]);}
})

return false;
}

When you select item from list it will trigger listener event, you have passed through function parameter "listener".

To access the code

setAutoComplete('search_person','http://example.com/person.php','personselect');
$('body').bind('itemselected',function (event,input_event,ui){
$('#seach_key').val(ui.item.id);
return false;
});

Friday, August 6, 2010

jQuery Read More and Read Less

Here is the jQuery code for showing readmore and read less with sliding effect. You have to just add the jQuery.js file and the below javascript code.


Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.


Read More


var sliderHeight = "40";

$(document).ready(function(){

$('.slider').each(function () {
var current = $(this);
current.attr("box_h", current.height());
if(current.height() <= sliderHeight) $('#readmore_cnt').hide(); }); $(".slider").css("height", sliderHeight+ "px"); $(".slider_menu").click(function() { openSlider() }) }); function openSlider() { var open_height = $(".slider").attr("box_h") + "px"; $(".slider").animate({"height": open_height}, {duration: "slow" }); $(".slider_menu").html('');
$(".slider_menu").removeClass('view-more');
$(".slider_menu").addClass('view-less');
$(".slider_menu").unbind("click");
$(".slider_menu").click(function() { closeSlider() });
}

function closeSlider()
{
$(".slider").animate({"height": sliderHeight+ "px"}, {duration: "slow" });
$(".slider_menu").html('');
$(".slider_menu").removeClass('view-less');
$(".slider_menu").addClass('view-more');
$(".slider_menu").unbind("click");
$(".slider_menu").click(function() { openSlider() });
}

Wednesday, July 28, 2010

How to get past date from today

Here is the code,

$today = strtotime(date('y-m-d'));
for($i=0; $i < 7;$i++)
{
$days[] = date('y-m-d:l',($today-($i*24*60*60)));
}
print_r($days);die;

Output:
Array ( 
    [0] => 10-07-28:Wednesday    
    [1] => 10-07-27:Tuesday 
    [2] => 10-07-26:Monday  
    [3] => 10-07-25:Sunday  
    [4] => 10-07-24:Saturday   
   [5] => 10-07-23:Friday   
   [6] => 10-07-22:Thursday
 ) 


Note: The result might be different as your testing date will be different.

Getting real IP

Here is the function that will give you a real IP address

function getIP() {
if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
}
elseif (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
}
elseif (getenv('HTTP_X_FORWARDED')) {
$ip = getenv('HTTP_X_FORWARDED');
}
elseif (getenv('HTTP_FORWARDED_FOR')) {
$ip = getenv('HTTP_FORWARDED_FOR');
}
elseif (getenv('HTTP_FORWARDED')) {
$ip = getenv('HTTP_FORWARDED');
}
else {
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}

Resource from comment of this link
"http://www.cyberciti.biz/faq/php-howto-read-ip-address-of-remote-computerbrowser/"

Tuesday, April 27, 2010

Google Map Code link

http://code.google.com/apis/maps/documentation/overlays.html

   if (GBrowserIsCompatible()) {
map = new GMap(document.getElementById("map"));
map.setCenter(new GLatLng(33.5923607, -86.9924358), 13);
var point = new GLatLng(33.5923607,-86.9924358);
var marker=new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(details);
});

map.addOverlay(marker);
}


Tuesday, March 23, 2010

PHP file upload class

/**
* File uploader class
* @name FileUploader
* @author Ritesh
*/
class FileUploader
{
/**
* Constant variables
*/
const ERR_INVALID_FILE = 'Invalid file';
const ERR_FILE_SIZE = 'File size is too large';
const ERR_UNKNOWN = 'Unknown file upload error';
const ERR_FILE_EXISTS = 'File already exist';


/**
* Default 100 KB
* @var string $_filesize
*/
private $_filesize = "102400";

/**
*
* @var array $_file_types
*/
private $_file_types = array('image/jpeg','image/ico','image/gif','image/png');

/**
* detault root folder of class file
* @var string $_upload_path
*/
private $_upload_path = ".";

/**
* error message
* @var string $_error
*/
private $_error = '';

/**
* @var string $_uploaded_file
*/
private $_uploaded_file = '';

/**
* Add other files
* @param array $file_types
*/
function addFileTypes($file_types)
{
$this->_file_types = array_merge($this->_file_types,$file_types);
}

/**
* reset upload file types
* @param array $file_types
*/
function resetFileTypes($file_types)
{
$this->_file_types = $file_types;
}

/**
* set file size
* @param int $size
*/
function setFileSize($size)
{
$this->_filesize = $size;
}

/**
* set file upload path
* @param string $path
*/
function setUploadPath($path)
{
$this->_upload_path = $path;
}

/**
* set error message
* @param string $error
*/
function setError($error)
{
$this->_error = $error;
}

/**
* return error message
* @return string
*/
function getError()
{
return __($this->_error);
}

/**
* File upload function to upload file
* @param string $input_name
* @param boolean $check_file_exists
* @param string $saved_file_name
* @return boolean
*/
function upload( $input_name, $check_file_exists = false, $saved_file_name = null )
{
$file_type = $_FILES[$input_name]['type'];
$file_size = $_FILES[$input_name]['size'];

if($saved_file_name == null)
$saved_file_name = $_FILES[$input_name]['name'];
else
$saved_file_name = $saved_file_name.".".$this->getFileExt($_FILES[$input_name]['name']);

# Check file type
if (!in_array($file_type, $this->_file_types))
{
$this->setError(self::ERR_INVALID_FILE);
return false;
}

# Check file size
if ($file_size > $this->_filesize)
{
$this->setError(self::ERR_FILE_SIZE);
return false;
}

# Check for unknown error
if ($_FILES[$input_name]["error"] > 0)
{
$this->setError(self::ERR_UNKNOWN);
return false;
}

# Check file exist
if ($check_file_exists && file_exists($this->_upload_path . DS . $saved_file_name))
{
$this->setError(self::ERR_FILE_EXISTS);
return false;
}

$result = move_uploaded_file($_FILES[$input_name]["tmp_name"],$this->_upload_path . DS . $saved_file_name);

if (!$result)
{
$this->setError(self::ERR_UNKNOWN);
$this->_uploaded_file = '';
return false;
}
else
{
$this->_uploaded_file = $saved_file_name;
}

return $result;
}

function getUploadedFile()
{
return $this->_uploaded_file;
}

/**
* get file extention
* @param string $file_name
*/
private function getFileExt($file_name)
{
$filename = strtolower($file_name) ;
$exts = split("[/\\.]", $file_name) ;
$n = count($exts)-1;
$exts = $exts[$n];
return $exts;
}


}

?>

Tuesday, February 23, 2010

TinyMce image uploader

The best image uploader for tinyMce editor. You can found it at http://www.net4visions.com/downloads.html

Monday, February 8, 2010

PHP Generating MO Language file from PO file

/**
* Generate Mo File from an array generate by PO file
* @param Object $file PO file path with file name
* @param String $msgid_key msgid key in PO file
* @param String $msgid_value msgstr value for above msgid
* @param String $mo_file mo file path
* @return boolean
*/
function writePo($file,$msgid_key,$msgid_value,$mo_file){

$fd = fopen($file->filepath, "r+b"); // File will get closed by PHP on return
if (!$fd) {
$msg = sprintf(__('The file %s could not be open for write'),$file_name);
//do whatever you want with this error msg
return FALSE;
}

$context = "MSGID";
$lineno = 0;
$wflag = false;
while (!feof($fd)) {

$line = fgets($fd, 10*1024); // A line should not be this long

if ($lineno == 0) {
// The first line might come with a UTF-8 BOM, which should be removed.
$line = str_replace("\xEF\xBB\xBF", '', $line);
}
$lineno++;
$line = trim(strtr($line, array("\\\n" => "")));

if (!strncmp("msgid", $line, 5) && $context = "MSGID") {
$line = trim(substr($line, 5));
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The PO file %s contains a syntax error on %d line'),$file->filename,$lineno);
//do whatever you want with this error msg
return FALSE;
}
if($quoted == $msgid_key){
$wflag = true;
$context = "MSGSTR";
}
}
if (!strncmp("msgstr", $line, 5)) {

if($context == "MSGSTR" && $wflag == true){
fclose($fd);
$wflag = false;
//write msgdtr value to file
$msg = "msgstr ".'"'.$msgid_value.'"';
$lines = file($file->filepath);
$lines[$lineno-1] = $msg . "\r\n";
// Turn array back into a string to write to file
$data = implode('',$lines);
$fp = fopen($file->filepath,'wb');
fwrite($fp,$data);
fclose($fp);

//generate mo file
if(file_exists($mo_file)){
$mo_lines = file($mo_file);
foreach($mo_lines as $key => $value){
if(strlen(strstr($value,$msgid_key)) > 0){
$mo_lines[$key] = "'".addslashes($msgid_key)."' =>".$msgid_value.",\r\n";
$data = implode('',$mo_lines);
$fm = fopen($mo_file,'wb');
fwrite($fm,$data);
fclose($fm);
return true; //found msg key then return
}
else if(strlen(strstr($value,");")) > 0 ){
$mo_lines[$key] = "'".addslashes($msgid_key)."'=>".$msgid_value.",\r\n";
$mo_lines[] = ");";
$data = implode('',$mo_lines);
$fm = fopen($mo_file,'wb');
fwrite($fm,$data);
fclose($fm);
return true;
}
}
}
else {
$data = "#do not touch this file. This is machine generated fie.\r\n#Changes in file structure may cause file parsing error.\r\n\r\n";
$data .= '$translation = Array('."\r\n";
$data .= "'".addslashes($msgid_key)."'=>".$msgid_value.",\r\n";
$data .= ");";
$fm = fopen($mo_file,'wb');
fwrite($fm,$data);
fclose($fm);
}
}
}
}
return true;
}

PHP Reading PO file (the file generated from php source)

Hi Guy's,

Here is the code for parsing PO file for editing in PHP. I have little modified the Drupal's code.

/**
* Parses Gettext Portable Object file into an array
* @param Object $file PO file path with file name
* @param string $search_key search word to find msgid in po file
* File object corresponding to the PO file to read
*/
function readPo($file,$search_key) {

$fd = fopen($file->filepath, "rb"); // File will get closed by PHP on return
$file_name = $file->filename;
if (!$fd) {
$msg = sprintf(__('The translation import failed, because the file %s could not be read'),$file_name);
//do whatever you want with this error msg
return FALSE;
}

$context = "COMMENT"; // Parser context: COMMENT, MSGID, MSGID_PLURAL, MSGSTR and MSGSTR_ARR
$current = array(); // Current entry being read
$plural = 0; // Current plural form
$lineno = 0; // Current line
$lang_arr = Array(); // total message in the file

while (!feof($fd)) {

$line = fgets($fd, 10*1024); // A line should not be this long
if ($lineno == 0) {
// The first line might come with a UTF-8 BOM, which should be removed.
$line = str_replace("\xEF\xBB\xBF", '', $line);
}
$lineno++;
$line = trim(strtr($line, array("\\\n" => "")));
if (!strncmp("#", $line, 1)) { // A comment
if ($context == "COMMENT") { // Already in comment context: add
$current["#"][] = substr($line, 2);
}
elseif (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) { // End current entry, start a new one

if(!empty($search_key)){
$pattern = "/\b".$search_key."\b/i";
if(preg_match($pattern ,trim($current['msgid'])))
$lang_arr[] = $current;
}
else
$lang_arr[] = $current;

$current = array();
$current["#"][] = substr($line, 2);
$context = "COMMENT";
}
else { // Parse error
$msg = sprintf(__('The translation file %s contains an error: "msgstr" was expected but not found on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
}
elseif (!strncmp("msgid_plural", $line, 12)) {
if ($context != "MSGID") { // Must be plural form for current entry
$msg = sprintf(__('The translation file %s contains an error: "msgid_plural" was expected but not found on %d line'),$file_name,$lineno);
$this->ErrSucc->addError($msg);
return FALSE;
}
$line = trim(substr($line, 12));
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The translation file %s contains a syntax error on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$current["msgid"] = $current["msgid"] ."\0". $quoted;
$context = "MSGID_PLURAL";
}
elseif (!strncmp("msgid", $line, 5)) {
if ($context == "MSGSTR") { // End current entry, start a new one
//$lang_arr[] = $current;
$current = array();
}
elseif ($context == "MSGID") { // Already in this context? Parse error
$msg = sprintf(__('The translation file %s contains an error: "msgid" is unexpected on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$line = trim(substr($line, 5));
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The translation file %s contains a syntax error on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$current["msgid"] = $quoted;
$context = "MSGID";
}
elseif (!strncmp("msgstr[", $line, 7)) {
if (($context != "MSGID") && ($context != "MSGID_PLURAL") && ($context != "MSGSTR_ARR")) { // Must come after msgid, msgid_plural, or msgstr[]
$msg = sprintf(__('The translation file %s contains an error: "msgstr[]" is unexpected on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
if (strpos($line, "]") === FALSE) {
$msg = sprintf(__('The translation file %s contains a syntax error on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$frombracket = strstr($line, "[");
$plural = substr($frombracket, 1, strpos($frombracket, "]") - 1);
$line = trim(strstr($line, " "));
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The translation file %s contains a syntax error on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$current["msgstr"][$plural] = $quoted;
$context = "MSGSTR_ARR";
}
elseif (!strncmp("msgstr", $line, 6)) {
if ($context != "MSGID") { // Should come just after a msgid block
$msg = sprintf(__('The translation file %s contains an error: "msgstr" is unexpected on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$line = trim(substr($line, 6));
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The translation file %s contains a syntax error on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
$current["msgstr"] = $quoted;
$context = "MSGSTR";
}
elseif ($line != "") {
$quoted = $this->_parse_quoted($line);
if ($quoted === FALSE) {
$msg = sprintf(__('The translation file %s contains a syntax error on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
if (($context == "MSGID") || ($context == "MSGID_PLURAL")) {
$current["msgid"] .= $quoted;
}
elseif ($context == "MSGSTR") {
$current["msgstr"] .= $quoted;
}
elseif ($context == "MSGSTR_ARR") {
$current["msgstr"][$plural] .= $quoted;
}
else {
$msg = sprintf(__('The translation file %s contains an error: there is an unexpected string on %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
}
}

// End of PO file, flush last entry
if (($context == "MSGSTR") || ($context == "MSGSTR_ARR")) {

if(!empty($search_key)){
$pattern = "/\b".$search_key."\b/i";
if(preg_match($pattern ,trim($current['msgid'])))
$lang_arr[] = $current;
}
else
$lang_arr[] = $current;
}
elseif ($context != "COMMENT") {
$msg = sprintf(__('The translation file %s ended unexpectedly at %d line'),$file_name,$lineno);
//do whatever you want with this error msg
return FALSE;
}
fclose($fd);

return $lang_arr;
}

/**
* Parses a string in quotes
*
* @param $string
* A string specified with enclosing quotes
* @return
* The string parsed from inside the quotes
*/
function _parse_quoted($string) {
if (substr($string, 0, 1) != substr($string, -1, 1)) {
return FALSE; // Start and end quotes must be the same
}
$quote = substr($string, 0, 1);
$string = substr($string, 1, -1);
if ($quote == '"') { // Double quotes: strip slashes
return stripcslashes($string);
}
elseif ($quote == "'") { // Simple quote: return as-is
return $string;
}
else {
return FALSE; // Unrecognized quote
}
}

Tuesday, January 26, 2010

Convert PHP source file to PO file

I have written a simple code for generating PHP source code to PO file. I hope it may help you.

Here $file is your php file path (ex c:/my_file/test.php) with message content as __('your message in php code');

$msg_lines = "";
$po_obj = new POContent();
$po_obj->generatePoContent($file,$msg_lines);

#write po file content
$po_strings = "";
foreach($msg_lines as $msgid => $line_contents)
{
$po_strings .= "# Translator comments\r\n";
$po_strings .= "#. Programmer comments\r\n";
foreach($line_contents['line'] as $key => $line)
$po_strings .= "#: ".$line."\r\n";
$po_strings .= "msgid \"".$msgid."\"\r\n";
$po_strings .= "msgstr ''\r\n";
$po_strings .= "\r\n";
}

$po_file_path = 'c:/my_file/test.po';
$fh = fopen($po_file_path,'wb');
if (!$fh) {
echo __('PO File generation failed');
}
else{
fwrite($fh,$po_strings);
fclose($fh);
echo __('PO File generated successfully');
}

class POContent{
/**
* Generate PO File by reading entire particular component's source file
* @param $file String (PHP Source file path to parse)
* @param $msg_lines String (Refrence variable to store all the msgid)
* @return
*/
function generatePoContent($file,&$msg_lines){
//open source file
$datas = file($file);
$msg_file = basename($file);
$pattern ="/__\([\"\']([^()]+)[\"\']\)/";

foreach($datas as $indx => $data){
$msgs = "";
preg_match($pattern, $data, $msgs);
if(count($msgs) > 0){
if(!array_key_exists($msgs[1],$msg_lines)){
$msg_lines[$msgs[1]]['file'][$msg_file] = $msg_file.":Line No.".($indx+1);
$msg_lines[$msgs[1]]['line'][] = $msg_file.":Line No.".($indx+1);
}
else{
$temp_line = $msg_lines[$msgs[1]]['file'][$msg_file];
if(!array_key_exists($msg_file,$msg_lines[$msgs[1]]['file'])){
$msg_lines[$msgs[1]]['file'][$msg_file] = $msg_file.":Line No.".($indx+1);
$msg_lines[$msgs[1]]['line'][] = $msg_file.":Line No.".($indx+1);
}
else{
$msg_lines[$msgs[1]]['file'][$msg_file] = $temp_line.",".($indx+1);
$msg_lines[$msgs[1]]['line'][count($msg_lines[$msgs[1]]['line'])-1]=$temp_line.",".($indx+1);
}
}
}
}
}
}

Now You can check the c:/my_file/test.po