Sobreescribir funciones internas de PHP mediante namespaces

Una de las novedades que trae PHP 5.3 son los namespaces, un modo de encapsulación de elementos. Gracias a los namespaces podemos ejecutar un mismo código usando diferentes namespaces y así obteniendo diferentes resultados.

Esta opción nos permite sobreescribir funciones de PHP y usarlas en nuestro código:

namespace Foo;
function file_put_contents( $filename, $data, $flags = 0, $context = null ) {
$return = \file_put_contents( $filename, $data, $flags, $context );
chmod($filename, 0444);
return $return;
}

What’s new in PHP V5.3, Part 3: Namespaces

openark kit: utilidades DBA para MySQL

openark kit es una serie de scripts en Python que nos facilitará las tareas de DBA (sobre todo para aquellos que no es nuestro fuerte). Consta de las siguientes aplicaciones:

openark kit

Nitobi UI: elementos UI para javascript

Impresionante librería para incluir elementos UI en nuestras aplicaciones javascript. Contiene los siguientes elementos:

  • Grid: tabla con celdas estilo hoja de cálculo
  • TreeGrid: igual que el anterior pero permite desplegar filas
  • ComboBox: un combo mas interactivo, como los de auto-sugerencias
  • TabStrip: gestión de pestañas
  • Tree: árbol de datos, tipo directorios/ficheros
  • FishEye: aumentar elementos con efecto “ojo de pez”
  • Callout: mensajes popup en plan bocadillo
  • Spotlight: resaltar elementos DOM, muy útil para realizar guías interactivas
  • Calendar: calendarios
  • Toolkit: herramientas varias para Ajax

Nitobi UI

Realizar gráficas con MySQL y Google Graph

Buen ejemplo para obtener la URL que nos dibuja gráficas usando Google Graph mediante procedimientos almacenados de MySQL. Está sacado de este ejemplo, que a su vez está sacado de este otro para Oracle.

DELIMITER $$
DROP FUNCTION IF EXISTS `dm_midas`.`FNC_GOOGRAPH_DB_SIZE`$$
CREATE FUNCTION `dm_midas`.`FNC_GOOGRAPH_DB_SIZE` (
p_chart_type CHAR,
p_height INT,
p_width INT) RETURNS varchar(3000) CHARSET latin1
READS SQL DATA
BEGIN
/* Author:    Walter Heck - OlinData */
/* Date:      20090216 */
/* Note:      After an idea by Alex Gorbachev - Pythian */
/*            http://www.pythian.com/blogs/1490/google-charts-for-dba-tablespaces-allocation */
/* variable declaration */
DECLARE v_done BOOLEAN default false;
DECLARE v_url varchar(3000);
DECLARE v_schema_name varchar(3000);
DECLARE v_data_length_sum int;
DECLARE v_data_length_total int;
DECLARE v_legend_labels varchar(3000);
DECLARE v_chart_labels varchar(3000);
DECLARE v_chart_data varchar(3000);
/* Cursor declaration */
DECLARE c_schema_sizes cursor for
select
t.table_schema,
round(sum(t.data_length + t.index_length) / 1024 / 1024) as data_length_schema
from
information_schema.tables t
group by
t.table_schema
order by
t.table_schema;
/* Handler declaration */
DECLARE CONTINUE HANDLER FOR NOT FOUND SET v_done = true;
/* Initialize the variables */
SET v_legend_labels = '';
SET v_chart_labels = '';
SET v_chart_data = '';
/* Get the total data length + index_length for all tables */
select
round(sum(t.data_length + t.index_length) / 1024 / 1024) as data_length_total
into
v_data_length_total
from
information_schema.tables t;
/* Open the cursor */
OPEN c_schema_sizes;
/* Loop through the cursor */
get_data: LOOP
/* Fetch the next row of data into our variables */
FETCH c_schema_sizes INTO v_schema_name, v_data_length_sum;
/* if there is no more data, v_done will be true */
IF v_done THEN
/* Exit the loop */
LEAVE get_data;
END IF;
/* Add the schema name to the labels for the legend */
IF v_legend_labels = '' THEN
SET v_legend_labels = v_schema_name;
ELSE
SET v_legend_labels = concat(v_legend_labels, '|', v_schema_name);
END IF;
/* Add the total size of the schema to the labels */
IF v_chart_labels = '' THEN
SET v_chart_labels = v_data_length_sum;
ELSE
SET v_chart_labels = concat(v_chart_labels, '|', v_data_length_sum);
END IF;
/* Get the percentage of the total size as the graph's data */
IF v_chart_data = '' THEN
SET v_chart_data = ROUND(v_data_length_sum / v_data_length_total, 2) * 100;
ELSE
SET v_chart_data = concat(v_chart_data, ',', ROUND(v_data_length_sum / v_data_length_total, 2) * 100);
END IF;
END LOOP get_data;
/* Close the cursor */
CLOSE c_schema_sizes;
/* Build up the google graph url */
SET v_url = 'http://chart.apis.google.com/chart?';
SET v_url = CONCAT(v_url, 'cht=', p_chart_type);
SET v_url = CONCAT(v_url, '&chs=', p_width , 'x', p_height);
SET v_url = CONCAT(v_url, '&chtt=Database Sizes (MB)');
SET v_url = CONCAT(v_url, '&chl=', v_chart_labels);
SET v_url = CONCAT(v_url, '&chd=t:', v_chart_data);
SET v_url = CONCAT(v_url, '&chdl=', v_legend_labels);
/* return the url as the function's result */
RETURN v_url;
END$$
DELIMITER ; 

