20071029

ipsojobs return, devolviendo código a la comunidad

La gente de ipsojobs ha creado una categoría en su blog que se titula ipsojobs-return, que contiene artículos técnicos, tanto en inglés como en castellano sobre how-tos que se han usado en la página ipsojobs.com.

De momento, acaba de aparecer un segundo tutorial, explicando como crear un widget de tipo UWA (Universal Widget API) que se puede utilizar en NetVibes, en iGoogle y en nuestro propio blog.

El anterior artículo hablaba de como zippear y cachear los javascripts y los CSSs de una página para optimizar la descarga de un site.

ipsojobs.com es una bolsa de trabajo on-line especializada en trabajos urgentes y usa un modelo de administración distribuida remunerando a los administradores de cada ciudad utilizando google adsense.

Nuevo widget UWA para ipsojobs.com

Esta semana hemos estado preparando un widget UWA en ipsojobs, UWA significa "Universal Widget API" y es una especie de standard creado por netvibes para poder crear Widgets en cualquier plataforma (Netvibes, igoogle, opera, iPhone) una especie de "write once, run everywhere" que prometia Sun con Java en su momento pero aplicado al mundo de los Widgets.

Ya puestos a crear un widget, lo hemos creado con UWA, aunque es posible que si salen incompatibilidades debamos crear n-widgets para las n-plataformas sobre las que queramos desarrollar.

Ipsojobs UWA Widget in action

El widget pretende ser algo un poco más complejo que un simple lector de RSS, en concreto los objetivos del widget son:


  • Permitir seleccionar fácilmente la ciudad sobre la que queremos consultar las ofertas de trabajo de ipsojobs.

  • La selección de la ciudad debe ser "dinámica" dado que cada día aparecen ciudades nuevas no puede ser una lista estática.

  • Cuando estas viendo las ofertas de una ciudad siempre podrás cambiar a otra ciudad fácilmente.

  • El número de ofertas por ciudad debe ser personalizable.

  • Una vez seleccionada una ciudad el widget debe "recordar la preferencia" y mostrar las ofertas de la ciudad hasta que el usuario decida cambiarla.


Si quereis probarlo simplemente podéis visitar http://www.ipsojobs.com/widgets/uwa.html

El código del widget UWA es relativamente sencillo, se basa en un sólo fichero XHTML con todos los javascripts y los CSS incrustados.

Declaración:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:widget="http://www.netvibes.com/ns/" >
<head>


<meta name="author" content="Agusti Pons, omatech.com" />
<meta name="description" content="ipsojobs.com find jobs easy in your city" />


<meta name="apiVersion" content="1.0" />
<meta name="autoRefresh" content="20" />
<meta name="debugMode" content="true" />


<link rel="stylesheet" type="text/css" href="http://www.netvibes.com/themes/uwa/style.css" />
<script type="text/javascript" src="http://www.netvibes.com/js/UWA/load.js.php?env=Standalone">


De esta parte, sólo cabe destacar que se debe modificar el autor y la descripción así como el parámetro debugMode, que en producción deberá ser false. El debugMode=true es muy practico porque manda los mensajes de error a la consola del navegador y se puden consultar con el Firebug por ejemplo.

Javascripts útiles:


