Wednesday, April 27, 2016

Shell script to scan folders and delete all but the most recent ones

root@server1 [~]# cat rm-releases.sh

#!/bin/bash

DIRECTORY="releases"

for i in $(ls -l /home | grep - | awk '{print $8}'| sed 's|[/]||g'); do
#  echo ${i%%/};

  if [ -d "/home/${i%%/}/$DIRECTORY" ]; then
    TARGETDIR=$(ls -t /home/${i%%/}/$DIRECTORY | head -1)
#    echo $TARGETDIR;
    for j in $(ls -l "/home/$i/$DIRECTORY" | grep - | awk '{print $8}' | sed 's|[/]||g'); do
      if [ "$j" != "$TARGETDIR" ]; then
        echo "rm /home/$i/$DIRECTORY/${j}"
        rm -rf "/home/$i/$DIRECTORY/${j}"
      fi
    done
#    break;
  fi
done

Friday, December 04, 2015

Downgrade PHP Version from 5.5 to 5.4 on Ubuntu 14.04

First one have to install the PPA containing PHP54:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:ondrej/php5-oldstable
sudo apt-get update
sudo apt-get install -y php5

Then install Apache+fcgid+php5.4:

sudo apt-get update
sudo apt-get upgrade
sudo apt-get remove --purge `dpkg -l | grep php | grep -w 5.5 | awk '{print $2}' | xargs`
sudo apt-get purge apache2 php5 libapache2-mod-php5
sudo sed -i.bak "s/trusty/precise/g" /etc/apt/sources.list
sudo apt-get update
sudo apt-get install apache2 apache2-suexec libapache2-mod-fcgid php5-cgi
sudo apt-get install php5-mysql php5-curl php5-gd php5-intl php-pear php5-imagick php5-imap php5-mcrypt php5-memcache php5-ming php5-ps php5-pspell php5-recode php5-sqlite php5-tidy php5-xmlrpc php5-xsl php5-xdebug
sudo sed -i "s/precise/trusty/g" /etc/apt/sources.list
dpkg --get-selections | egrep '^(apache|php)' | sed 's/install/hold/g' | sudo dpkg --set-selections
sudo apt-get update
sudo apt-get install  mysql-client mysql-server phpmyadmin

Note that the "switch" between trusty and precise was needed because PPA Ondrej does not have packages for trusty

Finally, continue setting up the environment as here: http://www.howtoforge.com/how-to-set-up-apache2-with-mod_fcgid-and-php5-on-ubuntu-12.04


Thursday, November 19, 2015

On-the-fly Symfony form for searches

Version 1: Typeless form

Inside the controller:
$q = $request->query->get('q');
$data = array('q' => $q); 
$searchForm = $this->get('form.factory')
    ->createNamedBuilder('', 'form', $data, array(
        'csrf_protection' => false,
        'method' => 'GET',
    ))
    ->add('q', 'text', array(
        'required' => false,
    ))
    ->getForm();

if($q) {
    $data = $searchForm->handleRequest($request)->getData();
    $qb
        ->andWhere($qb->expr()->like('name',  ':q'))
        ->setParameter('q', $data['q']);
} 
return $this->render('@Bundle:Entity:index.html.twig', array(
            'searchForm'    => $searchForm->createView()
        ));

Version 2:  using FormType

Inside controller:
$filterForm = $this->createForm(new SomeFilterType(), null, array(
    'method' => 'GET',
));

$filterForm->handleRequest($request);
if ($filterForm->isValid()) {
    $name = $filterForm->get('name')->getNormData();
//
}

Wednesday, November 18, 2015

Failed to download zendframework/zend-stdlib from dist

Problem

# php composer.phar install
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
  - Removing zendframework/zend-stdlib (2.5.1)
  - Installing zendframework/zend-stdlib (2.2.3)
    Downloading: Connecting...    Failed to download zendframework/zend-stdlib from dist: The "https://api.github.com/repos/zendframework/Component_ZendStdlib/zipball/7c87ce4e840957596bf3401fa4ae4fb0355682e2" file could not be downloaded (HTTP/1.1 404 Not Found)
    Now trying to download from source
  - Installing zendframework/zend-stdlib (2.2.3)
    Cloning 7c87ce4e840957596bf3401fa4ae4fb0355682e2


                                                                                                                   
  [RuntimeException]                                                                                               
  Failed to clone git@github.com:zendframework/Component_ZendStdlib.git via git, https, ssh protocols, aborting.   
  - git://github.com/zendframework/Component_ZendStdlib.git                                                        
    error: The requested URL returned error: 403 Forbidden while accessing https://github.com/zendframework/Compo  
  nent_ZendStdlib.git/info/refs  

Steps to solve:

1.  Verify the connection to github

# ssh -T git@github.com  Permission denied (publickey).
2. Verify that ssh agent is running

# eval "$(ssh-agent -s)"  
Agent pid 100 
3. Verify that the key is loaded into the ssh agent

# ssh-add -l
The agent has no identities.
# ssh-add   
Identity added: /home/{user}/.ssh/id_rsa (/home/{user}/.ssh/id_rsa) 
4. Set-up github's credentials for local computer
# git config --global user.name "{githubuser}"
then copy the local key from  /home/{user}/.ssh/id_rssa.pub into {githubuser}'s account (Settings->SSH keys->Add SSH key)

