php cache

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »


<pre lang="php">
<?php

$url = "http://www.site.com/file.php";
$dest_file = "footercache.txt"; //be sure it is chmod-ed to 0666 !!

$pagesource = request_cache($url, $dest_file, 3600*24*7);
echo $pagesource;

function request_cache($url, $dest_file, $timeout=7200) {

  if(strlen($dest_file) > 100) $dest_file = substr($dest_file, 20, 60) . substr($dest_file, strlen($dest_file) - 4);//keep some chars and the probable extension

  if(!file_exists($dest_file) || filemtime($dest_file) < (time()-$timeout)) {

    $data = @file_get_contents($url);
    if ($data !== false) {

      $tmpf = tempnam("/tmp","YWS");
      $fp = @fopen($tmpf,"w");
      @fwrite($fp, $data);
      @fclose($fp);
      if(file_exists($dest_file)) @unlink($dest_file);
      rename($tmpf, $dest_file);

    }else{

      touch($dest_file);//update its date only

    }

  } else {

    $data = file_get_contents($dest_file);

  }
  return($data);

}

?>
</pre>


Common PHP functions

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »


<pre lang="php">
<?php
if(version_compare(phpversion(), "5.2.0", "<") && !function_exists("json_encode")){
  include($CFG->root_dir . "/common/json/JSON.php");
  function json_encode($str) {$json = new Services_JSON(); return $json->encode($str);}
  function json_decode($str) {$json = new Services_JSON(); return $json->decode($str);}
}

function parse_input($var_array, $var_name){
  if(!isset($var_array[$var_name])) return "";

  if(!is_array($var_array[$var_name])){
    if (!get_magic_quotes_gpc()) {
      $retVal = trim(addslashes($var_array[$var_name]));
    } else {
      $retVal = trim($var_array[$var_name]);
    }
  }else{
    if (!get_magic_quotes_gpc()) {
      foreach ($var_array[$var_name] as $value){
        $retVal[] = trim(addslashes($value));
      }
    } else {
      foreach ($var_array[$var_name] as $value) {
        $retVal[] = trim($value);
      }
    }
  }
  return $retVal;
}

function dprint($var, $message = ""){
  if(DEBUG){
    echo("DEBUG : $message\r\n");
    if(is_array($var) || is_object($var)){
      print_r($var);
    }else{
      echo($var);
    }
    echo("\r\n");
  }
}

function from_sql_date($sqltime, $date_format="d.m.Y"){
  if("0000-00-00 00:00:00" == $sqltime || "0000-00-00" == $sqltime) return "";

  list($y,$m,$d,$h,$i,$s) = sscanf($sqltime,"%4d-%2d-%2d %2d:%2d:%2d");
  date_default_timezone_set("Etc/GMT+2");
  $time_src = mktime($h, $i, $s, $m, $d, $y);
  return date($date_format, $time_src);
}

function to_sql_date($date){
  list($d,$m,$y) = sscanf($date,"%2d.%2d.%4d");
  $time_src = mktime(0, 0, 0, $m, $d, $y);
  return date("Y-m-d 00:00:00", $time_src);
}
?></pre>


Menu at mouse cursor

Posted: April 16th, 2008 | Author: | Filed under: Developers, Javascript | No Comments »


<pre lang="javascript">
<STYLE TYPE="text/css">
<!--
#dek {POSITION:absolute;VISIBILITY:hidden;Z-INDEX:200;}
//-->
</STYLE>
<DIV ID="dek"></DIV>
<SCRIPT TYPE="text/javascript">
<!--
function popUp(theURL, myWidth, myHeight) {
  var winName = 'feedback';
  var features='toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1';
  //var myWidth = 290;
  //var myHeight = 360;
  var isCenter = 'true';
  if(window.screen)if(isCenter)if(isCenter=="true"){
    var myLeft = (screen.width-myWidth)/2;
    var myTop = (screen.height-myHeight)/2;
    features+=(features!='')?',':'';
    features+=',left='+myLeft+',top='+myTop;
  }
  var handle = window.open(theURL,winName,features+((features!='')?',':'')+'width='+myWidth+',height='+myHeight);
  handle.opener = window;
  handle.focus();
  return handle;
}

Xoffset=0; // modify these values to ...
Yoffset= 0; // change the popup position.
var old,skn,iex=(document.all),yyy=Yoffset;//-1000;
var ns4=document.layers
var ns6=document.getElementById&&!document.all
var ie4=document.all
var must_close = false;
var mouse_x = 0;
var mouse_y = 0;
var timeoutId = false;
function initdek(){
  if (ns4) skn=document.dek;
  else if (ns6) skn=document.getElementById("dek").style;
  else if (ie4) skn=document.all.dek.style;
  
  if(ns4)document.captureEvents(Event.MOUSEMOVE);
  else{
    skn.visibility="visible"
    skn.display="none"
  }
  document.onmousemove=get_mouse;
}
//ONMOUSEOVER="keep_it_open()" ONMOUSEOUT="about_to_close()"
function popupdek(msg){
  keep_it_open();
  var content='<div style="border:1px solid #999; padding:10px;background-color:#f87" ONMOUSEOVER="keep_it_open()" ONMOUSEOUT="about_to_close()">' + msg + '</div>';
  
  yyy=Yoffset;
  skn.left = mouse_x;
  skn.top = mouse_y;
  if(ns4){skn.document.write(content);skn.document.close();skn.visibility="visible"}
  if(ns6){document.getElementById("dek").innerHTML=content;skn.display=''}
  if(ie4){document.all("dek").innerHTML=content;skn.display=''}
}