<script type="text/javascript">
<![CDATA[
function showhide(e)
{
//el = document.getElementById(e);
el = widget.body.getElementsByClassName(e)[0];
el.style.display = el.style.display == "block" ? "none" : "block";
}


function getlang()
{
return widget.lang.substr(0, 2);
}


function link(url)
{
if (widget && widget.openURL)
{
widget.openURL(url);
}
}


function getSelected(ctrl)
{
for(i=0;i
{
if(ctrl[i].checked)
{
return ctrl[i].value;
}
}
return '';
}


function setcity(url)
{
widget.setBody('<p>...</p>');
widget.setValue('url', url);
UWA.Data.getFeed(widget.getValue('url')+'?lang='+getlang(), ipsowidget.display);
}


function selectcity()
{
widget.setTitle('ipsojobs.com widget - setting...');
UWA.Data.getText('http://www.ipsojobs.com/api/controller.php?action=zones_sites_list&xsl=netvibes〈='+getlang(), ipsowidget.zones_sites_processor);
}


function replace(texto,s1,s2)
{
return texto.split(s1).join(s2);
}


function get_change_city()
{
var lang = getlang();
if (lang=='es')
{
return 'Cambiar ciudad';
}
if (lang=='ca')
{
return 'Canviar ciutat';
}
if (lang=='fr')
{
return 'Changer de ville';
}
else
{
return 'Select city';
}
}
]]>
</script>


Las dos funciones más interesantes son setcity() y selectcity() que detallo a continuación:


function setcity(url)
{
widget.setBody('<p>...</p>');
widget.setValue('url', url);
UWA.Data.getFeed(widget.getValue('url')+'?lang='+getlang(), ipsowidget.display);
}


Recibe como parámetro la url del RSS que nos han clicado en la pagina de selección de la ciudad, primero ponemos unos puntos suspensivos para indicar que estamos cargando (widget.setBody('<p>...</p>');) posteriormente actualizamos el valor de la preferencia url (recordad que es oculta y el usuario no la puede ver) con la instrucción widget.setValue('url', url); y finalmente cargamos el feed RSS en el body, fijaos que utilizamos la url de la preferencia que acabamos de actualizar pero le añadimos el parámetro lang basándonos en el language del navegador del usuario UWA.Data.getFeed(widget.getValue('url')+'?lang='+getlang(), ipsowidget.display);.

Para mostrar el RSS feed en el body fijaros que llamamos a la función display del widget que veremos más abajo declarada como ipsowidget.display = function(feed) esta función es muy parecida a la que se explica en el HOWTO de como mostrar un RSS en la web de Netvibes.


function selectcity()
{
widget.setTitle('ipsojobs.com widget - setting...');
UWA.Data.getText('http://www.ipsojobs.com/api/controller.php?action=zones_sites_list&xsl=netvibes〈='+getlang(), ipsowidget.zones_sites_processor);
}


La función selectcity, sólo tiene dos lineas, la primera modifica el título del widget widget.setTitle('ipsojobs.com widget - setting...'); indicando que no estamos en ningúna ciudad sino en la pantalla de setting. La segunda linea carga una url especial de ipsojobs que genera el html necesario para mostrar el seleccionable de las distintas zonas y ciudades UWA.Data.getText('http://www.ipsojobs.com/api/controller.php?action=zones_sites_list&xsl=netvibes〈='+getlang(), ipsowidget.zones_sites_processor); con el html resultante se llama a la función ipsowidget.zones_sites_processor que veremos más abajo y simplemente machaca el body con el nuevo html. Cabe destacar que el html contiene la lista de zonas y sus ciudades ocultas, al clicar sobre la zona se llama a la función showhide para mostrar las ciudades de esta zona. Con iGoogle he comprovado que el desplegado y el plegado no funcionan muy bien porque el widget no se redimensiona correctamente, en cambio si arrastras el titulo del widget como si lo fueses a reposicionar, entonces se recalcula la altura del mismo correctamente.

Preferencias y CSSs:


<title>ipsojobs.com widget
<link rel="icon" type="image/png" href="http://www.netvibes.com/favicon.ico" />


<widget:preferences>
<preference name="url" type="hidden" label="URL" defaultValue="" />
<preference name="limit" type="range" label="Number of items to display" defaultValue="10" step="1" min="1" max="25" />
</widget:preferences>


<style type="text/css">
/* your CSS rules */


body {
height: 400px;
}


a:hover {
cursor: pointer;
}


h2 {
color: #8CC402;
}


h3 {
color: #8CC402;
}


</style>

Aquí podemos ver que creamos una preferencia llamada url de tipo hidden, es la que nos servira para almacenar la url del recurso RSS de la ciudad seleccionada. También creamos el parametro limit que permitirá al usuario seleccionar el numero de ofertas a mostrar en el rango de 1 a 25.

El meollo de la cuestión:


<script type="text/javascript">
<![CDATA[
var ipsowidget = {}


ipsowidget.feed = false;

ipsowidget.display = function(feed)
{
// get the number of items to display
widget.preferences[1].max = feed.items.length;


var toolbar=widget.createElement('h2');
var website_url=replace(widget.getValue('url'), '/rss/controller.php', '');
toolbar.setHTML(''+feed.title+'');


var toolbar2=widget.createElement('h3');
toolbar2.setHTML(''+get_change_city()+'');


widget.setTitle('ipsojobs.com - '+feed.title);

// create the 'ul' element, applying it the CSS class 'nv-feedList'
var feedList = widget.createElement('ul');


// your 'ul' element MUST make use of the 'nv-feedList' class
// to ensure your widget uses the UWA UI library
feedList.className = 'nv-feedList';


// number of parsed items
var j = 0;


// loop through the downloaded items
for(var i=0; i < feed.items.length; i++)
{
// if the limit is reached, stop looping
if (j >= widget.getValue('limit')) break;


// for each item, create the 'li' element
var item = feed.items[i];
var li = widget.createElement('li');


// create and fill the 'a' element of the item with the item's link
var a = widget.createElement('a');
a.href = item.link;


// fill the 'a' element with the item's title
var displayTitle = item.title;
a.innerHTML = displayTitle;


// build the title from the 255 first characters of the content
// remove the content's HTML tags along the way
var title = item.content.stripTags().truncate(255);
a.title = title;


// set a tooltip on the 'a' element, with the item's content
a.onmouseover = function()
{
UWA.Utils.setTooltip(this, this.content, 250);
}


// finally append the 'a' element we just filled, into the 'li' element
li.appendChild(a);


// ...and append the 'li' element to the main 'ul' element
feedList.appendChild(li);
j++;
}


var general=widget.createElement('div');
general.appendChild(toolbar);
general.appendChild(toolbar2);
general.appendChild(feedList);
// once the needed items have been parsed,
// send the main 'ul' element to the HTML body tag
widget.setBody(general);
}


ipsowidget.zones_sites_processor = function(text)
{
widget.setBody(text);
}


widget.onLoad = function()
{
if (widget.getValue('url')=='')
{
selectcity();
}
else
{
//alert(getlang());
UWA.Data.getFeed(widget.getValue('url')+'?lang='+getlang(), ipsowidget.display);
}
}
]]>
</script>


La mayoría de este código es muy parecido al HOWTO de como hacer un RSS widget con UWA (solucionando algún pequeño bug) con las siguientes diferencias:


var toolbar=widget.createElement('h2');
var website_url=replace(widget.getValue('url'), '/rss/controller.php', '');
toolbar.setHTML(''+feed.title+'');


var toolbar2=widget.createElement('h3');
toolbar2.setHTML(''+get_change_city()+'');


widget.setTitle('ipsojobs.com - '+feed.title);


En este fragmento creamos el elemento DOM que nos muestra el nombre de la ciudad seleccionada (con un link a la misma) y el elemento que nos permite cambiar de ciudad. En la última linea también actualizamos la barra de título del widget con el nombre de la ciudad seleccionada.

Al final, hemos añadido los fragmentos DOM creados.

var general=widget.createElement('div');
general.appendChild(toolbar);
general.appendChild(toolbar2);
general.appendChild(feedList);
// once the needed items have been parsed,
// send the main 'ul' element to the HTML body tag
widget.setBody(general);


El onLoad también esta un poco tuneado, en el ejemplo siempre carga la url, pero en nuestro caso puede ser que el widget se haya instalado por primera vez y no tengamos ninguna url en concreto, por eso hacemos lo siguiente:


widget.onLoad = function()
{
if (widget.getValue('url')=='')
{
selectcity();
}
else
{
//alert(getlang());
UWA.Data.getFeed(widget.getValue('url')+'?lang='+getlang(), ipsowidget.display);
}
}


Simplemente detecta si ya tenemos una url fijada y sino llamamos a selectcity que ya se encarga de hacer la llamada AJAX correspondiente para mostrar el selector de ciudades. En caso contrario (este usuario ya tenia la preferencia url fijada para este widget) simplemente la cargamos llamando a UWA.Data.getFeed, fijaros que obtengo el lenguaje del navegador y intento llamar con el lenguaje más apropiado al RSS que me interesa.

Finalmente el body de la página


</head>
<body>
<p>Welcome to the ipsojobs.com widget </p>
<p>...</p>
</body>
</html>


Esta parte no tiene misterio, simplemente mostramos un body, que en seguida se machacará con la función widget.onLoad, que hemos visto más arriba.

20071011

Cache and GZIP your javascripts and CSSs files to speed up your site



I've been trying to mix different sources to optimize the download speed of the javascript files and the CSS files of any web application, in particular I've worked for the IPSOJobs new urgent job bank web page, but it can be applicable in a more general way.

Your Web application can use this files if:


  • You can use .htaccess in your hosting

  • You have CSS only and JS only folders to apply to the whole folder

  • You can use PHP in your hosting



If all the above conditions are met, you can simply add three files to your CSS and/or JS folder and you are done.

Please, take with caution and do some testing, don't use directly in a production environment.


Of course, I'll not give any waranty of succes and you have to check the results using the Firebug Extension of Firefox, the "Live HTTP Headers" extension and the YSlow plugin of the Firebug Extension.

First file .htaccess:
Modify your .htaccess file to include the following:


AddHandler application/x-httpd-php .css .js
php_value auto_prepend_file gzip-start.php
php_value auto_append_file gzip-end.php


This code, tells Apache to automatically run the gzip-start.php before the requested javascript or css file and to run the file gzip-end.php after the conclusion of the requested file.

It's a powerful way to create common headers and footers to pages or files, but be aware that it comes at a cost, it's more fast to serve the static file alone than to run an php script before and one after the file, of course, you have to do some testing and see if it's worthy to do so.

Second file, the magical gzip-start.php:



function get_http_mdate()
{
return gmdate('D, d M Y H:i:s', filemtime($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'])).' GMT';
}

function check_modified_header()
{// This function is based on code from http://ontosys.com/php/cache.html
$headers=apache_request_headers();
$if_modified_since=preg_replace('/;.*$/', '', $headers['If-Modified-Since']);
if(!$if_modified_since)
{
return;
}

$gmtime=get_http_mdate();

if ($if_modified_since == $gmtime)
{
header("HTTP/1.1 304 Not Modified");
exit;
}
}

check_modified_header();

// Open a gzipped buffer
ob_start ("ob_gzhandler");

if (strpos($_SERVER['PHP_SELF'], '.js')>0)
{// Javascript file
header("Content-type: text/javascript");
}
elseif (strpos($_SERVER['PHP_SELF'], '.css')>0)
{// CSS file
header("Content-type: text/css");
}

$offset = 60000000; // Far far away in time

// Expires
header("Expires: ".gmdate("D, d M Y H:i:s", time() + $offset) . " GMT");

// Cache-Control
header("Cache-Control: must-revalidate, max-age=".(time()+$offset));

header("Last-Modified: ".get_http_mdate());

// generate unique ID, using the modification date and the absolute path to the file
$hash = md5(filemtime($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']).$_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']);
header('Etag: "'.$hash.'"');

?>


The concept is clear, this file is interpreted by the PHP runtime rigth before the output of the requested file.

Let's see the different parts of the file:


check_modified_header();


This function looks for the modification date of the requested file (filemtime($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF'])) and returns a HTTP 304 (Not Modified) if the file is fresh, to do that, first looks for a request header If-Modified-Since and then compare the dates.


// Open a gzipped buffer
ob_start ("ob_gzhandler");

if (strpos($_SERVER['PHP_SELF'], '.js')>0)
{// Javascript file
header("Content-type: text/javascript");
}
elseif (strpos($_SERVER['PHP_SELF'], '.css')>0)
{// CSS file
header("Content-type: text/css");
}


These lines opens a PHP buffer with the trick that it's using GZip compression, this is a very good feature of PHP that enables you to output gzipped content without any modification. Afterwards we put the Content-Type of the resulting file, depending of the extension of the file we put text/css or text/javascript.


$offset = 60000000; // Far far away in time

// Expires
header("Expires: ".gmdate("D, d M Y H:i:s", time() + $offset) . " GMT");

// Cache-Control
header("Cache-Control: must-revalidate, max-age=".(time()+$offset));


These lines put the Expires and Cache-Control headers, both far away in time, we create the variable offset with a constant 60 million seconds (about 2 years) and use that to generate a Expires header and a Cache-Control header with the value of two years in the future.

Be warned, your CSS and your JS files will be cached in a lot of proxies and client browsers, you have to use a "rename file policy" in your HTML to prevent the users from using old versions of the files. We've got little javascripts and css files to change, but I recommend to split these kind of files in different folders, for instance /js/usually-modified/omatech.js and apply only the caching technique to the folder usually-modified, then rename each time the .js file with a timestamp, say omatech_20071010.js, and change your html code to reflect the new version.



header("Last-Modified: ".get_http_mdate());

$hash = md5(filemtime($_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']).$_SERVER['DOCUMENT_ROOT'].$_SERVER['PHP_SELF']);
header('Etag: "'.$hash.'"');


The last lines, creates a Last-Modified header, used to indicate the client browser the freshness of the file for future requests, this have interactions with the Cache-Control/max-age and the Expires headers (out of the reach of this post).

Finally we generate an unique Etag header, based on the update time of the requested file and it's full path.


Third and last file, the not less magical gzip-end.php:


header('Content-Length: ' . ob_get_length());
ob_end_flush();
?>


This file simply creates dinamically a Content-Length header with the size of the gzipped buffer we have been using for this request, and then flushes it's contents.

Simple eh ?


I hope you enjoyed and finded useful, feel free to change and play with the code.


I would like to thank the sources where I took inspiration and code:

The tutorial of CSS compression,
Facilitate User Experience with CSS Compression, from Max Kiesler

Good introduction to the problem of speeding up the webpages through caching and zipping javascripts
Serving Javascript Fast, by Cal Henderson

And always a good tutorial even for novices (in Spanish)
¿Por qué y cómo crear un espacio web "cache friendly"? from jcea

20071010

Fascicles de setembre del 2007

Una vegada passat setembre, sempre m'agrada posar la llista de fascicles que he vist anunciats a la tele, de fet les normes son, que els hagi vist a la tele i que m'hagi enrecordat d'apuntar-los :)

Potser aquest any que ja estic definitivament enganxat a la FOX i al AXN fins al punt que no veig gairebé mai les altres cadenes, no he pogut recopilar tots els que han sortit.


Fascicles d'aquest any:


  • Santísima Trinidad

  • Los cuentos de Calleja

  • Cantiflas

  • Formula 1 - SuperSlot

  • Leyendas de Le Mans

  • Stephen King

  • Las tortugas ninja

  • Scalextrix Seat Sport

  • Curso de Ingles de PlanetaAgostini

  • Mickey GEO

  • Ferrari

  • Urgencias en DVD

  • Pilates

  • Biblioteca de Cesar Vidal

  • Monta tu Dinosaurio

  • Lo mejor de la Zarzuela en DVD

  • Erase una vez El Cuerpo Humano

  • Tarta de Fresa

  • Transformers

  • Punto de cruz

  • Las 3 mellizas

  • Pokemon en DVD

  • Monta tu casa Andaluza

  • Guia Esencial de Belleza

  • Curso practico de Pilates

  • Tiranosaurio Rex

  • Los crimenes de Agatha Christie

  • Desafíos Matemáticos

  • La energía de las piedras




TOTAL: 29

Aquí podeu trobar:

20070908

Avui arranca IPSOJOBS, un nou concepte de borsa de treball on-line



Avui arranca IPSOJOBS un projecte intern d'Omatech que esdevindrà el líder en el mercat (poc explorat) de les feines urgents.

IPSOJOBS, te una orientació clarament global, inicialment traduït l'interface en català, castellà, anglés, xines i japones, permet introduïr o cercar ofertes de feina a Barcelona, Girona, Kyoto, Madrid, New York i Shanghai.



El creixement de la web l'estem basant en el que jo anomeno "Greedy Grow" que es basa en que la gent que vol guanyar diners gestionant una bossa de treball IPSOJOBS a la seva ciutat o area pot guanyar d'un 50% a un 100% de la publicitat generada pel seu "IPSOJOBS site", nomes cal que ens possem en contacte i ens doni les seves dades i el seu codi d'adsense de google, per més informació

20070830

Simple substring-before function in php


function substring_before($haystack, $needle)
{
if ($i=stripos($haystack, $needle))
{// Needle found, return from start to needle
return(substr($haystack, 0, $i));
}
else
{// Needle not found
return $haystack;
}
}


Really need an explanation ?

20070829

How to create a simple code checking process in PHP

The other day I was wondering exactly where a call to a function named "get_message" is used in all our php files and xsl files, it's easy to find using some advanced text editor like notepad++ and it's "search in files" functionality.

But, the problem was, I doesn't only need to know where are the calls, I need to know what parameter are used in each call, for example, get_message('HEADER') or get_message('KEYWORDS'), and afterwards I need to check the database to see if the given message (HEADER and KEYWORDS) is inserted there or not.

Of course, do that manually is a very, very, time consuming task, for that reason if prepared a code checking php that can save your day in similar problems.

First, let's create a structure:


function check_dir ($dir_name, $recursive)
{
$handle=opendir($dir_name);
if ($handle)
{
while (false!==($file=readdir($handle)))
{ if (is_file($dir_name.'/'.$file))
{// It's a file
if (substr($file, -3)=='php' && substr($file, 0, 1)!='.')
{// PHP file detected (the second condition avoids MAC temporary files to be checked)
check_php($dir_name.'/'.$file);
}
if (substr($file, -3)=='xsl' && substr($file, 0, 1)!='.')
{// XSL file detected (the second condition avoids MAC temporary files to be checked)
check_xsl($dir_name.'/'.$file);
}
}
}
if ($recursive)
{// The parameter tell us to look for subfolders
closedir($handle);
$handle=opendir($dir_name);
while (false!==($file=readdir($handle)))
{// Loop through the files
if (is_dir($dir_name.'/'.$file))
{// It's a folder
if ($file!='.' && $file!='..')
{// Check the next subfolder, avoiding the current and the parent folders
check_dir($dir_name.'/'.$file, $recursive);
}
}
}
}
closedir($handle);
}
else
{
echo 'I cannot open the folder '.$dir_name;
echo chr(13).chr(10).'
';
}
}



This function loops thought an initial folder and, if the second parameter is set to true, continues checking the directory hierarchy.

There are two functions to check the PHP files and the XSLs files, you can extend this checking to whatever kind of files you want.

Let's see the check_php function:


function check_php($file_path)
{
$file=fopen($file_path,'r');
while(!feof($file))
{// Loop until the end of the file
$line=fgets($file); // read line by line
if (preg_match('/get_message[ ]*\(\'([A-Z_]*)\'\)/', $line, $resultats)>0)
{
array_push($GLOBALS['messages_php'], $resultats[1]);
}
$GLOBALS['cont_lineas_php']++;
}
fclose($file);
}


As you can see in this simple but powerful code, we loop thought the php source file, line by line, and only whith a single if condition check if the line contains a get_message and take the parameter as the result of the evaluation of the regular expression.

This requires further explanation:

preg_match, takes a regular expression as first argument, then checks this regexp against the second argument ($line in the example) and put the resulting part of the evaluation (if any) in an array (the third parameter $resultats in our example). The function returns 0 if no matches where found or the number of matches instead.

The regular expression needs too a little bit of explanation, creating a regex from scratch is relatively simple, but it's a tricky language and very difficult to maintain:

- The regular expression starts with "/" and ends with "/" (first mistery solved)
- "get_message" this is a literal that we are looking for in the input
- "[ ]*" this means that we expect none or any number of whitespaces in the input just after the get_message array, this is for avoid the problem of undetecting some calls like "get_message ('blah')" or "get_message ('blah')" instead of the commonly used "get_message('blah')"
- \(\' and \'\) simply used to detect the string opening with (' and ending with ') the backslashes simply are the escape characters of the regular expressions.
- ([A-Z_]*) Thats the core of the regexp we are trying to create, simply indicates that we are looking for any combination of uppercase letters "A-Z" and underscores "_", the square brackets indicates the different permutations and the star means zero or more characters in the combination. Last but not least, the enclosing parenthesis makes the included combination a result of the regular expression evaluation, only the parenthesized part of the regexp can be taken after the evaluation as part of the result, that is the part that is returned to the $resultats array when finished.

The theory explained, let's look for a couple of examples:
$keywords=get_message ('KEYWORDS'); --> return 1 and $result is an array containing the value KEYWORDS
$description=get_message('DESCRIPTION'); --> return 1 and $result is an array containing the value DESCRIPTION
$hello_world=get_message('HELLO_WORLD'); --> return 1 and $result is an array containing the value HELLO_WORLD
$hola = 'hola'; --> return 0

Additionally we increase the global counter of php lines in all the application with the line $GLOBALS['cont_lineas_php']++;

The check_xsl function is very similar to the check_php function only looking for a different regular expression and updates other variables:


function check_xsl($file_path)
{
$file=fopen($file_path,'r');
while(!feof($file))
{
$line=fgets($file);
if (preg_match('/[ ]*([A-Z_]*)0)
{
if (!stripos($line, ' {
array_push($GLOBALS['messages_xsl'], $resultats[1]);
}
}
$GLOBALS['cont_lineas_xsl']++;
}
fclose($file);
}



Now let's look for the part where we call the functions:


check_dir($_SERVER['DOCUMENT_ROOT'], false);
check_dir($_SERVER['DOCUMENT_ROOT'].'/actions/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/admin/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/ajax/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/batchs/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/captcha/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/conf/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/models/', true);


check_dir($_SERVER['DOCUMENT_ROOT'].'/rss/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/styles/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/utils/', true);
check_dir($_SERVER['DOCUMENT_ROOT'].'/views/', true);

echo 'PHP LINES: '.$GLOBALS['cont_lineas_php'];
echo chr(13).chr(10).'
';
echo 'XSL LINES: '.$GLOBALS['cont_lineas_xsl'];
echo chr(13).chr(10).'
';
echo chr(13).chr(10).'
';


This calls simply check all the directories I needed to check and output the number of lines of php and xsl that we have.

Finally we want to do a more sophisticated analysis with the data we have collected, we want to look if all the messages collected in
the arrays $GLOBALS['messages_xsl'] and $GLOBALS['messages_php'] really exists in the database and report if there are some inexistent (which is an error and must be solved)


$unics=array_unique(array_merge($GLOBALS['messages_php'], $GLOBALS['messages_xsl']));
$no_existents=array_filter($unics, 'not_exist_message');
echo 'NONEXISTING MESSAGES IN THE DB: '.count($no_existents);
echo chr(13).chr(10).'
';
echo implode($no_existents, ', ');
echo chr(13).chr(10).'
';
echo chr(13).chr(10).'
';

echo 'UNIQUE MESSAGES IN GENERAL: '.count($unics);
echo chr(13).chr(10).'
';
echo implode($unics, ', ');
echo chr(13).chr(10).'
';
echo chr(13).chr(10).'
';


The first line merges the two arrays with array_merge, then generates an unique array and put it into $unics variable.

The second line filters the $unics array with a custom function that checks the database for this message in particular, here is the function:


function not_exist_message ($value)
{
return(!exist_message($value));
}

function exist_message ($value)
{
$sql='select count(*) num
from messages m
where codi="'.$value.'"
';

$dbh=get_db_handler();
$result = mysql_query($sql, $dbh);
if(!$result)
{
return false;
}
$row = mysql_fetch_array($result, MYSQL_ASSOC);
return($row['num']>0);
}


The array_filter, runs the function in the second parameter thought each element of the array, and the resulting array contains only the elements that the function evaluates as true. The function exist_message simply executes an sql statement that counts the number of occurrences of the given message in the database.

That's all, for completeness here is the initial part of the declaration of variables and includes and so on:


require_once($_SERVER['DOCUMENT_ROOT'].'/conf/ompDB.php');

echo 'Code control report:';
echo chr(13).chr(10).'
';

$GLOBALS['cont_lineas_php']=0;
$GLOBALS['messages_php']=array();
$GLOBALS['cont_lineas_xsl']=0;
$GLOBALS['messages_xsl']=array();


And a sample of output generated by the execution of the php file:


Code control report:
PHP LINES: 7886
XSL LINES: 992

NONEXISTING MESSAGES IN THE DB: 28
HEADER_CENTRAL_EDITABLE_POSTS_CLEAR, STATIC_HEADER_HOW_IT_WORKS, STATIC_CONTENT_HOW_IT_WORKS, HEADER_MESSAGE_ADD_POST, STATIC_HEADER_FOLLOW_OFFERS, STATIC_CONTENT_FOLLOW_OFFERS, EXPLICATION_RSS_LINK_CITY, EXPLICATION_RSS_LINK_CATEGORY, SECURITY_ERROR_HEADER, SECURITY_ERROR, SECURITY_ERROR_NOT_EDITABLE, EDIT_YOUR_POST, POST_UPDATED, POST_UPDATED_LONG, POST_UPDATE_ERROR, POST_UPDATE_ERROR_LONG, HEADER_POST_SAVED_ERROR, ERROR_POST_UNKNOWN, ERROR_SITE_UNKNOWN, SUBJECT_SEND_TO_A_FRIEND, PREBODY_SEND_TO_A_FRIEND, POSTBODY_SEND_TO_A_FRIEND, MESSAGE_SENT_SUCCESFULLY, MESSAGE_SENT_ERROR, EXPLICATION_RSS, EXPLICATION_CITIES_RSS, EXPLICATION_CATE_RSS, EDITABLE_POST_LINK

UNIQUE MESSAGES IN GENERAL: 123
LANGUAGE_NOT_SUPPORTED, LANGUAGE_CHANGED, TITLE, ADD_POST_SINGLE, ADD_POST, EDITABLE_POSTS, EDITABLE_POSTS_CLEAR, HEADER_CENTRAL_EDITABLE_POSTS_CLEAR, HEADER_SEARCH, SEARCH_ERROR, STATIC_HEADER_WHO_WE_ARE, STATIC_CONTENT_WHO_WE_ARE, STATIC_HEADER_CONDITIONS, STATIC_CONTENT_CONDITIONS, STATIC_HEADER_WHAT_IS, STATIC_CONTENT_WHAT_IS, STATIC_HEADER_HOW_IT_WORKS, STATIC_CONTENT_HOW_IT_WORKS, DONE, CATEGORY_NEEDED, TITLE_NEEDED, DESCRIPTION_NEEDED, CONTACT_NEEDED, SECURITY_CODE_NEEDED, HEADER_MESSAGE_ADD_POST, INSERT_YOUR_POST, POST_SAVED, POST_SAVED_LONG, POST_SAVE_ERROR, POST_SAVE_ERROR_LONG, HEADER_CENTRAL_ADD_POST, STATIC_HEADER_FOLLOW_OFFERS, STATIC_CONTENT_FOLLOW_OFFERS, EXPLICATION_RSS_LINK_CITY, EXPLICATION_RSS_LINK_CATEGORY, HEADER_CENTRAL_EDIT_POST, SECURITY_ERROR_HEADER, SECURITY_ERROR, SECURITY_ERROR_NOT_EDITABLE, EDIT_YOUR_POST, POST_UPDATED, POST_UPDATED_LONG, POST_UPDATE_ERROR, POST_UPDATE_ERROR_LONG, HEADER_CENTRAL_EDITABLE_POSTS, HEADER_CENTRAL_HOME, HEADER_CENTRAL_POST, HEADER_POST_SAVED, HEADER_POST_SAVED_ERROR, GO_TO, HEADER_CENTRAL_CATEGORIES, REPORT_POSTED, REPORT_NOT_POSTED, FLAG_SHORT, MOTIVES, REPORT, SEND_SHORT, NAME_EMAIL, FRIEND_EMAIL, MESSAGE_EMAIL, SUBMIT_EMAIL, ACTIVE_POSTS, LAST_ACTIVE_POST, CITY, POST_DETAIL_FLAG_INCORRECT, POST_DETAIL_FLAG_CORRECT, ERROR_POST_UNKNOWN, ERROR_NAME_EMAIL, ERROR_FRIEND_EMAIL, ERROR_MESSAGE_EMAIL, ERROR_SITE_UNKNOWN, SUBJECT_SEND_TO_A_FRIEND, PREBODY_SEND_TO_A_FRIEND, POSTBODY_SEND_TO_A_FRIEND, MESSAGE_SENT_SUCCESFULLY, MESSAGE_SENT_ERROR, TIME_DAYS, TIME_DAY, TIME_HOURS, TIME_HOUR, TIME_MINUTES, TIME_MINUTE, TIME_FEW, SEARCH_BOX_TEXT, BUTTON_SEARCH, HEADER_CITIES, HEADER_AD, GLOBAL_SELECT_LANG, GLOBAL_SELECT_CITY, STATIC_WHO_WE_ARE, STATIC_BLOG, STATIC_CONDITIONS, STATIC_WHAT_IS_IPSO, HEADER_CATEGORIES, HOME_SELECT_CITY, HOME_CITIES, HOME_LANGUAGES, HEADER_TITLE_HOME_OFFER, VIEW_DETAIL, POST_CATEGORY, POSTED, NO_POST_IN_SEARCH, POST_TITLE, POST_TITLE_EXPLAIN, POST_CATEGORY_EXPLAIN, POST_DESCRIPTION, POST_DESCRIPTION_EXPLAIN, POST_CONTACT_CONDITIONS, POST_CONTACT_CONDITIONS_EXPLAIN, CAPTCHA, CAPTCHA_EXPLAIN, POST_SUBMIT_BUTTON, EXPLICATION_RSS, EXPLICATION_CITIES_RSS, EXPLICATION_CATE_RSS, EDITABLE_POST_LINK, NO_POST_IN_CATEGORY, RELATED_POSTS, FLAG_LONG, SEND_LONG, VIEWED, TIMES, CATEGORIES


Ways to improve:
- We must upgrade the code count of lines avoiding whitespace-only lines and commented lines.

That's all folks

20070821

Cumpleaños feliz para la cheerleader de Heroes



Hoy es un gran dia para los seguidores masculinos de la serie Heroes, Hayden Panettiere, la actriz que encarna a Claire la famosa Cheerleader de la serie cumple 18 años.

Para todos aquellos que han tenido fantasias con esta chica, felicidades, ya son legales (por lo menos en gran parte del mundo)

:)

Ah, felicidades para ti también, Hayden !

20070813

Harry Potter via amazon.com


El mateix dia 21 de juliol vaig fer la comanda de l'últim volum de Harry Potter (and the deathly hallows).

El dijous em va arribar de Amazon US (vaig ser tonto de no demanar-lo a UK) i vaig flipar amb el packaging especial que portava.

Als costats posava "HARRY POTTER AND THE DEATHLY HALLOWS" i "YEAR 7" respectivament i a la part d'adalt sortia el típic mussol missatger.

Lo millor eren els missatges de warning:

ATTENTION MUGGLES - DO NOT DELIVER OR OPEN BEFORE JULY 21!

BRUTAL !!!




A part em vaig demanar dos llibres més (Fast food nation i On intelligence) pero els de amazon son la polla i van fer dos enviaments, un amb el packaging especial de Harry Potter i l'altre standard.

Això es customer care, lo demés son tonteries !



20070726

Meneame caido



Es raro en meneame tener downtime, pero cuando lo tienen lo hacen con estilo, como mínimo no se ve tanto como el plumber de bloglines i el gatito de twitter...

De hecho podeis continuar viendo la pagina de error cuando querais en lounge