MySQL DB Pie Graph

Librería PHP para Paypal, Authorize.net y 2Checkout

PHP Payment es una librería PHP para realizar pagos en tres de las plataformas de pagos Paypal, Authorize.net y 2Checkout haciendo el proceso de pago bastante sencillo, como por ejemplo para Paypal:

// Include the paypal library
include_once ('Paypal.php');
// Create an instance of the paypal library
$myPaypal = new Paypal();
// Specify your paypal email
$myPaypal->addField('business', 'YOUR_PAYPAL_EMAIL');
// Specify the currency
$myPaypal->addField('currency_code', 'USD');
// Specify the url where paypal will send the user on success/failure
$myPaypal->addField('return', 'http://YOUR_HOST/payment/paypal_success.php');
$myPaypal->addField('cancel_return', 'http://YOUR_HOST/payment/paypal_failure.php');
// Specify the url where paypal will send the IPN
$myPaypal->addField('notify_url', 'http://YOUR_HOST/payment/paypal_ipn.php');
// Specify the product information
$myPaypal->addField('item_name', 'T-Shirt');
$myPaypal->addField('amount', '9.99');
$myPaypal->addField('item_number', '001');
// Specify any custom value
$myPaypal->addField('custom', 'muri-khao');
// Enable test mode if needed
$myPaypal->enableTestMode();
// Let's start the train!
$myPaypal->submitPayment();

PHP Payment Library for Paypal, Authorize.net and 2Checkout (2CO)

Intercambiando el valor de columnas en MYSQL

Interesantes métodos para intercambiar el valor de dos columnas en MySQL.

UPDATE swap_test SET x=y, y=@temp WHERE (@temp:=x) IS NOT NULL;

Este método no funciona cuando alguna de las columnas tiene valor NULL, y los paréntesis son obligatorios.

Otro método, que no tendría problemas con los NULL, sería:

UPDATE swaptest s1, swaptest s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;

Swapping Column Values in MySQL

Parsear HTML con PHP

Para obtener datos de un HTML, en vez de hacerlo con expresiones regulares, hacerlo mediante DOMDocument:

$oldSetting = libxml_use_internal_errors( true );
libxml_clear_errors();
$html = new DOMDocument();
$html->loadHtmlFile( $url );
$xpath = new DOMXPath( $html );
$links = $xpath->query( '//a' );
foreach ( $links as $link ) {
echo $link->getAttribute( 'href' ), "\n";
}
libxml_clear_errors();
libxml_use_internal_errors( $oldSetting ); 

Se utiliza libxml_use_internal_errors para evitar HTML mal formados

Me pregunto si para obtener tan solo un dato del HTML (title por ejemplo) es mejor el DOM o las expresiones regulares.

Extracting data from HTML

Le roban maestrosdelweb.com y forosdelweb.com a Christian Van Der Henst

Los eventos sucedieron, más o menos, así:

  1. Christian Van Der Henst cuenta por medio de su Twitter: «Fuck, alguien logro accesar a mi cuenta de Godaddy y cambio los datos de mis dominios», refiriéndose a Maestrosdelweb.com.
  2. Christian contacta a PayPal para que lo ayuden, sin éxito.
  3. El o los cybersquatters cambiaron los DNS de los dominios y también se apoderaron de su cuenta de Facebook.
  4. Teniendo el dominio maestrosdelweb.com ya apuntando a otro servidor, recrean el email personal de Christian y tratan de apoderarse de su hosting, sin éxito.
  5. Hace casi tres horas (de escrito este post) se apoderan de su cuenta de Gmail.

Esto es practicamente una pesadilla, toda tu propiedad virtual desaparece y es robada por alguien con mucho tiempo en las manos o con ganas de hacer dinero fácil. Lamentablemente GoDaddy (donde los dominios están registrados) y su soporte técnico no son de especial ayuda, lo cual es sumamente grave considerando que ellos pueden solucionar todo el problema en unos minutos.

Por el momento las mejores formas de ayudar son:

  • Escribiendo posts en sus respectivos blogs pidiendo más ayuda
  • Escribiendo en Twitter al respecto, usando el hashtag #MdW.
  • Escribiendo a @GodaddyGuy que por favor devuelvan el dominio, de preferencia en inglés. Pueden retwittear este mensaje.
  • ¡¡Ánimo Chris!!

    Vía / Alt1040