function get_mouse(e){
  if(ns4||ns6){
    mouse_x=e.pageX+Xoffset+'px';
    mouse_y=e.pageY+yyy + 'px';
  }else{
    if (document.documentElement){
      // IE6 +4.01
      mouse_x=event.x+document.documentElement.scrollLeft+Xoffset+'px';
      mouse_y=event.y+document.documentElement.scrollTop+yyy + 'px';
    }else if (document.body){
      // IE5 or DTD 3.2
      mouse_x=event.x+document.body.scrollLeft+Xoffset+'px';
      mouse_y=event.y+document.body.scrollTop+yyy + 'px';
    }
  }
}

function kill(){
//yyy=-1000;
if(ns4){skn.visibility="hidden";}
else if (ns6||ie4)
  skn.display="none"
  is_visible=0;
}

function keep_it_open(){
  if(timeoutId) clearTimeout(timeoutId);
  timeoutId = false;
}

function about_to_close(){
  timeoutId = setTimeout('kill()',1000);
}

function set_must_close(){
  must_close=true;
  kill();
}

initdek();

function showTags(str){
  var msg = "<strong>Tags:</strong><br/>" + str.replace(/\,/,'<br/>');
  msg += '<br/><form action=""><input type="text" size="10" value="enter tag.." name="tag"/><input type="submit" value="Add"></form>';
  popupdek(msg);
}
function showManage(pid){
  var msg = "<strong>Management:</strong><br/>" ;
  msg += '<a href="#" onclick="popUp(\'imageop/add_image~' + pid + '.html\',400,300)" >Add image</a><br/>';
  msg += '<a href="#" onclick="popUp(\'imageop/delete_image~' + pid + '.html\',400,300)" >Delete image</a><br/>';
  msg += '<br/><form action=""><input type="file" size="10" value="" name="uploadfile"/><br/><input type="submit" value="Upload"></form>';
  popupdek(msg);
}

function showLinks(pid, iurl){
  var msg = "<strong>Links:</strong><br/>" ;
  msg += '<a href="<?=$PROFILEORIGIN?>/list_profile~' + pid + '.html" target="_blank">Profile home</a><br/>';
  msg += '<a href="' + iurl + '" target="_blank" >Source URL</a><br/>';
  popupdek(msg);
}
//-->
</SCRIPT>
</pre>

Used as:
<a href="http://www.blogger.com/post-edit.do#" onmouseover="showTags('taglist,comma separated)');keep_it_open()" onmouseout="about_to_close()" onclick="return false">Tags</a>


RegEx email parser

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »

Split email formats in pieces through preg_match:

$str=' (|(([^a-zA-Z0-9_\-.]|)(.*?)(|[^a-zA-Z0-9_\-.]+?)([a-zA-Z0-9_\-.]+?)(|[^a-zA-Z0-9_\-.]+?)))(|[^a-zA-Z0-9_\-.])([a-zA-Z0-9_\-.]+?)(|[^a-zA-Z0-9_\-.])@(.+?)\.([^>]+)';


Format long texts

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »


<pre lang="php">
<?php
/**
 * Cut a text so it won't have more than $max_length chars and any word should not have more than $max_word chars
 *
 * @param int $length_limit
 * @param int $length_word
 */
function format_long_text($str, $max_length=99999, $max_word = 60){
  //limit string length
  $has_tail = false;
  if(strlen($str) > $max_length){
    $new_str = substr($str, 0, $max_length);
    //search for non-alpha char
    for($i = $max_length; $i < strlen($str) && ctype_alpha($str[$i]); $i++) $new_str .= $str[$i];
    $str = $new_str;
    $has_tail = true;
  }

  if(3 < $max_word && $max_word < $max_length){
    do{
      //$stripped_str = strip_tags($str);
      //$words = explode(' ', $stripped_str);
      $words = explode(' ', $str);
      $do_loop = false;
      foreach ($words as $word){

        if(strlen($word) > $max_word){
          //bug in IE: point followed by char does not split the text
          $fixed_word = str_replace('.', '. ', $word);

          $new_word = '';
          $j = 0;
          for($i = 0; $i < strlen($fixed_word); $i++){
            $j = (' ' == $fixed_word[$i]?0:$j+1);

            if(($j+1)%$max_word==0){
              $new_word .= ' ' . $fixed_word[$i];
            }else{
              $new_word .= $fixed_word[$i];
            }
          }
          $str = str_replace($word, $new_word, $str);
          $do_loop = true;
          break;
        }
      }
    }while($do_loop);
  }

  return $str . ($has_tail?'..':'');
}
?>
</pre>