then verify it:
# ssh -T git@github.com
Hi {githubuser}! You've successfully authenticated, but GitHub does not provide shell access.
5. Run composer update for the specific version you want
# php composer.phar require zendframework/zend-stdlib 2.2.3

Thursday, March 04, 2010

Extract display name from email address


/*
$tomatch = array('Name Surname ','name.surname@blah.com','"b. blah"@blah.co.nz','Some guy <"b. blah"@blah.co.nz>');

foreach ($tomatch as $email) {
print_r(extract_display_name_email($email));
}

*/

function extract_display_name_email($str){
$str = trim($str);
$pos = strrpos($str, '@');
if(false === $pos) return false;

//spaces inside the display name !
if('"' == $str[$pos-1]){
$newpos = strrpos(substr($str, 0, $pos - 1), '"');
if(0 === $newpos) {
$newpos = false; //no display name
}else{
$newpos = strrpos(substr($str, 0, $newpos - 1), ' '); //find last space before "
}
}else{
$newpos = strrpos($str, ' '); //if false then there is no display name
}

if($newpos !== false){
$displayname = trim(substr($str, 0, $newpos));
$email = trim(substr($str, $newpos));
}else{
$displayname = '';
$email = $str;
}
if($email[0] == '<') $email = substr($email, 1, -1); //strip <>
if(strlen($displayname) && $displayname[0] == '"') $displayname = substr($displayname, 1, -1); //strip "

return array('email'=>$email, 'displayname'=>$displayname);
}

Saturday, February 13, 2010

Replace urls in a content

function cleanlinks($var){
if(is_string($var)){
$var = preg_replace("/\n+/", ' ', $var);
$a = preg_match_all('/]*href\s*=\s*([\"\']+)([^\"\'\s>]+?)(\1|>)/i',$var,$matches);
if($a){
foreach ($matches[2] as $url){
$var = str_replace($url, '/', $var);
}
}
}
return $var;
}

Saturday, June 20, 2009

Meniuri










http://f-source.com/










http://www.brainjar.com/css/tabs/demo.html
http://dhtmlx.com/docs/products/dhtmlxTabbar/index.shtml
http://extjs.com/

Thursday, April 16, 2009

thumbnail with borders


function thumbnail($maxx, $maxy, $name_in, $name_out){
$pathinfo = pathinfo($name_in);
if(strtoupper($pathinfo['extension']) != 'JPG' && strtoupper($pathinfo['extension']) != 'JPEG'){
return false;
//not a jpeg image
}

$size = GetImageSize ($name_in); // params of image

// Check if both sides of image exceed allowable proportions.
if($size[0] < $maxx && $size[1] < $maxy) {
$imgWidth = $size[0];
$imgHeight = $size[1];
$dst_x = $dst_y = 0;
}
else {
// Find the largest side (width/height).
if($size[0] > $size[1]) {
$imgLarge = $size[0];
$imgWidth = $maxx;

// Divide that side by the maximum size allowed.
$aspectRatio = $imgLarge / $maxx;

// Determine size of remaining side (height) using the result above.
$imgHeight = round($size[1] / $aspectRatio);
$dst_x = 0;
$dst_y = abs($maxy - $imgHeight) / 2;
}
else {
$imgLarge = $size[1];
$imgHeight = $maxy;

// Divide that side by the maximum size allowed.
$aspectRatio = $imgLarge / $maxy;

// Determine size of remaining side (width) using the result above.
$imgWidth = round($size[0] / $aspectRatio);
$dst_x = abs($maxx - $imgWidth) / 2;
$dst_y = 0;
}
}

$im=@imagecreatefromjpeg($name_in); // path to your gallery
if (!$im) { /* See if it failed */
$im = imagecreate(150, 30); /* Create a blank image */
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
return false;
}

$small = imagecreatetruecolor($maxx, $maxy); // new image
$bgColor = imagecolorallocate($small, 255,255,255);
imagefilledrectangle($small, 0, 0, $maxx-1, $maxy-1, $bgColor);

ImageCopyResampled($small, $im, $dst_x, $dst_y, 0, 0, $imgWidth, $imgHeight, $size[0], $size[1]);
// below is main function resampling image
ImageDestroy($im); // free memory
if (ImageJPEG($small,$name_out,100)){
// try to save image
return true;
}else{
return false;
}
}

Wednesday, April 16, 2008

Secure file upload


function process_upload(){
global $_FILES;
$retVal = false;
$disallowed_ext = array('.php', '.php3', '.php4', '.shtml', '.pl', '.jsp', '.cgi','.exe');
$file_field = $_FILES['file'];

//detect if there are any uploaded files in $_FILES; return false if not
if($file_field['size'] != 0){
$path_parts = pathinfo($file_field['name']);
$ext = '.' . strtolower($path_parts["extension"]);
if(in_array($ext, $disallowed_ext)){
die("Wrong file type ($ext). Please upload other file types than : " . implode(' ',$disallowed_ext) );
}

$new_name = $file_field['name'];
if(move_uploaded_file($file_field['tmp_name'], "$this->working_dir/$new_name")){
chmod("$this->working_dir/$new_name", 0644);
$retVal[] = $new_name;
}

}
return $retVal;
}