Phrase to URL-format

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »

preg_replace('/[^a-zA-Z]+/','_',$phrase)


Instant popup on mouseover

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »


<pre lang="javascript">
<style type="text/css">
<!--
#dek {POSITION:absolute;VISIBILITY:hidden;Z-INDEX:200;}
//-->
</style>

<script type="text/javascript">
<!--
Xoffset=0; // modify these values to ...Yoffset= 20; // change the popup position.
var old,skn,iex=(document.all),yyy=-1000;
var ns4=document.layersvar ns6=document.getElementById&#038;&#038;!document.allvar ie4=document.all

if (ns4)skn=document.dek
else if (ns6)skn=document.getElementById("dek").style
else if (ie4)skn=document.all.dek.style
if(ns4)document.captureEvents(Event.MOUSEMOVE);
else{skn.visibility="visible"skn.display="none"}
document.onmousemove=get_mouse;

function popup(msg,bak){
  var content="
<table>
<tr>
<td";</td>
content += " bgcolor=\'"+bak+"\'";

  content += ">"+msg+"</td>
</tr>
</table>
";

  yyy=Yoffset;
  if(ns4){
    skn.document.write(content);
    skn.document.close();
    skn.visibility="visible"
  }
  if(ns6){
    document.getElementById("dek").innerHTML=content;
    skn.display=\'\'
  }
  if(ie4){
    document.all("dek").innerHTML=content;
    skn.display=\'\'
  }
}

function get_mouse(e){
  if(ns4||ns6){
    skn.left=e.pageX+Xoffset+\'px\';
    skn.top=e.pageY+yyy + \'px\';
  }else{
    if (document.documentElement){ // IE6 +4.01
      skn.left=event.x+document.documentElement.scrollLeft+Xoffset+\'px\';
      skn.top=event.y+document.documentElement.scrollTop+yyy + \'px\';
    }else if (document.body){ // IE5 or DTD 3.2
      skn.left=event.x+document.body.scrollLeft+Xoffset+\'px\';
      skn.top=event.y+document.body.scrollTop+yyy + \'px\';
    }
  }
}

function kill(){
  yyy=-1000;
  if(ns4){
    skn.visibility="hidden";
  }else if (ns6||ie4)skn.display="none"
}
//--></script></pre>

Usage: <a href="mylinkhere.php" onmouseover="popup('this is a help message', '#00FFFF')" onmouseout="kill()" >click here</a>


META tag library

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »

This library if for obtaining content for the META TAGS like keywords, description and also for computing tags to be used in searches based on the given text.

Metatag generator library (metataggen_library.zip)


Email validity check

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »

PHP code:


<pre lang="php">
<?php 
function is_email($email) {
  $x = '\d\w!\#\$%&\'*+\-/=?\^_`{|}~';    //just for clarity
  return   count($email = explode('@', $email, 3)) == 2 && 
      strlen($email[0]) < 65 && strlen($email[1]) < 256 && 
      preg_match("#^[$x]+(\.?([$x]+\.)*[$x]+)?$#", $email[0]) && 
      preg_match('#^(([a-z0-9]+-*)?[a-z0-9]+\.)+[a-z]{2,6}.?$#', $email[1]);
}
?>
</pre>


switch order of two records in a table

Posted: April 16th, 2008 | Author: | Filed under: Developers | No Comments »

When in need to change the order of a list use a field to store the order as an int:
Change the order of the records by switching the order value between consecutive elements.

<pre lang="php">
<?php 
switch ($action){
  case 'orderdown':
  case 'orderup':{ 
    //get all list and retain two elements: if moveup operation then I keep prev and current  
    //otherwise I keep current and next
    $rec_list = $this->getChildren($record->id_parent);//all records on this level
    $switch = array();
    for($i = 0; $i < count($rec_list) ; $i++){
      if($rec_list[$i]['id'] == $record['id']){
        if('orderup' == $what && $i != 0){    //not first
          $switch[$rec_list[$i-1]['id']] = $rec_list[$i]['corder'];
          $switch[$rec_list[$i]['id']] = $rec_list[$i-1]['corder'];
          break;
        }elseif('orderdown' == $what && $i != (count($rec_list)-1)){    //not last
          $switch[$rec_list[$i+1]['id']] = $rec_list[$i]['corder'];
          $switch[$rec_list[$i]['id']] = $rec_list[$i+1]['corder'];
          break;
        }
      }
    }

    //valid elements found. Switch them
    if(count($switch) > 0){
      foreach ($switch as $id=>$corder) {
        $sql = "UPDATE page SET corder=$corder WHERE$id";
        $result = mysql_query($sql) or die("SQL ERROR " . mysql_error() . " [$sql] on " . __FILE__ . " at line " . __LINE__);
      }
    }
  }break;
}
?>
</pre>