Thumbnail


function thumbnail($maxx, $maxy, $name_in, $name_out){
$size = GetImageSize ($name_in); // params of image

// Check if both sides of image exceed allowable proportions.
if(false && $size[0] < $maxx && $size[1] < $maxy) {
$imgWidth = $size[0];
$imgHeight = $size[1];
$dst_x = $dst_y = 0;
}
else {
// Find the largest side (width/height).
if($size[0] > $size[1]) {
$imgLarge = $size[0];
$imgWidth = $maxx;

// Divide that side by the maximum size allowed.
$aspectRatio = $imgLarge / $maxx;

// Determine size of remaining side (height) using the result above.
$imgHeight = round($size[1] / $aspectRatio);
$dst_x = 0;
$dst_y = abs($maxy - $imgHeight) / 2;
}
else {
$imgLarge = $size[1];
$imgHeight = $maxy;

// Divide that side by the maximum size allowed.
$aspectRatio = $imgLarge / $maxy;

// Determine size of remaining side (width) using the result above.
$imgWidth = round($size[0] / $aspectRatio);
$dst_x = abs($maxx - $imgWidth) / 2;
$dst_y = 0;
}
}

$im=@imagecreatefromjpeg($name_in); // path to your gallery
if (!$im) { /* See if it failed */
$im = imagecreate(150, 30); /* Create a blank image */
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an errmsg */
imagestring($im, 1, 5, 5, "Error loading $imgname", $tc);
return false;
}

$small = imagecreatetruecolor($maxx, $maxy); // new image
$bgColor = imagecolorallocate($small, 255,255,255);
imagefilledrectangle($small, 0, 0, $maxx-1, $maxy-1, $bgColor);

ImageCopyResampled($small, $im, $dst_x, $dst_y, 0, 0, $imgWidth, $imgHeight, $size[0], $size[1]);
// below is main function resampling image
ImageDestroy($im); // free memory
if (ImageJPEG($small,$name_out,100)){
// try to save image
return true;
}else{
return false;
}
}

Thursday, March 13, 2008

Extract file name from URI

$req = $_SERVER['REQUEST_URI'];


function parse_request_uri($req){
$filename = strrchr($req, '/');

if('/' == $filename[0]){
$filename = substr($filename, 1);
}

if(($pos = strpos($filename, '?'))!== false){
$filename = substr($filename, 0, $pos);
}

$parts = pathinfo($filename);
return urldecode(strtolower($parts['filename']));
}

Wednesday, January 09, 2008

Common PHP functions

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 sql_date_format($sqldate, $format = 'M j, Y  g:i a'){
 list($dy,$dm,$dd, $h,$m,$s) = sscanf($sqldate, "%4d-%2d-%2d %2d:%2d:%2d");
 $str = date($format, mktime($h, $m, $s, $dm, $dd, $dy));
 return $str;
}


Friday, November 16, 2007

RegEx email parser

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_\-.])@(.+?)\.([^>]+)';

Version #2:

if (preg_match('/^[^\W][a-zA-Z0-9_\.\-]+(\.[a-zA-Z0-9_\-]+)*\@[a-zA-Z0-9_\-]+(\.[a-zA-Z0-9_\-]+)*\.[a-zA-Z]{2,4}$/',$item['email'])) {
...
}

Tuesday, July 31, 2007

Format long texts


/**
* 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 unknown_type $length_limit
* @param unknown_type $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{
$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?'..':'');
}


Wednesday, April 25, 2007

META tag library

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.

http://www.worldsview.com/metataggen_library.zip

Friday, March 16, 2007

Monday, March 12, 2007

php cache


<?php

$url = 'http://www.site.com/file.php';
$dest_file = 'footercache.txt'; //be sure it is chmod-ed to 0666 !!
//Note: for requests by keyword use a cache folder whose rights are 0777 and define the destination file as
//$dest_file = CACHE_FOLDER . '/cache-' . preg_replace('/[^a-z0-9]+/','_', $keyword) . '.txt';
//this may need changes on the line checking the length of the dest_file


$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);
}

?>

Thursday, August 03, 2006

Email validity check

PHP code:

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]);
}

Thursday, July 06, 2006

switch order of two records in a table

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.

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=$id";
$result = mysql_query($sql) or die("SQL ERROR " . mysql_error() . " [$sql] on " . __FILE__ . " at line " . __LINE__);
}
}

Monday, July 03, 2006

Instant popup on mouseover


<STYLE TYPE="text/css">
<!--
#dek {POSITION:absolute;VISIBILITY:hidden;Z-INDEX:200;}
//-->
</STYLE>
<DIV ID="dek"></DIV>

<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.layers
var ns6=document.getElementById&&!document.all
var 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";

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>


Usage:


<a href="mylinkhere.php" ONMOUSEOVER="popup('Popup text','yellow')"; ONMOUSEOUT="kill()">click here</a>