Generated 2026-01-13 05:45
<?php
/**
* @category Gen
* @package Gen_Array
*/
class Gen_Array
{
public static function where(array $arr, $property, $condition)
{
$filtered = array();
foreach($arr as $key => $value) {
if (is_array($value) && isset($value[$property]) && $value[$property] == $condition) {
$filtered[$key] = $value;
}
}
return $filtered;
}
public static function reduce(array $arr, $property)
{
$reduced = array();
foreach($arr as $key => $value) {
if (is_array($value) && isset($value[$property])) {
$reduced[$key] = $value[$property];
}
}
return $reduced;
}
public static function search($str, array $arr)
{
require_once('Gen/Str.php');
foreach($arr as $key => $value) {
$value = Gen_Str::transformAccents($value);
$value = mb_strtolower($value);
if (preg_match("#$str#", $value)) return $key;
}
return false;
}
public static function count(array $arr)
{
return count($arr);
}
public static function computeNbrOfRecursiveElements(array $arr)
{
$result=array();
foreach ($arr as $values):
$num = 0;
foreach ($arr as $value):
if ($values == $value) {
$num++;
}
endforeach;
$result[$values] = $num;
endforeach;
return $result;
}
public static function getKeysFromArray(array $array)
{
$result = array();
foreach ($array as $key => $data) :
array_push($result,$key);
endforeach;
return $result;
}
public static function flatten(array $array)
{
foreach($array as $k=>$v) {
$array[$k]= (array) $v;
}
return call_user_func_array('array_merge',$array);
}
}
<?php
require_once('Gen/Str.php');
class Gen_ClassLoader
{
/**
*
* @param String $className ex: Theme
* @param String $moduleName ex:Album
* @param String $suffix ex:Controller
* @param String $directoryPath ex:'./application/Controller/
*/
public static function loadClass($classKey, $moduleName, $suffix = null, $directoryPath)
{
if($moduleName) {
$moduleName = Gen_Str::camelize($moduleName, false);
}
$className = (string) self::getClassName($classKey, $suffix);
/** perform action only if class not already loaded */
if (!class_exists($className, false)) {
$fileName = self::getFileName($classKey, $suffix);
$file = $directoryPath . ($moduleName ? $moduleName . '/' : '' ) . $fileName;
if (file_exists($file)) {
require($file);
return $className;
}
Gen_Log::log('File Not Found: ' . $file, 'Gen_ClassLoader::loadClass', 'warning');
return false;
}
return $className;
}
/**
* Format a File name
*
* @param string $controller key
* @return Gen_String
*/
public static function getFileName($str, $suffix = null)
{
return Gen_Str::namespaceToFile($str, $suffix);
}
/**
* Format a ClassName
*
* @param sting $controller key
* @return Gen_String
*/
public static function getClassName($str, $suffix = null)
{
$str = $str . ($suffix !== null ? ('_' . $suffix) : '');
return Gen_Str::classify($str);
}
}
<?php
/**
* @category Gen
* @package Gen_Cryptography
*/
class Gen_Cryptography
{
public static function encrypt($text)
{
$cipher='AES-128-CBC';
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($text, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
return $ciphertext;
}
public static function decrypt($ciphertext)
{
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
return $original_plaintext;
}
return false;
}
}
<?php
/**
* @category Gen
* @package Gen_Cryptography
*/
class Gen_Cryptography
{
public static function encrypt()
{
}
public static function decrypt()
{
}
}
<?php
/**
* @category Gen
* @package Gen_Css
*/
class Gen_Css
{
const LENGTH = '(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0';
const CSS3 = '(border-radius|box-shadow)';
const CSS_BLOCK = '{([^}]+)}';
const SELECTOR = '$';
public static $properties = array('margin-left','margin-right','margin-top','margin-bottom','margin','padding-left','padding-right','padding-top','padding-bottom','padding','display', 'position', 'border-color', 'border-left','border-right', 'border-top', 'border-bottom', 'border-radius', 'border', 'color','background-color', 'font', 'font-size', 'font-weight', 'line-height', 'text-transform', 'text-decoration', 'list-style-type', 'width', 'min-width', 'max-width', 'height', 'min-height', 'max-height', 'top', 'bottom', 'right', 'left');
public static $pseudoClasses = array('hover', 'before', 'after', 'focus', 'active');
public static $cacheDir = 'public/styles/';
public static $srcDir = 'css/';
public static $debug = false;
public static function getCacheFile($file)
{
return self::$cacheDir . $file;
}
public static function getSrcFile($file)
{
return self::$srcDir . $file;
}
public static function process($file)
{
$cacheFile = self::getCacheFile($file);
$srcFile = self::getSrcFile($file);
if (!file_exists($srcFile)) {
return false;
}
if (!file_exists($cacheFile) || (filemtime($cacheFile) < filemtime($srcFile)) || self::$debug) {
$content = self::parse($srcFile);
file_put_contents($cacheFile, $content);
}
return true;
}
public static function parse($file)
{
if (!file_exists($file))
{
return false;
}
$str = file_get_contents($file);
return self::parseStr($str);
}
public static function parseStr($str)
{
$str = self::importFilter($str);
$str = self::constantFilter($str);
$str = self::mixinFilter($str);
$str = self::minify($str);
return $str;
}
public static function match($pattern, $str, $flag = PREG_SET_ORDER)
{
$regexp = '/' . $pattern . '/s';
if(preg_match_all($regexp, $str, $matches, $flag)) {
return $matches;
}
return array();
}
public static function escape($str)
{
$str = str_replace('/', '\/', $str);
$str = str_replace('.', '\.', $str);
return $str;
}
public static function matchProperty($property, $str)
{
$regexp = '('. self::escape($property) .')\s*:\s*(.*?)\s*;';
return self::match($regexp, $str);
}
public static function matchSelector($selector, $str)
{
$regexp = '('. self::escape($selector) .')\s*{\s*(.*?)\s*}';
return self::match($regexp, $str);
}
/****************************
* Filters *
****************************/
public static function importFilter($str)
{
$regexp = '#@import ?\("([^)]*)"\);#';
preg_match_all($regexp, $str, $matches, PREG_SET_ORDER);
foreach($matches as $match) {
$replace = '/** ' . $match[0] . ' */';
$file = self::getSrcFile($match[1]);
if (file_exists($file)) {
$replace .= "\n" . file_get_contents($file);
}
$str = str_replace($match[0], $replace, $str);
}
return $str;
}
public static function minify($str)
{
$str = preg_replace('#\/\*[\s\S]*?\*\/#', '', $str); // delete comments
$str = preg_replace('#\s+#', ' ', $str); // Normalize white spaces
$str = preg_replace('#\s*([!{}:;>+,\]\)])#', '$1', $str); // delete unnecessary white spaces
$str = preg_replace('#([!{}:;>+\(\[,])\s*#', '$1', $str); // delete unnecessary white spaces
$str = preg_replace('#}#', "}\n", $str); // split lines
$str = preg_replace('#^\s+|\s+$#', '', $str); // trim file
return $str;
}
public static function constantFilter($str)
{
$results = array();
$regexp = '#@constants ?{([^}]+)}#s';
preg_match($regexp, $str, $matches);
if ($matches) {
$parts = explode(';', rtrim(rtrim($matches[1]), ';'));
foreach ($parts as $part) {
$var = explode(':', $part);
$key = self::SELECTOR . trim($var[0]);
$value = trim($var[1]);
$str = str_replace($key, $value, $str);
}
$str = preg_replace($regexp, '', $str);
}
return $str;
}
public static function mixinFilter($str)
{
$properties = self::matchProperty('mixin', $str);
foreach ($properties as $prop)
{
$selectors = self::matchSelector('.' . $prop[2], $str);
$selector = $selectors ? $selectors[0][2] : '';
$str = str_replace($prop[0], $selector, $str);
}
return $str;
}
}
<?php
class Gen_Date
{
const DEFAULT_LANGUAGE = 'en';
protected static $_date_format = array(
'en' => array (
'short' => 'j M Y',
'short_time' => 'j M Y \a\t g:ia',
'long' => 'F jS, Y',
'long_time' => 'F jS, Y \a\t g:ia',
'numeric' => 'Y/m/j',
'numeric_time' => 'Y/m/j \a\t g:ia',
'smart_date' => 'l, \a\t g:ia',
'time' => 'g:ia',
),
'fr' => array (
'short' => 'j M Y',
'short_time' => 'j M Y à G\hi',
'long' => 'j F Y',
'long_time' => 'j F Y à G\hi',
'numeric' => 'd/m/Y',
'numeric_time' => 'd/m/Y à G\hi',
'smart_date' => 'l, à G\hi',
'time' => 'G\hi',
),
'de' => array (
'short' => 'j M Y',
'short_time' => 'j M Y \u\m G:i',
'long' => 'j. F Y',
'long_time' => 'j. F Y \u\m G:i',
'numeric' => 'd.m.Y',
'numeric_time' => 'd.m.Y \u\m G:i',
'smart_date' => 'l, \u\m G:i',
'time' => 'G:i',
),
'es' => array (
'short' => 'j M Y',
'short_time' => 'j M Y a las G:i',
'long' => 'j \d\e F Y',
'long_time' => 'j \d\e F Y a las G:i',
'numeric' => 'd/m/Y',
'numeric_time' => 'd/m/Y a las G:i',
'smart_date' => 'l, a las G:i',
'time' => 'G:i',
),
'it' => array (
'short' => 'j M Y',
'short_time' => 'j M Y alle ore G.i',
'long' => 'j F Y',
'long_time' => 'j F Y alle ore G.i',
'numeric' => 'd/m/Y',
'numeric_time' => 'd/m/Y alle ore G.i',
'smart_date' => 'l, alle ore G.i',
'time' => 'G.i',
),
'pt' => array (
'short' => 'j M Y',
'short_time' => 'j M Y às G:i',
'long' => 'j/n Y',
'long_time' => 'j/n Y às G:i',
'numeric' => 'd/m/Y',
'numeric_time' => 'd/m/Y às G:i',
'smart_date' => 'l, às G:i',
'time' => 'G:i',
),
);
protected static $_date_messages = array(
'en' => array (
'now' => 'a few seconds ago',
'seconds' => '%d seconds ago',
'minutes' => array('singular' => 'a minute ago' , 'plural' => '%d minutes ago'),
'hours' => array('singular' => 'an hour ago' , 'plural' => '%d hours ago'),
'days' => '%s',
'date' => '%s',
'today' => 'Today, at %s',
'yesterday' => 'Yesterday, at %s',
'tomorrow' => 'Tomorrow, at %s',
'period' => 'from %s to %s',
),
'fr' => array (
'now' => 'Il y a quelques secondes',
'seconds' => 'Il y a %d secondes',
'minutes' => array('singular' => 'Il y a une minute' , 'plural' => 'Il y a %d minutes'),
'hours' => array('singular' => 'Il y a une heure' , 'plural' => 'Il y a %d heures'),
'days' => '%s',
'date' => 'le %s',
'today' => 'Aujourd\'hui, à %s',
'yesterday' => 'Hier, à %s',
'tomorrow' => 'Demain, à %s',
'period' => 'du %s au %s',
),
'de' => array (
'now' => 'Vor einigen Sekunden',
'seconds' => 'Vor %d Sekunden',
'minutes' => array('singular' => 'Vor einer Minute' , 'plural' => 'Vor %d Minuten'),
'hours' => array('singular' => 'Vor einer Stunde' , 'plural' => 'Vor %d Stunden'),
'days' => '%s',
'date' => 'am %s',
'today' => 'Heute um %s',
'yesterday' => 'Gestern um %s',
'tomorrow' => 'Morgen um %s',
'period' => 'von %s auf %s',
),
'es' => array (
'now' => 'Hace unos segundos',
'seconds' => 'Hace %d segundos',
'minutes' => array('singular' => 'Hace un minuto' , 'plural' => 'Hace %d minutos'),
'hours' => array('singular' => 'Hace una hora' , 'plural' => 'Hace %d horas'),
'days' => '%s',
'date' => 'el %s',
'today' => 'Hoy a la(s) %s',
'yesterday' => 'Ayer a la(s) %s',
'tomorrow' => 'Mañana a la(s) %s',
'period' => 'de %s a %s',
),
'it' => array (
'now' => 'Pochi secondi fa',
'seconds' => '%d secondi fa',
'minutes' => array('singular' => 'Un minuto fa' , 'plural' => '%d minuti fa'),
'hours' => array('singular' => 'Uno ora fa' , 'plural' => '%d ore fa'),
'days' => '%s',
'date' => 'il %s',
'today' => 'Oggi alle %s',
'yesterday' => 'Ieri alle %s',
'tomorrow' => 'Domani alle %s',
'period' => 'da %s \'a %s',
),
'pt' => array (
'now' => 'Há alguns segundos',
'seconds' => 'Há %d segundos',
'minutes' => array('singular' => 'Há um minuto' , 'plural' => 'Há %d minutos'),
'hours' => array('singular' => 'Há uma hora' , 'plural' => 'Há %d horas'),
'days' => '%s',
'date' => 'a %s',
'today' => 'Hoje às %s',
'yesterday' => 'Ontem às %s',
'tomorrow' => 'Amanhã às %s',
'period' => 'de %s a %s',
),
);
protected static $_days = array(
'en' => array(
'Sunday' => 'Sunday',
'Sun' => 'Sun',
'Monday' => 'Monday',
'Mon' => 'Mon',
'Tuesday' => 'Tuesday',
'Tue' => 'Tue',
'Wednesday' => 'Wednesday',
'Wed' => 'Wed',
'Thursday' => 'Thursday',
'Thu' => 'Thu',
'Friday' => 'Friday',
'Fri' => 'Fri',
'Saturday' => 'Saturday',
'Sat' => 'Sat',
),
'fr' => array(
'Sunday' => 'Dimanche',
'Sun' => 'Dim',
'Monday' => 'Lundi',
'Mon' => 'Lun',
'Tuesday' => 'Mardi',
'Tue' => 'Mar',
'Wednesday' => 'Mercredi',
'Wed' => 'Mer',
'Thursday' => 'Jeudi',
'Thu' => 'Jeu',
'Friday' => 'Vendredi',
'Fri' => 'Ven',
'Saturday' => 'Samedi',
'Sat' => 'Sam',
),
'de' => array(
'Sunday' => 'Sonntag',
'Sun' => 'So',
'Monday' => 'Montag',
'Mon' => 'Mo',
'Tuesday' => 'Dienstag',
'Tue' => 'Di',
'Wednesday' => 'Mittwoch',
'Wed' => 'Mi',
'Thursday' => 'Donnerstag',
'Thu' => 'Do',
'Friday' => 'Freitag',
'Fri' => 'Fr',
'Saturday' => 'Samstag',
'Sat' => 'Sa',
),
'es' => array(
'Sunday' => 'Domingo',
'Sun' => 'Dom',
'Monday' => 'Lunes',
'Mon' => 'Lun',
'Tuesday' => 'Martes',
'Tue' => 'Mar',
'Wednesday' => 'Miércoles',
'Wed' => 'Mié',
'Thursday' => 'Jueves',
'Thu' => 'Jue',
'Friday' => 'Viernes',
'Fri' => 'Vie',
'Saturday' => 'Sábado',
'Sat' => 'Sáb',
),
'it' => array(
'Sunday' => 'Domenica',
'Sun' => 'Dom',
'Monday' => 'Lunedì',
'Mon' => 'Lun',
'Tuesday' => 'Martedì',
'Tue' => 'Mar',
'Wednesday' => 'Mercoledì',
'Wed' => 'Mer',
'Thursday' => 'Giovedì',
'Thu' => 'Gio',
'Friday' => 'Venerdì',
'Fri' => 'Ven',
'Saturday' => 'Sabato',
'Sat' => 'Sab',
),
'do' => array(
'Sunday' => 'Domingo',
'Sun' => 'Dom',
'Monday' => 'Segunda-feira',
'Mon' => 'Seg',
'Tuesday' => 'Terca-feira',
'Tue' => 'Ter',
'Wednesday' => 'Quarta-feira',
'Wed' => 'Qua',
'Thursday' => 'Quinta-feira',
'Thu' => 'Qui',
'Friday' => 'Sexta-feira',
'Fri' => 'Sex',
'Saturday' => 'Sábado',
'Sat' => 'Sáb',
),
);
protected static $_months = array(
'en' => array(
'January' => 'January',
'Jan' => 'Jan',
'February' => 'February',
'Feb' => 'Feb',
'March' => 'March',
'Mar' => 'Mar',
'April' => 'April',
'Apr' => 'Apr',
'May' => 'May',
'May' => 'May',
'June' => 'June',
'Jun' => 'Jun',
'July' => 'July',
'Jul' => 'Jul',
'August' => 'August',
'Aug' => 'Aug',
'September' => 'September',
'Sep' => 'Sep',
'October' => 'October',
'Oct' => 'Oct',
'November' => 'November',
'Nov' => 'Nov',
'December' => 'December',
'Dec' => 'Dec',
),
'fr' => array(
'January' => 'Janvier',
'Jan' => 'Jan',
'February' => 'Février',
'Feb' => 'Fév',
'March' => 'Mars',
'Mar' => 'Mar',
'April' => 'Avril',
'Apr' => 'Avr',
'May' => 'Mai',
'May' => 'Mai',
'June' => 'Juin',
'Jun' => 'Juin',
'July' => 'Juillet',
'Jul' => 'Juil',
'August' => 'Août',
'Aug' => 'Aou',
'September' => 'Septembre',
'Sep' => 'Sep',
'October' => 'Octobre',
'Oct' => 'Oct',
'November' => 'Novembre',
'Nov' => 'Nov',
'December' => 'Décembre',
'Dec' => 'Déc',
),
'de' => array(
'January' => 'Januar',
'Jan' => 'Jan',
'February' => 'Februar',
'Feb' => 'Feb',
'March' => 'März',
'Mar' => 'Mrz',
'April' => 'April',
'Apr' => 'Apr',
'May' => 'Mai',
'May' => 'Mai',
'June' => 'Juni',
'Jun' => 'Jun',
'July' => 'Juli',
'Jul' => 'Jul',
'August' => 'August',
'Aug' => 'Aug',
'September' => 'September',
'Sep' => 'Sep',
'October' => 'Oktober',
'Oct' => 'Okt',
'November' => 'November',
'Nov' => 'Nov',
'December' => 'Dezember',
'Dec' => 'Dez',
),
'es' => array(
'January' => 'Enero',
'Jan' => 'Ene',
'February' => 'Febrero',
'Feb' => 'Feb',
'March' => 'Marzo',
'Mar' => 'Mar',
'April' => 'Abril',
'Apr' => 'Abr',
'May' => 'Mayo',
'May' => 'May',
'June' => 'Junio',
'Jun' => 'Jun',
'July' => 'Julio',
'Jul' => 'Jul',
'August' => 'Agosto',
'Aug' => 'Ago',
'September' => 'Septiembre',
'Sep' => 'Sep',
'October' => 'Octubre',
'Oct' => 'Oct',
'November' => 'Noviembre',
'Nov' => 'Nov',
'December' => 'Diciembre',
'Dec' => 'Dic',
),
'it' => array(
'January' => 'Gennaio',
'Jan' => 'Gen',
'February' => 'Febbraio',
'Feb' => 'Feb',
'March' => 'Marzo',
'Mar' => 'Mar',
'April' => 'Aprile',
'Apr' => 'Apr',
'May' => 'Maggio',
'May' => 'Mag',
'June' => 'Giugno',
'Jun' => 'Giu',
'July' => 'Luglio',
'Jul' => 'Lug',
'August' => 'Agosto',
'Aug' => 'Ago',
'September' => 'Settembre',
'Sep' => 'Set',
'October' => 'Ottobre',
'Oct' => 'Ott',
'November' => 'Novembre',
'Nov' => 'Nov',
'December' => 'Dicembre',
'Dec' => 'Dic',
),
'pt' => array(
'January' => 'Janeiro ',
'Jan' => 'Jan',
'February' => 'Fevereiro',
'Feb' => 'Fev',
'March' => 'Março',
'Mar' => 'Mar',
'April' => 'Abril',
'Apr' => 'Abr',
'May' => 'Maio',
'May' => 'Mai',
'June' => 'Junho',
'Jun' => 'Jun',
'July' => 'Julho',
'Jul' => 'Jul',
'August' => 'Agosto',
'Aug' => 'Ago',
'September' => 'Setembro',
'Sep' => 'Sep',
'October' => 'Outubro',
'Oct' => 'Out',
'November' => 'Novembro',
'Nov' => 'Nov',
'December' => 'Dezembro',
'Dec' => 'Dez',
),
);
public static function getWallLabel($type, $lang, $plural = 0)
{
if(!array_key_exists($lang, self::$_date_messages)) $lang = self::DEFAULT_LANGUAGE;
if(is_array(self::$_date_messages[$lang][$type])) {
if($plural > 1) {
return self::$_date_messages[$lang][$type]['plural'];
} else {
return self::$_date_messages[$lang][$type]['singular'];
}
} else {
return self::$_date_messages[$lang][$type];
}
}
public static function create($date = null)
{
if($date instanceof Datetime) {
return $date;
}
if (is_array($date)) {
$year = isset($date['year']) ? (int) $date['year'] : '00';
$month = isset($date['month']) ? (int) $date['month'] : '00';
$day = isset($date['day']) ? (int) $date['day'] : '00';
$hour = isset($date['hour']) ? (int) $date['hour'] : '00';
$min = isset($date['min']) ? (int) $date['min'] : '00';
$sec = isset($date['sec']) ? (int) $date['sec'] : '00';
return new DateTime($year.'-'.$month.'-'.$day.' '.$hour.':'.$min.':'.$sec);
}
return new DateTime($date);
}
public static function toTimestamp(Datetime $date)
{
return strtotime($date->format('Y-m-d h:i:s'));
}
public static function add(Datetime $date, $diff = array())
{
$timestamp = self::toTimestamp($date);
if(is_int($diff)) {
$diff = array('day' => $diff);
}
if (isset($diff['week'])) {
$diff['day'] = $diff['week'] * 7;
}
$newdate = date('Y-m-d h:i:s', mktime(
date('h', $timestamp) + (isset($diff['hour']) ? $diff['hour'] : null),
date('i', $timestamp) + (isset($diff['minute']) ? $diff['minute'] : null),
date('s', $timestamp) + (isset($diff['second']) ? $diff['second'] : null),
date('m', $timestamp) + (isset($diff['month']) ? $diff['month'] : null),
date('d', $timestamp) + (isset($diff['day']) ? $diff['day'] : null),
date('Y', $timestamp) + (isset($diff['year']) ? $diff['year'] : null)
));
return new Datetime($newdate);
}
public static function dayOfWeek($date = null)
{
$date = self::create($date);
$day = $date->format('w');
return $day == 0 ? 7 : $day;
}
public static function compare(Datetime $date1, Datetime $date2)
{
return ((strtotime($date1->format('Y/m/d H:i:s')) - strtotime($date2->format('Y/m/d H:i:s'))) > 0);
}
public static function diff($date1, $date2 = null)
{
if($date2 == null){
$date2 = time();
}
else{
$date2 = strtotime($date2->format('Y/m/d H:i:s'));
}
$date1 = self::create($date1);
return round($date2 - strtotime($date1->format('Y/m/d H:i:s'))) / (3600 * 24);
}
public static function diffTime($date1, $date2 = null)
{
if($date2 == null){
$date2 = time();
}
else{
$date2 = strtotime($date2->format('Y/m/d H:i:s'));
}
$date1 = self::create($date1);
return (strtotime($date1->format('Y/m/d H:i:s')) - $date2);
}
public static function greaterThan($date, $days)
{
return (self::diff($date) >= (int) $days);
}
public static function lessThan($date, $day)
{
return (self::diff($date) <= (int) $day);
}
public static function getAge($date)
{
$date = self::create($date);
$today = new Datetime();
$age = (int) ($today->format('Y') - $date->format('Y'));
if ($today->format('m') < $date->format('m')) {
return $age - 1;
}
if (($today->format('m') == $date->format('m')) && ($today->format('d') - $date->format('d'))) {
return $age - 1;
}
return $age;
}
public static function translate($formatted_date, $lang)
{
if(!array_key_exists($lang, self::$_date_messages)) $lang = self::DEFAULT_LANGUAGE;
$formatted_date = str_replace(self::$_months[self::DEFAULT_LANGUAGE], self::$_months[$lang], $formatted_date);
$formatted_date = str_replace(self::$_days[self::DEFAULT_LANGUAGE], self::$_days[$lang], $formatted_date);
return $formatted_date;
}
public static function typeExist($type)
{
return array_key_exists($type, self::$_date_format[self::DEFAULT_LANGUAGE]);
}
public static function format($date, $format = 'short', $timezone = false, $lang = null)
{
if(empty($lang)) {
require_once('Gen/I18n.php');
$lang = (Gen_I18n::getLocale()) ? Gen_I18n::getLocale() : self::DEFAULT_LANGUAGE;
}
if(!array_key_exists($lang, self::$_date_format)) $lang = self::DEFAULT_LANGUAGE;
if (!($date instanceof DateTime) && !($date instanceof DateInterval)) {
$date = new DateTime((string) $date);
}
// if($timezone) {
// $timezone = Gen_Geo::getTimezone();
// if($timezone) {
// $date->setTimezone(new DateTimeZone($timezone));
// }
// }
if(self::typeExist($format)) {
$date_formated = $date->format(self::$_date_format[$lang][$format]);
} else {
$date_formated = $date->format($format);
}
return self::translate($date_formated, $lang);
}
/**
* create a DateTime
* @param year : 2010
* @param month : janvier
* @param day : 10
*/
public static function array2datetime($year,$month="janvier",$day="01"){
$monthArray = array(
"janvier" => "01",
"fevrier" => "02",
"mars" => "03",
"avril" => "04",
"mai" => "05",
"juin" => "06",
"juillet" => "07",
"aout" => "08",
"septembre" => "09",
"octobre" => "10",
"novembre" => "11",
"decembre" => "12"
);
return new DateTime("$year-{$monthArray[$month]}-$day");
}
public static function getMonthArray(){
return array(
"01" => "Janvier",
"02" => "Février",
"03" => "Mars",
"04" => "Avril",
"05" => "Mai",
"06" => "Juin",
"07" => "Juillet",
"08" => "Août",
"09" => "Septembre",
"10" => "Octobre",
"11" => "Novembre",
"12" => "Décembre"
);
}
/**
* create a string from a DateTime
* @param year : 2010
* @param month : janvier
* @param day : 10
*/
public static function datetime2string($date){
require_once("Gen/Str.php");
$monthArray = self::getMonthArray();
$month = Gen_Str::urlDasherize($monthArray[$date->format('m')]);
return "{$date->format('d')}-$month-{$date->format('Y')}";
}
/**
* accept 10-janvier-2010 or janvier-2010 or 2010
* @param string $date
*/
public static function string2datetime($date){
$dateArray= array();
$month = self::getMonthRegExpr();
if(preg_match("/(0[1-9]|[12][0-9]|3[01])-($month)-(20\d\d)/",$date,$dateArray)){
return self::array2datetime($dateArray[3],$dateArray[2],$dateArray[1]);
}
else if(preg_match("/($month)-(20\d\d)/",$date,$dateArray)){
return self::array2datetime($dateArray[2],$dateArray[1]);
}
else{
return self::array2datetime($date);
}
}
/**
* retrieve the string "janvier|fevrier...
*/
public static function getMonthRegExpr(){
return "janvier|fevrier|mars|avril|mai|juin|juillet|aout|septembre|octobre|novembre|decembre";
}
public static function period($startDate, $endDate, $format = 'short', $timezone = true, $lang = null)
{
require_once('Gen/I18n.php');
$lang = (Gen_I18n::getLocale()) ? Gen_I18n::getLocale() : self::DEFAULT_LANGUAGE;
if(!array_key_exists($lang, self::$_date_messages)) $lang = self::DEFAULT_LANGUAGE;
if (!($startDate instanceof DateTime)) {
$startDate = new DateTime($startDate);
}
if (!($endDate instanceof DateTime)) {
$endDate = new DateTime($endDate);
}
return vsprintf(self::$_date_messages[$lang]['period'], array(self::format($startDate, $format, $lang), self::format($endDate, $format, $lang)));
}
public static function smartDate($date)
{
require_once('Gen/I18n.php');
$lang = (Gen_I18n::getLocale()) ? Gen_I18n::getLocale() : self::DEFAULT_LANGUAGE;
if (!($date instanceof DateTime)) {
$date = new DateTime($date);
}
$current_date = new DateTime();
$diff = self::diffTime($current_date, $date);
$seconds = round($diff);
$minutes = round($diff / 60);
$hours = round($diff / (60*60));
$days = round($diff / (60*60*24));
// Future
if($days == -1) return vsprintf(self::getWallLabel('tomorrow', $lang), self::format($date, 'time', $lang));
// Past
if($seconds < 30) {
return vsprintf(self::getWallLabel('now', $lang, $seconds), $seconds);
}
if($minutes < 1){
return vsprintf(self::getWallLabel('seconds', $lang, $seconds), $seconds);
}
if($minutes < 60){
return vsprintf(self::getWallLabel('minutes', $lang, $minutes), $minutes);
}
if($hours < 24){
return vsprintf(self::getWallLabel('hours', $lang, $hours), $hours);
}
if($days < 7){
if($days == 1) return vsprintf(self::getWallLabel('yesterday', $lang), self::format($date, 'time', false, $lang));
return vsprintf(self::getWallLabel('days', $lang), self::format($date, 'smart_date', false, $lang));
}
if($days == 0) return vsprintf(self::getWallLabel('today', $lang), self::format($date, 'time', false, $lang));
if($diff < 0) return vsprintf(self::getWallLabel('date', $lang), self::format($date, 'long', false, $lang));
return vsprintf(self::getWallLabel('date', $lang), self::format($date, 'long', false, $lang));
}
public static function getMonth($number, $lang)
{
$months = self::getMonthArray();
$month = $months[$number > 10 ? $number : "0".$number];
return str_replace(self::$_months['fr'], self::$_months[$lang], $month);
}
}
<?php
class Gen_Enum
{
protected static $_data = array();
public static function get($id)
{
return isset(static::$_data[$id]) ? static::$_data[$id] : null;
}
public static function getPropertyById($id, $property, $default = null)
{
return (isset(static::$_data[$id]) && isset(static::$_data[$id][$property])) ? static::$_data[$id][$property] : $default;
}
public static function getLabel($id)
{
return _t(self::getPropertyById($id, 'label'));
}
public static function getKey($id)
{
return self::getPropertyById($id, 'key');
}
public static function getDescription($id)
{
return self::getPropertyById($id, 'description');
}
public static function map($data)
{
return array_intersect_key(static::$_data, array_flip((array) $data));
}
public static function getProperties($property)
{
$properties = array();
foreach (static::$_data as $id => $data) {
if (isset($data[$property])) {
$properties[$id] = $data[$property];
}
}
return $properties;
}
public static function getKeys()
{
return self::getProperties('key');
}
public static function getLabels($translate = true)
{
return self::getProperties('label');
}
public static function getIds()
{
return array_keys(static::$_data);
}
public static function toArray()
{
return static::$_data;
}
}
<?php
/**
* @category Gen
* @package Gen_Exception
*/
class Gen_Exception extends Exception
{
}
<?php
class Gen_File
{
const RSS_DELAY = 30;
const SYNC_NEW = 1;
const SYNC_RECENT = 2;
const SYNC_ALL = 3;
public static function getModeLabel($mode)
{
switch($mode) {
case self::SYNC_NEW:
return 'SYNC_NEW';
case self::SYNC_RECENT:
return 'SYNC_RECENT';
case self::SYNC_ALL:
return 'SYNC_ALL';
}
return 'Does not exist';
}
public static function getExtension($fileName)
{
return strtolower(array_pop(explode('.', $fileName)));
}
public static function hasExpired($filePath, $hours = 24)
{
if (!file_exists($filePath)) return true;
$diff = date_diff(new DateTime(date('Y-m-d H:i:s', filemtime($filePath))), new DateTime('now'));
return (($diff->y * 365 * 24 * 60) + ($diff->m * 30 * 24 * 60) + ($diff->d * 24 * 60) + ($diff->h * 60) + $diff->i)/60 >= $hours;
}
public static function copy($src, $dest)
{
$dir = dirname($dest);
if (!file_exists($src) || !file_exists($dir) && !mkdir($dir, 0777, true)) {
return false;
}
return copy($src, $dest);
}
public static function sync($src, $dest, $mode = self::SYNC_NEW)
{
if(!file_exists($dest) || ((filemtime($src) > filemtime($dest)) && $mode == self::SYNC_RECENT) || ($mode == self::SYNC_ALL)) {
return self::copy($src, $dest);
}
return false;
}
public static function write($filePath, $content = '', $override = true)
{
$dir = dirname($filePath);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$file = null;
if (!file_exists($filePath)) {
$file = fopen($filePath,'x+');
} elseif($override) {
$file = fopen($filePath,'w+');
} else {
return false;
}
if(false !== $file) {
fwrite($file, trim($content));
fclose($file);
return true;
}
return false;
}
public static function read($filePath)
{
return file_get_contents($filePath);
}
public static function remove($fileName)
{
self::delete($fileName);
}
public static function delete($fileName)
{
if(!file_exists($fileName)) {
return false;
}
if(is_dir($fileName)) {
$dir = opendir($fileName);
while(false !== ($file = readdir($dir)) ) {
if (($file == '.' ) || ($file == '..')) {
continue;
}
self::delete($fileName.'/'.$file);
}
return rmdir($fileName);
}
return unlink($fileName);
}
public static function move($srcFile, $destFile)
{
if(self::copy($srcFile, $destFile)) {
return self::delete($srcFile);
}
return false;
}
public static function rss_parser($url) {
$rss = false;
$stream = '';
$handle = fopen($url, "rb");
if (false !== $handle) {
$stream = stream_get_contents($handle);
$stream = str_replace('dc:date', 'pubDate', $stream);
$rss = @simplexml_load_string($stream);
fclose($handle);
}
return $rss;
}
/**
* Note to do your own check to make sure the directory exists that you first call it on.
*/
public static function recurse_copy($src,$dst) {
$dir = opendir($src);
@mkdir($dst);
while(false !== ($file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if (is_dir($src . '/' . $file)) {
recurse_copy($src . '/' . $file, $dst . '/' . $file);
} else {
copy($src . '/' . $file, $dst . '/' . $file);
}
}
}
closedir($dir);
}
public static function listDir($rootDir)
{
$dirs = (array) $rootDir;
if($files = scandir($rootDir)) {
foreach($files as $file) {
$dir = $rootDir.'/'.$file;
if(($file != '.') && ($file != '..') && is_dir($dir)) {
$dirs = array_merge($dirs, self::listDir($dir));
}
}
}
return $dirs;
}
public static function recursiveSync($src, $dest, $mode = self::SYNC_NEW)
{
$results = array();
if($files = scandir($src)) {
foreach($files as $file) {
$srcFile = $src.'/'.$file;
$destFile = $dest.'/'.$file;
if(($file != '.') && ($file != '..')) {
if(is_dir($srcFile)) {
$results = array_merge($results, self::recursiveSync($srcFile, $destFile, $mode));
} else {
if(self::sync($srcFile, $destFile, $mode)) {
$results[] = $file;
}
}
}
}
}
return $results;
}
public static function recursiveCopy($src, $dest, $lastUpdate = null)
{
$results = array();
if($files = scandir($src)) {
foreach($files as $file) {
$srcFile = $src.'/'.$file;
$destFile = $dest.'/'.$file;
if(($file != '.') && ($file != '..')) {
if(is_dir($srcFile)) {
$results = array_merge($results, self::recursiveCopy($srcFile, $destFile, $lastUpdate));
} elseif($lastUpdate === null || filemtime($srcFile) > $lastUpdate) {
if(self::copy($srcFile, $destFile)) {
$results[] = $file;
}
}
}
}
}
return $results;
}
/**
* @param string $fileName
* @return array $data
*/
public static function readCsv($fileName, $options = array()){
$options = array_merge(array(
'delimiter' => ';',
'enclosure' => ' ',
'escape' => '\\',
'lenght' => 1000,
'header' => true
), $options);
if(($handle = fopen($fileName, 'r')) == false) {
return false;
}
$data = array();
$first = true;
while($row = fgetcsv($handle, $options['lenght'], $options['delimiter'], $options['enclosure'], $options['escape'])) {
switch (true) {
case $options['header'] == true && $first:
$headers = $row;
$first = false;
break;
case $options['header'] == true:
foreach($headers as $k => $col) {
$tmp[$col] = isset($row[$k])?$row[$k]:null;
}
$row = $tmp;
default:
$data[] = $row;
break;
}
}
fclose($handle);
return $data;
}
public static function encodeCsv($data, $options = array()){
$options = array_merge(array(
'delimiter' => ';',
'enclosure' => '"',
'lenght' => 1000,
'header' => true
), $options);
$csv = '';
$first = true;
$header = '';
foreach($data as $row)
{
foreach($row as $key => $col)
{
if($options['header'] && $first) {
$header .= self::_escapeCsv($key, $options).$options['delimiter'];
}
if(is_array($col)) {
$col = implode("-", $col);
}
$csv .= self::_escapeCsv($col, $options).$options['delimiter'];
}
$csv = rtrim($csv, $options['delimiter'])."\n";
$first = false;
}
if($options['header']) {
$csv = $header."\n".$csv;
}
return $csv;
}
private static function _escapeCsv($text, array $options)
{
$text = str_replace(array("\n", "\r", "\n\r"), " ", $text);
$text = utf8_decode($text);
$text = str_replace($options['enclosure'], $options['enclosure'].$options['enclosure'], $text);
return $options['enclosure'].$text.$options['enclosure'];
}
}
<?php
require_once('Gen/Form/Base.php');
class Gen_Form extends Gen_Form_Base
{
}
<?php
class Gen_Geo
{
const LOCAL_IP = '81.252.204.205';
protected static $_country_code;
protected static $_country_name;
protected static $_region;
protected static $_city;
protected static $_timezone;
protected static $_country;
public static $_geoip = false;
public static function getCountryCode()
{
if(self::$_country_code) return self::$_country_code;
if(self::$_geoip) {
require_once('Gen/Controller/Request.php');
self::$_country_code = geoip_country_code_by_name(Gen_Controller_Request::getIp());
} else {
require_once(MS_LIB_DIR .'GeoIP/geoip.inc');
$gi = geoip_open(MS_LIB_DIR .'GeoIP/GeoIP.dat', GEOIP_STANDARD);
self::$_country_code = geoip_country_code_by_addr($gi, self::LOCAL_IP);
geoip_close($gi);
}
return self::$_country_code;
}
public static function getCountryName()
{
if(self::$_country_name) return self::$_country_name;
if(self::$_geoip) {
require_once('Gen/Controller/Request.php');
self::$_country_name = geoip_country_name_by_name(Gen_Controller_Request::getIp());
} else {
require_once(MS_LIB_DIR .'GeoIP/geoip.inc');
$gi = geoip_open(MS_LIB_DIR .'GeoIP/GeoIP.dat', GEOIP_STANDARD);
self::$_country_name = geoip_country_name_by_addr($gi, self::LOCAL_IP);
geoip_close($gi);
}
return self::$_country_name;
}
public static function getRegion()
{
if(self::$_region) return self::$_region;
if(self::$_geoip) {
require_once('Gen/Controller/Request.php');
$region = geoip_region_by_name(Gen_Controller_Request::getIp());
self::$_region['region'];
} else {
self::$_region = self::getCity()->region;
}
return self::$_region;
}
public static function getCity()
{
if(self::$_city) return self::$_city;
if(self::$_geoip) {
require_once('Gen/Controller/Request.php');
self::$_city = geoip_record_by_name(Gen_Controller_Request::getIp());
} else {
require_once(MS_LIB_DIR .'GeoIP/geoipcity.inc');
require_once(MS_LIB_DIR .'GeoIP/geoipregionvars.php');
$gi = geoip_open(MS_LIB_DIR .'GeoIP/GeoIPCity.dat', GEOIP_STANDARD);
self::$_city = geoip_record_by_addr($gi, self::LOCAL_IP);
geoip_close($gi);
}
return self::$_city;
}
public static function getTimezone()
{
if(self::$_timezone) return self::$_timezone;
$country = self::getCountryCode();
if(self::$_geoip) {
self::$_timezone = geoip_time_zone_by_country_and_region($country);
} else {
require_once(MS_LIB_DIR .'GeoIP/timezone.php');
$region = self::getRegion();
self::$_timezone = get_time_zone($country, $region);
}
return self::$_timezone;
}
}
<?php
/** @see Gen_Hash_Base */
require_once ('Gen/Hash/Base.php');
/**
* @category Gen
* @package Gen_Hash
*/
class Gen_Hash extends Gen_Hash_Base
{
}
<?php
require_once('Html/Element.php');
require_once('Html/Link.php');
require_once('Html/Style.php');
class Gen_Html
{
public static $tags = array('html', 'head', 'meta', 'title', 'script', 'link', 'body', 'header', 'footer', 'aside', 'nav', 'a', 'u', 'i', 'em', 'strong', 'div', 'p', 'ul', 'li', 'ol', 'dl', 'dt', 'dd', 'form', 'input', 'select', 'option', 'textarea', 'button');
}
<?php
class Gen_I18n
{
protected static $_locale;
protected static $_data = array();
public static $_path;
const DEFAULT_FILENAME = 'I18n';
public static function setLocale($locale)
{
$oldLocale = self::getLocale();
Gen_Log::log('old: '.$oldLocale .'- new: ' .$locale, 'Gen_I18n::setLocale', 'info');
self::$_locale = $locale;
self::$_data = self::loadFile();
return $oldLocale;
}
public static function getLocale()
{
return self::$_locale;
}
public static function loadFile($locale = null)
{
$data = array();
$path = self::getPath($locale);
if (file_exists($path)) {
include($path);
} else {
Gen_Log::log('file '.$path.' does not exist', 'Gen_I18n::loadFile', 'warning');
}
return $data;
}
public static function translate($text)
{
$key = md5(preg_replace('#\\\*"#', '"', $text));
if (!isset(self::$_data[$key]) || self::$_data[$key] == '') {
return $text;
}
return self::$_data[$key];
}
public static function getPath($locale = null, $fileName = null)
{
$locale = ($locale !== null) ? $locale : self::$_locale;
return self::$_path . $locale . '/' . (($fileName === null) ? self::DEFAULT_FILENAME : $fileName) . '.php';
}
public static function write($locale = null, array $translations = array(), $overwrite = false, $fileName = null)
{
$cryptedTranslations = $overwrite ? array() : Gen_I18n::loadFile($locale);
foreach($translations as $key => $translation) {
$value = is_array($translation) ? $translation['suggestion'] : $translation;
$key = preg_replace('#\\\*"#', '"', $key);
$cryptedTranslations[md5($key)] = $value;
}
$path = self::getPath($locale, $fileName);
$content = '<?php return array(';
$first = true;
foreach ($cryptedTranslations as $key => $value) {
if ($value !== '') {
$value = preg_replace('#\\\*"#', '\"', $value);
$content .= ($first ? '' : ",\n") . "'" . $key . '\' => "' . $value . '"';
$first = false;
}
}
$content .= '); ?>';
require_once('Gen/File.php');
Gen_File::write($path, $content);
}
public static function writeScript($path, array $translations = array())
{
$content = 'i18n = {';
$first = true;
foreach ($translations as $translation) {
if ($translation['suggestion'] !== '') {
$key = preg_replace('#\\\*"#', '\"', $translation['message']);
$value = preg_replace('#\\\*"#', '\"', $translation['suggestion']);
$content .= ($first ? '' : ",\n") . '"' . $key . '" : "' . $value . '"';
$first = false;
}
}
$content .= '};';
require_once('Gen/File.php');
Gen_File::write($path, $content);
}
public static function writeXml($path, array $translations = array())
{
$content = '<xml>';
$first = true;
foreach ($translations as $translation) {
if ($translation['suggestion'] !== '') {
$key = preg_replace('#\\\*"#', '\"', $translation['message']);
$value = preg_replace('#\\\*"#', '\"', $translation['suggestion']);
$content .= ($first ? '' : ",\n") . '<translation key="' . $key . '" value="' . $value . '"/>';
$first = false;
}
}
$content .= '</xml>';
require_once('Gen/File.php');
Gen_File::write($path, $content);
}
}
<?php
require_once('Gen/Image/Base.php');
class Gen_Image extends Gen_Image_Base
{
//Resize the image to match the new width. Same ratio as original. Do not crop height.
public static function resizeWidth($image0, $width)
{
if (self::hasImagick()) {
$image = $image0->clone();
$image->thumbnailImage($width, 0);
} elseif (self::hasGd()) {
$ratio = self::getRatio($image0);
$image = self::resize($image0, $width, $width/$ratio);
}
return $image;
}
//Same for height
public static function resizeHeight($image0, $height)
{
if (self::hasImagick()) {
$image = $image0->clone();
$image->thumbnailImage(0, $height);
} elseif (self::hasGd()) {
$ratio = self::getRatio($image0);
$image = self::resize($image0, $height*$ratio, $height);
}
return $image;
}
public static function getRatio($image)
{
$width = self::getWidth($image);
$height = self::getHeight($image);
if (!$width || !$height) {
return false;
}
return $width/$height;
}
public static function squarify($image0, $length)
{
if (self::hasImagick()) {
$image = self::resize($image0, $length, $length);
} elseif (self::hasGd()) {
$sx = imageSx($image0);
$sy = imageSy($image0);
$max = max($sx, $sy);
$min = min($sx, $sy);
$diff = $max - $min;
if ($sx >= $sy) {
$dx = intval($diff / 2);
$dy = 0;
} else {
$dx = 0;
$dy = intval($diff / 2);
}
$image = imagecreatetruecolor($length,$length);
imagecopyresampled($image, $image0, 0, 0, $dx, $dy, $length, $length, $min, $min);
}
return $image;
}
public static function getIccProfile($key)
{
$path = MS_LIB_DIR.'/Gen/Image/ICC_Profiles/'.$key.'.icc';
if (file_exists($path)) {
return file_get_contents($path);
}
}
public static function clean($image, $gray=false)
{
if (self::hasImagick()) {
if (!self::isJpeg($image)) {
$image->setImageFormat('JPEG');
}
if ($gray) {
$image->profileImage('icc', self::getIccProfile('ISOcoated_v2_grey1c_bas'));
$image->setImageType(Imagick::IMGTYPE_GRAYSCALE);
$image->setImageColorspace(Imagick::COLORSPACE_GRAY);
} else {
$image->profileImage('icc', self::getIccProfile('eciRGB_v2'));
$image->setImageType(Imagick::IMGTYPE_TRUECOLOR);
$image->setImageColorspace(Imagick::COLORSPACE_RGB);
}
}
return $image;
}
public static function getJpegCompressionQuality($file)
{
$cmd = MS_ROOT_DIR . 'shell/jpegquality ' . $file;
$shOutput = shell_exec($cmd);
$pos = strrpos ($shOutput , 'Average quality');
if ($pos !== false) {
$sub = trim(substr($shOutput, $pos));
$cQ = preg_filter('#Average quality: [0-9\.]+% \(([0-9]+)%\)#', '$1', $sub);
} else {
$cQ = false;
}
if (!$cQ || !is_numeric($cQ) || $cQ < 0) {
//If quality cannot be estimated, return 100
$cQ = 100;
}
return $cQ;
}
public static function isJpeg($image)
{
if (self::hasImagick()) {
return $image->getImageFormat() == 'JPEG';
} else {
//... GD cannot check his own image type...
return false;
}
}
public static function saveForWeb($src, $dest, $max = 1000, $quality = 90)
{
$img = self::create($src);
$width = self::getWidth($img);
$height = self::getHeight($img);
if($width >= $height && $width > $max) {
$img = self::resizeWidth($img, $max);
} elseif($height > $max) {
$img = self::resizeHeight($img, $max);
}
return self::write($img, $dest, 'jpeg', $quality, true);
}
}
<?php
class Gen_Image
{
protected static $_adapter;
protected static function getAdapter()
{
if(null === self::$_adapter){
if(extension_loaded('gd')) {
require_once('Gen/Image/Gd.php');
self::$_adapter = 'Gen_Image_Gd';
} elseif(extension_loaded('imagick')) {
require_once('Gen/Image/Imagick.php');
self::$_adapter = 'Gen_Image_Imagick';
} else {
throw new Exception("No Graphical Library found in Gen_Image::getAdapter()");
}
}
return self::$_adapter;
}
public static function __callStatic($method, $args)
{
$adapter = self::getAdapter();
if(!method_exists($adapter, $method)) {
throw new Exception('Call to undefined function `' . $method . '` for adapter `'. $adapter .'` in Gen_Image');
}
return call_user_func_array(array($adapter, $method), $args);
}
public static function getRatio($image)
{
$width = self::getWidth($image);
$height = self::getHeight($image);
if (!$width || !$height) {
return false;
}
return $height/$width;
}
//Resize the image to match the new width. Same ratio as original. Do not crop height.
public static function resizeWidth($img, $width)
{
$ratio = self::getRatio($img);
return self::resize($img, $width, $width * $ratio);
}
//Same for height
public static function resizeHeight($img, $height)
{
$ratio = self::getRatio($image0);
return self::resize($image0, $height / $ratio, $height);
}
public static function saveForWeb($src, $dest, $max = 2000, $quality = 90)
{
$img = self::create($src);
$width = self::getWidth($img);
$height = self::getHeight($img);
if($width >= $height && $width > $max) {
$img = self::resizeWidth($img, $max);
} elseif($height > $max) {
$img = self::resizeHeight($img, $max);
}
return self::write($img, $dest, 'jpeg', $quality, true);
}
}
<?php
class Gen_Log
{
protected static $_logs = array();
protected static $_startTime;
protected static $_previousTime;
protected static $_stopTime;
protected static $_count = 0;
public static $_debug = false;
public static function getLogs()
{
return self::$_logs;
}
public static function start()
{
if (!isset(self::$_startTime)) {
self::$_startTime = microtime(true);
self::$_previousTime = self::$_startTime;
self::log('Logger Start', 'Gen_Log::start');
}
return self::$_startTime;
}
public static function stop()
{
if (!isset(self::$_stopTime)) {
self::$_stopTime = microtime(true);
self::log('Logger Stop', 'Logger::stop');
}
return self::$_stopTime;
}
public static function log($message, $src, $level = 'info')
{
if (!self::$_debug) {
return false;
}
$start = self::start();
$time = microtime(true);
if (isset(self::$_logs[self::$_count])) {
self::$_logs[self::$_count]['duration'] = $time - self::$_previousTime;
self::$_count++;
}
self::$_logs[self::$_count] = array(
'message' => $message,
'src' => (string) $src,
'level' => (string) $level,
'elapsed' => $time - $start,
'duration' => 0
);
self::$_previousTime = $time;
return $time;
}
public static function render()
{
$str = '<div class="block">';
$str.= '<p><b>Exec. Time</b>: ' . round(self::stop() - self::start(), 4) . ' s<p>';
$str.= '<div class="box">';
foreach (self::$_logs as $log) {
$message = $log['message'];
if($message instanceof Gen_Entity) {
$message = $message->toArray();
}
if (is_object($message) || is_array($message)) {
$message = '<pre>' . print_r($message, true) .'</pre>';
}
if(is_bool($message)) {
$message = $message ? 'TRUE' : 'FALSE';
}
$str .= '<div class="block br-small">'
. '<span class="debug-'.$log['level'].'"><b>'.$log['level'].'</b></span> - '
. '<span style="width: 100px;"><b>'.$log['src'].'</b></span> - '
. '<span style="width: 100px;"><b>'.$log['elapsed'].'</b> s</span> - '
. '<span style="width: 100px;"><b>'.round($log['duration']*1000, 2).'</b> ms</span>'
. '</div>'
. '<div class="block br-small">'.$message.'</div>';
}
return $str.'</tbody></table>';
}
public static function out($var, $label = null)
{
if(is_bool($var)) {
$var = $var ? 'TRUE' : 'FALSE';
}
$str = '<p>';
if($label) {
$str .= '<strong>'.$label.'</strong>';
}
$str .= '<pre>' . print_r($var, true) .'</pre>';
return $str.'</p>'."\n\n";
}
}
<?php
# Parsedown
# http://parsedown.org
#
# Integrated into Gen by Mathieu WEBER
class Gen_Markdown
{
# Enables GFM line breaks.
private static $_breaksEnabled = false;
private static $_referenceMap = array();
private static $strongRegex = array(
'*' => '/^[*]{2}((?:[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
'_' => '/^__((?:[^_]|_[^_]*_)+?)__(?!_)/us',
);
private static $emRegex = array(
'*' => '/^[*]((?:[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
'_' => '/^_((?:[^_]|__[^_]*__)+?)_(?!_)\b/us',
);
private static $specialCharacters = array(
'\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!',
);
private static $textLevelElements = array(
'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
'i', 'rp', 'sub', 'code', 'strike', 'marquee',
'q', 'rt', 'sup', 'font', 'strong',
's', 'tt', 'var', 'mark',
'u', 'xm', 'wbr', 'nobr',
'ruby',
'span',
'time',
);
public static function setBreaksEnabled($breaksEnabled)
{
self::$_breaksEnabled = $breaksEnabled;
return $this;
}
public static function parse($text)
{
self::$_referenceMap = array();
# standardize line breaks
$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "\n", $text);
# replace tabs with spaces
$text = str_replace("\t", ' ', $text);
# remove surrounding line breaks
$text = trim($text, "\n");
# split text into lines
$lines = explode("\n", $text);
# iterate through lines to identify blocks
$blocks = self::_findBlocks($lines);
# iterate through blocks to build markup
$markup = self::_compile($blocks);
# trim line breaks
$markup = trim($markup, "\n");
return $markup;
}
private static function _findBlocks(array $lines, $blockContext = null)
{
$block = null;
$context = null;
$contextData = null;
foreach ($lines as $line)
{
$indentedLine = $line;
$indentation = 0;
while(isset($line[$indentation]) and $line[$indentation] === ' ') {
$indentation++;
}
if ($indentation > 0) {
$line = ltrim($line);
}
switch ($context)
{
case null:
$contextData = null;
if ($line === '') {
continue 2;
}
break;
case 'fenced code': // ~~~ javascript
if ($line === '') {
$block['content'][0]['content'] .= "\n";
continue 2;
}
if (preg_match('/^[ ]*'.$contextData['marker'].'{3,}[ ]*$/', $line)) {
$context = null;
}
else {
if ($block['content'][0]['content']){
$block['content'][0]['content'] .= "\n";
}
$string = htmlspecialchars($indentedLine, ENT_NOQUOTES, 'UTF-8');
$block['content'][0]['content'] .= $string;
}
continue 2;
case 'markup':
if (stripos($line, $contextData['start']) !== false) { # opening tag
$contextData['depth']++;
}
if (stripos($line, $contextData['end']) !== false) {# closing tag
if ($contextData['depth'] > 0) {
$contextData['depth']--;
}
else {
$context = null;
}
}
$block['content'] .= "\n".$indentedLine;
continue 2;
case 'li':
if ($line === '') {
$contextData['interrupted'] = true;
continue 2;
}
if ($contextData['indentation'] === $indentation and preg_match('/^'.$contextData['marker'].'[ ]+(.*)/', $line, $matches)) {
if (isset($contextData['interrupted'])) {
$nestedBlock['content'] []= '';
unset($contextData['interrupted']);
}
unset($nestedBlock);
$nestedBlock = array(
'name' => 'li',
'content type' => 'lines',
'content' => array(
$matches[1],
),
);
$block['content'] []= & $nestedBlock;
continue 2;
}
if (empty($contextData['interrupted']))
{
$value = $line;
if ($indentation > $contextData['baseline'])
{
$value = str_repeat(' ', $indentation - $contextData['baseline']) . $value;
}
$nestedBlock['content'] []= $value;
continue 2;
}
if ($indentation > 0) {
$nestedBlock['content'] []= '';
$value = $line;
if ($indentation > $contextData['baseline']) {
$value = str_repeat(' ', $indentation - $contextData['baseline']) . $value;
}
$nestedBlock['content'] []= $value;
unset($contextData['interrupted']);
continue 2;
}
$context = null;
break;
case 'quote':
if ($line === '') {
$contextData['interrupted'] = true;
continue 2;
}
if (preg_match('/^>[ ]?(.*)/', $line, $matches)) {
$block['content'] []= $matches[1];
continue 2;
}
if (empty($contextData['interrupted'])) {
$block['content'] []= $line;
continue 2;
}
$context = null;
break;
case 'code':
if ($line === '') {
$contextData['interrupted'] = true;
continue 2;
}
if ($indentation >= 4) {
if (isset($contextData['interrupted'])) {
$block['content'][0]['content'] .= "\n";
unset($contextData['interrupted']);
}
$block['content'][0]['content'] .= "\n";
$string = htmlspecialchars($line, ENT_NOQUOTES, 'UTF-8');
$string = str_repeat(' ', $indentation - 4) . $string;
$block['content'][0]['content'] .= $string;
continue 2;
}
$context = null;
break;
case 'table':
if ($line === '')
{
$context = null;
continue 2;
}
if (strpos($line, '|') !== false)
{
$nestedBlocks = array();
$substring = preg_replace('/^[|][ ]*/', '', $line);
$substring = preg_replace('/[|]?[ ]*$/', '', $substring);
$parts = explode('|', $substring);
foreach ($parts as $index => $part)
{
$substring = trim($part);
$nestedBlock = array(
'name' => 'td',
'content type' => 'line',
'content' => $substring,
);
if (isset($contextData['alignments'][$index]))
{
$nestedBlock['attributes'] = array(
'align' => $contextData['alignments'][$index],
);
}
$nestedBlocks []= $nestedBlock;
}
$nestedBlock = array(
'name' => 'tr',
'content type' => 'blocks',
'content' => $nestedBlocks,
);
$block['content'][1]['content'] []= $nestedBlock;
continue 2;
}
$context = null;
break;
case 'paragraph':
if ($line === '') {
$block['name'] = 'p'; # dense li
$context = null;
continue 2;
}
if ($line[0] === '=' and chop($line, '=') === '')
{
$block['name'] = 'h1';
$context = null;
continue 2;
}
if ($line[0] === '-' and chop($line, '-') === '')
{
$block['name'] = 'h2';
$context = null;
continue 2;
}
if (strpos($line, '|') !== false and strpos($block['content'], '|') !== false and chop($line, ' -:|') === '')
{
$values = array();
$substring = trim($line, ' |');
$parts = explode('|', $substring);
foreach ($parts as $part)
{
$substring = trim($part);
$value = null;
if ($substring[0] === ':')
{
$value = 'left';
}
if (substr($substring, -1) === ':')
{
$value = $value === 'left' ? 'center' : 'right';
}
$values []= $value;
}
# ~
$nestedBlocks = array();
$substring = preg_replace('/^[|][ ]*/', '', $block['content']);
$substring = preg_replace('/[|]?[ ]*$/', '', $substring);
$parts = explode('|', $substring);
foreach ($parts as $index => $part)
{
$substring = trim($part);
$nestedBlock = array(
'name' => 'th',
'content type' => 'line',
'content' => $substring,
);
if (isset($values[$index]))
{
$value = $values[$index];
$nestedBlock['attributes'] = array(
'align' => $value,
);
}
$nestedBlocks []= $nestedBlock;
}
# ~
$block = array(
'name' => 'table',
'content type' => 'blocks',
'content' => array(),
);
$block['content'] []= array(
'name' => 'thead',
'content type' => 'blocks',
'content' => array(),
);
$block['content'] []= array(
'name' => 'tbody',
'content type' => 'blocks',
'content' => array(),
);
$block['content'][0]['content'] []= array(
'name' => 'tr',
'content type' => 'blocks',
'content' => array(),
);
$block['content'][0]['content'][0]['content'] = $nestedBlocks;
# ~
$context = 'table';
$contextData = array(
'alignments' => $values,
);
# ~
continue 2;
}
break;
default:
throw new Exception('Unrecognized context - '.$context);
}
if ($indentation >= 4)
{
$blocks []= $block;
$string = htmlspecialchars($line, ENT_NOQUOTES, 'UTF-8');
$string = str_repeat(' ', $indentation - 4) . $string;
$block = array(
'name' => 'pre',
'content type' => 'blocks',
'content' => array(
array(
'name' => 'code',
'content type' => null,
'content' => $string,
),
),
);
$context = 'code';
continue;
}
switch ($line[0])
{
case '#':
if (isset($line[1]))
{
$blocks []= $block;
$level = 1;
while (isset($line[$level]) and $line[$level] === '#')
{
$level++;
}
$string = trim($line, '# ');
$string = self::_parseLine($string);
$block = array(
'name' => 'h'.$level,
'content type' => 'line',
'content' => $string,
);
$context = null;
continue 2;
}
break;
case '<':
$position = strpos($line, '>');
if ($position > 1)
{
$substring = substr($line, 1, $position - 1);
$substring = chop($substring);
if (substr($substring, -1) === '/')
{
$isClosing = true;
$substring = substr($substring, 0, -1);
}
$position = strpos($substring, ' ');
if ($position)
{
$name = substr($substring, 0, $position);
}
else
{
$name = $substring;
}
$name = strtolower($name);
if ($name[0] == 'h' and strpos('r123456', $name[1]) !== false) # hr, h1, h2, ...
{
if ($name == 'hr')
{
$isClosing = true;
}
}
elseif ( ! ctype_alpha($name))
{
break;
}
if (in_array($name, self::$textLevelElements))
{
break;
}
$blocks []= $block;
$block = array(
'name' => null,
'content type' => null,
'content' => $indentedLine,
);
if (isset($isClosing))
{
unset($isClosing);
continue 2;
}
$context = 'markup';
$contextData = array(
'start' => '<'.$name.'>',
'end' => '</'.$name.'>',
'depth' => 0,
);
if (stripos($line, $contextData['end']) !== false)
{
$context = null;
}
continue 2;
}
break;
case '>':
if (preg_match('/^>[ ]?(.*)/', $line, $matches))
{
$blocks []= $block;
$block = array(
'name' => 'blockquote',
'content type' => 'lines',
'content' => array(
$matches[1],
),
);
$context = 'quote';
$contextData = array();
continue 2;
}
break;
case '[':
$position = strpos($line, ']:');
if ($position)
{
$reference = array();
$label = substr($line, 1, $position - 1);
$label = strtolower($label);
$substring = substr($line, $position + 2);
$substring = trim($substring);
if ($substring === '')
{
break;
}
if ($substring[0] === '<')
{
$position = strpos($substring, '>');
if ($position === false)
{
break;
}
$reference['link'] = substr($substring, 1, $position - 1);
$substring = substr($substring, $position + 1);
}
else
{
$position = strpos($substring, ' ');
if ($position === false)
{
$reference['link'] = $substring;
$substring = false;
}
else
{
$reference['link'] = substr($substring, 0, $position);
$substring = substr($substring, $position + 1);
}
}
if ($substring !== false)
{
if ($substring[0] !== '"' and $substring[0] !== "'" and $substring[0] !== '(')
{
break;
}
$lastChar = substr($substring, -1);
if ($lastChar !== '"' and $lastChar !== "'" and $lastChar !== ')')
{
break;
}
$reference['title'] = substr($substring, 1, -1);
}
self::$_referenceMap[$label] = $reference;
continue 2;
}
break;
case '`':
case '~':
if (preg_match('/^([`]{3,}|[~]{3,})[ ]*(\w+)?[ ]*$/', $line, $matches))
{
$blocks []= $block;
$block = array(
'name' => 'pre',
'content type' => 'blocks',
'content' => array(
array(
'name' => 'code',
'content type' => null,
'content' => '',
),
),
);
if (isset($matches[2]))
{
$block['content'][0]['attributes'] = array(
'class' => 'language-'.$matches[2],
);
}
$context = 'fenced code';
$contextData = array(
'marker' => $matches[1][0],
);
continue 2;
}
break;
case '-':
case '*':
case '_':
if (preg_match('/^([-*_])([ ]{0,2}\1){2,}[ ]*$/', $line))
{
$blocks []= $block;
$block = array(
'name' => 'hr',
'content' => null,
);
continue 2;
}
}
switch (true)
{
case $line[0] <= '-' and preg_match('/^([*+-][ ]+)(.*)/', $line, $matches):
case $line[0] <= '9' and preg_match('/^([0-9]+[.][ ]+)(.*)/', $line, $matches):
$blocks []= $block;
$name = $line[0] >= '0' ? 'ol' : 'ul';
$block = array(
'name' => $name,
'content type' => 'blocks',
'content' => array(),
);
unset($nestedBlock);
$nestedBlock = array(
'name' => 'li',
'content type' => 'lines',
'content' => array(
$matches[2],
),
);
$block['content'] []= & $nestedBlock;
$baseline = $indentation + strlen($matches[1]);
$marker = $line[0] >= '0' ? '[0-9]+[.]' : '[*+-]';
$context = 'li';
$contextData = array(
'indentation' => $indentation,
'baseline' => $baseline,
'marker' => $marker,
'lines' => array(
$matches[2],
),
);
continue 2;
}
if ($context === 'paragraph')
{
$block['content'] .= "\n".$line;
continue;
}
else
{
$blocks []= $block;
$block = array(
'name' => 'p',
'content type' => 'line',
'content' => $line,
);
if ($blockContext === 'li' and empty($blocks[1]))
{
$block['name'] = null;
}
$context = 'paragraph';
}
}
if ($blockContext === 'li' and $block['name'] === null)
{
return $block['content'];
}
$blocks []= $block;
unset($blocks[0]);
return $blocks;
}
private static function _compile(array $blocks)
{
$markup = '';
foreach ($blocks as $block)
{
$markup .= "\n";
if (isset($block['name']))
{
$markup .= '<'.$block['name'];
if (isset($block['attributes']))
{
foreach ($block['attributes'] as $name => $value)
{
$markup .= ' '.$name.'="'.$value.'"';
}
}
if ($block['content'] === null)
{
$markup .= ' />';
continue;
}
else
{
$markup .= '>';
}
}
switch ($block['content type'])
{
case null:
$markup .= $block['content'];
break;
case 'line':
$markup .= self::_parseLine($block['content']);
break;
case 'lines':
$result = self::_findBlocks($block['content'], $block['name']);
if (is_string($result)) # dense li
{
$markup .= self::_parseLine($result);
break;
}
$markup .= self::_compile($result);
break;
case 'blocks':
$markup .= self::_compile($block['content']);
break;
}
if (isset($block['name']))
{
$markup .= '</'.$block['name'].'>';
}
}
$markup .= "\n";
return $markup;
}
private static function _parseLine($text, $markers = array(" \n", '![', '&', '*', '<', '[', '\\', '_', '`', 'http', '~~'))
{
if (isset($text[1]) === false or $markers === array()) {
return $text;
}
$markup = '';
while ($markers)
{
$closestMarker = null;
$closestMarkerIndex = 0;
$closestMarkerPosition = null;
foreach ($markers as $index => $marker)
{
$markerPosition = strpos($text, $marker);
if ($markerPosition === false) {
unset($markers[$index]);
continue;
}
if ($closestMarker === null or $markerPosition < $closestMarkerPosition) {
$closestMarker = $marker;
$closestMarkerIndex = $index;
$closestMarkerPosition = $markerPosition;
}
}
if ($closestMarker === null or isset($text[$closestMarkerPosition + 1]) === false) {
$markup .= $text;
break;
}
else {
$markup .= substr($text, 0, $closestMarkerPosition);
}
$text = substr($text, $closestMarkerPosition);
unset($markers[$closestMarkerIndex]);
switch ($closestMarker)
{
case " \n":
$markup .= '<br />'."\n";
$offset = 3;
break;
case '![':
case '[':
if (strpos($text, ']') and preg_match('/\[((?:[^][]|(?R))*)\]/', $text, $matches))
{
$element = array(
'!' => $text[0] === '!',
'text' => $matches[1],
);
$offset = strlen($matches[0]);
if ($element['!'])
{
$offset++;
}
$remainingText = substr($text, $offset);
if ($remainingText[0] === '(' and preg_match('/\([ ]*(.*?)(?:[ ]+[\'"](.+?)[\'"])?[ ]*\)/', $remainingText, $matches))
{
$element['link'] = $matches[1];
if (isset($matches[2]))
{
$element['title'] = $matches[2];
}
$offset += strlen($matches[0]);
}
elseif (self::$_referenceMap)
{
$reference = $element['text'];
if (preg_match('/^\s*\[(.*?)\]/', $remainingText, $matches))
{
$reference = $matches[1] === '' ? $element['text'] : $matches[1];
$offset += strlen($matches[0]);
}
$reference = strtolower($reference);
if (isset(self::$_referenceMap[$reference]))
{
$element['link'] = self::$_referenceMap[$reference]['link'];
if (isset(self::$_referenceMap[$reference]['title']))
{
$element['title'] = self::$_referenceMap[$reference]['title'];
}
}
else
{
unset($element);
}
}
else
{
unset($element);
}
}
if (isset($element))
{
$element['link'] = str_replace('&', '&', $element['link']);
$element['link'] = str_replace('<', '<', $element['link']);
if ($element['!'])
{
$markup .= '<img alt="'.$element['text'].'" src="'.$element['link'].'"';
if (isset($element['title']))
{
$markup .= ' title="'.$element['title'].'"';
}
$markup .= ' />';
}
else
{
$element['text'] = self::_parseLine($element['text'], $markers);
$markup .= '<a href="'.$element['link'].'" target="_blank"';
if (isset($element['title']))
{
$markup .= ' title="'.$element['title'].'"';
}
$markup .= '>'.$element['text'].'</a>';
}
unset($element);
}
else
{
$markup .= $closestMarker;
$offset = $closestMarker === '![' ? 2 : 1;
}
break;
case '&':
if (preg_match('/^&#?\w+;/', $text, $matches))
{
$markup .= $matches[0];
$offset = strlen($matches[0]);
}
else
{
$markup .= '&';
$offset = 1;
}
break;
case '*':
case '_':
if ($text[1] === $closestMarker and preg_match(self::$strongRegex[$closestMarker], $text, $matches))
{
$markers[$closestMarkerIndex] = $closestMarker;
$matches[1] = self::_parseLine($matches[1], $markers);
$markup .= '<strong>'.$matches[1].'</strong>';
}
elseif (preg_match(self::$emRegex[$closestMarker], $text, $matches))
{
$markers[$closestMarkerIndex] = $closestMarker;
$matches[1] = self::_parseLine($matches[1], $markers);
$markup .= '<em>'.$matches[1].'</em>';
}
if (isset($matches) and $matches)
{
$offset = strlen($matches[0]);
}
else
{
$markup .= $closestMarker;
$offset = 1;
}
break;
case '<':
if (strpos($text, '>') !== false)
{
if ($text[1] === 'h' and preg_match('/^<(https?:[\/]{2}[^\s]+?)>/i', $text, $matches))
{
$elementUrl = $matches[1];
$elementUrl = str_replace('&', '&', $elementUrl);
$elementUrl = str_replace('<', '<', $elementUrl);
$markup .= '<a href="'.$elementUrl.'" target="_blank">'.$elementUrl.'</a>';
$offset = strlen($matches[0]);
}
elseif (strpos($text, '@') > 1 and preg_match('/<(\S+?@\S+?)>/', $text, $matches))
{
$markup .= '<a href="mailto:'.$matches[1].'">'.$matches[1].'</a>';
$offset = strlen($matches[0]);
}
elseif (preg_match('/^<\/?\w.*?>/', $text, $matches))
{
$markup .= $matches[0];
$offset = strlen($matches[0]);
}
else
{
$markup .= '<';
$offset = 1;
}
}
else
{
$markup .= '<';
$offset = 1;
}
break;
case '\\':
if (in_array($text[1], self::$specialCharacters))
{
$markup .= $text[1];
$offset = 2;
}
else
{
$markup .= '\\';
$offset = 1;
}
break;
case '`':
if (preg_match('/^(`+)[ ]*(.+?)[ ]*(?<!`)\1(?!`)/', $text, $matches))
{
$elementText = $matches[2];
$elementText = htmlspecialchars($elementText, ENT_NOQUOTES, 'UTF-8');
$markup .= '<code>'.$elementText.'</code>';
$offset = strlen($matches[0]);
}
else
{
$markup .= '`';
$offset = 1;
}
break;
case 'http':
if (preg_match('/^https?:[\/]{2}[^\s]+\b\/*/ui', $text, $matches))
{
$elementUrl = $matches[0];
$elementUrl = str_replace('&', '&', $elementUrl);
$elementUrl = str_replace('<', '<', $elementUrl);
$markup .= '<a href="'.$elementUrl.'" target="_blank">'.$elementUrl.'</a>';
$offset = strlen($matches[0]);
}
else
{
$markup .= 'http';
$offset = 4;
}
break;
case '~~':
if (preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $text, $matches))
{
$matches[1] = self::_parseLine($matches[1], $markers);
$markup .= '<del>'.$matches[1].'</del>';
$offset = strlen($matches[0]);
}
else
{
$markup .= '~~';
$offset = 2;
}
break;
}
if (isset($offset))
{
$text = substr($text, $offset);
}
$markers[$closestMarkerIndex] = $closestMarker;
}
return $markup;
}
}
<?php
require_once('Tcpdf/tcpdf.php');
class Gen_Pdf extends TCPDF
{
const H_ALIGN_LEFT = 'L';
const H_ALIGN_RIGHT = 'R';
const H_ALIGN_CENTER = 'C';
const H_ALIGN_JUSTIFY = 'J';
const V_ALIGN_TOP = 'T';
const V_ALIGN_BOTTOM = 'B';
const V_ALIGN_MIDDLE = 'M';
const ORIENTATION_PORTRAIT = 'P';
const ORIENTATION_LANDSCAPE = 'L';
const UNIT_MM = 'mm';
protected $_colorspace = 'cmyk';
public function __construct ($orientation=self::ORIENTATION_PORTRAIT, $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false)
{
parent::__construct ($orientation, $unit, $format, $unicode, $encoding, $diskcache);
}
public function setBottomCellMargin($value)
{
$this->setCellMargin('B', $value);
}
public function setTopCellMargin($value)
{
$this->setCellMargin('T', $value);
}
public function setRightCellMargin($value)
{
$this->setCellMargin('R', $value);
}
public function setLeftCellMargin($value)
{
$this->setCellMargin('L', $value);
}
public function setCellMargin($margin, $value)
{
$margins = $this->getCellMargins();
if (isset($margins[$margin])) $margins[$margin] = $value;
$this->setCellMargins($margins['L'], $margins['T'], $margins['R'], $margins['B']);
}
public function getBox($key, $page = null)
{
$dim = $this->getPageDimensions($page);
if(!isset($dim[$key])) { return false; }
$k = $this->k;
$box = $dim[$key];
return array(
'llx' => $box['llx'] / $k,
'lly' => $box['lly'] / $k,
'urx' => $box['urx'] / $k,
'ury' => $box['ury'] / $k,
'width' => ($box['urx'] - $box['llx']) / $k,
'height' => ($box['ury'] - $box['lly']) / $k
);
}
public function setColorspace($colorspace)
{
$this->_colorspace = $colorspace;
}
/* Color conversion */
public function convertHTMLColorToDec($hex='#FFFFFF')
{
switch($this->_colorspace)
{
case 'rgb':
return $this->hex2rgb($hex);
break;
case 'gray':
return $this->hex2gray($hex);
break;
case 'cmyk':
default:
return $this->hex2cmyk($hex);
break;
}
}
protected function hex2rgb($hex)
{
$color = str_replace('#','',$hex);
$rgb = array(hexdec(substr($color,0,2)), hexdec(substr($color,2,2)), hexdec(substr($color,4,2)));
return $rgb;
}
protected function rgb2cmyk($rgb)
{
$r = $rgb[0];
$g = $rgb[1];
$b = $rgb[2];
$cyan = 255 - $r;
$magenta = 255 - $g;
$yellow = 255 - $b;
$black = min($cyan, $magenta, $yellow);
$cyan = @(($cyan - $black) / (255 - $black)) * 255;
$magenta = @(($magenta - $black) / (255 - $black)) * 255;
$yellow = @(($yellow - $black) / (255 - $black)) * 255;
return array(round(100 * $cyan / 255), round(100 * $magenta / 255), round(100 * $yellow / 255), round(100 * $black / 255));
}
protected function hex2cmyk($hex)
{
return $this->rgb2cmyk($this->hex2rgb($hex));
}
protected function rgb2gray($rgb)
{
$r = $rgb[0];
$g = $rgb[1];
$b = $rgb[2];
$g = round(($r+$g+$b)/3);
return array($g, $g, $g);
}
protected function hex2gray($hex)
{
return $this->rgb2gray($this->hex2rgb($hex));
}
}
<?php
class Gen_Pivot
{
protected $_dataSource = array();
protected $_colKey;
protected $_rowKeys;
protected $_valueKey;
protected $_cols = array();
protected $_rows = array();
protected $_values = array();
protected $_rowsTotals = array();
protected $_groupsTotals = array();
protected $_colsTotals = array();
public function __construct($dataSource = null)
{
$this->_dataSource = $dataSource;
}
public function setColumn($key)
{
$this->_colKey = $key;
return $this;
}
public function addRow($key)
{
$this->_rowKeys[] = $key;
return $this;
}
public function setValue($key)
{
$this->_valueKey = $key;
return $this;
}
protected function _fetch()
{
/** Rows + Cols **/
foreach($this->_dataSource as $id => $data)
{
if($data instanceof Gen_Entity_Abstract) {
$data = $data->toArray();
}
$dataValue = $data[$this->_valueKey];
$colValue = $data[$this->_colKey];
if(!isset($this->_cols[$colValue])) {
$this->_cols[$colValue] = array();
}
$this->_cols[$colValue][$id] = $dataValue;
$previousRowValue = null;
foreach($this->_rowKeys as $i => $rowKey)
{
$rowValue = $data[$rowKey];
if(!isset($this->_rows[$i])) {
$this->_rows[$i] = array();
}
if(!isset($this->_rows[$i][$previousRowValue])) {
$this->_rows[$i][$previousRowValue] = array();
}
if(!isset($this->_rows[$i][$previousRowValue][$rowValue])) {
$this->_rows[$i][$previousRowValue][$rowValue] = array();
}
$this->_rows[$i][$previousRowValue][$rowValue][$id] = $dataValue;
$previousRowValue = $rowValue;
}
// if(!isset($this->_rows[$groupValue][$rowValue])) {
// $this->_rows[$groupValue][$rowValue] = array();
// }
// $this->_rows[$groupValue][$rowValue][$id] = $dataValue;
}
ksort($this->_rows);
ksort($this->_cols);
/** Values **/
foreach($this->_rows as $i => $groups)
{
ksort($groups);
$this->_values[$i] = array();
foreach($groups as $groupValue => $rows)
{
ksort($rows);
$this->_values[$i][$groupValue] = array();
foreach($rows as $rowValue => $rowDataSet)
{
$this->_values[$i][$groupValue][$rowValue] = array();
foreach($this->_cols as $colValue => $colDataSet)
{
$valueDataSet = array_intersect_assoc($rowDataSet, $colDataSet);
$value = array_sum($valueDataSet);
$this->_values[$i][$groupValue][$rowValue][$colValue] = $value;
// if(!isset($this->_rowsTotals[$rowValue])) { $this->_rowsTotals[$rowValue] = 0; }
// $this->_rowsTotals[$rowValue] += $value;
// if(!isset($this->_colsTotals[$colValue])) { $this->_colsTotals[$colValue] = 0; }
// $this->_colsTotals[$colValue] += $value;
}
}
}
}
}
public function build()
{
$this->_fetch();
$html = '<table class="txt">';
$html .= '<thead><tr>';
$html .= '<th></th>';
foreach($this->_cols as $colValue => $dataSet)
{
$html .= '<th>'. htmlentities($colValue) .'</th>';
}
// $html .= '<th>'. _t("TOTAL") .'</th>';
$html .= '</tr></thead>';
$html .= '<tbody>';
$html .= $this->_buildGroup(0);
$html .= '</tbody>';
// $html .= '<tfoot><tr>';
// $html .= '<td>'. _t("TOTAL") .'</td>';
// foreach($this->_colsTotals as $colValue => $value)
// {
// $html .= '<td>'. _amount($value) .'</td>';
// }
// $html .= '<td>'. _amount(array_sum($this->_colsTotals)) .'</td>';
// $html .= '</tr></tfoot>';
$html .= '</table>';
return $html;
}
protected function _buildGroup($i, $groupValue = null)
{
if(!isset($this->_values[$i][$groupValue])) {
return false;
}
$html = '';
foreach($this->_values[$i][$groupValue] as $rowValue => $dataSet)
{
$html .= '<tr>';
$html .= '<td style="padding-left: '.(10 + $i*20).'px;">'. $rowValue .'</td>';
foreach($dataSet as $colValue => $value)
{
$html .= '<td>'. _amount($value) .'</td>';
}
$html .= $this->_buildGroup($i+1, $rowValue);
}
return $html;
}
public function render()
{
echo $this->build();
}
}
<?php
class Gen_Repository
{
/**
* the Singleton Instance
* @var Gen_Repository
*/
protected static $_instances;
protected $_data;
/**
* Constructor
*
* Gen_View_Stack implements singleton
* Instantiate using {@link getInstance()}
*
* @return void
*/
public function __construct()
{
$this->_data = array();
}
/**
* Enforce singleton; disallow cloning
*
* @return void
*/
private function __clone()
{
}
/**
* Singleton instance
*
* @return Gen_Event_Handler
*/
public static function getInstance($namespace = 'Gen_Repository_Default')
{
if (!isset(self::$_instances[$namespace])) {
self::$_instances[$namespace] = new self();
}
return self::$_instances[$namespace];
}
public function set($key, $value)
{
$this->_data[$key] = $value;
return $this;
}
public function get($key, $default = null)
{
return isset($this->_data[$key]) ? $this->_data[$key] : $default;
}
public function add($value)
{
$this->_data[] = $value;
return $this;
}
public function append($key, $value)
{
$this->_data[$key] = isset($this->_data[$key]) ? $this->_data[$key] + $value : $value;
return $this;
}
public function prepend($key, $value)
{
$this->_data[$key] = isset($this->_data[$key]) ? $value + $this->_data[$key] : $value;
return $this;
}
public function toArray()
{
return $this->_data;
}
}
<?php
/**
* @category Gen
* @package Gen_Str
*/
class Gen_Str
{
const INDENT = "\t";
const DELIMITER = '_';
public static function indent($str, $nbr = 1)
{
$indent = null;
for ($i=0; $i<$nbr; $i++) {
$indent .= self::INDENT;
}
return $indent . str_replace("\n", "\n$indent", $str);
}
public static function camelize($str, $lcfirst = true)
{
$parts = explode('_', $str);
$str = null;
foreach($parts as $part) {
$str .= ($str || !$lcfirst)? ucfirst(mb_strtolower($part)) : mb_strtolower($part);
}
return $str;
}
public static function shorten($str, $limit = 50)
{
if (isset($str[$limit])) {
$str = mb_substr($str, 0, $limit - 3, 'UTF-8') . "...";
}
return $str;
}
public static function underscore($str)
{
$str = str_replace('-', '_', $str);
$str = preg_replace('#([A-Z]+)([A-Z][a-z])#', '$1_$2', $str);
$str = preg_replace('#([a-z])([A-Z])#', '$1_$2', $str);
return mb_strtolower($str);;
}
public static function dasherize($str)
{
return str_replace('_', '-', self::underscore($str));
}
public static function urlDasherize($str)
{
$str = self::transformAccents($str);
$str = str_replace('-','_',$str);
$str = preg_replace('#[^a-z0-9\._ \']#', '', mb_strtolower($str));
$str = preg_replace('#[\._ \']#', '-', $str);
$str = preg_replace('#[-]+#', '-', $str);
return trim($str, '-');
}
public static function htmlify($str)
{
$str = '<p>' . _br($str) . '</p>';
return $str;
}
public static function uniq($length = 6, $useDigits = true)
{
$digits = "0123456789";
$characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
if ($useDigits) $characters .= $digits;
$str = null;
$max = strlen($characters) - 1;
for ($i = 0; $i < $length; $i++) {
$str .= $characters[mt_rand(0, $max)];
}
return $str;
}
public static function textify($str)
{
$str = preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s','',$str);
$str = str_replace('<br />', "\n", $str);
$str = str_replace('</p>', "\n", $str);
return html_entity_decode(trim(strip_tags($str)));
}
public static function jsoninfy($str)
{
$str = htmlspecialchars($str, ENT_NOQUOTES, 'UTF-8');
$str = preg_replace("/(\r\n|\n|\r)/", "\\n", $str);
$str = preg_replace('#\\\*"#', '\\"', $str);
return $str;
}
public static function transformAccents($str)
{
$accents_replacements = array(
'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e',
'È' => 'e', 'É' => 'e', 'Ê' => 'e', 'Ë' => 'e',
'à' => 'a', 'â' => 'a', 'ä' => 'a', 'á' => 'a', 'ã' => 'a', 'å' => 'a',
'À' => 'a', 'Â' => 'a', 'Ä' => 'a', 'Á' => 'a', 'Ã' => 'a', 'Å' => 'a',
'î' => 'i', 'ï' => 'i', 'í' => 'i', 'ì' => 'i',
'Î' => 'i', 'Ï' => 'i', 'Í' => 'i', 'Ì' => 'i',
'ô' => 'o', 'ö' => 'o', 'ò' => 'o', 'ó' => 'o', 'õ' => 'o',
'Ô' => 'o', 'Ö' => 'o', 'Ò' => 'o', 'Ó' => 'o', 'Õ' => 'o',
'ù' => 'u', 'û' => 'u', 'ü' => 'u', 'ú' => 'u',
'Ù' => 'u', 'Û' => 'u', 'Ü' => 'u', 'Ú' => 'u',
'ý' => 'y', 'Ý' => 'y', 'ÿ' => 'y',
'ç' => 'c', 'Ç' => 'c',
'ñ' => 'n', 'Ñ' => 'n'
);
$accents = array();
$replacements = array();
foreach($accents_replacements as $accent => $replacement) {
array_push($accents, $accent);
array_push($replacements, $replacement);
}
return str_replace($accents, $replacements, $str);
}
public static function keyify($str)
{
$str = self::urlDasherize($str);
$str = str_replace('-', '_', $str);
return $str;
}
public static function labelize($str)
{
$str = self::keyify($str);
$str = ucwords(str_replace('_', ' ', $str));
return $str;
}
public static function classify($str)
{
$str = self::camelize($str, false);
$str = str_replace(' ', '_', ucwords(str_replace('::', ' ', $str)));
return $str;
}
public static function constantize($str)
{
$str = mb_strtoupper($str);
return $str;
}
public static function namespaceToFile($str, $suffix, $extension = '.php')
{
$str = self::camelize($str, false);
$str = str_replace(' ', '/', ucwords(str_replace('::', ' ', $str)));
return $str . $suffix . $extension;
}
public static function toFile($str, $suffix = '.php')
{
$str = str_replace('_', '/', $str);
$str .= $suffix;
return $str;
}
public static function pluralize($str)
{
$exceptions = array(
'child' => 'children',
'person' => 'people'
);
if(isset($exceptions[$str])) { return $exceptions[$str]; }
$pattern = array('#([^oe])y\b#', '#ess\b#', '#(s|x|z|ch|sh)\b#');
$replace = array('$1ie','esse', '$1e');
$str = preg_replace($pattern, $replace, $str) . 's';
return $str;
}
public static function lcfirst($str)
{
$str = mb_strtolower(substr($str, 0, 1)) . substr($str, 1);
return $str;
}
public static function split($str)
{
$str = self::transformAccents($str);
$str = mb_strtolower($str);
$keywords = preg_split("/[\s,-.]+/", $str, -1, PREG_SPLIT_NO_EMPTY);
return $keywords;
}
public function map($str, $data)
{
/**
* extract variables $var & $inflector for each tag
* a tag is delimited by {:tag}
* inflectors can be specified with `|`
*/
$tag = '[a-z][a-zA-Z.]*';
$inflector = '\|[a-z][a-zA-Z| :"]*';
$pattern = "{:($tag)($inflector)?}";
preg_match_all('#' . $pattern . '#', $str, $matches);
/**
* compute recursive value from $data
* these values are delimited by `.`
*/
foreach ($matches[1] as $key => $var) {
$parts = explode('.', $var);
$value = $data;
foreach ($parts as $part) {
$value = (object) $value;
if (isset($value->$part)) {
$value = $value->$part;
} /** elseif (isset($default[$var])) {
$value = $default[$var];
break;
} */ else {
$value = '';
break;
}
}
/** replace :tag by computed $value */
str_replace("{:$var}", (string) $value, $str);
}
return $str;
}
public static function toLower($str)
{
return mb_strtolower($str);
}
public static function substr($str, $start, $lenght = null)
{
return mb_substr($str, $start, $lenght, 'UTF-8');
}
public static function left($str, $lenght)
{
return self::substr($str, 0, $length);
}
public static function right($str, $lenght)
{
return self::substr($str, 0, - $length);
}
}
<?php
require_once('Gen/Str.php');
/**
* @category Gen
* @package Gen_String
*/
class Gen_String
{
protected $_str;
public function __toString()
{
return $this->_str;
}
public function __construct($str = '')
{
$this->_str = (string) $str;
}
public function __call($name, $args)
{
if(!method_exists('Gen_Str', $name)) {
throw new Exception('Call to undefined function ' . $name . ' in Gen_String');
}
array_unshift($args, $this->_str);
$this->_str = call_user_func_array(array('Gen_Str', $name), $args);
return $this;
}
public function suffix($suffix)
{
$this->_str .= $suffix;
return $this;
}
public function prefix($prefix)
{
$this->_str = $prefix . $this->_str;
return $this;
}
public function replace($search, $replace)
{
$this->_str = str_replace($search, $replace, $this->_str);
return $this;
}
public function lenght()
{
return strlen($this->_str);
}
public function endsWith($search)
{
return ($search == Gen_Str::substr($this->_str, - strlen($search)));
}
public function ltrim($search)
{
$this->_str = ltrim($this->_str, $search);
return $this;
}
public function rtrim($search)
{
$this->_str = rtrim($this->_str, $search);
return $this;
}
}
<?php
require_once('Gen/Translate/Pattern.php');
class Gen_Translate
{
public static function findPhrases($folder, $pattern, $date = null)
{
$result = array();
$result = array_merge($result, self::parseFolder($folder, $pattern, $date));
$result = array_merge($result, self::parseFolder($folder, Gen_Translate_Pattern::CONTEXT, $date));
$result = array_merge($result, self::parseFolder($folder, Gen_Translate_Pattern::PLURAL, $date));
return $result;
}
public static function parseFolder($folder, $pattern, $date = null, array $phrases = array())
{
//Warnings are not displayed when folder is not a folder but a file
//We then set folder as the dirname of folder whith only one file, the basename of folder
$folders = @scandir($folder);
if ($folders == false) {
$folders = (array) basename($folder);
$folder = dirname($folder) . '/';
}
foreach($folders as $file) {
$filePath = $folder . $file;
if (is_dir($filePath) && ($file != '.') && ($file != '..') && ($file != '.svn')) {
$phrases = self::parseFolder($filePath .'/', $pattern, $date, $phrases);
} elseif(strpos($file, '.' . Gen_Translate_Pattern::getExtensionById($pattern)) && ($date === null || filemtime($filePath) > strtotime($date))) {
$phrases = array_merge($phrases, self::parseFile($filePath, $pattern));
}
}
return $phrases;
}
public static function parseFile($filePath, $pattern)
{
$phrases = array();
$content = file_get_contents($filePath);
$condition = Gen_Translate_Pattern::getConditionById($pattern);
if (!$condition || preg_match("#" . $condition . "#", $content)) {
preg_match_all(Gen_Translate_Pattern::getPatternById($pattern), $content, $matches);
foreach($matches[0] as $id => $match) {
$message = preg_replace('#\\\*"#', '"', $matches[1][$id]);
$context = ($pattern == Gen_Translate_Pattern::CONTEXT && isset($matches[2])) ? $matches[2][$id] : '';
$key = ($context && $pattern == Gen_Translate_Pattern::CONTEXT) ? ('{context:' . $context . '}' . $message) : $message;
$phrases[md5($key)] = self::parse($pattern, $message, $context, $filePath);
if ($pattern == Gen_Translate_Pattern::PLURAL) {
$message = preg_replace('#\\\*"#', '"', $matches[2][$id]);
$phrases[md5($message)] = self::parse($pattern, $message);
}
}
}
return $phrases;
}
public static function parse($pattern, $message, $context = null, $filePath = null)
{
$phrase['message'] = $message;
if ($context !== null) $phrase[Gen_Translate_Pattern::getKeyById($pattern)] = $context;
if ($pattern == Gen_Translate_Pattern::JAVASCRIPT) {
$phrase[Gen_Translate_Pattern::getKeyById(Gen_Translate_Pattern::CONTEXT)] = Gen_Translate_Pattern::getKeyById($pattern);
} elseif ($pattern == Gen_Translate_Pattern::FLASH) {
$phrase[Gen_Translate_Pattern::getKeyById(Gen_Translate_Pattern::CONTEXT)] = strtolower(basename($filePath, '.xml'));
}
return $phrase;
}
}
<?php
/**
* @category Gen
* @package Gen_Unit
*/
class Gen_Unit
{
const MM = 'mm';
const CM = 'cm';
const INCH = 'in';
const PIXEL = 'px';
const PT = 'pt';
const DIGITAL_DPI = 72;
const PRINT_DPI = 300;
//To pixel conversions
public static function mmToPixel($value, $dpi)
{
return round(self::mmToInch($value) * $dpi);
}
public static function inchToPixel($value, $dpi)
{
return round($value * $dpi);
}
public static function ptToPixel($value, $dpi)
{
return round($value * $dpi/72);
}
//From pixel conversions
public static function pixelToMm($value, $dpi)
{
return self::inchToMm($value / $dpi);
}
public static function pixelToInch($value, $dpi)
{
return $value / $dpi;
}
public static function pixelToPt($value, $dpi)
{
return Math.round($value * 72/$dpi);
}
//Inch <-> Mm
public static function mmToInch($value)
{
return $value / 25.4;
}
public static function inchToMm($value)
{
return $value * 25.4;
}
//Resolution
public static function getResolution($pixel, $mm)
{
return $pixel / self::mmToInch($mm);
}
}
<?php
class Gen_Validate
{
const DEFAULT_ERROR_MESSAGE = "Invalid value.";
const REGEXP_TITLE = '[a-zA-Z0-9].*';
protected $_conditions;
protected $_errors;
protected $_messages;
public static $_defaults = array(
'email' => "Invalid email format.",
'emails' => "Invalid email format.",
'url' => "Invalid url format.",
'regexp' => "Invalid text format.",
'presence' => "This value is mandatory.",
'length' => "This text must contain {number} caracters",
'min_length' => "This text is too short. It must contain at least {number} caracters",
'max_length' => "This text is too long. It must contain no more than {number} caracters",
'acceptance' => "You need to accept to continue.",
'min_file_size' => "File size is too small.",
'max_file_size' => "File size is too large.",
'min_image_width' => "Image width is too small.",
'max_image_width' => "Image width is too large.",
'min_image_height' => "Image height is too small.",
'image_width' => "Image witdh must be {number} px.",
'image_height' => "Image height must be {number} px.",
'file_extension' => "Invalid file extention.",
'file_upload' => "File upload error.",
'younger_than' => "You must be younger than {number} years old.",
'older_than' => "You must be older than {number} years old.",
'title' => "Format de titre non valide. Il doit commencer par une lettre ou un chiffre.",
'number' => "Invalid number.",
'positive_number' => "This number must be positiv.",
'min' => "Minimum value of {number}",
'max' => "Maximum value of {number}",
);
public function __construct()
{
$this->_conditions = array();
$this->_errors = array();
$this->_messages = array();
}
/**
* Gets the validation errors
*
* @return array
*/
public function getErrors()
{
return $this->_errors;
}
/**
* Sets external validation errors
*
* @param array $errors
* @return Gen_Validate
*/
public function setErrors(array $errors)
{
$this->_errors = $errors;
return $this;
}
/**
* Resets the errors
* needed by @see isValid
*/
public function resetErrors()
{
unset($this->_errors);
$this->_errors = array();
}
/**
* Adds an error
* build the message based on the template message and the data
* @param string $template
* @param array $data
*/
public function addError($template, $param = null)
{
if(!is_array($param)){
$this->_errors[] = _t($template, array('number' => (string) $param));
} else {
$this->_errors[] = _t($template);
}
}
/**
* Verify that the data is valid
* uses previously set conditions
*
* @param mixed $data
* @return bool
*/
public function isValid($data)
{
$valid = true;
$this->resetErrors();
foreach ($this->_conditions as $key => $value) {
if (false === $this->_execute($key, $data, $value)) {
$valid = false;
}
}
return $valid;
}
/**
* Adds a validation rule (condition)
*
* @param string $condition function key for validation
* @param mixed $param additionnal parameter to match
* @param mixed $message optional error message
* @return Gen_Validate
*/
public function validate($condition, $param = null, $message = null)
{
$this->_conditions[$condition] = $param;
if (null !== $message) {
$this->_messages[$condition] = (string) $message;
}
return $this;
}
protected function _execute($key, $data, $value = null)
{
require_once('Gen/Str.php');
$method = Gen_Str::camelize($key);
if(method_exists($this, $method))
{
if (false === $this->$method($data, $value))
{
$this->_generateError($key);
return false;
}
return true;
}
/** @todo: use Validate Exception */
throw new Exception('Undefined validation method: '. $method .' in '. __CLASS__ .'::execute()');
}
protected function _generateError($key)
{
$template = isset($this->_messages[$key]) ? $this->_messages[$key] :
isset(self::$_defaults[$key]) ? self::$_defaults[$key] : self::DEFAULT_ERROR_MESSAGE;
$this->addError($template, $this->_conditions[$key]);
}
/**
* Validation Rules
*
* validation rules (or conditions) are
* static public functions, so that they can be either
*
* - called directly for a quick validation Gen_Validate::email($value)
*
* - chained through the Validate object and called via @see _execute().
* in that case, the Validate Object will also provide
* an array of errors corresponding to the validation
*
*/
public static function email($value)
{
return (bool) filter_var(trim($value), FILTER_VALIDATE_EMAIL);
}
/**
* Validates one or ; separated emails
*
* @param string $value
* @return bool
*/
public static function emails($value)
{
$emails = explode(';', $value);
$valid = true;
foreach ($emails as $email) {
if (false === filter_var(trim($email), FILTER_VALIDATE_EMAIL)) {
return false;
}
}
return true;
}
public static function url($value)
{
return (bool) preg_match('|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $value);
}
public static function regexp($value, $regexp)
{
return (bool) preg_match('#'. $regexp .'#', $value);
}
public static function presence($value)
{
return (null != $value);
}
public static function length($value, $target)
{
return (mb_strlen($value) == $target);
}
public static function minLength($value, $min)
{
return (mb_strlen($value) >= $min);
}
public static function maxLength($value, $max)
{
return (mb_strlen($value) <= $max);
}
public static function acceptance($value)
{
return ('on' == $value);
}
public static function minFileSize(array $file, $min)
{
if (!isset($file['name']) || !$file['name']) return true;
$fileSize = filesize($file['tmp_name']);
return ($fileSize >= $min);
}
public static function maxFileSize(array $file, $max)
{
if (!isset($file['name']) || !$file['name']) return true;
$fileSize = filesize($file['tmp_name']);
return ($fileSize <= $max);
}
public static function minImageWidth(array $file, $min)
{
if (!isset($file['name']) || !$file['name']) return true;
$imageInfo = getimagesize($file['tmp_name']);
return $imageInfo[0] >= $min;
}
public static function maxImageWidth(array $file, $max)
{
if (!isset($file['name']) || !$file['name']) return true;
$imageInfo = getimagesize($file['tmp_name']);
return ($imageInfo[0] <= $max);
}
public static function minImageHeight(array $file, $min)
{
if (!isset($file['name']) || !$file['name']) return true;
$imageInfo = getimagesize($file['tmp_name']);
return ($imageInfo[1] >= $min);
}
public static function maxImageHeight(array $file, $max)
{
if (!isset($file['name']) || !$file['name']) return true;
$imageInfo = getimagesize($file['tmp_name']);
return ($imageInfo[1] <= $max);
}
public static function imageWidth(array $file, $value)
{
if (!isset($file['name']) || !$file['name']) return true;
$imageInfo = getimagesize($file['tmp_name']);
return ($imageInfo[0] == $value);
}
public static function imageHeight(array $file, $value)
{
if (!isset($file['name']) || !$file['name']) return true;
$imageInfo = getimagesize($file['tmp_name']);
return ($imageInfo[1] == $value);
}
public static function fileExtension(array $file, $validExtensions)
{
if (!isset($file['name']) || !$file['name']) return true;
$validExtensions = (array) $validExtensions;
$split = explode('.',$file['name']);
$ext = strtolower(array_pop($split));
return in_array($ext, $validExtensions);
}
public static function fileUpload(array $file)
{
if(!isset($file['error'])) {
return false;
}
return ((0 == $file['error']) && is_uploaded_file($file['tmp_name']) && isset($file['name']) && $file['name']);
}
public function youngerThan($date, $age)
{
require_once('Gen/Date.php');
return (Gen_Date::getAge($date) <= (int) $age);
}
public static function olderThan($date, $age)
{
require_once('Gen/Date.php');
return (Gen_Date::getAge($date) >= (int) $age);
}
public static function title($title)
{
return self::regexp($title, self::REGEXP_TITLE);
}
public static function number($number)
{
return is_numeric($number);
}
public static function ean($number)
{
if(is_numeric($number) && strlen($number)==13)
{
$sum = 0;
for($i=0;$i<6;$i++)
{
$sum += substr($number, 2*$i+1, 1) * 3;
$sum += substr($number, 2*$i, 1);
}
if((10-$sum%10)%10==substr($number, 12, 1))
{
return true;
}
}
return false;
}
public static function availableEan($ean)
{
require_once ('Bo/Album/Sku.php');
return Bo_Album_Sku::availableEan($ean);
}
public static function positiveNumber($number)
{
return is_numeric($number) && $number>=0;
}
public static function min($number, $min)
{
return (int) $number >= (int) $min;
}
public static function max($number, $max)
{
return (int) $number <= (int) $max;
}
}
<?php
require_once('Gen/Dom/Element.php');
class Gen_Xml extends Gen_Dom_Element
{
protected $_version = '1.0';
protected $_encoding = 'utf-8';
public function getVersion()
{
return $this->_version;
}
public function setVersion($version)
{
$this->_version = $version;
return $this;
}
public function getEncoding()
{
return $this->_encoding;
}
public function setEncoding($encoding)
{
$this->_encoding = $encoding;
return $this;
}
public function render()
{
return '<?xml version="'. $this->_version .'" encoding="'. $this->_encoding .'"?>' . parent::render();
}
}
<?php
class Gen_Controller_Acl
{
const DEFAULT_CONTROLLER = 'all';
const DEFAULT_ACTION = 'all';
const DEFAULT_RESULT = 0;
protected $_authorizations = array();
public function permit($roles, $controllers, $actions)
{
$roles = (array) $roles;
$controllers = (array) $controllers;
$actions = (array) $actions;
foreach($roles as $role) {
$auth = isset($this->_authorizations[$role]) ? $this->_authorizations[$role] : array();
foreach($controllers as $controller) {
$controllerAuth = isset($auth[$controller]) ? $auth[$controller] : array();
foreach($actions as $action) {
$controllerAuth[$action] = 1;
}
$auth[$controller] = $controllerAuth;
}
$this->_authorizations[$role] = $auth;
}
}
public function can($role, $controller, $action)
{
$auth = $this->getAuthorization($role);
if(null === $auth) {
Gen_Log::log('NO Role defined', 'Gen_Acl::can', 'warning');
return self::DEFAULT_RESULT;
}
$result = self::DEFAULT_RESULT;
foreach(array($controller, self::DEFAULT_CONTROLLER) as $c) {
if(isset($auth[$c])) {
$result = isset($auth[$c][$action])
? $auth[$c][$action]
: (isset($auth[$c][self::DEFAULT_ACTION])
? $auth[$c][self::DEFAULT_ACTION]
: self::DEFAULT_RESULT);
if($result) {
return $result;
}
}
}
Gen_Log::log('NO Controller defined', 'Gen_Acl::can', 'warning');
return $result;
}
public function canRoute($role, $route)
{
$name = is_array($route) ? $route[0] : $route;
$router = Gen_Controller_Front::getRouter();
$route = $router->getRoute($name);
return $this->allows($role, $route['default']['controller'], $route['default']['action']);
}
public function getAuthorization($role)
{
return isset($this->_authorizations[$role]) ? $this->_authorizations[$role] : null;
}
public function getAuthorizations()
{
return $this->_authorizations;
}
public function setAuthorizations($authorizations)
{
$this->_authorizations = $authorizations;
return $this;
}
}
<?php
require_once('Gen/Str.php');
/**
* @category Gen
* @package Gen_Controller
*/
abstract class Gen_Controller_Action
{
/**
* The Request
* @var Gen_Controller_Request
*/
protected $_request;
/**
* The Response
* @var Gen_Controller_Response
*/
protected $_response;
/**
* The current action
* @var string
*/
protected $_currentAction = 'undefined';
/**
* the Controller name
* based on class name if none provided
* @var string
*/
protected $_name;
/**
* The View
* @var Gen_View_Base
*/
protected $_view;
/**
* The Layout key
* @var string
*/
protected $_layout;
/**
* Indicator for rendering
* @var bool
*/
protected $_performRendering = true;
/**
* Indicator for processing
*/
protected $_process = true;
/**
* List of Filters
* @var array
*/
protected $_filters = array();
/**
* List of Breadcrumbs
* @var array
*/
protected $_breadcrumbs = array();
protected $_appMenu = array();
protected $_currentEvent;
/**
* Format Action Method based on action key
*
* format is {:action|camelCase}Action
*
* @param string $action
* @return string $actionMethod
*/
public static function getActionMethod($action)
{
return Gen_Str::camelize($action) . 'Action';
}
public function setCurrentAction($action)
{
$this->_currentAction = (string) $action;
return $this;
}
public function getCurrentAction()
{
return $this->_currentAction;
}
/**
* Gets the Controller Name
*
* @return string
*/
public function getName()
{
if (!isset($this->_name)) {
$this->_name = (string) $this->getDefaultName();
}
return $this->_name;
}
public function getDefaultName()
{
$class = str_replace('Controller', '', get_class($this));
return Gen_Str::underscore($class);
}
/**
* Sets the Request
*
* @param Gen_Controller_Request $request
* @return Controller
*/
public function setRequest(Gen_Controller_Request $request)
{
$this->_request = $request;
return $this;
}
/**
* Gets the Request
*
* @return Gen_Controller_Request $request
*/
public function getRequest()
{
if (!isset($this->_request)) {
require_once ('Gen/Controller/Request.php');
$this->_request = new Gen_Controller_Request();
}
return $this->_request;
}
/**
* Sets the Response
*
* @param Gen_Controller_Response $response
* @return Controller
*/
public function setResponse(Gen_Controller_Response $response)
{
$this->_response = $response;
return $this;
}
/**
* Gets the Response
*
* @return Gen_Controller_Response $response
*/
public function getResponse()
{
if (!isset($this->_response)) {
require_once ('Gen/Controller/Response.php');
$this->_response = new Gen_Controller_Response();
}
return $this->_response;
}
/**
* Retrieve a given Parameter by key
*
* @return mixed
*/
public function getParam($key, $default = null)
{
return $this->getRequest()->getParam($key, $default);
}
/**
* Gets all Parameters
*
* @return Gen_Hash $params
*/
public function getParams()
{
return $this->getRequest()->getParams();
}
/**
* Gets current Url
*
* @return string
*/
public function getCurrentUrl(array $data = array(), $relative = true)
{
return $this->getRequest()->getCurrentUrl($data, $relative);
}
/**
* Sets the View
*
* @param Gen_View_Base $view
* @return Controller
*/
public function setView(Gen_View_Base $view)
{
$this->_view = $view;
return $this;
}
/**
* Gets the View
*
* @return Gen_View_Base $view
*/
public function getView()
{
if (!isset($this->_view)) {
require_once ('Gen/View/Base.php');
$this->_view = new Gen_View_Base();
}
return $this->_view;
}
/**
* Sets the Layout key
*
* @param layout
* @return Controller
*/
public function setLayout($layout)
{
$this->_layout = (string) $layout;
return $this;
}
/**
* Gets the Layout
*
* @return Gen_View_Layout $layout
*/
public function getLayout()
{
return $this->_layout;
}
/**
* Disables the layout rendering
* @return Gen_Controller_Action
*/
public function disableLayout()
{
$this->_layout = null;
return $this;
}
public function performRendering()
{
return $this->_performRendering;
}
public function enableRendering()
{
$this->_performRendering = true;
return $this;
}
public function disableRendering()
{
$this->_performRendering = false;
return $this;
}
public function stopProcessing()
{
$this->_process = false;
return $this;
}
/************************************
* Session *
************************************/
private static function _sessionToken()
{
return 'App_Session_' . APP_KEY . '_' . APP_VERSION;
}
public function setSession($key, $value)
{
$token = self::_sessionToken();
if(!isset($_SESSION[$token])) {
$_SESSION[$token] = array();
}
$_SESSION[$token][$key] = $value;
}
public function unsetSession($key)
{
$value = null;
$token = self::_sessionToken();
if(isset($_SESSION[$token])) {
if(isset($_SESSION[$token][$key])) {
$value = $_SESSION[$token][$key];
unset($_SESSION[$token][$key]);
}
$_SESSION[$token][$key] = null;
}
return $value;
}
public function getSession($key, $default = null)
{
$token = self::_sessionToken();
if(isset($_SESSION[$token]) && isset($_SESSION[$token][$key])) {
return $_SESSION[$token][$key];
}
return $default;
}
public function getPersistentParam($key, $default = null)
{
$value = $this->getParam($key);
if(null !== $value) {
$this->setSession($key, $value);
}
return $this->getSession($key, $default);
}
/************************************
* Cookie *
************************************/
public function getCookie($name = 'Gen_Cookie')
{
if (!isset($this->_cookies[$name])) {
require_once('Gen/Http/Cookie.php');
$this->_cookies[$name] = new Gen_Http_Cookie($name);
}
return $this->_cookies[$name];
}
public function assignCookie($key, $value)
{
$this->getCookie()->setParam($key, $value);
return $this;
}
/************************************
* Filters *
************************************/
public function addFilter($name, array $actions, $controller = null)
{
if(($controller === null) || ($controller == $this->getName()))
{
$name = (string) $name;
if (!isset($this->_filters[$name])) {
$this->_filters[$name] = $actions;
} else {
$this->_filters[$name] = array_merge($this->_filters[$name], $actions);
}
}
return $this;
}
public function removeFilter($name, array $actions)
{
$name = (string) $name;
if (isset($this->_filters[$name])) {
Gen_Log::log($this->_filters[$name],'Gen_Controller_Action::removeFilter', 'warning');
$this->_filters[$name] = array_diff($this->_filters[$name], $actions);
Gen_Log::log($this->_filters[$name],'Gen_Controller_Action::removeFilter', 'warning');
}
return $this;
}
public function getFilters()
{
return $this->_filters;
}
/*********************************
* Breadcrumb *
*********************************/
public function addBreadcrumb($label, $route = null)
{
$this->_breadcrumbs[] = array(
'label' => $label,
'route' => $route
);
return $this;
}
public function getBreadcrumbs()
{
return $this->_breadcrumbs;
}
/*********************************
* Breadcrumb *
*********************************/
public function addMenuItem($label, $route)
{
$this->_appMenu[] = array(
'label' => $label,
'route' => $route
);
return $this;
}
public function getAppMenu()
{
return $this->_appMenu;
}
/**
* Constructor
*
* calls {@link init()}
*/
public function __construct()
{
$this->init();
}
/**
* Init function to be implemented by Action Controller
*/
public function init() {}
public function onProcessStart(){}
public function onProcessEnd(){}
public function onActionStart(){}
public function onActionEnd(){}
public function onRenderStart(){}
public function process(Gen_Controller_Request $request, Gen_Controller_Response $response)
{
$this->_request = $request;
$this->_response = $response;
Gen_Log::log('on Process Start', 'Gen_Controller_Action::process');
$this->onProcessStart();
$action = $this->getRequest()->getAction();
/** filter */
if ($this->_process) {
Gen_Log::log($this->getFilters(), 'Filters');
$this->filter($action);
}
/** execute */
if ($this->_process) {
$this->execute($action);
}
$this->onProcessEnd();
return $this->getResponse();
}
public function filter($action)
{
foreach ($this->getFilters() as $filterName => $filterActions) {
/** should we filter ? */
if (in_array($action, $filterActions)) {
/** call filter if exists */
$filterMethod = Gen_Str::camelize($filterName) . 'Filter';
Gen_Log::log($filterMethod, 'filter');
if (method_exists($this, $filterMethod)) {
/** filters applied */
if (!$this->$filterMethod($action)) {
$this->stopProcessing();
return false;
}
} else {
throw new Exception("Unknown filter $filterMethod in " . get_class($this) . "::filter");
}
}
}
return true;
}
public function execute($action)
{
Gen_Log::log($action, 'Gen_Controller_Action::execute');
$this->setCurrentAction($action);
$this->onActionStart();
if ($this->_process) {
$method = (string) $this->getActionMethod($action);
if (method_exists($this, $method)) {
/** execute action */
$this->$method();
/** render view */
if ($this->performRendering() && $this->_process) {
$this->render();
}
} else {
throw new Exception("Cannot execute given action: $method in " . get_class($this) . "::execute()");
}
}
if ($this->_process) {
$this->onActionEnd();
}
}
public function render($request = null, $controller = null, $module = null)
{
if(!($request instanceof Gen_Controller_Request)) {
$action = $request;
$request = $this->getRequest();
if ($action !== null) {
$request->setAction($action);
}
if ($controller !== null) {
$request->setController($controller);
}
if ($module !== null) {
$request->setModule($module);
}
}
$this->disableRendering();
Gen_Log::log('onRenderStart', 'Gen_Controller_Action::render');
$this->onRenderStart();
Gen_Log::log('rendering', 'Gen_Controller_Action::render');
/** sets defaults */
$options = $request->toArray();
/** gestion du format de rendu */
switch($options['format']) {
case 'rss':
$this->getResponse()->setContentType('text/xml; charset=utf-8');
$this->setLayout('layout::rss');
break;
case 'xml':
$this->getResponse()->setContentType('text/xml; charset=utf-8');
$this->disableLayout();
break;
case 'json':
$this->getResponse()->setContentType('application/json; charset=utf-8');
$this->disableLayout();
break;
case 'txt':
$this->getResponse()->setContentType('text/plain; charset=utf-8');
$this->disableLayout();
break;
case 'ajax':
$this->disableLayout();
case 'html':
default:
$options['format'] = null;
$this->getResponse()->setContentType('text/html; charset=utf-8');
break;
}
if($request->getParam('disable_layout', false)) {
$this->disableLayout();
}
$view = $this->getView();
$view->setLayout($this->_layout);
$view->assign('appMenu', $this->getAppMenu());
$view->assign('breadcrumbs', $this->getBreadcrumbs());
$content = $view->render($options);
/** appends the result to the response body */
$this->getResponse()->appendBody($content);
return $content;
}
public function redirect($name, array $params = array(), $relative = true)
{
return $this->redirectUrl($this->url($name, $params, $relative));
}
public function redirectUrl($url,$params = array())
{
require_once('Gen/Http/Request.php');
/** @hack */
if(isset($_GET['show_log'])) {
$params['show_log'] = true;
}
$url = Gen_Http_Request::buildUrl($url, $params);
$this->disableRendering();
$this->stopProcessing();
/** @hack */ if(isset($_GET['stop_processing'])) { return false; }
$this->getResponse()->redirect($url);
}
public function permanentRedirect($name, array $params = array(), $relative = true)
{
return $this->permanentRedirectUrl($this->url($name, $params, $relative));
}
public function permanentRedirectUrl($url)
{
$this->disableRendering();
$this->stopProcessing();
/** @hack */ if(isset($_GET['stop_processing'])) { return false; }
$this->getResponse()->permanentRedirect($url);
}
public function getBackUrl($default = null)
{
return $this->getParam('redirect', isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : $default);
}
public function redirectBack($name = 'default', array $params = array())
{
$this->redirectUrl($this->getBackUrl($this->url($name, $params)));
}
/**
* Helper for Router::url()
*
* @param string $name of the Route
* @param array $data to build the url
* @return string the corresponding url
*/
public function url($name = 'default', array $data = array(), $relative = true)
{
require_once('Gen/Controller/Front.php');
return $this->getRouter()->url($name, $data, $relative);
}
public function getRouter()
{
return Gen_Controller_Front::getInstance()->getRouter();
}
public function viewData($key, $value)
{
$this->getView()->assign($key, $value);
return $this;
}
public function setFlash($key, $value)
{
Gen_Session_Flash::getInstance()->set($key, $value);
return $this;
}
public function getFlash($key, $default = null)
{
return Gen_Session_Flash::getInstance()->get($key, $default);
}
public function setMessage($message, $level = 'info', $params = null, $translate = true)
{
Gen_Session_Flash::getInstance()->set('Gen_Controller_Message', $translate ? _t($message, $params) : $message);
Gen_Session_Flash::getInstance()->set('Gen_Controller_Message_Level', $level);
return $this;
}
public function setWarning($message)
{
$this->setMessage($message, 'warning');
return $this;
}
public function setError($message)
{
$this->setMessage($message, 'error');
return $this;
}
public function getMessage($default = null)
{
return Gen_Session_Flash::getInstance()->get('Gen_Controller_Message', $default);
}
public function getMessageLevel($default = 'info')
{
return Gen_Session_Flash::getInstance()->get('Gen_Controller_Message_Level', $default);
}
/************************************
* Form *
************************************/
public function getForm($className = null)
{
require_once('Gen/Repository.php');
$repo = Gen_Repository::getInstance('Gen_Controller_Action_Forms');
$className = $className ? $className : 'Form_' . str_replace('Controller', '', get_class($this));
if (!$repo->get($className)) {
$fileName = str_replace('_', '/', $className) . '.php';
require_once ($fileName);
$serializedForm = $this->getFlash($className);
$form = $serializedForm ? unserialize($serializedForm) : new $className();
$repo->set($className, $form);
}
return $repo->get($className);
}
public function setForm(Gen_Form $form)
{
$this->setFlash(get_class($form), serialize($form));
return $this;
}
/***********************************
* EVENTS *
***********************************/
public function fire($name,$params = array())
{
return Gen_Controller_Front::fire($name, $params);
}
public function processEvent($action, Gen_Controller_Event $event)
{
$listener = $this->getListenerMethod($action);
if (!method_exists($this, $listener)) {
throw new Exception("Call to undefined listener: $listener in " . get_class($this) . "::processEvent()");
}
$this->setEvent($event);
return $this->$listener();
}
public static function getListenerMethod($action)
{
return Gen_Str::camelize($action) . 'Listener';
}
public function getEvent()
{
return $this->_currentEvent;
}
public function setEvent(Gen_Controller_Event $event)
{
$this->_currentEvent = $event;
}
// DEBUG
public function trace($msg, $label = "Gen_Controller_Action::trace")
{
require_once('Gen/Log.php');
Gen_Log::log($msg, $label, 'warning');
return Gen_Controller_Front::sendMail(Gen_Log::render());
}
}
<?php
/**
* Event. which can be listened
*/
class Gen_Controller_Event
{
protected $value = null;
protected $processed = false;
protected $name;
protected $parameters;
/**
* Constructs a new Event.
*
* @param string $name The event name
* @param array $parameters An array of parameters
*/
public function __construct($name, $parameters = array())
{
$this->name = $name;
$this->parameters = $parameters;
}
/**
* Returns the event name.
*
* @return string The event name
*/
public function getName()
{
return $this->name;
}
/**
* Sets the return value for this event.
*
* @param mixed $value The return value
*/
public function setReturnValue($value)
{
$this->value = $value;
}
/**
* Returns the return value.
*
* @return mixed The return value
*/
public function getReturnValue()
{
return $this->value;
}
/**
* Sets the processed flag.
*
* @param Boolean $processed The processed flag value
*/
public function setProcessed($processed)
{
$this->processed = (boolean) $processed;
}
/**
* Returns whether the event has been processed by a listener or not.
*
* @return Boolean true if the event has been processed, false otherwise
*/
public function isProcessed()
{
return $this->processed;
}
/**
* Returns the event parameters.
*
* @return array The event parameters
*/
public function getParams()
{
return $this->parameters;
}
/**
* Returns true if the parameter exists.
*
* @param string $name The parameter name
*
* @return Boolean true if the parameter exists, false otherwise
*/
public function hasParam($name)
{
return array_key_exists($name, $this->parameters);
}
/**
* Returns a parameter value.
*
* @param string $name The parameter name
* @param mixed $default The default returned value
*
* @return mixed The parameter value
*/
public function getParam($key, $default = null)
{
return (isset($this->parameters[$key]) && ($this->parameters[$key] !== '')) ? $this->parameters[$key] : $default;
}
/**
* Sets a parameter.
*
* @param string $name The parameter name
* @param mixed $value The parameter value
*/
public function setParam($name, $value)
{
$this->parameters[$name] = $value;
}
}
<?php
/** @see Gen_Exception */
require_once ('Gen/Exception.php');
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Exception extends Gen_Exception
{
}
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_NotFoundException extends Gen_Controller_Exception
{
}
<?php
require_once('Gen/Session/Flash.php');
/**
* The Front Controller
*
* the Front Controller managers incoming Requests and render the final Response
*
* Use the static method {@link run()} to start the Front Controller process
*
* The Front Controller implements the Singleton pattern
* to ensure that only one process is performed
*
* The incoming Request is passed to the Router
* to determine the first Controller Action to process
*
* Finaly the Response is rendered
*
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Front
{
public static $env = 'localhost';
public static $debug = false;
public static $appName = 'Gen';
public static $appMail = null;
/**
* the Controllers directory
* defaulted to ./application/Controller/
* @var string
*/
public static $controllerDir = './application/Controller/';
protected static $_viewDir;
/**
* The Singleton instance
* @var Gen_Controller_Front
*/
protected static $_instance;
/**
* The Request
* @var Gen_Controller_Request
*/
protected $_request;
/**
* The Response
* @var Gen_Controller_Response
*/
protected $_response;
/**
* The Router
* @var Gen_Controller_Router
*/
protected $_router;
/**
* The Cookie
* @var Gen_Http_Cookie
*/
protected $_cookie;
protected $_handleError = true;
protected $_eventDispatcher;
/**
* Constructor
*
* Instantiate using {@link getInstance()}; event handler is a singleton
* object.
*
* @return void
*/
protected function __construct()
{
}
/**
* Enforce singleton; disallow cloning
*
* @return void
*/
private function __clone()
{
}
/**
* Singleton instance
*
* @return Gen_Controller_Front
*/
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
/**
* Sets the Request
*
* @param Gen_Controller_Request $request
* @return Controller
*/
public function setRequest(Gen_Controller_Request $request)
{
$this->_request = $request;
return $this;
}
/**
* Gets the Request
*
* @return Gen_Controller_Request $request
*/
public function getRequest()
{
if (!isset($this->_request)) {
require_once ('Gen/Controller/Request.php');
$this->_request = new Gen_Controller_Request();
}
return $this->_request;
}
/**
* Sets the Response
*
* @param Gen_Controller_Response $response
* @return Controller
*/
public function setResponse(Gen_Controller_Response $response)
{
$this->_response = $response;
return $this;
}
/**
* Gets the Response
*
* @return Gen_Controller_Response $response
*/
public function getResponse()
{
if (!isset($this->_response)) {
require_once ('Gen/Controller/Response.php');
$this->_response = new Gen_Controller_Response();
}
return $this->_response;
}
/**
* Gets the Router
*
* defaults it to Gen_Controller_Route if none provided
*
* @return Gen_Controller_Route
*/
public function getRouter()
{
if (!isset($this->_router)) {
require_once('Gen/Controller/Router.php');
$this->_router = new Gen_Controller_Router();
}
return $this->_router;
}
/**
* Sets the Router
*
* @param Gen_Controller_Router
* @return Gen_Front_Controller
*/
public function setRouter(Gen_Controller_Router $router)
{
$this->_router = $router;
return $this;
}
/**
* Set base url
*
* @param string $baseUrl
* @return Gen_Controller_Front
*/
public function setBaseUrl($baseUrl)
{
$this->getRouter->setBaseUrl($baseUrl);
return $this;
}
/**
* Sets the Cookie
*
* @param Gen_Http_Cookie $cookie
* @return Controller
*/
public function setCookie(Gen_Http_Cookie $cookie)
{
$this->_cookie = $cookie;
return $this;
}
/**
* Gets the Cookie
*
* @return Gen_Http_Cookie $cookie
*/
public function getCookie()
{
if (!isset($this->_cookie)) {
require_once ('Gen/Http/Cookie.php');
$this->_cookie = new Gen_Http_Cookie();
}
return $this->_cookie;
}
public static function setViewDir($dir)
{
self::$_viewDir = $dir;
require_once('Gen/View/Base.php');
Gen_View_Base::$defaultBaseDir = $dir;
}
public function setHandleError($handleError)
{
$this->_handleError = (bool) $handleError;
}
/**
* Run the Front Controller process
*
* add optionals controller directory
*
* @param string|array $controllerDir
* @return Gen_Controller_Response
*/
public static function run()
{
$frontController = self::getInstance();
$request = $frontController->getRequest();
$response = $frontController->getResponse();
return $frontController->process($request, $response);
}
public function process(Gen_Controller_Request $request, Gen_Controller_Response $response)
{
try {
/** initiate */
Gen_Log::log('initiate', 'Gen_Controller_Front::process');
$this->initiate();
/** route */
Gen_Log::log('route', 'Gen_Controller_Front::process');
if($this->getRouter()->route($request)) {
/** process */
Gen_Log::log($request->toArray(), 'Request');
$response = $this->dispatch($request, $response);
} else {
Gen_Log::log('No route matched', 'Gen_Controller_Front::process');
$response->notFound();
}
/** handle Failure */
if (!$request->isAjax()) {
Gen_Log::log('handleFailure', 'Gen_Controller_Front::process');
$response = $this->handleFailure($request, $response);
}
/** send response */
Gen_Log::log('Send Response', 'Gen_Controller_Front::process');
$response->send();
/** finalize */
$this->finalize();
return $response;
} catch (Exception $e) {
/** send mail to support */
try {
self::sendExceptionMail($e);
} catch(Exception $mailE) { }
/** send a 505 internal error response */
$response = $this->getResponse()->error();
if (!$request->isAjax()) {
$request = $this->getRequest()
->setModule('')
->setController('error')
->setAction('error')
->setFormat('html');
if(self::$debug) {
$_GET['show_log'] = true;
$msg = $e->getMessage() . "\n\nin file " . $e->getFile() . "\non line " . $e->getLine() . "\n\nSTACK TRACE:\n\n" . $e->getTraceAsString();
Gen_Log::log('<pre>'.$msg.'</pre>', 'Gen_Controller_Front::process', 'error');
}
$response = $this->dispatch($request, $response);
}
$response->send();
}
}
/**
* Dispatches a request
*
* Determines the Controller and let it process the request
*
* @param Gen_Controller_Request $request
* @param Gen_Controller_Response $response
* @return Gen_Controller_Response $response
*/
public function dispatch(Gen_Controller_Request $request, Gen_Controller_Response $response)
{
$controllerName = $request->getController();
$moduleName = $request->getModule();
require_once('Gen/ClassLoader.php');
$className = Gen_ClassLoader::loadClass($controllerName, $moduleName,'Controller', self::$controllerDir);
if (!class_exists($className)) {
Gen_Log::log('Class Not Found: '. $className, 'Gen_Controller_Front::dispatch', 'warning');
return $response->notFound();
}
$controller = new $className();
$response = $controller->process($request, $response);
return $response;
}
public function handleFailure(Gen_Controller_Request $request, Gen_Controller_Response $response)
{
if (!$response->isJson()) {
switch ($response->getStatus()) {
/** OK, on a white list base */
case 200:
case 201:
case 202:
case 301:
case 302:
case 304:
break;
/** warning */
case 400:
case 405:
$request
->setController('error')
->setAction('warning')
->setModule('')
->setFormat('');
Gen_Log::log('Redirect > Warning', 'Gen_Controller_Front::handleFailure');
$response = $this->dispatch($request, $response);
break;
/** unauthorized */
case 401:
$request
->setController('error')
->setAction('unauthorized')
->setModule('')
->setFormat('');
Gen_Log::log('Redirect > Unauthorized', 'Gen_Controller_Front::handleFailure');
$response = $this->dispatch($request, $response);
break;
/** not found */
case 404:
$request
->setController('error')
->setAction('not_found')
->setModule('')
->setFormat('');
Gen_Log::log('Redirect > Not Found', 'Gen_Controller_Front::handleFailure');
$response = $this->dispatch($request, $response);
break;
case 500:
default:
$request
->setController('error')
->setAction('error')
->setModule('')
->setFormat('');
Gen_Log::log('Redirect > Error', 'Gen_Controller_Front::handleFailure');
$response = $this->dispatch($request, $response);
break;
}
}
return $response;
}
public function initiate()
{
session_start();
require_once('Gen/Session/Flash.php');
Gen_Session_Flash::getInstance()->load();
}
public function finalize()
{
Gen_Session_Flash::getInstance()->save();
}
public static function sendExceptionMail(Exception $e)
{
$msg = $e->getMessage() . "\n\n"
. ' in file ' . $e->getFile() . "\n"
. ' on line ' . $e->getLine()
. "\n\n"
. "STACK TRACE:\n\n" . $e->getTraceAsString();
return self::sendMail($msg);
}
public static function sendMail($msg, $level='Error')
{
if(SEND_MAIL === true)
{
$email = '"'. self::$appName .'"<'. self::$appMail .'>';
$headers = 'From: '. $email ."\n"
. 'Reply-To: '. $email ."\n"
. "X-Mailer: Gen Mailer\n"
. "MIME-Version: 1.0\n"
. "Content-type: text/plain; charset=UTF-8\n";
$msg .= "\n\n"
. ' *****************************************************' . "\n\n"
. ' >>> Include Path: ' . ini_get('include_path') . "\n\n"
. ' >>> GET:' . "\n\n" . print_r($_GET, true) . "\n\n"
. ' >>> POST:' . "\n\n" . print_r($_POST, true) . "\n\n"
. ' >>> FILES:' . "\n\n" . print_r($_FILES, true) . "\n\n"
. ' >>> SESSION:' . "\n\n" . print_r($_SESSION, true) . "\n\n"
. ' >>> SERVER:' . "\n\n" . print_r($_SERVER, true);
$title = '[' . self::$appName . '][' . self::$env .'] '. $level;
/** @todo : mail with beanstalk */
require_once('PHPMailer/class.phpmailer.php');
$mail = new PHPMailer();
// $mail->IsSMTP(); // send via SMTP
// $mail->SMTPAuth = true; // turn on SMTP authentication
// $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
// $mail->Username = ''; // SMTP username
// $mail->Password = ''; // SMTP password
// $mail->Host = '';
// $mail->Port = 465;
$mail->From = self::$appName;
$mail->FromName = 'Support';
$mail->AddAddress(self::$appMail, 'Support');
$mail->AddReplyTo(self::$appMail, 'Support');
$mail->Subject = $title;
$mail->Body = $msg;
try {
if (!$mail->Send()) {
Gen_Log::log($mail->ErrorInfo, 'PhpMailer', 'error');
}
} catch (Exception $e) {
Gen_Log::log($e->getMessage(), 'PhpMailer', 'error');
}
}
return true;
}
public static function executeAction($action, $controller = null, $params = array())
{
return self::getInstance()->getDispatcher()->executeAction($action, $controller, $params);
}
/***********************************
* EVENTS *
***********************************/
public static function fire($name, $params = array())
{
require_once('Gen/Controller/Event.php');
$event = new Gen_Controller_Event($name, $params);
return self::getInstance()->getEventDispatcher()->fire($event);
}
public function getEventDispatcher()
{
if (!isset($this->_eventDispatcher)) {
require_once('Gen/Controller/Event/Dispatcher.php');
$this->_eventDispatcher = new Gen_Controller_Event_Dispatcher();
}
return $this->_eventDispatcher;
}
public function setEventDispatcher(Gen_Controller_Event_Dispatcher $dispatcher)
{
$this->_eventDispatcher = $dispatcher;
return $this;
}
/**
* Notifies all listeners of a given event until one returns a non null value.
* Used in a delegation chain
* @param Event $event A Event instance
*
* @return Event The Event instance
*/
public function fireUntil(Gen_Controller_Event $event)
{
foreach ( $this->getEventDispatcher()->getListeners($event->getName()) as $listener) {
if ($this->getEventDispatcher()->notify($listener, $event)) {
$event->setProcessed(true);
break;
}
}
return $event;
}
/***********************************
* ACL *
***********************************/
/**
* Gets the Acl
*
* defaults it to Gen_Controller_Acl if none provided
*
* @return Gen_Controller_Acl
*/
public function getAcl()
{
if (!isset($this->_acl)) {
require_once('Gen/Controller/Acl.php');
$this->_acl = new Gen_Controller_Acl();
}
return $this->_acl;
}
/**
* Sets the Acl
*
* @param Gen_Controller_Acl
* @return Gen_Front_Controller
*/
public function setAcl(Gen_Controller_Acl $acl)
{
$this->_acl = $acl;
return $this;
}
}
<?php
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Request
{
/**
* The Action
* @var string
*/
protected $_action = 'index';
/**
* The Controller
* @var string
*/
protected $_controller = 'index';
/**
* Optional Module
* @var string
*/
protected $_module = null;
/**
* Optional Format
* default is HTML
* @var string
*/
protected $_format = null;
/**
* The Parameters
* @var array
*/
protected $_params = array();
/**
* Sets the Action
*
* @param string $action
* @return Request
*/
public function setAction($action)
{
$this->_action = (string) $action;
return $this;
}
/**
* Get the Action
*
* @return string
*/
public function getAction()
{
return $this->_action;
}
/**
* Sets the Controller
*
* @param string $controller
* @return Request
*/
public function setController($controller)
{
$this->_controller = (string) $controller;
return $this;
}
/**
* Get the Controller
*
* @return string
*/
public function getController()
{
return $this->_controller;
}
/**
* Sets the Module
*
* @param string $module
* @return Request
*/
public function setModule($module)
{
$this->_module = (string) $module;
return $this;
}
/**
* Get the Module
*
* @return string
*/
public function getModule()
{
return $this->_module;
}
/**
* Sets the Format
*
* @param string $format
* @return Request
*/
public function setFormat($format)
{
$this->_format = (string) $format;
return $this;
}
/**
* Get the Format
*
* @return string
*/
public function getFormat()
{
if (!isset($this->_format)) {
if ($format = $this->getParam('format')) {
$this->_format = (string) $format;
}
}
return $this->_format;
}
/**
* Get the Parameters
*
* @return string
*/
public function getParams()
{
return $this->_params;
}
/** should not be used
public function setParams($params)
{
require_once('Gen/Hash.php');
$this->_params = new Gen_Hash($params);
return $this;
} */
public function getParam($key, $default = null)
{
return (isset($this->_params[$key])&& ($this->_params[$key] !== '')) ? $this->_params[$key] : $default;
}
public function setParam($key, $value)
{
$this->_params[$key] = $value;
return $this;
}
public function addParams($data)
{
$this->_params = array_merge($this->_params, $data);
return $this;
}
public function getUrl()
{
return $_SERVER['REQUEST_URI'];
}
public function getServer()
{
return MS_SERVER_NAME;
}
public function getCurrentUrl(array $data = array(), $relative = true)
{
$url_infos = parse_url($_SERVER['REQUEST_URI']);
$params = array();
if (isset($url_infos['query'])) {
parse_str($url_infos['query'], $params);
}
$params = array_merge($params, $data);
return ($relative ? '' : ('http://' . $_SERVER['HTTP_HOST'])) . $url_infos['path'] . (count($params) ? ('?' . http_build_query($params)) : '');
}
static public function getIp()
{
$ip = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : $_SERVER['REMOTE_ADDR'];
if(strpos($ip, ',')) {
$ip = substr($ip, 0, strpos($ip, ','));
}
return $ip;
}
static public function isGoogleBot()
{
$ip = ip2long(self::getIp());
return $ip >= 1123631104 && $ip <= 1123639295;
}
static public function getBrowser()
{
$user_agent = $_SERVER['HTTP_USER_AGENT'];
// Opera/9.80 (Windows NT 5.1; U; fr) Presto/2.2.15 Version/10.00
// Opera/9.80 (Windows NT 5.1; U; fr) Presto/2.2.15 Version/10.10
// Mozilla/5.0 (Windows; U; Windows NT 5.1; fr; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6 (.NET CLR 3.5.30729)
// Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; MDDS; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
// Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; MDDS; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
// Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.0 (KHTML, like Gecko) Chrome/3.0.195.38 Safari/532.0
// Mozilla/5.0 (Windows; U; Windows NT 5.1; fr-FR) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16
switch(true) {
case (strpos($user_agent, 'MSIE') !== false):
$browser = 'IE';
break;
case (strpos($user_agent, 'AppleWebKit') !== false && strpos($user_agent, 'Chrome') !== false):
$browser = 'CHROME';
break;
case (strpos($user_agent, 'AppleWebKit') !== false && strpos($user_agent, 'Chrome') === false):
$browser = 'SAFARI';
break;
case (strpos($user_agent, 'Gecko') !== false && strpos($user_agent, 'KHTML') === false):
$browser = 'FIREFOX';
break;
case (strpos($user_agent, 'Opera') !== false):
$browser = 'OPERA';
break;
default:
$browser = 'OTHER';
break;
}
return $browser;
}
public function getMethod()
{
return $_SERVER['REQUEST_METHOD'];
}
public function isGet()
{
return ('GET' == $this->getMethod());
}
public function isPost()
{
return ('POST' == $this->getMethod());
}
public function isAjax()
{
return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') ? true : false;
}
public function toArray()
{
return array(
'module' => $this->_module,
'controller' => $this->_controller,
'action' => $this->_action,
'format' => $this->_format
);
}
}
<?php
/** @see Gen_Http_Response */
require_once('Gen/Http/Response.php');
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Response extends Gen_Http_Response
{
}
<?php
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Router
{
const CONSTANT = 'Gen_Controller_Router_Route_Constant';
const SEPARATOR = '/';
const MARKER = ':';
const DEFAULT_REGEXP = '([a-zA-Z_.-]+)';
/**
* Application Base Url
* @var string
*/
protected static $_baseUrl = '/';
/**
* Application Server Name
* @var string
*/
protected static $_serverName = '';
/**
* Hash of name Routes
* @var Gen_Hash
*/
protected $_routes = array();
/**
* Global params available for all routes
* ex: can be used to manage lang easily
* @var array
*/
protected $_params = array();
/**
* Sets the base url
*
* @param string $baseUrl
* @return void
*/
public static function setBaseUrl($baseUrl)
{
self::$_baseUrl = $baseUrl;
}
/**
* Gets the base url
*
* @return string
*/
public static function getBaseUrl()
{
return self::$_baseUrl;
}
/**
* Sets the server name
*
* @param string $serverName
* @return void
*/
public static function setServerName($serverName)
{
self::$_serverName = $serverName;
}
/**
* Gets the server name
*
* @return string
*/
public static function getServerName()
{
return self::$_serverName;
}
/** Cleans a given url
*
* removes the GET parameters
* removes the base url
*
* @example www.mysite.com/base/url/thing/to/do?option=foo
* is turned into `thing/to/do`
*
* @param string url
* @return string $cleanUrl
*/
public static function cleanUrl($url)
{
$pattern = '#^' . self::$_baseUrl . '((.*[^/])/?)?$#';
$parts = explode('?', $url);
return preg_replace($pattern, '$1', $parts[0]);
}
public function getRoute($name)
{
return isset($this->_routes[$name]) ? $this->_routes[$name] : null;
}
public function getRoutes()
{
return $this->_routes;
}
public function setRoutes(array $routes)
{
$this->_routes = $routes;
return $this;
}
public function setParam($key, $value)
{
$this->_params[$key] = $value;
return $this;
}
public function route(Gen_Controller_Request $request)
{
$url = self::cleanUrl($request->getUrl());
$url = rtrim($url,"/");
Gen_Log::log('url to be matched : ' . $url, 'Gen_Controller_Router::route', 'info');
foreach($this->_routes as $route) {
if($params = self::match($route, $url)) {
/* set request controller, action and params */
if (!isset($params['controller']) || !isset($params['action'])) {
Gen_Log::log('No controller or action defined', 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($route, 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($params, 'Gen_Controller_Router::route', 'warning');
return false;
}
$request
->setController($params['controller'])
->setAction($params['action'])
->addParams($params)
->addParams($_GET)
->addParams($_POST);
if(isset($params['module'])) {
$request->setModule($params['module']);
}
$format = isset($params['format']) ? $params['format'] : $request->getParam('format');
$request->setFormat($format);
return $request;
}
}
Gen_Log::log('No match found :(', 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($this->_routes, 'Gen_Controller_Router::route', 'info');
return false;
}
public function url($name = 'default', array $data = array(), $relative = true)
{
if ($route = $this->getRoute($name))
{
$server = $relative ? '' : 'http://' . self::$_serverName;
$data = array_merge($this->_params, $data);
return $server . self::$_baseUrl . self::buildUrl($route, $data);
} else {
require_once('Gen/Controller/Exception.php');
throw new Gen_Controller_Exception("Undefined Route: $name in Gen_Controller_Router");
}
}
/**
*
* @param $name name of the path, for exemple event_show
* @param $pattern url with :var for each var, for example /event/:id/show
* @param $defaults default element, must have controller, action and optionally a format, a module or a variable's default value
* @param $req matches the var with a regexp
*/
public function addRoute($name, $pattern, $defaults = array(), $req = array())
{
$route['name'] = $name;
$route['pattern'] = preg_replace('#\(|\)|\?#', '', $pattern);
$route['defaults'] = $defaults;
preg_match_all('#:([a-z0-9_]+)#', $pattern, $matches);
$vars = isset($matches[1]) ? $matches[1] : null;
$regexp = $pattern;
foreach ($vars as $var) {
$replace = isset($req[$var]) ? $req[$var] : self::DEFAULT_REGEXP;
$replace = '(?<'.$var.'>'.$replace.')';
$regexp = str_replace(':' . $var, $replace,$regexp);
}
$route['vars'] = $vars;
$route['regexp'] = '#^'.$regexp.'$#';
$this->_routes[$name] = $route;
return $this;
}
public static function match(array $route, $url)
{
$result = $route['defaults'];
if (preg_match_all($route['regexp'], $url, $matches)) {
foreach($route['vars'] as $var) {
if (isset($matches[$var])) {
$result[$var] = $matches[$var][0];
}
}
return $result;
}
return false;
}
/**
* create a url with a root and data
* @param array $route
* @param array $data
*/
public static function buildUrl(array $route, array $data)
{
$result = array();
$url = $route['pattern'];
foreach($route['vars'] as $var) {
$replace = null;
if(isset($data[$var])) {
$replace = $data[$var];
unset($data[$var]);
}
$url = str_replace(':'.$var, $replace, $url);
}
$url = rtrim($url, '/');
$anchor = null;
if (isset($data['#'])) {
$anchor = '#' . $data['#'];
unset($data['#']);
}
foreach ($data as $key => $row) {
if($row !== null && $row !== '') {
$getMethod = 1;
}
else{
unset($data[$key]);
}
}
$query = isset($getMethod) ? '?' . http_build_query($data) : '';
return $url . $query . $anchor;
}
}
<?php
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Router
{
const CONSTANT = 'Gen_Controller_Router_Route_Constant';
const SEPARATOR = '/';
const MARKER = ':';
const DEFAULT_REGEXP = '([a-zA-Z_.-]+)';
/**
* Application Base Url
* @var string
*/
protected static $_baseUrl = '/';
/**
* Application Server Name
* @var string
*/
protected static $_serverName = '';
/**
* Hash of name Routes
* @var Gen_Hash
*/
protected $_routes = array();
/**
* Global params available for all routes
* ex: can be used to manage lang easily
* @var array
*/
protected $_params = array();
/**
* Sets the base url
*
* @param string $baseUrl
* @return void
*/
public static function setBaseUrl($baseUrl)
{
self::$_baseUrl = $baseUrl;
}
/**
* Gets the base url
*
* @return string
*/
public static function getBaseUrl()
{
return self::$_baseUrl;
}
/**
* Sets the server name
*
* @param string $serverName
* @return void
*/
public static function setServerName($serverName)
{
self::$_serverName = $serverName;
}
/**
* Gets the server name
*
* @return string
*/
public static function getServerName()
{
return self::$_serverName;
}
/** Cleans a given url
*
* removes the GET parameters
* removes the base url
*
* @example www.mysite.com/base/url/thing/to/do?option=foo
* is turned into `thing/to/do`
*
* @param string url
* @return string $cleanUrl
*/
public static function cleanUrl($url)
{
$pattern = '#^' . self::$_baseUrl . '((.*[^/])/?)?$#';
$parts = explode('?', $url);
return preg_replace($pattern, '$1', $parts[0]);
}
public function getRoute($name)
{
return isset($this->_routes[$name]) ? $this->_routes[$name] : null;
}
public function getRoutes()
{
return $this->_routes;
}
public function setRoutes(array $routes)
{
$this->_routes = $routes;
return $this;
}
public function setParam($key, $value)
{
$this->_params[$key] = $value;
return $this;
}
public function route(Gen_Controller_Request $request)
{
$url = self::cleanUrl($request->getUrl());
$url = rtrim($url,"/");
Gen_Log::log('url to be matched : ' . $url, 'Gen_Controller_Router::route', 'info');
foreach($this->_routes as $route) {
if($params = self::match($route, $url)) {
/* set request controller, action and params */
if (!isset($params['controller']) || !isset($params['action'])) {
Gen_Log::log('No controller or action defined', 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($route, 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($params, 'Gen_Controller_Router::route', 'warning');
return false;
}
$request
->setController($params['controller'])
->setAction($params['action'])
->addParams($params)
->addParams($_GET)
->addParams($_POST);
if(isset($params['module'])) {
$request->setModule($params['module']);
}
$format = isset($params['format']) ? $params['format'] : $request->getParam('format');
$request->setFormat($format);
return $request;
}
}
Gen_Log::log('No match found :(', 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($this->_routes, 'Gen_Controller_Router::route', 'info');
return false;
}
public function url($name = 'default', array $data = array(), $relative = true)
{
if ($route = $this->getRoute($name))
{
$server = $relative ? '' : 'http://' . self::$_serverName;
$data = array_merge($this->_params, $data);
return $server . self::$_baseUrl . self::buildUrl($route, $data);
} else {
require_once('Gen/Controller/Exception.php');
throw new Gen_Controller_Exception("Undefined Route: $name in Gen_Controller_Router");
}
}
/**
*
* @param $name name of the path, for exemple event_show
* @param $pattern url with :var for each var, for example /event/:id/show
* @param $defaults default element, must have controller, action and optionally a format, a module or a variable's default value
* @param $req matches the var with a regexp
*/
public function addRoute($name, $pattern, $defaults = array(), $req = array())
{
$route['name'] = $name;
$route['pattern'] = preg_replace('#\(|\)|\?#', '', $pattern);
$route['defaults'] = $defaults;
preg_match_all('#:([a-z0-9_]+)#', $pattern, $matches);
$vars = isset($matches[1]) ? $matches[1] : null;
$regexp = $pattern;
foreach ($vars as $var) {
$replace = isset($req[$var]) ? $req[$var] : self::DEFAULT_REGEXP;
$replace = '(?<'.$var.'>'.$replace.')';
$regexp = str_replace(':' . $var, $replace,$regexp);
}
$route['vars'] = $vars;
$route['regexp'] = '#^'.$regexp.'$#i';
$this->_routes[$name] = $route;
return $this;
}
public static function match(array $route, $url)
{
$result = $route['defaults'];
if (preg_match_all($route['regexp'], $url, $matches)) {
foreach($route['vars'] as $var) {
if (isset($matches[$var])) {
$result[$var] = $matches[$var][0];
}
}
return $result;
}
return false;
}
/**
* create a url with a root and data
* @param array $route
* @param array $data
*/
public static function buildUrl(array $route, array $data)
{
$result = array();
$url = $route['pattern'];
foreach($route['vars'] as $var) {
$replace = null;
if(isset($data[$var])) {
$replace = $data[$var];
unset($data[$var]);
}
$url = str_replace(':'.$var, $replace, $url);
}
/** @hack to avoid empty parameters when they are not mandatory **/
$url = str_replace('//', '/', $url);
$url = trim($url, '/');
$anchor = null;
if (isset($data['#'])) {
$anchor = '#' . $data['#'];
unset($data['#']);
}
foreach ($data as $key => $row) {
if($row !== null && $row !== '') {
$getMethod = 1;
}
else{
unset($data[$key]);
}
}
$query = isset($getMethod) ? '?' . http_build_query($data) : '';
return $url . $query . $anchor;
}
}
<?php
/**
* @category Gen
* @package Gen_Controller
*/
class Gen_Controller_Router
{
const CONSTANT = 'Gen_Controller_Router_Route_Constant';
const SEPARATOR = '/';
const MARKER = ':';
const DEFAULT_REGEXP = '([a-zA-Z_.-]+)';
/**
* Application Base Url
* @var string
*/
protected static $_baseUrl = '/';
/**
* Application Server Name
* @var string
*/
protected static $_serverName = '';
/**
* Hash of name Routes
* @var Gen_Hash
*/
protected $_routes = array();
/**
* Sets the base url
*
* @param string $baseUrl
* @return void
*/
public static function setBaseUrl($baseUrl)
{
self::$_baseUrl = $baseUrl;
}
/**
* Gets the base url
*
* @return string
*/
public static function getBaseUrl()
{
return self::$_baseUrl;
}
/**
* Sets the server name
*
* @param string $serverName
* @return void
*/
public static function setServerName($serverName)
{
self::$_serverName = $serverName;
}
/**
* Gets the server name
*
* @return string
*/
public static function getServerName()
{
return self::$_serverName;
}
/** Cleans a given url
*
* removes the GET parameters
* removes the base url
*
* @example www.mysite.com/base/url/thing/to/do?option=foo
* is turned into `thing/to/do`
*
* @param string url
* @return string $cleanUrl
*/
public static function cleanUrl($url)
{
$pattern = '#^' . self::$_baseUrl . '((.*[^/])/?)?$#';
$parts = explode('?', $url);
return preg_replace($pattern, '$1', $parts[0]);
}
public function getRoute($name)
{
return isset($this->_routes[$name]) ? $this->_routes[$name] : null;
}
public function getRoutes()
{
return $this->_routes;
}
public function setRoutes(array $routes)
{
$this->_routes = $routes;
return $this;
}
public function route(Gen_Controller_Request $request)
{
$url = self::cleanUrl($request->getUrl());
$url = rtrim($url,"/");
Gen_Log::log('url to be matched : ' . $url, 'Gen_Controller_Router::route', 'info');
foreach($this->_routes as $route) {
if($params = self::match($route, $url)) {
/* set request controller, action and params */
if (!isset($params['controller']) || !isset($params['action'])) {
Gen_Log::log('No controller or action defined', 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($route, 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($params, 'Gen_Controller_Router::route', 'warning');
return false;
}
$request
->setController($params['controller'])
->setAction($params['action'])
->addParams($params)
->addParams($_GET)
->addParams($_POST);
if(isset($params['module'])) {
$request->setModule($params['module']);
}
$format = isset($params['format']) ? $params['format'] : $request->getParam('format');
$request->setFormat($format);
return $request;
}
}
Gen_Log::log('No match found :(', 'Gen_Controller_Router::route', 'warning');
Gen_Log::log($this->_routes, 'Gen_Controller_Router::route', 'info');
return false;
}
public function url($name = 'default', array $data = array(), $relative = true)
{
if ($route = $this->getRoute($name))
{
$server = $relative ? '' : 'http://' . self::$_serverName;
return $server . self::$_baseUrl . self::buildUrl($route, $data);
} else {
require_once('Gen/Controller/Exception.php');
throw new Gen_Controller_Exception("Undefined Route: $name in Gen_Controller_Router");
}
}
/**
*
* @param $name name of the path, for exemple event_show
* @param $pattern url with :var for each var, for example /event/:id/show
* @param $defaults default element, must have controller, action and optionally a format, a module or a variable's default value
* @param $req matches the var with a regexp
*/
public function addRoute($name, $pattern, $defaults = array(), $req = array())
{
$route['name'] = $name;
$route['pattern'] = preg_replace('#\(|\)|\?#', '', $pattern);
$route['defaults'] = $defaults;
preg_match_all('#:([a-z0-9_]+)#', $pattern, $matches);
$vars = isset($matches[1]) ? $matches[1] : null;
$regexp = $pattern;
foreach ($vars as $var) {
$replace = isset($req[$var]) ? $req[$var] : self::DEFAULT_REGEXP;
$replace = '(?<'.$var.'>'.$replace.')';
$regexp = str_replace(':' . $var, $replace,$regexp);
}
$route['vars'] = $vars;
$route['regexp'] = '#^'.$regexp.'$#';
$this->_routes[$name] = $route;
return $this;
}
public static function match(array $route, $url)
{
$result = $route['defaults'];
if (preg_match_all($route['regexp'], $url, $matches)) {
foreach($route['vars'] as $var) {
if (isset($matches[$var])) {
$result[$var] = $matches[$var][0];
}
}
return $result;
}
return false;
}
/**
* create a url with a root and data
* @param array $route
* @param array $data
*/
public static function buildUrl(array $route, array $data)
{
$result = array();
$url = $route['pattern'];
foreach($route['vars'] as $var) {
$replace = null;
if(isset($data[$var])) {
$replace = $data[$var];
unset($data[$var]);
}
$url = str_replace(':'.$var, $replace, $url);
}
$url = rtrim($url, '/');
$anchor = null;
if (isset($data['#'])) {
$anchor = '#' . $data['#'];
unset($data['#']);
}
foreach ($data as $key => $row) {
if($row !== null && $row !== '') {
$getMethod = 1;
}
else{
unset($data[$key]);
}
}
$query = isset($getMethod) ? '?' . http_build_query($data) : '';
return $url . $query . $anchor;
}
}
<?php
require_once('Gen/Controller/Event.php');
require_once('Gen/ClassLoader.php');
class Gen_Controller_Event_Dispatcher
{
public static $observerDir = './app/Controller/';
protected $_listeners = array();
/**
* Returns all listeners from the Dispatcher. It is used for caching mainly
*
* @return array An array of listeners
*/
public function getListeners()
{
return $this->_listeners;
}
/**
* Sets all listeners of the Dispatcher. It is used for caching mainly
*
* @param array $listeners
*
* @return Gen_Controller_Event_Dispatcher $dipatcher
*/
public function setListeners(array $listeners)
{
$this->_listeners = $listeners;
return $this;
}
/**
* Fires an Event
*
* @param Gen_Controller_Event $event
*/
public function fire(Gen_Controller_Event $event)
{
$listeners = $this->getEventListeners($event->getName());
Gen_Log::log(sprintf('event : %s | listeners : %s', $event->getName(),json_encode($listeners)), 'Gen_Controller_Front::fireEvent', 'info');
if(empty($listeners)) {
Gen_Log::log('Event not listened: ' . $event->getName() , 'Gen_Controller_Front::fireEvent', 'warning');
} else {
foreach ($listeners as $listener) {
$this->notify($listener, $event);
}
}
return $event;
}
/**
* Notifies all Listeners of the Event
*
* @param array $listerner array(observer,[module],action)
* @param Gen_Controller_Event $event
*/
public function notify(array $listerner, Gen_Controller_Event $event)
{
$module = null;
if(array_key_exists('module',$listerner)){
$module = $listerner['module'];
}
$className = Gen_ClassLoader::loadClass($listerner['observer'], $module, 'Controller', self::$observerDir);
if($className == false) {
Gen_Log::log('Listener `'.$className.'` does not exist', 'Gen_Controller_Event_Dispatcher::notify','warning');
return false;
}
$observer = new $className();
Gen_Log::log('START', $className .'::' . $listerner['action'], 'info');
return $observer->processEvent($listerner['action'],$event);
}
/**
* Connects an observer to a given event name.
*
* @param string $eventName An event name
* @param mixed $observer A PHP callable
* @param array $param parameters needed by the listeners
*/
public function addEventListener($eventName, $observer, $paramNames=array())
{
if (!isset($this->_listeners[$eventName])) {
$this->_listeners[$eventName] = array();
}
if(!is_array($observer)) {
$observer = array('observer' => $observer, 'action' => $eventName);
}
$this->_listeners[$eventName][] = $observer;
}
/**
* Connects a bunch of observers to a given event name.
*
* @param string $eventName An event name
* @param array $listener A PHP callable
* @param array $param parameters needed by the listeners
*/
public function addEventListeners($eventName, $observers,$paramNames = array())
{
foreach ($observers as $observer){
$this->addListener($eventName,$observer,$paramNames);
}
}
/**
* Disconnects a listener for a given event name.
*
* @param string $eventName An event name
* @param mixed $listener A PHP callable
*
* @return mixed false if listener does not exist, null otherwise
*/
public function removeEventListener($eventName, $observer)
{
if (!isset($this->_listeners[$eventName])) {
return false;
}
foreach ($this->_listeners[$eventName] as $i => $callable) {
if ($observer === $callable) {
unset($this->_listeners[$eventName][$i]);
}
}
}
/**
* Returns true if the given event name has some listeners.
*
* @param string $eventName The event name
*
* @return Boolean true if some listeners are connected, false otherwise
*/
public function hasEventListeners($eventName)
{
if (!isset($this->_listeners[$eventName])) {
$this->_listeners[$eventName] = array();
}
return (boolean) count($this->_listeners[$eventName]);
}
/**
* Returns all listeners associated with a given event name.
*
* @param string $eventName The event name
*
* @return array An array of array listeners
*/
public function getEventListeners($eventName)
{
if (!isset($this->_listeners[$eventName])) {
return array();
}
return $this->_listeners[$eventName];
}
}
<?php
/** @see Gen_Http_Response */
require_once('Gen/Controller/Response.php');
/**
* @category Gen
* @package Gen_Controller_Response
*/
class Gen_Controller_Response_Json extends Gen_Controller_Response
{
protected $_properties = array();
public function __construct()
{
$this->setContentType('application/json; charset=utf-8');
return $this;
}
public function setProperty($key, $value)
{
$this->_properties[(string) $key] = $value;
return $this;
}
public function getProperty($key, $default = null)
{
return isset($this->_properties[$key]) ? $this->_properties[$key] : $default;
}
public function setProperties(array $properties)
{
$this->_properties = $properties;
return $this;
}
public function addProperties(array $properties)
{
$this->_properties += $properties;
return $this;
}
public function getProperties()
{
return $this->_properties;
}
public function outputBody()
{
echo self::toJson($this->_properties);
}
public static function toJson($mixed)
{
$str = '';
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$str .= ($str ? ', ' : '') . '"' . $key .'" : ' . self::toJson($value);
}
$str = '{' . $str . '}';
} else {
$str = '"' . self::sanitize($mixed) . '"';
}
return $str;
}
public function sanitize($text)
{
$text = utf8_decode((string) $text);
$text = str_replace('"', '\"', $text);
return utf8_encode(preg_replace("#\s#", ' ', $text));
}
}
<?php
abstract class Gen_Dao_Abstract
{
protected static $_logger;
private static $_adapter;
private static $_config;
protected static $_prefix;
protected static $_encryptionKey = 'FR6928KOWABUNGA57XV12222EOF4758RJGK595UTI39JGJ38RIANBDNWWLLLL03JO1N238RHJELMAPZ098F7R6HN4';
protected $_name;
public static function config($driver, $host, $dbname, $user, $password, $prefix = null)
{
self::$_config = array(
'DRIVER' => $driver,
'HOST' => $host,
'DBNAME' => $dbname,
'USER' => $user,
'PASSWORD' => $password
);
self::$_prefix = $prefix;
return true;
}
public static function getAdapter()
{
if (!isset(self::$_adapter)) {
$dns = self::$_config['DRIVER']
. ":host=" . self::$_config['HOST']
. ";dbname=" . self::$_config['DBNAME'];
self::$_adapter = new PDO($dns, self::$_config['USER'], self::$_config['PASSWORD'], array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4"));
}
return self::$_adapter;
}
public function getName()
{
return $this->_name;
}
public function getTableName()
{
return (self::$_prefix ? self::$_prefix . '_' : '') . $this->_name;
}
public function escapeTableName()
{
return '`'.$this->getTableName().'`';
}
public function findByFilters(array $filters = array())
{
$options = $this->buildOptions($filters);
$bind = $options['bind'];
unset($options['bind']);
return $this->findAll($options, $bind);
}
public function findById($id, array $options = array(), array $bind = array())
{
if (isset($options['lang'])) {
$options['where'][] = $this->getTableName().'_lang.parent_id = :id';
} else {
$options['where'][] = $this->getTableName().'.id = :id';
}
$bind['id'] = $id;
$result = $this->findAll($options, $bind);
return array_pop($result);
}
public function findByIds(array $ids = array(), array $filters = array())
{
return $this->findByProperty('id', $ids, $filters);
}
public function findByProperty($property, array $ids = array(), array $filters = array())
{
$options = $this->buildOptions($filters);
$bind = $options['bind'];
$sql = null;
$i=0;
$ids = array_unique($ids);
foreach ($ids as $id)
{
if($id)
{
$i++;
$key = 'key_'.$i;
if (isset($options['lang'])) {
$options['cols'] = $this->getTableName() .'.*, '. $this->getTableName() . '_lang' .'.*';
$options['join'] = 'INNER JOIN '. $this->getTableName() . '_lang'
. ' ON '. $this->getTableName() . '_lang' .'.parent_id = '. $this->getTableName() .'.id'
. ' AND ' . $this->getTableName() . '_lang.lang = :lang' ;
$bind['lang'] = $options['lang'];
}
$opt = $options;
$opt['where'][] = '`'.$this->getTableName().'`.`'.$property.'` = :' . $key;
unset($opt['order']);
$sql .= ($sql ? "\n UNION \n" : '') . self::buildFinder($this->getTableName(), $opt);
$bind[$key] = $id;
}
}
if(null !== $sql) {
$sql .= "\n".self::buildOrder($options);
return $this->findBySql($sql, $bind);
}
return false;
}
public function findOne($options = array(), $bind = array())
{
$options['limit'] = 1;
$result = $this->findAll($options, $bind);
return array_pop($result);
}
public function findAll(array $options = array(), array $bind = array())
{
if (isset($options['lang'])) {
$options['cols'][] = $this->getTableName() .'.*, '. $this->getTableName() . '_lang' .'.*';
$options['join'][] = 'INNER JOIN '. $this->getTableName() . '_lang'
. ' ON '. $this->getTableName() . '_lang' .'.parent_id = '. $this->getTableName() .'.id'
. ' AND ' . $this->getTableName() . '_lang.lang = :lang' ;
$bind['lang'] = $options['lang'];
}
$query = self::buildFinder($this->getTableName(), $options);
return $this->findBySql($query, $bind);
}
public function findBySql($sql, array $bind = array())
{
$stmt = $this->query($sql, $bind);
$result = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result[$row['id']] = $row;
}
return $result;
}
public function count(array $filters = array())
{
$options = $this->buildOptions($filters);
$options['cols'] = 'count(distinct('. $this->getTableName() .'.id)) as count';
if (isset($options['lang'])) {
$options['join'][] = 'INNER JOIN '. $this->getTableName() . '_lang'
. ' ON '. $this->getTableName() . '_lang' .'.parent_id = '. $this->getTableName() .'.id'
. ' AND ' . $this->getTableName() . '_lang.lang = :lang' ;
$options['bind']['lang'] = $options['lang'];
}
$sql = $this->buildFinder($this->getTableName(), $options);
$stmt = $this->query($sql, $options['bind']);
$rows = $stmt->fetchAll();
return $rows[0]['count'];
}
public function findIds(array $options = array(), array $bind = array())
{
$options['cols'] = '`'. $this->getTableName() . '`.id';
$sql = self::buildFinder($this->getTableName(), $options);
$stmt = $this->query($sql, $bind);
return $stmt->fetchAll(PDO::FETCH_COLUMN);
}
public function insert(array $data, array $options = array())
{
$table = $this->getTableName() . (isset($options['lang']) ? '_lang' : '');
$sql = self::buildInsert($table, $data);
$this->query($sql, $data);
return self::getAdapter()->lastInsertId();
}
public function updateById($id, array $data, array $options = array(), array $bind = array())
{
$options['where'][] = (isset($options['lang']) ? '`parent_id`' : '`id`') . ' = :id';
$bind['id'] = $id;
return $this->update($data, $options, $bind);
}
public function update(array $data, array $options = array(), array $bind = array())
{
$table = $this->getTableName();
if(isset($options['lang'])) {
$options['where'][] = '`lang` = :lang';
$bind['lang'] = $options['lang'];
$table .= '_lang';
}
$sql = self::buildUpdate($table, $data, $options);
$bind = array_merge($data, $bind);
$stmt = $this->query($sql, $bind);
return true;
}
public function deleteById($id, array $options = array(), array $bind = array())
{
$options['where'][] = '`' . $this->getTableName() . '`.`id` = :id';
$bind['id'] = (int) $id;
$options['limit'] = 1;
return $this->delete($options, $bind);
}
public function delete(array $options, array $bind = array())
{
$table = $this->getTableName();
if(isset($options['lang'])) {
$options['where'][] = '`lang` = :lang';
$bind['lang'] = $options['lang'];
$table .= '_lang';
}
$sql = self::buildDelete($table, $options);
$stmt = $this->query($sql, $bind);
return true;
}
public function query($sql, array $bind = array())
{
$stmt = $this->getAdapter()->prepare($sql);
if (false === $stmt->execute($bind)) {
require_once('Gen/Dao/Exception.php');
throw new Exception(
"SQL error in Gen_Dao_Abstract::query()\n"
. "SQL: '$sql'\n"
. "Bindings: " . print_r($bind, true) . "\n"
. "Error: " . print_r($stmt->errorinfo(), true));
}
Gen_Log::log("<p>$sql</p><pre>" . print_r($bind, true) . '</pre>', get_class($this).'::query');
return $stmt;
}
public function buildOptions(array $filters = array())
{
$options = $bind = array();
if(isset($filters['is_null'])) {
$fields = (array) $filters['is_null'];
foreach($fields as $field) {
$options['where'][] = $this->escapeTableName().'.`'.$field.'` IS NULL';
}
}
if(isset($filters['deleted'])) {
$options['where'][] = $this->escapeTableName() . '.`deleted` = :deleted';
$bind['deleted'] = $filters['deleted'];
}
if(isset($filters['limit'])) {
$options['limit'] = (int) $filters['limit'];
}
if(isset($filters['cols'])) {
$options['cols'] = $filters['cols'];
}
if(isset($filters['order'])) {
$options['order'] = $filters['order'];
// $options['order'] = $this->escapeTableName() . '.' . $filters['order'];
if(isset($filters['sort'])) {
$options['order'] .= ' ' . $filters['sort'];
}
}
if(isset($filters['group'])) {
$options['group'] = (int) $filters['group'];
}
if(isset($filters['rand'])) {
$options['rand'] = (int) $filters['rand'];
}
if (isset($filters['npp'])) {
$options['limit'] = (int) $filters['npp'];
if(isset($filters['page'])) {
$options['offset'] = (int) $filters['npp'] * (int) ($filters['page']-1);
}
}
$options['bind'] = $bind;
return $options;
}
public static function buildFinder($table, array $options = array())
{
$query = '';
$options['table'] = isset($options['table']) ? $options['table'] : $table;
if (isset($options['rand']) && is_int($options['rand'])) {
$limit = isset($options['limit']) ? $options['limit'] : null;
$options['limit'] = $options['rand'];
if ($limit) $options['limit'] = max($limit, $options['rand']);
$query .= 'SELECT * FROM (';
}
$query .= 'SELECT '
. (isset($options['cols']) ? implode(',', (array) $options['cols']) : '`' . $table . '`.*')
. ' from `' . $options['table'] . '`'
. self::buildJoin($options)
. self::buildWhere($options)
. self::buildGroup($options)
. self::buildOrder($options)
. self::buildLimit($options)
. self::buildOffset($options);
if (isset($options['rand'])) {
$options['order'] = 'rand()';
if ($limit) {
$options['limit'] = $limit;
} else {
unset($options['limit']);
}
$query .= ') rs';
$query .= self::buildOrder($options)
. self::buildLimit($options);
}
return $query;
}
public static function buildInsert($table, array $data)
{
$cols = array();
$markers = array();
foreach ($data as $key => $value) {
$cols[] = '`'. $key .'`';
$markers[] = ':' . $key;
}
return 'INSERT `'. $table .'` ('. implode(',', $cols) . ') VALUES(' . implode(',', $markers) .')';
}
public static function buildUpdate($table, array $data, array $options = array())
{
foreach ($data as $key => $value) {
$fields[] = '`'. $key .'` = :'. $key;
}
if(!isset($fields)) {
return false;
}
$query = 'UPDATE `'. $table .'`'
. self::buildJoin($options)
. ' SET ' . implode(',', $fields)
. self::buildWhere($options);
return $query;
}
public static function buildDelete($table, array $options = array())
{
$query = 'delete from `' . $table . '`'
. self::buildJoin($options)
. self::buildWhere($options)
. self::buildLimit($options);
return $query;
}
public static function buildWhere(array $options)
{
return (isset($options['where']) ? ' WHERE ' . implode(' AND ', (array) $options['where']) : null);
}
public static function buildJoin(array $options)
{
return (isset($options['join']) ? ' ' . implode(' ', (array) $options['join']) : null);
}
public static function buildGroup(array $options)
{
return (isset($options['group']) ? ' GROUP BY ' . implode(',', (array) $options['group']) : null);
}
public static function buildOrder(array $options)
{
return (isset($options['order']) ? ' ORDER BY ' . implode(',', (array) $options['order']) : null);
}
public static function buildLimit(array $options)
{
return (isset($options['limit']) ? ' LIMIT ' . (int) $options['limit'] : null);
}
public static function buildOffset(array $options)
{
return ((isset($options['offset']) && $options['offset'] >= 0) ? ' OFFSET ' . (int) $options['offset'] : null);
}
}
<?php
/** @see Gen_Exception */
require_once ('Gen/Exception.php');
/**
* @category Gen
* @package Gen_Dao
*/
class Gen_Dao_Exception extends Gen_Exception
{
}
<?php
/**
* @category Gen
* @package Gen_Dom
*/
class Gen_Dom_Element
{
const INDENT = "\t";
protected $_tag;
protected $_attributes;
protected $_content;
protected $_childrens;
public function __construct($tag, array $attributes = array(), $content = null)
{
$this->_tag = (string) $tag;
$this->setContent($content);
$this->_attributes = $attributes;
$this->init();
}
public function init()
{
/**
* for User implementation only
* please use inheritance and parent::__construct()
* if you need to add specific features
*/
}
/********************************************
* Attributes *
********************************************/
public function setAttributes(array $attributes = array())
{
$this->_attributes = $attributes;
return $this;
}
public function addAttributes(array $attributes = array())
{
$this->_attributes += $attributes;
return $this;
}
public function getAttributes()
{
return $this->_attributes;
}
public function setAttribute($key, $value)
{
$this->_attributes[(string)$key] = (string) $value;
return $this;
}
public function getAttribute($key, $default = null)
{
return (isset($this->_attributes[$key]) && ('' !== $this->_attributes[$key]))
? $this->_attributes[$key]
: $default;
}
public function resetAttribute($key)
{
$attr = $this->getAttribute($key);
unset($this->_attributes[$key]);
return $attr;
}
public function setId($id)
{
return $this->setAttribute('id', $id);
}
public function getId()
{
return $this->getAttribute('id');
}
/********************************************
* Content *
********************************************/
public function getContent()
{
return $this->_content;
}
public function setContent($content)
{
$this->_content = (null !== $content) ? (array) $content : array();
return $this;
}
public function append($node)
{
$this->_content[] = $node;
return $this;
}
public function prepend($node)
{
array_unshift($this->_content, $node);
return $this;
}
public function wrap($tag, array $attributes = array())
{
$element = new self($tag, $attributes);
return $element->append($this);
}
public function addChild($tag, array $attributes = array(), $content = null)
{
$element = new self($tag, $attributes, $content);
$this->append($element);
return $element;
}
/********************************************
* Item Renderers *
********************************************/
/**
* Renders the attributes
* @use htmlspecialchars to sanitize the values
* @return string
*/
public function renderAttributes()
{
$str = '';
foreach($this->_attributes as $name => $value) {
$str .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"';
}
return $str;
}
/**
* Renders the content
* @return string
*/
public function renderContent()
{
$str = implode("\n", $this->_content);
return ($str !== null ? $str : '');
}
/**
* Renders the Dom Element
* @return string
*/
public function render()
{
$str = $this->renderStart()
. $this->renderContent()
. $this->renderEnd();
return $str;
}
public function renderStart()
{
return '<' . $this->_tag . $this->renderAttributes() . '>';
}
public function renderEnd()
{
return '</' . $this->_tag . '>';
}
public function __toString()
{
try {
$str = (string) $this->render();
return $str;
} catch (Exception $e) {
return $e->getMessage();
}
}
}
<?php
require_once('Gen/Entity/Date.php');
abstract class Gen_Entity_Abstract
{
protected $_id = null;
protected static function _int($value)
{
return (null === $value) ? null : (int) $value;
}
protected static function _string($value)
{
return (null === $value) ? null : (string) $value;
}
protected static function _bool($value)
{
return (null === $value) ? null : ($value ? 1 : 0);
}
protected static function _float($value)
{
if(is_string($value)) { $value = str_replace(' ', '', $value); }
return (null === $value) ? null : (float) $value;
}
protected static function _date($value)
{
return new Gen_Entity_Date($value);
}
protected static function _array($value)
{
return (array) $value;
}
public function setId($id)
{
$this->_id = empty($id) ? null : (int) $id;
return $this;
}
public function getId()
{
return $this->_id;
}
public function exists()
{
return (null !== $this->_id);
}
public function is(Gen_Entity_Abstract $entity)
{
return (($this->_id !== null) && ($this->_id === $entity->getId()));
}
public function __construct($data = array())
{
$this->update($data);
}
public function writeProperty($key, $value)
{
$method = $this->formatWriter($key);
if(method_exists($this, $method))
{
$this->$method($value);
return $this;
}
return false;
}
public function readProperty($key, $default = null)
{
if(preg_match('#::#', $key)) {
$parts = preg_split('#::#', $key);
$first = array_shift($parts);
$entity = $this->readProperty($first);
if($entity instanceof Gen_Entity_Abstract)
{
return $entity->readProperty(implode('::', $parts));
}
return $default;
}
$method = $this->formatReader($key);
if(method_exists($this, $method))
{
return $this->$method();
}
return $default;
}
public function writerExists($key)
{
$method = $this->formatWriter($key);
return method_exists($this, $method);
}
public function readerExists($key)
{
$method = $this->formatReader($key);
return method_exists($this, $method);
}
public function propertyExists($key)
{
return $this->readerExists($key) && $this->writerExists($key);
}
public function update(array $data)
{
foreach ($data as $key => $value) {
if (false === $this->writeProperty($key, $value)) {
if (('_id' == substr($key, -3))
&& (null !== $entity = $this->readProperty(substr($key, 0, -3)))
&& ($entity instanceof Gen_Entity_Abstract))
{
$entity->setId($value);
}
}
}
return $this;
}
public function increment($property, $increment = 1)
{
$value = $this->readProperty($property) + (int) $increment;
$this->writeProperty($property, $value);
return $this;
}
public function toArray()
{
require_once('Gen/Str.php');
$result = array();
foreach (get_class_methods($this) as $method) {
if('get' == substr($method,0,3)) {
$key = Gen_Str::underscore(substr($method,3));
$value = $this->$method();
if ($value instanceof Gen_Entity_Abstract) {
$value = $value->getId();
$key .= '_id';
} elseif (($value instanceof Gen_Entity_Date) || ($value instanceof DateTime)) {
$value = $value->format('Y-m-d H:i:s');
} elseif ($value instanceof Gen_Entity_Dictionary) {
$value = $value->keys();
$key .= '_ids';
}
$result[$key] = $value;
}
}
return $result;
}
public function __toString()
{
return get_class($this) . ' Entity';
}
public function map($pattern)
{
require_once('Gen/Str.php');
return Gen_Str::map($this, $pattern);
}
public function formatMethod($method)
{
require_once('Gen/Str.php');
return Gen_Str::camelize($method, false);
}
public function formatReader($method)
{
return 'get' . $this->formatMethod($method);
}
public function formatWriter($method)
{
return 'set' . $this->formatMethod($method);
}
}
<?php
/** @see Gen_Dao_Abstract */
require_once ('Gen/Dao/Abstract.php');
require_once ('Gen/Repository.php');
abstract class Gen_Entity_Dao extends Gen_Dao_Abstract
{
protected $_className;
private function _checkType(Gen_Entity_Abstract $entity)
{
if ($entity instanceof $this->_className) {
return true;
}
throw new Exception('Gen_Entity_Dao expects '. $this->_className .'. '. get_class($entity) . ' given.');
}
private function _getEntity()
{
if (isset($this->_className)) {
return new $this->_className();
}
throw new Exception('Gen_Entity_Dao class name is not defined');
}
/**
* Inserts a given Entity
*
* makes use of abstract function {@link _prepare()}
*
* @param Gen_Entity_Abstract
* @return bool
*/
public function create(Gen_Entity_Abstract $entity, array $options = array())
{
$this->_checkType($entity);
$lang = isset($options['lang']) ? $options['lang'] : null;
unset($options['lang']);
$data = $this->_prepare($entity);
$this->insert($data);
$entity->setId(self::getAdapter()->lastInsertId());
if (null !== $lang) {
$data = $this->_prepareML($entity);
$data['parent_id'] = $entity->getId();
$data['lang'] = $lang;
$options['lang'] = $lang;
$this->insert($data, $options);
}
return true;
}
/**
* Updates a given Entity
*
* makes use of abstract function {@link _prepare()}
*
* @param Gen_Entity_Abstract $entity
* @return bool
*/
public function modify(Gen_Entity_Abstract $entity, array $options = array(), array $bind = array())
{
$this->_checkType($entity);
$id = $entity->getId();
if (isset($options['lang'])) {
$data = $this->_prepareML($entity);
if ($this->findById($entity->getId(), $options)) {
$this->updateById($id, $data, $options, $bind);
} else {
$data['parent_id'] = $entity->getId();
$data['lang'] = $options['lang'];
$this->insert($data, $options);
}
}
unset($options['lang']);
$data = $this->_prepare($entity);
$this->updateById($id, $data, $options, $bind);
return true;
}
/**
* Returns a dictionary of entities from a SQL query
*
* @param string $sql the query
* @param array $bind list of values to bind to the sql query
* @return Gen_Entity_Dictionary
*/
public function findBySql($sql, array $bind = array())
{
$stmt = $this->query($sql, $bind);
require_once('Gen/Entity/Dictionary.php');
$result = new Gen_Entity_Dictionary($this->_className);
$rows = array();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$result->add($this->_cache($row));
$rows[] = $row;
}
Gen_Log::log('<pre>'.print_r($rows, true).'</pre>', get_class($this).'::finBySql');
return $result;
}
protected function _cache(array $row) {
$namespace = 'Gen_Dao_Cache_' . $this->_className;
if (!$entity = Gen_Repository::getInstance($namespace)->get($row['id'])) {
$entity = $this->_getEntity();
$this->_build($row, $entity);
Gen_Repository::getInstance($namespace)->set($row['id'], $entity);
}
return $entity;
}
/**
* Map an Entity to SQL Data
*
* @param Gen_Entity_Abstract
* @return array
*/
//protected function _prepare(Gen_Entity_Abstract $entity) { }
/**
* Creates an Entity from SQL Data
*
* @param array $data
* @param Gen_Entity_Abstract $entity
*/
//protected function _build(array $row, Gen_Entity_Abstract $entity) { }
/**
* Retrieve an Entity by Id
*
* @param int $id
* @param array $options
* @return Gen_Entity_Abstract
*/
public function findById($id, array $options = array(), array $bind = array())
{
$options['where'][] = $this->getTableName() . '.id = :id';
$bind['id'] = $id;
$options['limit'] = 1;
return $this->findAll($options, $bind)->first();
}
public function findByProperty($property, array $ids = array(), array $filters = array())
{
$result = parent::findByProperty($property, $ids, $filters);
if(false === $result) {
require_once('Gen/Entity/Dictionary.php');
$result = new Gen_Entity_Dictionary($this->_className);
}
return $result;
}
public function getLastInsertId()
{
return $this->getAdapter()->lastInsertId();
}
}
<?php
require_once('Gen/Date.php');
class Gen_Entity_Date
{
protected $_date;
protected $_timezone = false;
protected $_lang = null;
public function __construct($date = null)
{
if(null !== $date) {
$this->_date = Gen_Date::create($date);
}
}
public function toDatetime()
{
return $this->_date;
}
public function update($date)
{
if(null == $date) {
$this->_date = null;
} else {
$this->_date = Gen_Date::create($date);
}
return $this;
}
public function toTimestamp()
{
return strtotime($this->_date->format('Y-m-d H:i:s'));
}
public function format($format = 'Y-m-d H:i:s')
{
if(null === $this->_date) {
return null;
}
if($format == 'smart_date') {
return Gen_Date::smartDate($this->_date);
}
return Gen_Date::format($this->_date, $format, $this->_timezone, $this->_lang);
}
public function greaterThan($datetime2)
{
if($datetime2 instanceof Gen_Entity_Date) {
$datetime2 = $datetime2->toDatetime();
}
return ($this->_date >= $datetime2);
}
public function diff($datetime2, $absolute = false)
{
if($datetime2 instanceof Gen_Entity_Date) {
$datetime2 = $datetime2->toDatetime();
}
return $this->_date->diff($datetime2, $absolute);
}
public function __toString()
{
return (string) $this->format();
}
}
<?php
/**
* @category Gen
* @package Gen_Entity
*/
class Gen_Entity_Dictionary implements Iterator
{
protected $_data;
protected $_className;
public function getClassName()
{
return $this->_className;
}
public function __toString()
{
return 'Gen_Entity_Dictionary '.$this->_className;
}
public function __construct($mixed)
{
$this->_data = array();
if ($mixed instanceof Gen_Entity_Abstract) {
$this->_className = get_class($mixed);
$this->add($mixed);
return $this;
}
if ($mixed instanceof Gen_Entity_Dictionary) {
$this->_className = $mixed->getClassName();
$this->update($mixed);
return $this;
}
$this->_className = (string) $mixed;
}
/**
* Helpers
*/
private function _checkType($mixed)
{
if(($mixed instanceof Gen_Entity_Dictionary) && $mixed->typeOf($this->_className)) return true;
if ($this->typeOf($mixed)) return true;
throw new Exception ('Gen_Entity_Dictionary expects ' . $this->_className . '. ' . $mixed . ' given.');
}
public function typeOf ($mixed)
{
return is_object ($mixed) ?
$mixed instanceof $this->_className
: (is_subclass_of ($this->_className, $mixed)
|| strtolower ($mixed) == strtolower ($this->_className));
}
/**
* Basic functions
*/
public function add(Gen_Entity_Abstract $entity)
{
$this->_checkType($entity);
$this->_data[$entity->getId()] = $entity;
return $this;
}
public function remove(Gen_Entity_Abstract $entity)
{
$this->_checkType($entity);
$result = isset($this->_data[$entity->getId()]) ? $this->_data[$entity->getId()] : false;
if($result) {
unset($this->_data[$entity->getId()]);
}
return $result;
}
public function get($mixed, $default = null)
{
if ($mixed instanceof Gen_Entity_Abstract) {
$mixed = $mixed->getId();
}
return isset($this->_data[$mixed]) ? $this->_data[$mixed] : $default;
}
public function update(Gen_Entity_Dictionary $data)
{
$this->_checkType($data);
$this->_data = $data->toArray();
return $this;
}
public function merge(Gen_Entity_Dictionary $data)
{
$this->_checkType($data);
$this->_data += $data->toArray();
return $this;
}
public function reset($mixed)
{
if ($mixed instanceof Gen_Entity_Dictionary || is_array($mixed)) {
if ($mixed instanceof Gen_Entity_Dictionary) {
$this->_checkType($mixed->getClassName());
}
$reseted = new self($this->_className);
foreach ($mixed as $key => $value) {
if ($entity = $this->reset($value)) {
$reseted->add($entity);
}
}
return $reseted;
}
$reseted = $this->get($mixed);
if ($reseted) {
unset($this->_data[$reseted->getId()]);
}
return $reseted;
}
public function reverse()
{
$this->_data = array_reverse($this->_data, true);
return $this;
}
public function toArray()
{
return $this->_data;
}
/**
* Tools
*/
public function keys()
{
return array_keys($this->_data);
}
public function count()
{
return count($this->_data);
}
public function first()
{
return reset($this->_data);
}
public function last()
{
return end($this->_data);
}
public function shift()
{
return array_shift($this->_data);
}
public function exists($key)
{
return isset($this->_data[$key]);
}
public function slice($offset, $length)
{
$this->_data = array_slice($this->_data, $offset, $length);
return $this;
}
public function ksort($sort_flags = SORT_REGULAR)
{
ksort($this->_data, $sort_flags);
return $this;
}
/**
* Data processing
*/
/**
* Filters the dictionary based on a property condition
* @param string $property
* @param mixed $condition
* @return Gen_Entity_Dictionary $filtered
*/
public function where($property, $conditions)
{
$conditions = (array) $conditions;
$filtered = new self($this->_className);
foreach ($this->_data as $key => $entity) {
if(('_id' == substr($property, -3)) && (null !== $ref = $entity->readProperty(substr($property, 0, -3))) && ($ref instanceof Gen_Entity_Abstract)) {
$value = $ref->getId();
} else {
$value = $entity->readProperty($property);
}
foreach($conditions as $condition) {
if ($value == $condition) {
$filtered->add($entity);
}
}
}
return $filtered;
}
public function except($property, $condition)
{
$filtered = new self($this->_className);
foreach ($this->_data as $key => $entity) {
if ($entity->readProperty($property) != $condition) {
$filtered->add($entity);
}
}
return $filtered;
}
/**
* Returns a dictionary with a unique property per entity
* @param string $property
* @return Gen_Entity_Dictionary $unique
*/
public function unique($property)
{
$unique = array();
foreach ($this->_data as $entity){
$unique[$entity->readProperty($property)] = $entity;
}
return new self($this->_className, array_intersect($this->_data, $unique));
}
/**
* Returns a dictionary with a unique property per entity
* @param string $property
* @return Gen_Entity_Dictionary $unique
*/
public function sum($property)
{
$sum = 0;
foreach ($this->_data as $entity){
$sum += $entity->readProperty($property);
}
return $sum;
}
/**
* Returns an array of all entities' $property
* @param string $property
* @return Array $reduced
*/
public function reduce($property)
{
$reduced = array();
foreach ($this->_data as $key => $entity) {
$reduced[$key] = $entity->readProperty($property);
}
return $reduced;
}
/**
* Returns an array of entity properties
*
* This function is used to load all entities of a Dictionary at the same time
*
* @param string properties to collect
* @return array reduced
*/
public function collect($mixed, $properties)
{
$collected = new Gen_Entity_Dictionary($mixed);
$properties = (array) $properties;
foreach ($this->_data as $key => $entity) {
foreach ($properties as $property) {
$item = $entity->readProperty($property);
if ($item instanceof Gen_Entity_Abstract) {
$collected->add($item);
}
}
}
return $collected;
}
public function groupBy($property)
{
$groups = array();
foreach ($this->_data as $key => $entity) {
$item = $entity->readProperty($property);
if ($item instanceof Gen_Entity_Abstract) {
$item = $item->getId();
}
if (!isset($groups[$item])) {
$groups[$item] = new self($this->_className);
}
$groups[$item]->add($entity);
}
return $groups;
}
public function pivot($rowProperty, $colProperty)
{
$groups = array();
Gen_Log::log("Row Property: $rowProperty", 'Gen/Entity/Dictonnay::pivot', 'warning');
foreach ($this->_data as $key => $entity) {
$rowItems = $entity->readProperty($rowProperty);
if ($rowItems instanceof Gen_Entity_Abstract) {
$rowItems = $rowItems->getId();
} else if($rowItems instanceof Gen_Entity_Dictionary) {
$rowItems = $rowItems->keys();
Gen_Log::log($rowItems, 'Gen/Entity/Dictonnay::pivot Gen_Entity_Dictionary', 'warning');
}
$rowItems = (array) $rowItems;
Gen_Log::log($rowItems, 'Gen/Entity/Dictonnay::pivot rowItems', 'warning');
$colItem = $entity->readProperty($colProperty);
if ($colItem instanceof Gen_Entity_Abstract) {
$colItem = $colItem->getId();
}
foreach($rowItems as $rowItem) {
if (!isset($groups[$rowItem])) {
$groups[$rowItem] = array();
$groups[$rowItem][$colItem] = new self($this->_className);
} elseif(!isset($groups[$rowItem][$colItem])) {
$groups[$rowItem][$colItem] = new self($this->_className);
}
$groups[$rowItem][$colItem]->add($entity);
}
}
return $groups;
}
public function copy()
{
$copy = new self($this->_className);
$copy->update($this);
return $copy;
}
/**
* Implements Iterator
*/
public function rewind()
{
reset($this->_data);
}
public function key()
{
return key($this->_data);
}
public function current()
{
return current($this->_data);
}
public function next()
{
return next($this->_data);
}
public function valid()
{
return ($this->current() !== false);
}
public function toJson()
{
$json = $this->toArray();
foreach ($json as $id => $jElement) {
$json[$id] = $jElement->toArray();
}
$json = json_encode($json);
return $json;
}
}
<?php
/** Gen_Exception */
require_once ('Gen/Exception.php');
class Gen_Entity_Exception extends Gen_Exception
{
}
<?php
/** Gen_Hash_Base */
require_once ('Gen/Hash.php');
/**
* @category Gen
* @package Gen_Entity
*/
class Gen_Entity_Hash extends Gen_Hash
{
public function set($key, Gen_Entity_Abstract $entity)
{
return parent::set($key, $entity);
}
public function merge($data)
{
if($data instanceof Gen_Hash_Base) {
$data = $data->toArray();
}
$this->_data += $data;
return $this;
}
public function get($mixed)
{
if ($mixed instanceof Gen_Entity_Abstract) {
$mixed = $mixed->getId();
}
return parent::get($mixed);
}
public function add(Gen_Entity_Abstract $entity)
{
return parent::set($entity->getId(), $entity);
}
public function search(Gen_Entity_Abstract $entity)
{
return parent::search($entity);
}
public function extractClass($class)
{
$extract = clone $this;
foreach ($this->_data as $key => $value) {
if (!($value instanceof $class)) {
$extract->reset($key);
}
}
return $extract;
}
public function filterClass($class)
{
$filter = clone $this;
foreach ($this->_data as $key => $value) {
if ($value instanceof $class) {
$filter->reset($key);
}
}
return $filter;
}
public function where($property, $condition)
{
$filtered = clone $this;
foreach($this->_data as $key => $value) {
if ($value->readProperty($property) != $condition) {
$filtered->reset($key);
}
}
return $filtered;
}
public function join($separator, $pattern)
{
require_once('Gen/Str.php');
return implode($separator, $this->map($pattern));
}
public function map($pattern)
{
$map = array();
foreach ($this->_data as $key => $entity) {
$map[$key] = $entity->map($pattern);
}
return $map;
}
public function unique($property)
{
$unique = new self();
foreach ($this->_data as $entity){
$unique->set($entity->$property, $entity);
}
return $unique;
}
public function reduce($property)
{
$reduced = array();
foreach($this->_data as $key => $entity)
{
$reduced[$key] = $entity->readProperty($property);
}
return $reduced;
}
public function collect($properties)
{
$collected = new Gen_Entity_Hash();
$properties = (array) $properties;
foreach($this->_data as $entity) {
foreach ($properties as $property) {
$item = $entity->readProperty($property);
$collected->set($item->getId(), $item);
}
}
return $collected;
}
}
<?php
/** Gen Base User class **/
require_once('Gen/Entity/Abstract.php');
abstract class Gen_Entity_User extends Gen_Entity_Abstract
{
protected $_authenticated;
public function getName()
{
return $this->_firstName . ' ' . strtoupper($this->_lastName);
}
public function getInitials()
{
return substr($this->_firstName, 0, 1) . substr($this->_lastName, 0, 1);
}
public function setAuthenticated($authenticated)
{
$this->_authenticated = $authenticated ? 1 : 0;
return $this;
}
public function getAuthenticated()
{
return $this->_authenticated;
}
public function isAuthenticated()
{
return (bool) $this->_authenticated;
}
public function isUser(User $user)
{
if ($user->getId() == null) {
return false;
}
return ($this->_id == $user->getId());
}
public function isAdmin()
{
return (bool) $this->_admin;
}
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
require_once('Gen/Form/Textbox.php');
require_once('Gen/Form/Hidden.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Autocomplete extends Gen_Form_Element
{
protected $_action;
protected $_datasource = array();
protected $_readOnly = 0;
public function setAction($action)
{
$this->_action = $action;
return $this;
}
public function __construct(array $attributes = array())
{
parent::__construct('div', $attributes);
$this->addClass('autocomplete');
}
public function setDatasource(array $datasource)
{
$this->_datasource = $datasource;
return $this;
}
public function requireScript()
{
$id = $this->getId();
$value = isset($this->_datasource[$this->getValue()])
? $this->_datasource[$this->getValue()]
: null;
$valueId = $this->getValue();
$options = array();
if(isset($value)) {
$options['value'] = array($valueId, $value);
}
if($this->getReadOnly()) {
$options['readonly'] = 1;
}
$options = json_encode($options);
return "new Manolosanctis.Autocomplete('" . $id . "', '" . $this->_action ."', " . $options .");";
}
}
<?php
require_once('Gen/Html/Element.php');
/** @see Gen_Html_Element */
require_once('Gen/Form/Element.php');
require_once('Gen/Form/Textbox.php');
require_once('Gen/Form/Number.php');
require_once('Gen/Form/Textarea.php');
require_once('Gen/Form/Richtext.php');
require_once('Gen/Form/File.php');
require_once('Gen/Form/Checkbox.php');
require_once('Gen/Form/ImageCheckbox.php');
require_once('Gen/Form/Hidden.php');
require_once('Gen/Form/Password.php');
require_once('Gen/Form/Radio.php');
require_once('Gen/Form/Submit.php');
require_once('Gen/Form/Select.php');
require_once('Gen/Form/MultiCheckbox.php');
require_once('Gen/Form/MultiRadio.php');
require_once('Gen/Form/Autocomplete.php');
require_once('Gen/Form/Textboxlist.php');
require_once('Gen/Form/Date.php');
require_once('Gen/Form/Time.php');
require_once('Gen/Form/Rating.php');
require_once('Gen/Form/Email.php');
require_once('Gen/Form/Tel.php');
require_once('Gen/Form/Url.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Base extends Gen_Html_Element
{
protected $_name = null;
protected $_elements;
public function __construct()
{
$this->_elements = array();
parent::__construct('form', array('method' => 'POST'));
if ($this->_name) {
$this->setId($this->_name . '_form');
}
}
public function getElements()
{
return $this->_elements;
}
public function addElement(Gen_Form_Element $element)
{
$this->_elements[$element->getId()] = $element;
$this->append($element);
return $this;
}
public function disableElement($key)
{
if ($element = $this->getElement($key)) {
$element->disable();
}
return $this;
}
public function getElement($id)
{
return isset($this->_elements[$id]) ? $this->_elements[$id] : null;
}
public function disable($id)
{
$this->getElement($id)->disable();
return $this;
}
public function setAction($action)
{
return $this->setAttribute('action', $action);
}
public function setMethod($method)
{
return $this->setAttribute('method', $method);
}
public function getMethod()
{
return $this->getAttribute('method', 'POST');
}
public function setName($name)
{
$this->_name = (string) $name;
return $this;
}
public function getName()
{
return $this->_name;
}
public function getValues()
{
$values = array();
foreach ($this->_elements as $key => $element) {
if ($element->enabled() && !($element instanceof Gen_Form_Submit)&& !($element instanceof Gen_Form_File)) {
$values[$key] = $element->getValue();
}
}
return $values;
}
public function setValues($data)
{
if ($data instanceof Gen_Entity_Abstract) {
$data = $data->toArray();
}
foreach ($this->_elements as $key => $element) {
$value = isset($data[$key]) ? $data[$key] : null;
$element->setValue($value);
}
return $this;
}
public function setValue($key, $value)
{
if ($element = $this->getElement($key)) {
$element->setValue($value);
}
return $this;
}
public function getFiles()
{
$values = array();
foreach ($this->_elements as $key => $element) {
if ($element->enabled() && ($element instanceof Gen_Form_File)) {
$values[$key] = $element->getValue();
}
}
return $values;
}
public function moveFile($key, $fileName)
{
$el = $this->getElement($key);
if($el instanceof Gen_Form_File) {
return $el->move($fileName);
}
return false;
}
public function buildId($key)
{
if ($name = $this->_name) {
$key = $name .'_'. $key;
}
return $key;
}
public function buildName($key)
{
if ($name = $this->_name) {
$key = $name .'['. $key .']';
}
return $key;
}
public function createElement($type, $id, array $attributes = array())
{
switch ($type) {
case 'text':
case 'textbox':
$element = new Gen_Form_Textbox();
break;
case 'number':
$element = new Gen_Form_Number();
break;
case 'email':
$element = new Gen_Form_Email();
break;
case 'tel':
$element = new Gen_Form_Tel();
break;
case 'url':
$element = new Gen_Form_Url();
break;
case 'textarea':
$element = new Gen_Form_Textarea();
break;
case 'richtext':
$element = new Gen_Form_Richtext();
break;
case 'file':
$element = new Gen_Form_File();
$element->setName($id);
if(!$this->getAttribute('enctype')){$this->setAttribute('enctype','multipart/form-data');}
break;
case 'checkbox':
$element = new Gen_Form_Checkbox();
break;
case 'imagecheckbox':
$element = new Gen_Form_ImageCheckbox();
break;
case 'hidden':
$element = new Gen_Form_Hidden();
break;
case 'password':
$element = new Gen_Form_Password();
break;
case 'radio':
$element = new Gen_Form_Radio();
break;
case 'select':
$element = new Gen_Form_Select();
break;
case 'multicheckbox':
$element = new Gen_Form_MultiCheckbox();
break;
case 'multiradio':
$element = new Gen_Form_MultiRadio();
break;
case 'autocomplete':
$element = new Gen_Form_Autocomplete();
break;
case 'textboxlist':
$element = new Gen_Form_Textboxlist();
break;
case 'date':
case 'datetime':
$element = new Gen_Form_Date();
if($type == 'datetime') {
$element->enableTime();
}
break;
case 'time':
$element = new Gen_Form_Time();
break;
case 'rating':
$element = new Gen_Form_Rating();
break;
case 'submit':
$element = new Gen_Form_Submit();
$element->setName('form[' . $id .']');
break;
default:
require_once('Gen/Form/Exception.php');
throw new Gen_Form_Exception("Unknown type: $type in Gen_Form::createElement");
break;
}
if (($type != 'submit') && ($type != 'file')) {
$element->setName($this->buildName($id));
}
$element->setId($id)
->addAttributes($attributes);
$this->addElement($element);
return $element;
}
public function isValid($data = array())
{
$valid = true;
if(empty($data)) {
if($this->getMethod() == 'POST' && isset($_POST[$this->_name])) {
$data = $_POST[$this->_name];
}
if($this->getMethod() == 'GET' && isset($_GET[$this->_name])) {
$data = $_GET[$this->_name];
}
}
foreach ($this->_elements as $key => $element) {
$value = isset($data[$key]) ? $data[$key] : null;
if ($element->enabled() && !$element->isValid($value)) {
$valid = false;
}
}
return $valid;
}
public function getErrors()
{
$errors = array();
foreach ($this->_elements as $key => $element) {
$errors = array_merge($errors, $element->getErrors());
}
return $errors;
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Checkbox extends Gen_Form_Input
{
protected $_type = 'checkbox';
// protected $_displayLabel = 1;
protected $_checkedValue = 1;
protected $_uncheckedValue = 0;
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
parent::setValue($this->_checkedValue);
}
public function setCheckedValue($checkedValue)
{
$this->_checkedValue = $checkedValue;
parent::setValue($checkedValue);
return $this;
}
public function setValue($value)
{
if ($value == $this->_checkedValue) {
$this->check();
} else {
$this->uncheck();
}
return $this;
}
public function getValue()
{
return ($this->isChecked() ? $this->_checkedValue : $this->_uncheckedValue);
}
public function isChecked()
{
return ($this->getAttribute('checked') ? true : false);
}
public function check()
{
$this->setAttribute('checked' , true);
return $this;
}
public function uncheck()
{
$this->resetAttribute('checked');
return $this;
}
// public function renderLabel()
// {
// return $this->_label ? '<span class="label_' . $this->_type . '">' . ($this->_label && $this->_enableTranslation ? _t($this->_enableTranslationHtml ? $this->_label : _sanitize($this->_label)) : $this->_label) . "</span>\n" : '';
// }
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
require_once('Gen/Date.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Date extends Gen_Form_Element
{
protected $_date;
protected $_enable_time = false;
protected $_firstYear = 1990;
protected $_lastYear = 2020;
protected $_format = 'Y/m/d H:s';
public function setValue($date)
{
if(null != $date) {
$date = Gen_Date::create($date);
$date = $date->format($this->_format);
} else {
$date = null;
}
return parent::setValue($date);
}
public function __construct(array $attributes = array())
{
parent::__construct('div', $attributes);
$this->addClass('date');
}
public function render()
{
$name = $this->getName();
$day = new Gen_Form_Select();
$day->setName($name.'[day]')
->setEmptyLabel('day')
->setDatasource(array(1 => '1', 2 => '2', 3 => '3', 4 => '4', 5 => '5', 6 => '6', 7 => '7', 8 => '8', 9 => '9', 10 => '10', 11 => '11', 12 => '12', 13 => '13', 14 => '14', 15 => '15', 16 => '16', 17 => '17', 18 => '18', 19 => '19', 20 => '20', 21 => '21', 22 => '22', 23 => '23', 24 => '24', 25 => '25', 26 => '26', 27 => '27', 28 => '28', 29 => '29', 30 => '30', 31 => '31'))
->disableWrapper();
$month = new Gen_Form_Select();
$month->setName($name.'[month]')
->setEmptyLabel('month')
->setDatasource(array(1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'Jully', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December'))
->disableWrapper();
$this->append($day);
$this->append($month);
return parent::render();
}
public function enableTime($enableTime)
{
$this->_enable_time = (bool) $enableTime;
return $this;
}
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
require_once('Gen/Date.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Date extends Gen_Form_Textbox
{
protected $_date;
protected $_enable_time = false;
protected $_firstYear;
protected $_lastYear;
protected $_format = 'Y/m/d';
public function setValue($date)
{
if(null != $date) {
$date = Gen_Date::create($date);
$date = $date->format($this->_format);
} else {
$date = null;
}
return parent::setValue($date);
}
public function __construct(array $attributes = array())
{
$this->_icon = 'calendar';
parent::__construct($attributes);
$this->addClass('date');
}
public function render()
{
$this->appendScript('$(function() {$( "#'. $this->getId() .'" ).datepicker({dateFormat : \'yy-mm-dd\'});});');
return parent::render();
}
public function enableTime($enableTime)
{
$this->_enable_time = (bool) $enableTime;
return $this;
}
}
<?php
/** @see Gen_Html_Element */
require_once('Gen/Html/Element.php');
require_once('Gen/Html/Script.php');
require_once('Gen/Validate.php');
/**
* @category Gen
* @package Gen_Form
*/
abstract class Gen_Form_Element extends Gen_Html_Element
{
const DISPLAY_BEFORE = 0;
const DISPLAY_AFTER = 1;
protected $_wrapper = 'div';
protected $_label = null;
protected $_displayLabel = true;
protected $_comment;
protected $_scripts = array();
protected $_required = false;
protected $_validator;
protected $_enabled = true;
protected $_enableScript = true;
protected $_enableTranslation = true;
protected $_enableTranslationHtml = true;
protected $_unit;
protected $_icon;
public function setName($name)
{
return $this->setAttribute('name', (string) $name);
}
public function getName()
{
return $this->getAttribute('name');
}
public function setValue($value)
{
return $this->setAttribute('value', trim((string) $value));
}
public function getValue()
{
return $this->getAttribute('value');
}
public function setWrapper($wrapper)
{
$this->_wrapper = $wrapper;
return $this;
}
public function setReadOnly($value = 1)
{
$value = $value ? 1 : 0;
if ($value) {
$this->addClass('readonly');
} else {
$this->removeClass('readonly');
}
return $this->setAttribute('readonly', $value);
}
public function getReadOnly()
{
return $this->getAttribute('readonly');
}
public function disableWrapper()
{
$this->_wrapper = null;
return $this;
}
public function setLabel($label)
{
$this->_label = (string) $label;
return $this;
}
public function getLabel()
{
return $this->_label;
}
public function displayLabel()
{
$this->_displayLabel = true;
return $this;
}
public function hideLabel()
{
$this->_displayLabel = false;
return $this;
}
public function setComment($comment)
{
$this->_comment = (string) $comment;
return $this;
}
public function getComment($comment)
{
return $this->_comment;
}
public function appendScript($script)
{
$scriptNode = new Gen_Html_Script();
$this->_scripts[] = $scriptNode->append($script);
return $this;
}
public function includeScript($src)
{
$scriptNode = new Gen_Html_Script(array('src' => $src));
$this->_scripts[] = $scriptNode;
return $this;
}
public function disable()
{
$this->_enabled = false;
return $this;
}
public function enable()
{
$this->_enabled = true;
return $this;
}
public function enabled()
{
return $this->_enabled;
}
public function disableScript()
{
$this->_enableScript = false;
return $this;
}
public function enableTranslation()
{
$this->_enableTranslation = true;
return $this;
}
public function disableTranslation()
{
$this->_enableTranslation = false;
return $this;
}
public function enableTranslationHtml()
{
$this->_enableTranslationHtml = true;
return $this;
}
public function disableTranslationHtml()
{
$this->_enableTranslationHtml = false;
return $this;
}
public function setHint($value)
{
$this->setAttribute('placeHolder', _t($value));
return $this;
}
public function getHint()
{
return $this->getAttribute('placeHolder');
}
public function setIcon($value)
{
$this->_icon = $value;
return $this;
}
public function getIcon()
{
return $this->_icon;
}
public function setUnit($unit)
{
$this->_unit = $unit;
return $this;
}
/********************************************
* Item Renderers *
********************************************/
public function renderRequired()
{
return $this->_required ? '<span class="field-required">*</span>' : '';
}
public function renderLabel()
{
return $this->_displayLabel ? '<label id="' . $this->getId() . '_label" for="'.$this->getId().'">' . ($this->_enableTranslation ? _t($this->_enableTranslationHtml ? $this->_label : _sanitize($this->_label)) : $this->_label) . $this->renderRequired() ."</label>\n" : '';
}
public function renderComment()
{
return $this->_comment ? '<div class="comment">' . ($this->_enableTranslation ? _t($this->_enableTranslationHtml ? $this->_comment : _sanitize($this->_comment)) : $this->_comment) . "</div>\n" : '';
}
public function renderUnit()
{
return $this->_unit ? '<div id="' . $this->getId() . '_unit" class="unit">'.$this->_unit.'</div>': '';
}
public function render()
{
if (!$this->_enabled) {
return null;
}
if(!$this->_wrapper) {
return parent::render();
}
$str = '<div class="field" id="'.$this->getId().'_field">';
$str .= $this->renderLabel();
$str .= '<div class="field-content">';
if($this->_icon) {
$str .= '<div class="field-group">';
}
$str .= parent::render();
if($this->_icon) {
$str .= '<span class="field-icon"><i class="fa fa-'.$this->_icon.'"></i></span></div>';
}
$str .= $this->renderUnit()
. $this->renderComment()
. $this->renderErrors()
. '</div>';
$str .= $this->renderScript()
. implode("\n", $this->_scripts);
$str .= '</div>';
return $str;
}
/****************************
* Validator *
****************************/
public function getValidator()
{
if (!isset($this->_validator)) {
$this->_validator = new Gen_Validate();
}
return $this->_validator;
}
public function isValid($value = null)
{
$this->setValue($value);
$value = $this->getValue();
if ($this->_required || !empty($value)) {
return $this->getValidator()->isValid($value);
}
$this->getValidator()->resetErrors();
return true;
}
public function validate($condition, $param = null, $message = null)
{
$this->getValidator()->validate($condition, $param, $message);
return $this;
}
public function setRequired($required = true)
{
$this->_required = (bool) $required;
if ($this->_required === true) {
$this->setAttribute('required', 'required');
$this->validate('presence');
} else {
$this->resetAttribute('required');
}
return $this;
}
public function isRequired()
{
return (null === $this->_required) ? $this->_required : false;
}
public function getErrors()
{
return $this->getValidator()->getErrors();
}
public function addError($message, $param = null)
{
$this->getValidator()->addError($message, $param);
return $this;
}
public function renderErrors()
{
$str = null;
foreach ($this->getErrors() as $error) {
$str .= '<div class="validation-error">' . $error . '</div>';
}
return $str;
}
public function renderScript()
{
$str = $this->_enableScript ? $this->requireScript() : null;
return $str ? '<script type="text/javascript">'.$str.'</script>' : null;
}
public function requireScript()
{
return false;
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Email extends Gen_Form_Input
{
protected $_type = 'email';
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$this->validate('email');
}
}
<?php
/** Gen_Exception */
require_once ('Gen/Exception.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Exception extends Gen_Exception
{
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_File extends Gen_Form_Input
{
protected $_type = 'file';
protected $_file;
protected $_max_size;
public function __construct(array $attributes = array())
{
$this->_max_size = 5*1024*1024;
parent::__construct($attributes);
}
public function fileSize($min, $max)
{
$this->_max_size = $max;
$this
->setAttribute('maxlength', (int) $max)
->validate('min_file_size', (int) $min)
->validate('max_file_size', (int) $max);
return $this;
}
public function mimeTypes($mimeTypes)
{
$mimeTypes = (array) $mimeTypes;
$this->setAttribute('accept', implode(',', $mimeTypes));
$this->validate('file_extension', $mimeTypes);
return $this;
}
public function setValue($value)
{
return $this->_file = $value;
}
public function getValue()
{
return isset($_FILES[$this->getName()]) ? $_FILES[$this->getName()] : null;
}
public function getFileName()
{
$file = $this->getValue();
return isset($file['name']) ? $file['name'] : null;
}
public function getExtension()
{
return strtolower(array_pop(explode('.', $this->getFileName())));
}
public function isUploaded()
{
return (isset($_FILES[$this->getName()]) && ($_FILES[$this->getName()]['name'] != null));
}
public function move($fileName)
{
$file = $this->getValue();
$dir = dirname($fileName);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
return move_uploaded_file($file['tmp_name'], $fileName);
}
public function isValid($value = null)
{
$this->getValidator()->resetErrors();
/** check if file was sent */
if (!isset($_FILES[$this->getName()]) || (isset($_FILES[$this->getName()]) && $_FILES[$this->getName()]['name'] == null)) {
if ($this->_required) {
$this->addError("Erreur lors du téléchargement du fichier.");
return false;
}
}
if(isset($_FILES[$this->getName()]) && $_FILES[$this->getName()]['name'] && $_FILES[$this->getName()]['error'])
{
switch($_FILES[$this->getName()]['error'])
{
case 1:
case 2:
$this->addError("Maximum upload filesize exeeded.");
break;
default:
$this->addError("Error Uploading the file.");
break;
}
return false;
}
return parent::isValid();
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Hidden extends Gen_Form_Input
{
protected $_type = 'hidden';
public function render()
{
return Gen_Dom_Element::render();
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Checkbox.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_ImageCheckbox extends Gen_Form_Checkbox
{
protected $_titleLabel;
protected $_labelClass;
public function setTitleLabel($title){
$this->_titleLabel = $title;
return $this;
}
public function getTitleLabel(){
return $this->_titleLabel;
}
public function setLabelClass($class){
$this->_labelClass = $class;
return $this;
}
public function getLabelClass(){
return $this->_labelClass;
}
public function renderLabel()
{
if($this->_label)
return '<label id="' . $this->getId() . '_label" for="'.$this->getId().'" class="label_' . $this->_type . ' ' .$this->_labelClass .'" title="'.$this->getTitleLabel().'">' . $this->_label . "</label>";
else
return '<label id="' . $this->getId() . '_label" for="'.$this->getId().'" class="label_' . $this->_type . ' ' .$this->_labelClass .'" title="'.$this->getTitleLabel().'"></label>';
}
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
/**
* @category Gen
* @package Gen_Form
*/
abstract class Gen_Form_Input extends Gen_Form_Element
{
protected $_tag = 'input';
protected $_type;
public function __construct(array $attributes = array())
{
parent::__construct('input', $attributes);
$this->setAttribute('type', $this->_type);
$this->setAttribute('class', 'input-' . $this->_type);
}
public function getType()
{
return $this->getAttribute('type');
}
}
<?php
require_once('Gen/Form/Element.php');
class Gen_Form_List extends Gen_Form_Element
{
protected $_dataSource = array();
public function setDataSource($data)
{
$this->_dataSource = $data;
return $this;
}
public function getDataSource()
{
return $this->_dataSource;
}
}
<?php
require_once('Gen/Dom/Element.php');
class Gen_Form_ListElement extends Gen_Dom_Element
{
}
<?php
require_once('Gen/Form/List.php');
require_once('Gen/Form/Checkbox.php');
class Gen_Form_MultiCheckbox extends Gen_Form_List
{
protected $_selectedValues = array();
protected $_valueAttribute = 'id';
protected $_labelAttribute = 'label';
protected $_groupAttribute = null;
public function __construct()
{
parent::__construct('ul', array('class' => 'multicheckbox'));
}
public function setValue($value)
{
if($value instanceof Gen_Entity_Dictionary) {
$value = $value->reduce($this->_valueAttribute);
}
$this->_selectedValues = (array) $value;
return $this;
}
public function getValue()
{
return $this->_selectedValues;
}
public function setLabelAttribute($labelAttribute)
{
$this->_labelAttribute = (string) $labelAttribute;
return $this;
}
public function setValueAttribute($valueAttribute)
{
$this->_valueAttribute = (string) $valueAttribute;
return $this;
}
public function setGroupAttribute($attribute)
{
$this->_groupAttribute = $attribute;
return $this;
}
public function select($value)
{
array_push($this->_selectedValues, $value);
}
public function bind()
{
if(null !== $this->_groupAttribute) {
foreach($this->_dataSource->groupBy($this->_groupAttribute) as $group => $data) {
$ul = new Gen_Html_Element('ul', array('class' => 'checkbox-group'));
$this->_buildItems($data, $ul);
$li = new Gen_Html_Element('li', array('class' => 'group'));
$span = new Gen_Html_Element('span', array('class' => 'group-label'));
$span->append($data->first()->readProperty($this->_groupAttribute)->readProperty($this->_labelAttribute));
$li->append($span)->append($ul);
$this->append($li);
}
} else {
$this->_buildItems($this->_dataSource, $this);
}
}
protected function _buildItems($dataSource, $ul)
{
foreach($dataSource as $id => $entity) {
if ($entity instanceof Gen_Entity_Abstract) {
$value = $entity->readProperty($this->_valueAttribute);
$label = $entity->readProperty($this->_labelAttribute);
} elseif (is_array($entity)) {
$value = $entity[$this->_valueAttribute];
$label = $entity[$this->_labelAttribute];
} else {
$value = $id;
$label = $entity;
}
$li = $this->_buildItem($value, $label);
$ul->append($li);
}
}
protected function _buildItem($value, $label)
{
$name = $this->getName() . '[]';
$checkbox = new Gen_Form_Checkbox();
$checkbox->setCheckedValue($value)
->setName($name)
->disableWrapper();
$span = new Gen_Html_Element('span');
$span->append($label);
foreach ($this->_selectedValues as $selectedValue) {
if ($value == $selectedValue) {
$checkbox->check();
}
}
$li = new Gen_Html_Element('li');
$li->append($checkbox)
->append($span);
return $li;
}
public function render()
{
$this->bind();
return parent::render();
}
}
<?php
require_once('Gen/Form/List.php');
require_once('Gen/Form/Radio.php');
class Gen_Form_MultiRadio extends Gen_Form_List
{
protected $_selectedValue;
protected $_valueAttribute = 'id';
protected $_labelAttribute = 'label';
public function __construct()
{
parent::__construct('ul', array('class' => 'multiradio'));
}
public function setLabelAttribute($labelAttribute)
{
$this->_labelAttribute = (string) $labelAttribute;
return $this;
}
public function setValueAttribute($valueAttribute)
{
$this->_valueAttribute = (string) $valueAttribute;
return $this;
}
public function setValue($value)
{
$this->_selectedValue = ($value === '') ? null : $value;
return $this;
}
public function getValue()
{
return $this->_selectedValue;
}
public function select($value)
{
return $this->setValue($value);
}
public function bind()
{
$name = $this->getName();
foreach($this->_dataSource as $id => $entity) {
if ($entity instanceof Gen_Entity_Abstract) {
$value = $entity->readProperty($this->_valueAttribute);
$label = $entity->readProperty($this->_labelAttribute);
} elseif (is_array($entity)) {
$value = $entity[$this->_valueAttribute];
$label = $entity[$this->_labelAttribute];
} else {
$value = $id;
$label = $entity;
}
$radio = new Gen_Form_Radio();
$radio->setCheckedValue($value)
->setName($name)
->disableWrapper();
$span = new Gen_Html_Element('span', array('class' => 'multiradio-label'));
$span->append($label);
if ($value == $this->_selectedValue) {
$radio->check();
}
$li = new Gen_Html_Element('li', array('class' => 'multiradio-option'));
$li->append($radio)
->append($span);
$this->append($li);
}
}
public function render()
{
$this->bind();
return parent::render();
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Number extends Gen_Form_Input
{
protected $_type = 'number';
public function setStep($value)
{
$value = null === $value ? null : (int) $value;
return $this->setAttribute('step', $value);
}
public function setMin($value)
{
$value = null === $value ? null : (int) $value;
return $this->setAttribute('min', $value);
}
public function setMax($value)
{
$value = null === $value ? null : (int) $value;
return $this->setAttribute('max', $value);
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Password extends Gen_Form_Input
{
protected $_type = 'password';
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Radio extends Gen_Form_Input
{
protected $_type = 'radio';
protected $_checkedValue = 1;
protected $_uncheckedValue = null;
public function init()
{
parent::setValue($this->_checkedValue);
}
public function setCheckedValue($checkedValue)
{
$this->_checkedValue = $checkedValue;
parent::setValue($checkedValue);
return $this;
}
public function setValue($value)
{
if ($value == $this->_checkedValue) {
$this->check();
} else {
$this->uncheck();
}
return $this;
}
public function getValue()
{
return $this->isChecked() ? $this->_checkedValue : $this->_uncheckedValue;
}
public function isChecked()
{
return $this->getAttribute('checked');
}
public function check()
{
$this->setAttribute('checked' , true);
return $this;
}
public function uncheck()
{
$this->resetAttribute('checked');
return $this;
}
}
<?php
require_once('Gen/Form/List.php');
require_once('Gen/Form/Checkbox.php');
class Gen_Form_Rating extends Gen_Form_List
{
public function __construct()
{
parent::__construct('ul', array('class' => 'inline rating'));
}
public function bind()
{
$name = $this->resetAttribute('name');
$selectedValue = $this->resetAttribute('value');
foreach($this->_dataSource as $value => $label) {
$radio = new Gen_Html_Element('input', array('type' => 'radio'));
$radio->setAttribute('value', $value)
->setAttribute('name', $name);
if ($selectedValue == $value) {
$radio->setAttribute('checked', true);
}
$li = new Gen_Html_Element('li');
$li->append($radio);
$this->append($li);
}
}
public function render()
{
$this->bind();
return parent::render();
}
}
<?php
/** @see Gen_Form_Textarea */
require_once('Gen/Form/Textarea.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Richtext extends Gen_Form_Textarea
{
public function __construct(array $attributes = array())
{
$attributes['class'] = 'richtext';
parent::__construct($attributes);
}
}
<?php
require_once('Gen/Form/List.php');
class Gen_Form_Select extends Gen_Form_List
{
protected $_selectedValue;
protected $_valueAttribute = 'id';
protected $_valueType ='int';
protected $_labelAttribute = 'label';
protected $_emptyLabel = '-- select --';
protected $_multipleValues = false;
public function __construct(array $attributes = array())
{
parent::__construct('select', $attributes);
$this->setAttribute('class', 'select2');
}
public function setLabelAttribute($labelAttribute)
{
$this->_labelAttribute = (string) $labelAttribute;
return $this;
}
public function setValueAttribute($valueAttribute)
{
$this->_valueAttribute = (string) $valueAttribute;
return $this;
}
public function setValueType($type)
{
$this->_valueType = $type;
return $this;
}
public function setEmptyLabel($emptyLabel)
{
$this->_emptyLabel = $emptyLabel;
return $this;
}
public function allowMultipleValues()
{
$this->_multipleValues = true;
$this->setAttribute('multiple', "multiple");
$this->setName($this->getName().'[]');
return $this;
}
public function setValue($value)
{
if($this->_multipleValues) {
if($value instanceof Gen_Entity_Dictionary) {
$value = $value->reduce($this->_valueAttribute);
}
$this->_selectedValue = (array) $value;
return $this;
}
switch($this->_valueType)
{
case ($value === ''):
case ($value === null):
$this->_selectedValue = null;
break;
case 'int':
$this->_selectedValue = (int) $value;
break;
case 'float':
$this->_selectedValue = (float) $value;
break;
case 'string':
default:
$this->_selectedValue = $value;
}
return $this;
}
public function getValue()
{
return $this->_selectedValue;
}
public function select($value)
{
return $this->setValue($value);
}
public function setHint($hint)
{
$this->_emptyLabel = $hint;
return $this;
}
public function bind()
{
$option = new Gen_Html_Element('option');
$option->setAttribute('value', '')
->addClass('hint')
->append(_t($this->_emptyLabel));
$this->append($option);
foreach($this->_dataSource as $id => $entity) {
if ($entity instanceof Gen_Entity_Abstract) {
$value = $entity->readProperty($this->_valueAttribute);
$label = $entity->readProperty($this->_labelAttribute);
} elseif (is_array($entity)) {
$value = $entity[$this->_valueAttribute];
$label = $entity[$this->_labelAttribute];
} else {
$value = $id;
$label = $entity;
}
$option = new Gen_Html_Element('option');
$option->setAttribute('value', $value)
->append($label);
$selectedValues = (array) $this->_selectedValue;
foreach($selectedValues as $selectedValue) {
if ($value === $selectedValue) {
$option->setAttribute('selected', 'true');
}
}
$this->append($option);
}
}
public function render()
{
$this->bind();
return parent::render();
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Submit extends Gen_Form_Input
{
protected $_type = 'submit';
protected $_warning;
public function setLabel($label)
{
parent::setValue($this->_enableTranslation ? _t($label) : $label);
return $this;
}
public function setValue($value)
{
return $this;
}
public function setWarning($text)
{
$this->_warning = $text;
return $this;
}
public function getWarning()
{
return $this->_warning;
}
public function requireScript()
{
return "Gen.Form.Submit('".$this->getId()."', '".$this->getWarning()."');";
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Tel extends Gen_Form_Input
{
protected $_type = 'tel';
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Textarea extends Gen_Form_Element
{
protected $_tag = 'textarea';
public function __construct(array $attributes = array())
{
parent::__construct('textarea', $attributes);
}
public function render()
{
$value = $this->resetAttribute('value');
$this->setContent($value);
return parent::render();
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Textbox extends Gen_Form_Input
{
protected $_type = 'text';
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
require_once('Gen/Form/Textbox.php');
require_once('Gen/Form/Hidden.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Textboxlist extends Gen_Form_Element
{
protected $_action;
protected $_feed = array();
protected $_selectedValues = array();
public function setValue($value)
{
return $this->_selectedValues = (array) $value;
}
public function getValue()
{
return $this->_selectedValues;
}
public function setAction($action)
{
$this->_action = $action;
return $this;
}
public function feed(array $data)
{
$this->_feed = $data;
}
public function __construct(array $attributes = array())
{
parent::__construct('div', $attributes);
$this->addClass('textboxlist');
}
public function renderValue()
{
$init = array();
foreach($this->_feed as $key => $value) {
$init[] = '<li id="'.$key.'">' . htmlentities($value, ENT_COMPAT, 'UTF-8') . '</li>';
}
return '<ul class="textbox-init" style="display:none">' . implode("\n", $init) . '</ul>';
}
public function render()
{
$name = $this->resetAttribute('name');
$this->append('<span class="stretcher">:)</span>')
->append($this->renderValue())
->appendScript(
"new Manolosanctis.Textboxlist('{$this->getId()}', '$name', '{$this->_action}');"
);
return parent::render();
}
}
<?php
/** @see Gen_Form_Element */
require_once('Gen/Form/Element.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Time extends Gen_Form_Element
{
protected $_time;
protected $_format = 'H:i:s';
protected $_minutesOffset = 5;
protected $_startsAt = 0;
protected $_endsAt = 24;
public function setMinutesOffset($offset)
{
$offset = (int) $offset;
$offset = ($offset > 0) ? $offset : 0;
$offset = ($offset < 30) ? $offset : 30;
$this->_minutesOffset = $offset;
return $this;
}
public function setHourRange($start, $end = 24)
{
$this->_startsAt = $start;
$this->_endsAt = $end;
return $this;
}
public function setValue($time)
{
if(null != $time) {
require_once('Gen/Date.php');
$time = Gen_Date::create($time);
$time = $time->format($this->_format);
} else {
$time = null;
}
return parent::setValue($time);
}
public function __construct(array $attributes = array())
{
parent::__construct('div', $attributes);
$this->addClass('time');
}
public function render()
{
$name = $this->getName();
$hours = array(); $h = $this->_startsAt;
for($h; $h < $this->_endsAt; $h++) {
$hours[$h] = $h;
}
$hour = new Gen_Form_Select();
$hour->setName($name.'[hour]')
->setEmptyLabel('hour')
->setDatasource($hours)
->disableWrapper()
->removeClass('select2');
$minutes = array(); $t = 0;
for($t; $t < 60; $t = $t + $this->_minutesOffset) {
$minutes[$t] = (string) $t;
}
$min = new Gen_Form_Select();
$min->setName($name.'[min]')
->setEmptyLabel('min')
->setDatasource($minutes)
->disableWrapper()
->removeClass('select2');
$this->append($hour);
$this->append($min);
return parent::render();
}
}
<?php
/** @see Gen_Form_Input */
require_once('Gen/Form/Input.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Form_Url extends Gen_Form_Input
{
protected $_type = 'url';
public function __construct(array $attributes = array())
{
parent::__construct($attributes);
$this->validate('url');
}
}
<?php
/**
* @category Gen
* @package Gen_Hash
*/
class Gen_Hash_Base implements Iterator, ArrayAccess
{
protected $_data = array();
public function __construct($data = null)
{
if($data instanceof Gen_Hash_Base) {
$data = $data->toArray();
}
$this->_data = (array) $data;
}
/**
* Add a new data reference
* Gen_Hash_Base must be extended type hinting
*
* @param mixed $key
* @param mixed $value
* @return Gen_Hash_Base $hash;
*/
public function set($key, $value)
{
$this->_data[(string) $key] = $value;
return $this;
}
/**
* Unset a new data reference
*
* @param mixed $key
* @return Gen_Hash_Base $hash
*/
public function reset($key)
{
$result = $this->get($key);
unset($this->_data[$key]);
return $result;
}
public function update($data = array())
{
$this->_data = $data;
}
/**
* Get a given data
* @param mixed $key
* @return mixed|null $value;
*/
public function get($key ,$default = null)
{
return isset($this->_data[$key]) ? $this->_data[$key] : $default;
}
/**
* Merge a given Hash to the current context
* @param Gen_Hash_Base $hash
* @return Gen_Hash_Base $hash;
*/
public function merge($data)
{
if($data instanceof Gen_Hash_Base) {
$data = $data->toArray();
}
$this->_data = array_merge($this->_data, $data);
return $this;
}
/**
* Search the hash for a given value
* @param mixed $value
* @return mixed $key
*/
public function search($value)
{
return array_search($value, $this->_data, true);
}
public function count()
{
return count($this->_data);
}
public function isEmpty()
{
return (count($this->_data) > 0) ? false : true;
}
public function first()
{
return reset($this->_data);
}
public function last()
{
return end($this->_data);
}
public function shift()
{
return array_shift($this->_data);
}
public function exists($key)
{
return isset($this->_data[$key]);
}
/**
* Get the Data as an array
* @return array $array;
*/
public function toArray()
{
return $this->_data;
}
public function keys()
{
return array_keys($this->_data);
}
public function join($separator = "\n")
{
return implode($separator, $this->_data);
}
/** __toString() */
public function __toString()
{
return $this->join();
}
/** Implements ArrayAccess */
public function offsetSet($key, $value)
{
$this->set($key, $value);
}
public function offsetExists($key)
{
return isset($this->_data[$key]);
}
public function offsetUnset($key)
{
$this->reset($key);
}
public function offsetGet($key)
{
return $this->get($key);
}
/**
* Implements Iterator
*
* rewind()
* key()
* current()
* next()
* valid()
*/
public function rewind()
{
reset($this->_data);
}
public function key()
{
return key($this->_data);
}
public function current()
{
return current($this->_data);
}
public function next()
{
return next($this->_data);
}
public function valid()
{
return ($this->current() !== false);
}
/**
* Tools
*/
public function slice($offset, $length)
{
$this->_data = array_slice($this->_data, $offset, $length);
return $this;
}
}
<?php
/** Gen_Exception */
require_once ('Gen/Exception.php');
/**
* @category Gen
* @package Gen_Hash
*/
class Gen_Hash_Exception extends Gen_Exception
{
}
<?php
/** @see Gen_Html_Element */
require_once('Gen/Dom/Element.php');
/**
* @category Gen
* @package Gen_Form
*/
class Gen_Html_Element extends Gen_Dom_Element
{
protected $_display;
protected $_styles;
protected $_script;
public function __construct($tag, array $attributes = array())
{
$this->_display = true;
$this->_styles = array();
parent::__construct($tag, $attributes);
}
/**
* Determines wether the Element should be displayed or not
*
* caution ! this will not hide the element
* but literaly not generate any code
* @see render()
*
* @param bool $display
* @return Gen_Html_Element
*/
public function setDisplay($display)
{
$this->_display = (bool) $display;
return $this;
}
public function getDisplay()
{
return $this->_display;
}
/**
* Styles
*/
public function getStyles()
{
return $this->_styles;
}
public function setStyles(array $styles)
{
$this->_styles = $styles;
return $this;
}
public function getStyle($key, $default = null)
{
return isset($this->_styles[$key]) ? $this->_styles[$key] : $default;
}
public function setStyle($key, $value) {
$this->_styles[(string) $key] = (string) $value;
return $this;
}
public function setWidth($width) {
if(is_int($width) || is_float($width)) {
$width = $width.'px';
}
$this->_styles['width'] = $width;
return $this;
}
public function setHeight($height) {
if(is_int($height) || is_float($height)) {
$height = $height.'px';
}
$this->_styles['height'] = $height;
return $this;
}
public function hide()
{
return $this->setStyle('display', 'none');
}
/**
* Class
*/
public function setClass($class)
{
return $this->setAttribute('class', (string) $class);
}
public function getClass()
{
return $this->getAttribute('class');
}
public function addClass($class)
{
$class = $this->getClass() . " " . (string) $class;
$this->setClass(trim($class));
return $this;
}
public function removeClass($class)
{
$classStr = preg_replace("#\b$class\b#", ' ', $this->getClass());
$this->setClass(trim($classStr));
return $this;
}
public function render()
{
if($this->_display) {
if ($this->_styles) {
$style = '';
foreach($this->_styles as $key => $value) {
$style .= ($style ? ' ': '') . "$key: $value;";
}
$this->setAttribute('style', $style);
}
return parent::render();
}
return '';
}
}
<?php
/** @see Gen_Dom_Element */
require_once('Gen/Dom/Element.php');
class Gen_Html_Link extends Gen_Dom_Element
{
public function __construct(array $attributes = array())
{
parent::__construct('link', $attributes);
}
public function setHref($href)
{
$this->setAttribute('href', $href);
return $this;
}
public function getHref()
{
return $this->getAttribute('href');
}
public function setType($type)
{
$this->setAttribute('type', $type);
return $this;
}
public function setRel($rel)
{
$this->setAttribute('rel',$rel);
return $this;
}
}
<?php
class Gen_Html_Parser
{
const VALIDATOR_CSS_UNIT = '(([\+\-]?[0-9\.]+)(em|ex|px|in|cm|mm|pt|pc|\%))|0';
const VALIDATOR_URL = 'http://\\S+';
const VALIDATOR_CSS_PROPERTY = '[a-z\-]+';
const VALIDATOR_STYLE = '[^"]*';
protected static $_tags = 'a|b|blockquote|br|cite|d[ldt]|em|h[1-6]|i|img|li|ol|p|span|strong|u|ul';
protected static $_selfClosingTags = array('area', 'base', 'basefont', 'br', 'hr', 'input', 'img', 'link', 'meta', 'col', 'param');
protected static $_attributePattern = '@\s([-\w]+)\s*=\s*[\"\']([^"\']+)[\"\']@xsi';
protected static $_attributes = array(
'img' => array(
'width' => '[0-9]+',
'height' => '[0-9]+',
'src' => self::VALIDATOR_URL,
'style' => self::VALIDATOR_STYLE
),
'span' => array(
'style' => self::VALIDATOR_STYLE
),
'p' => array(
'style' => self::VALIDATOR_STYLE
),
'a' => array(
'href' => self::VALIDATOR_URL
)
);
protected static $_styleValidators = array(
'color' => '(\#[a-fA-F0-9]+)|([a-z ]+)',
'background-color' => '\#[a-zA-Z0-9]+',
'font-style' => '(normal|italic|oblique)',
'font-size' => '[\-a-z]+',
'margin-left' => self::VALIDATOR_CSS_UNIT,
'margin-right' => self::VALIDATOR_CSS_UNIT,
'text-align' => '(left|right|center|justify)',
'text-indent' => self::VALIDATOR_CSS_UNIT,
'text-decoration' => '(none|overline|underline|blink|line-through)',
'width' => self::VALIDATOR_CSS_UNIT,
'height' => self::VALIDATOR_CSS_UNIT
);
public static function stripTags($str, $tags = null)
{
if (is_array($tag)) {
$tag = implode('|', $tag);
}
$pattern = '#</?('. $tags .')\s[^>]+/?>#';
$str = preg_replace($pattern, '', $str);
return $str;
}
public static function stripComments($str)
{
$pattern = '#<!--.*?-->#';
$str = preg_replace($pattern, '', $str);
return $str;
}
public static function specialchars($str)
{
$str = str_replace('<', '<', $str);
$str = str_replace('>', '>', $str);
return $str;
}
public static function sanitize($str)
{
$tokens = array();
//tokenize opening tags with no attributes
$pattern = '#<(/)?('. self::$_tags .')>#';
$replace = '__SAFE_TAG_$1$2__';
$str = preg_replace($pattern, $replace, $str);
// tokenize tags with attributes
$pattern = '#<('. self::$_tags .')(?:\s+(?:[a-z]+)="(?:[^"\\\]*(?:\\\"[^"\\\]*)*)")*\s*(/)?>#';
preg_match_all($pattern, $str, $matches, PREG_SET_ORDER);
foreach($matches as $i => $match) {
$tokens[$i] = self::cleanTag($match[1], $match[0]);
$str = str_replace($match[0], '__SAFE_TOKEN_'.$i.'__', $str);
}
$str = self::stripComments($str);
$str = self::stripTags($str);
$str = self::specialchars($str);
foreach ($tokens as $i => $cleanTag) {
$str = str_replace('__SAFE_TOKEN_'.$i.'__', $cleanTag, $str);
}
$pattern = '#__SAFE_TAG_(/?(?:'. self::$_tags .'))__#';
$replace = '<$1>';
$str = preg_replace($pattern, $replace, $str);
return $str;
}
public static function cleanTag($tag, $str)
{
$cleanTag = '<' . $tag;
if ($tag === 'a') {
$cleanTag .= ' rel="nofolow" target="_blank"';
}
if (isset(self::$_attributes[$tag])) {
foreach(self::$_attributes[$tag] as $attr => $attrPattern) {
$pattern = '#'.$attr.'="('. $attrPattern .')"#';
preg_match($pattern, $str, $match);
if (isset($match[1])) {
if ($attr == 'style') {
$cleanTag .= ' style="' . self::cleanStyle($match[1]) . '"';
} else {
$cleanTag .= ' ' . $attr . '="' . $match[1] . '"';
}
}
}
}
if ($tag === 'img') {
$cleanTag .= ' /';
}
$cleanTag .= '>';
return $cleanTag;
}
public static function cleanStyle($style)
{
$cleanStyle = '';
foreach(self::$_styleValidators as $stl => $stlPattern) {
$pattern = '#[; ]?' . $stl . '\s*:\s*(' . $stlPattern . ')\s*;#i';
preg_match($pattern, $style, $match);
if (isset($match[1])) {
$cleanStyle .= ($cleanStyle ? ' ' : '') . $stl . ':' . $match[1] . ';';
}
}
return $cleanStyle;
}
public static function extractTags($str, $tag, $selfClosing = null)
{
if (is_array($tag)) {
$tag = implode('|', $tag);
}
if (is_null($selfClosing)) {
$selfClosing = in_array($tag, self::$_selfClosingTags);
}
$pattern = $selfClosing
? ('@<('. $tag .')(\s*[^>]*)\s*/?>@xsi')
: ('@<('.$tag.')([^>]*)>(.*)</'.$tag.'>@xsi');
$matches = array();
preg_match_all($pattern, $str, $matches, PREG_SET_ORDER);
$results = array();
foreach($matches as $i => $match) {
$results[$i] = array(
'tag' => strtolower($match[1]),
'attributes' => self::extractAttributes($match[2]),
'content' => isset($match[3]) ? trim($match[3]) : '',
'html' => $match[0]
);
}
return $results;
}
public static function extractAttributes($str)
{
$results = array();
$matches = array();
preg_match_all(self::$_attributePattern, $str, $matches, PREG_SET_ORDER);
foreach($matches as $match) {
$property = strtolower($match[1]);
$results[$property] = trim($match[2]);
}
return $results;
}
public static function parse($str, $url = null)
{
$url = urldecode($url);
$results = array();
$base_url = substr($url,0, strpos($url, "/",8));
$relative_url = substr($url,0, strrpos($url, "/")+1);
/*$str = str_replace(array("\n","\r","\t",'</span>','</div>'), '', $str);
$str = preg_replace('/(<(div|span)\s[^>]+\s?>)/', '', $str);*/
if (mb_detect_encoding($str, "UTF-8") != "UTF-8") {
$str = utf8_encode($str);
}
// Parse Title
$nodes = self::extractTags($str, 'title');
$results['title'] = $nodes[0]['content'];
$base_override = false;
/*/ Parse Base
$base_regex = '/<base[^>]*'.'href=[\"|\'](.*)[\"|\']/Ui';
preg_match_all($base_regex, $str, $base_match, PREG_PATTERN_ORDER);
if(strlen($base_match[1][0]) > 0)
{
$base_url = $base_match[1][0];
$base_override = true;
}*/
// Parse Description
$results['description'] = '';
$nodes = self::extractTags($str, 'meta');
foreach($nodes as $node)
{
if(isset($node['attributes']['name']) && $node['attributes']['name'] == 'description') {
$results['description'] = $node['attributes']['content'];
}
if(isset($node['attributes']['property'])) {
switch (($node['attributes']['property']))
{
case 'og:title':
$results['fb_title'] = $node['attributes']['content'];
break;
case 'og:description':
$results['fb_description'] = $node['attributes']['content'];
break;
case 'og:image':
$results['fb_image'] = $node['attributes']['content'];
break;
}
}
}
// Parse Images
$imageTags = self::extractTags($str, 'img');
$images = array();
for ($i=0;$i<=sizeof($imageTags);$i++)
{
$img = @$imageTags[$i]['attributes']['src'];
$width = isset($imageTags[$i]['attributes']['width']) ? $imageTags[$i]['attributes']['width'] : null;
$height = isset($imageTags[$i]['attributes']['height']) ? $imageTags[$i]['attributes']['height'] : null;
// $width = preg_replace("/[^0-9.]/", '', $imageTags[$i]['attributes']['width']);
// $height = preg_replace("/[^0-9.]/", '', $imageTags[$i]['attributes']['height']);
$ext = trim(pathinfo($img, PATHINFO_EXTENSION));
if($img && $ext != 'gif')
{
/**if (substr($img,0,7) == 'http://')**/
if(preg_match('#^http(s)?://(.*)#', $img))
;
else if (substr($img,0,1) == '/' || $base_override)
$img = $base_url . $img;
else
$img = $relative_url . $img;
if ($width == '' && $height == '')
{
$details = @getimagesize($img);
if(is_array($details))
{
list($width, $height, $type, $attr) = $details;
}
}
$width = intval($width);
$height = intval($height);
if ($width > 199 || $height > 199)
{
if (
(($width > 0 && $height > 0 && (($width / $height) < 3) && (($width / $height) > .2))
|| ($width > 0 && $height == 0 && $width < 700)
|| ($width == 0 && $height > 0 && $height < 700)
)
&& strpos($img, 'logo') === false)
{
$images[] = array('src' => $img, 'width' => $width, 'height' => $height);
}
}
}
}
if(isset($results['fb_image'])) {
array_unshift($images, array('src' => $results['fb_image'], 'width' => 200, 'height' => 200));
}
$results['images'] = $images;
return $results;
}
}
<?php
/** @see Gen_Dom_Element */
require_once('Gen/Dom/Element.php');
class Gen_Html_Script extends Gen_Dom_Element
{
public function __construct(array $attributes = array())
{
$attributes = array_merge(array('type' => 'text/javascript'), $attributes);
parent::__construct('script', $attributes);
/** force content to ' ' */
$this->append(' ');
}
public function setSrc($src)
{
$this->setAttribute('src', $src);
return $this;
}
public function getSrc()
{
return $this->getAttribute('src');
}
}
<?php
/** @see Gen_Dom_Element */
require_once('Gen/Html/Link.php');
class Gen_Html_Style extends Gen_Html_Link
{
public function __construct(array $attributes = array())
{
$properties = array('rel' => 'stylesheet', 'type' => 'text/css');
$attributes = array_merge($properties, $attributes);
parent::__construct($attributes);
}
}
<?php
require_once('Gen/Http/Security.php');
class Gen_Http_Cookie
{
const DEFAULT_NAME = 'Gen_Cookie';
const DEFAULT_TIMEOUT = 1728000; // 20days * 24h * 60min * 60s
const SEPARATOR_DATA = '¤';
const SEPARATOR_KEY = '|';
public static $key = '4b6Ad-8f5gD-h2jFk-6l9mG-o5H4J-ty2UI';
public static $baseUrl = '/';
protected $_name;
protected $_data;
protected $_expire;
protected $_domain;
protected $_salt;
public function __construct($name = self::DEFAULT_NAME, $path = '', $expire = null)
{
$this->_name = md5($name . self::$key);
$this->_data = array();
$this->_expire = isset($expire) ? (int) $expire : (time() + self::DEFAULT_TIMEOUT);
$this->setPath($path);
$this->_domain = $_SERVER['SERVER_NAME'];
$this->_salt = Gen_Http_Security::generateSalt();
$this->read();
}
public function setExpire($expire)
{
$this->_expire = (int) $expire;
if(isset($this->_data)) {
$this->write();
}
}
public function setPath($path)
{
$path = trim(self::$baseUrl .$path, '/\\').'/';
if ($path{0} != '/') $path = '/'.$path;
$path = rawurlencode($path);
$path = str_replace('%2F', '/', $path);
$path = str_replace('%7E', '~', $path);
$this->_path = $path;
}
public function setParam($key, $value)
{
if(preg_match('#¤|\|#', $key . $value)) {
require_once('Gen/Http/Exception.php');
throw new Gen_Http_Exception('Forbidden chars in cookie');
}
$this->_data[$key] = $value;
$this->write();
}
public function getParam($key, $default = null)
{
return isset($this->_data[$key]) ? $this->_data[$key] : $default;
}
public function unsetParam($key)
{
$value = null;
if(isset($this->_data[$key])) {
$value = $this->_data[$key];
unset($this->_data[$key]);
}
$this->write();
return $value;
}
public function setArray($key, array $data)
{
$this->setParam($key, serialize($data));
return $this;
}
public function getArray($key)
{
return unserialize($this->getParam($key));
}
public function write()
{
if (empty($this->_data)) {
return $this->reset();
}
$content = null;
$this->_data['salt'] = $this->_salt;
unset($this->_data['token']);
foreach($this->_data as $key => $value)
{
$content .= $key . self::SEPARATOR_KEY . $value . self::SEPARATOR_DATA;
}
$content .= 'token' . self::SEPARATOR_KEY . Gen_Http_Security::generateToken($content);
if(!setcookie($this->_name, $content, $this->_expire, $this->_path, $this->_domain, 0, true)) {
throw new Exception('Unable to set cookie for domain ' . $this->_domain);
}
return $this;
}
public function read()
{
$this->_data = array();
if (isset($_COOKIE[$this->_name]))
{
$content = substr($_COOKIE[$this->_name], 0, strpos($_COOKIE[$this->_name], 'token'));
$params = explode(self::SEPARATOR_DATA, $_COOKIE[$this->_name]);
foreach($params as $param)
{
$parts = explode(self::SEPARATOR_KEY, $param);
$this->_data[$parts[0]] = $parts[1];
}
if (isset($this->_data['token']) && Gen_Http_Security::validateToken($content, $this->_data['token'])) {
return true;
}
$this->reset();
return false;
}
return true;
}
public function reset()
{
unset($this->_data);
$this->_data = array();
setcookie($this->_name, false, time() - 3600, $this->_path, $this->_domain, 0, true);
unset($_COOKIE[$this->_name]);
return true;
}
}
<?php
/** @see Gen_Exception */
require_once ('Gen/Exception.php');
/**
* @category Gen
* @package Gen_Http
*/
class Gen_Http_Exception extends Gen_Exception
{
}
<?php
/**
* @category Gen
* @package Gen_Http
*/
class Gen_Http_Request
{
/**
* Http Version
*/
const VERSION = 'HTTP/1.1';
const USER_AGENT = 'Gen_Http_Request';
const CONNECT_TIME_OUT = 120;
const TIME_OUT = 120;
/**
* Make an HTTP request
*
* @return an array["http_info", "http_code", "reponse"]
*/
public static function send($url, $method, $params = array(), $verifySSL = false, $httpHeader=array())
{
$http_info = array();
$httpHeader = array_merge($httpHeader, array('Expect:'));
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_USERAGENT, self::USER_AGENT);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, self::CONNECT_TIME_OUT);
curl_setopt($ci, CURLOPT_TIMEOUT, self::TIME_OUT);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ci, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $verifySSL);
curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, $verifySSL ? 2 : 0);
//curl_setopt($ci, CURLOPT_HEADERFUNCTION, "Gen_Http_Request::getHeader");
curl_setopt($ci, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ci, CURLINFO_HEADER_OUT , true);
switch ($method) {
case 'POST':
curl_setopt($ci, CURLOPT_POST, true);
if (is_array($params) && count($params)) $params = http_build_query($params);
if ($params) curl_setopt($ci, CURLOPT_POSTFIELDS, $params);
break;
case 'DELETE':
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
$url = self::buildUrl($url, $params);
break;
case 'GET':
default:
$url = self::buildUrl($url, (array) $params);
break;
}
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
$http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$http_info = array_merge($http_info, curl_getinfo($ci));
curl_close ($ci);
return array (
'info' => $http_info,
'status' => $http_code,
'response' => $response
);
}
/**
* Get the header info to store.
*/
public static function getHeader($ch, $header) {
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
}
return strlen($header);
}
/**
*
* @param string $url
* @param array $params
*/
public static function buildUrl($url, array $params = array(), $anchor = null)
{
$urlInfos = parse_url($url);
$urlParams = array();
if (isset($urlInfos['query'])) {
parse_str($urlInfos['query'], $urlParams);
}
$params = array_merge($urlParams, $params);
return
(isset($urlInfos['scheme']) ? $urlInfos['scheme'].'://' : '')
.(isset($urlInfos['host']) ? $urlInfos['host'] : '')
.(isset($urlInfos['path']) ? $urlInfos['path'] : '')
.(count($params) ? ('?' . http_build_query($params)) : '')
.($anchor ? '#'.$anchor : '');
}
public static function parseUrl($url)
{
$response = self::send($url, 'GET');
if($response['status'] == 200) {
return $response['response'];
}
return false;
}
}
<?php
/**
* An Http Response Header Message
*
* for more details please see:
*
* Hypertext Transfer Protocol -- HTTP/1.1
* @link http://www.w3.org/Protocols/rfc2616/rfc2616.html
*
* An Http Response is composed of a Header and a Body
* Gen_Http_Response enable to set both
*
* use {@link send()} to send the response to the Client
* send() just makes use of sendHeaders() and outputBody()
*
* it implements an helper function {@link redirectUrl()}
* to redirect a Request to another url
*
* @category Gen
* @package Gen_Http
*/
class Gen_Http_Response
{
/**
* Http Version
*/
const VERSION = 'HTTP/1.1';
/**
* The Response Status Code
* defaulted to 200 OK
*/
protected $_statusCode = 200;
/**
* Response Filename
* used to output a file
*/
protected $_file = null;
protected $_format = 'html';
public static $_httpStatus = array
(
100 => 'Continue',
101 => 'Switching Protocols',
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found',
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
307 => 'Temporary Redirect',
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Time-out',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Large',
415 => 'Unsupported Media Type',
416 => 'Requested range not satisfiable',
417 => 'Expectation Failed',
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Time-out',
505 => 'HTTP Version not supported'
);
/**
* Response Headers
*/
/** general header fields */
const CACHE_CONTROL = 'Cache-Control';
const CONNECTION = 'Connection';
const DATE = 'Date';
const PRAGMA = 'Pragma';
const TRAILER = 'Trailer';
const TRANSFER_ENCODING = 'Transfer-Encoding';
const UPGRADE = 'Upgrade';
const VIA = 'Via';
const WARNING = 'Warning';
/** response header fields */
const ACCEPT_RANGES = 'Accept-Ranges';
const AGE = 'Age';
const ETAG = 'ETag';
const LOCATION = 'Location';
const PROXY_AUTHENTICATE = 'Proxy-Authenticate';
const RETRY_AFTER = 'Retry-After';
const SERVER = 'Server';
const VARY = 'Vary';
const WWW_AUTHENTICATE = 'WWW-Authenticate';
/** entity header fields */
const ALLOWED = 'Allow';
const CONTENT_ENCODING = 'Content-Encoding';
const CONTENT_LANGUAGE = 'Content-Language';
const CONTENT_LENGTH = 'Content-Length';
const CONTENT_LOCATION = 'Content-Location';
const CONTENT_MD5 = 'Content-MD5';
const CONTENT_RANGE = 'Content-Range';
const CONTENT_TYPE = 'Content-Type';
const CONTENT_DISPOSITION = 'Content-Disposition';
const EXPIRES = 'Expires';
const LAST_MODIFIED = 'Last-Modified';
const TITLE = 'Title';
/**
* The Headers values available to be sent
* @var array
*/
protected $_headers = array
(
self::CACHE_CONTROL => '',
self::CONNECTION => '',
self::DATE => '',
self::PRAGMA => '',
self::DATE => '',
self::LOCATION => '',
self::SERVER => '',
self::CONTENT_LENGTH => '',
self::CONTENT_LANGUAGE => '',
self::CONTENT_TYPE => 'text/html; charset=utf-8',
self::CONTENT_DISPOSITION => '',
self::EXPIRES => '',
self::LAST_MODIFIED => '',
self::TITLE => ''
);
/**
* The Response Body
* @var array
*/
protected $_body = array();
public function setFormat($format)
{
switch($format)
{
case 'xml':
case 'rss':
case 'excel':
case 'csv':
$this->setContentType('text/xml; charset=utf-8');
break;
case 'jpeg':
case 'jpg':
$this->setContentType('image/jpeg');
break;
case 'png':
$this->setContentType('image/pgn');
break;
case 'gif':
$this->setContentType('image/gif');
break;
case 'json':
$this->setContentType('application/json; charset=utf-8');
break;
case 'txt':
$this->setContentType('text/plain; charset=utf-8');
break;
case 'ajax':
case 'html':
$this->setContentType('text/html; charset=utf-8');
break;
default:
throw new Exception("Unknown format `".$format."` in Gen_Http_Response::setFormat.");
break;
}
$this->_format = $format;
return $this;
}
public function getFormat()
{
return $this->_format;
}
public function isJson()
{
return $this->_format == 'json';
}
/**
* Sets the Status Code
*
* must be a valid status
* @return Gen_Http_Response
*/
public function setStatusCode($statusCode)
{
$statusCode = (int) $statusCode;
if(isset(self::$_httpStatus[$statusCode])) {
$this->_statusCode = $statusCode;
} else {
throw new Exception(
"Try to set invalid status: $statusCode in Gen_Http_Response::setStatusCode()"
);
}
return $this;
}
/**
* Returns the Status Code
*
* @return string
*/
public function getStatusCode()
{
return $this->_statusCode;
}
/** @alias for getStatusCode() */
public function getStatus() { return $this->getStatusCode(); }
/**
* Builds a Status-Line
*
* example: HTTP/1.1 404 Not Found
*
* @return string
*/
public function getStatusLine()
{
return self::VERSION . ' ' . $this->_statusCode . ' ' . self::$_httpStatus[$this->_statusCode];
}
public function setFile($file)
{
if (!file_exists($file)) {
return $this->notFound('File not found : ' . $file);
}
$this->_file = $file;
$fileName = basename($file);
$this->setHeader(self::TITLE, $fileName);
$this->setContentLength(filesize($file));
$this->setLastModified(filemtime($file));
return $this;
}
public function setHeader($key, $value)
{
$key = (string) $key;
$value = (string) $value;
if (isset($this->_headers[$key])) {
/** prevent header injections
* CRLF not authorized in Http1.1 specifications
*/
$value = str_replace("\n", '' ,$value);
$value = str_replace("\r", '' ,$value);
$this->_headers[$key] = $value;
} else {
throw new Exception(
"Trying to set unsupported header: $key in Gen_Http_Response::setHeader()"
);
}
return $this;
}
public function setContentType($contentType)
{
$this->setHeader(self::CONTENT_TYPE, (string) $contentType);
return $this;
}
public function setContentLanguage($contentLanguage)
{
$this->setHeader(self::CONTENT_LANGUAGE, (string) $contentLanguage);
return $this;
}
public function setContentLength($contentLength)
{
$this->setHeader(self::CONTENT_LENGTH, (string) $contentLength);
return $this;
}
public function setExpires($timestamp)
{
$this->setHeader(self::EXPIRES, gmdate('D, d M Y H:i:s \G\M\T', $timestamp));
}
public function setLastModified($timestamp)
{
$this->setHeader(self::LAST_MODIFIED, gmdate('D, d M Y H:i:s \G\M\T', $timestamp));
}
public function isSent()
{
return headers_sent();
}
public function sendHeaders()
{
if (!$this->isSent()) {
/** send status line */
header($this->getStatusLine());
foreach ($this->_headers as $key => $value) {
$header = $value ? "$key: $value" : null;
/** send header fields only if set */
if ($header) {
header($header);
}
}
}
return $this;
}
/**
* Gets the Response body
* @return array
*/
public function getBody()
{
return $this->_body;
}
public function setBody(array $body)
{
$this->_body = $body;
return $this;
}
public function resetBody()
{
unset($this->_body);
$this->_body = array();
return $this;
}
public function appendBody($content)
{
$this->_body[] = $content;
return $this;
}
public function prependBody($content)
{
array_unshift($this->_body, $content);
return $this;
}
public function outputBody()
{
switch(true)
{
case $this->_file :
$this->outputFile();
break;
default :
echo $this->__toString();
break;
}
}
public function outputFile()
{
ob_clean();
flush();
readfile($this->_file);
}
public function send()
{
$this->sendHeaders();
$this->outputBody();
}
public function reset()
{
$this->resetBody();
return $this;
}
public function redirect($url)
{
$this->setStatusCode(302);
$this->setHeader(self::LOCATION, $url);
return $this;
}
public function permanentRedirect($url)
{
$this->setStatusCode(301);
$this->setHeader(self::LOCATION, $url);
return $this;
}
public function error($message = null)
{
$this->reset();
$this->setStatusCode(500); //500 Internal error
$this->appendBody((string) $message);
return $this;
}
public function notFound($message = null)
{
$this->reset();
$this->setStatusCode(404); //404 Not Found
$this->appendBody((string) $message);
return $this;
}
public function unauthorized($message = null)
{
$this->reset();
$this->setStatusCode(401); //401 Unauthorized Acces
$this->appendBody((string) $message);
return $this;
}
public function timeout($message = null)
{
$this->reset();
$this->setStatusCode(408); //408 Request Time-out
$this->appendBody((string) $message);
return $this;
}
public function badRequest($message = null)
{
$this->reset();
$this->setStatusCode(400); //400 Bad Request
$this->appendBody((string) $message);
return $this;
}
public function methodNotAllowed($message = null)
{
$this->reset();
$this->setStatusCode(405); //405 Method not allowed
$this->appendBody((string) $message);
return $this;
}
public function __toString()
{
return implode("\n", $this->_body);
}
}
<?php
class Gen_Http_Security
{
const DATA_SEPARATOR = '¤';
const KEY_SEPARATOR = '|';
public static $seed = 'AFg65-Tio89-3vbjU-I3n9d-D4577-GH56i';
public static $salt = '1y5E6-k8F8l-79mG6-Hss56-JfHg3-2gBNu';
const DEFAULT_TIMEOUT = 600; // 10 min * 60s
public static function generateSalt()
{
return md5(self::$salt . microtime() . rand());
}
public static function generateToken($params)
{
if (is_array($params)) {
ksort($params);
$str = null;
foreach ($params as $key => $value) {
$str .= $key . self::KEY_SEPARATOR . $value . self::DATA_SEPARATOR;
}
$params = rtrim($str, self::DATA_SEPARATOR);
}
$token = md5(self::$seed . $params);
return $token;
}
public static function validateToken($params, $challenge) {
$token = self::generateToken($params);
if ($token === $challenge) {
return true;
}
return false;
}
public static function sign($params)
{
$params = (array) $params;
$params['salt'] = self::generateSalt();
$params['exectime'] = time();
$params['token'] = self::generateToken($params);
return $params;
}
public static function verify(array $params, $timeout = self::DEFAULT_TIMEOUT)
{
return self::verifyToken($params) && self::verifyTimeout($params, $timeout);
}
public static function verifyToken(array $params)
{
if(!isset($params['token'])) {
return false;
}
$token = $params['token'];
unset($params['token']);
return self::validateToken($params, $token);
}
public static function verifyTimeout(array $params, $timeout = self::DEFAULT_TIMEOUT)
{
if (isset($params['exectime']) && (time() - $params['exectime'] > $timeout)) {
return false;
}
return true;
}
}
<?php
class Gen_Http_Url
{
protected $_data = array();
protected $_params = array();
public function __construct($url)
{
$this->_data = parse_url($url);
if(isset($this->_data['query'])) {
parse_str($this->_data['query'], $params);
$this->_params = $params;
}
}
protected function _getData($key, $default = null)
{
return isset($this->_data[$key]) ? $this->_data[$key] : $default;
}
public function getParam($key, $default = null)
{
return isset($this->_params[$key]) ? $this->_params[$key] : $default;
}
public function getHost($default = null)
{
return $this->_getData('host', $default);
}
public function getPath($default = null)
{
return $this->_getData('path', $default);
}
public function isYoutube()
{
return ($this->getHost() == 'www.youtube.com');
}
}
<?php
class Gen_Image_Base {
const FORMAT_BMP = 'bmp';
const FORMAT_GIF = 'gif';
const FORMAT_JPEG = 'jpeg';
const FORMAT_PNG = 'png';
public static $fontDir;
protected static $_supported_formats = array(
self::FORMAT_BMP, self::FORMAT_GIF, self::FORMAT_JPEG, self::FORMAT_PNG
);
protected static $imagick = null;
protected static $gd = null;
public static function hasGd()
{
if (self::$gd === null) {
self::$gd = extension_loaded('gd');
}
return self::$gd;
}
public static function hasImagick()
{
if (self::$imagick === null) {
self::$imagick = extension_loaded('imagick');
}
return self::$imagick;
}
public static function getHeight($image)
{
if (self::hasImagick()) {
$height = $image->getImageHeight();
} elseif (self::hasGd()) {
$height = imagesy($image);
}
return $height;
}
public static function getWidth($image)
{
if (self::hasImagick()) {
$width = $image->getImageWidth();
} elseif (self::hasGd()) {
$width = imagesx($image);
}
return $width;
}
public static function create($filePath)
{
if (!file_exists($filePath)) {
return false;
}
if (self::hasImagick()) {
$image = new Imagick();
$image->readImage($filePath);
} elseif (self::hasGd()) {
$imageInfo = getimagesize($filePath);
if ($imageInfo === false) return false;
switch ($imageInfo['mime']) {
case 'image/bmp':
$image = self::imageCreateFromBmp($filePath);
break;
case 'image/gif':
$image = imagecreatefromgif($filePath);
break;
case 'image/jpeg':
$image = imagecreatefromjpeg($filePath);
break;
case 'image/png':
$image = imagecreatefrompng($filePath);
break;
default:
return false;
}
$exif = exif_read_data($filePath);
Gen_Log::log($exif);
throw new Exception('stop');
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, -90, 0);
break;
case 8:
$image = imagerotate($image, 90, 0);
break;
}
}
}
return $image;
}
public static function write($image, $filePath, $format, $quality = 90, $destroy = true)
{
$success = false;
$dir = dirname($filePath);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
if (self::hasImagick()) {
$image->setImageFormat(strtoupper($format));
if ($format == self::FORMAT_JPEG) {
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality($quality);
}
$success = $image->writeImage($filePath);
} elseif (self::hasGd()) {
switch ($format) {
case self::FORMAT_JPEG:
$success = imageJpeg($image, $filePath, $quality);
break;
case self::FORMAT_PNG:
$success = imagepng($image, $filePath, $quality);
break;
case self::FORMAT_GIF:
$success = imagegif($image, $filePath);
break;
default:
break;
}
}
if ($destroy) {
self::destroy($image);
}
return $success;
}
public static function destroy($image)
{
if (self::hasImagick()) {
$image->destroy();
} elseif (self::hasGd()) {
imageDestroy($image);
}
return true;
}
public static function resize($image0, $width, $height)
{
if (self::hasImagick()) {
$image = $image0->clone();
$image->cropThumbnailImage($width, $height);
} elseif (self::hasGd()) {
$dr = $height/$width;
$sw = imagesx($image0);
$sh = imagesy($image0);
if ($sw == 0) return false;
$sr = $sh / $sw;
$image = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($image, 255, 255, 255);
imagefill($image, 0, 0, $white);
if ($sr == $dr) {
$dx = $dy = 0;
$rw = $width;
$rh = $height;
} elseif ($sr > $dr) {
$rw = $width;
$rh = intval($sr * $rw);
$dy = intval(($height - $rh) / 2);
$dx = 0;
} else {
$rh = $height;
$rw = intval($rh / $sr);
$dx = intval(($width - $rw) / 2);
$dy = 0;
}
imagecopyresampled($image, $image0, $dx, $dy, 0, 0, $rw, $rh, $sw, $sh);
}
return $image;
}
//Utility ? Currently unused
public static function imageCopyResampledBicubic(&$dst_image, &$src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
$rX = $src_w / $dst_w;
$rY = $src_h / $dst_h;
if ($rX < 1 && $rY < 1) {
return imagecopyresized($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
}
// we should first cut the piece we are interested in from the source
$src_img = imagecreatetruecolor($src_w, $src_h);
imagecopy($src_img, $src_image, 0, 0, $src_x, $src_y, $src_w, $src_h);
// this one is used as temporary image
$dst_img = imagecreatetruecolor($dst_w, $dst_h);
imagepalettecopy($dst_img, $src_img);
$w = 0;
for ($y = 0; $y < $dst_h; $y++) {
$ow = $w; $w = round(($y + 1) * $rY);
$t = 0;
for ($x = 0; $x < $dst_w; $x++) {
$r = $g = $b = 0; $a = 0;
$ot = $t; $t = round(($x + 1) * $rX);
for ($u = 0; $u < $w - $ow; $u++) {
for ($p = 0; $p < $t - $ot; $p++) {
$c = imagecolorsforindex($src_img, imagecolorat($src_img, $ot + $p, $ow + $u));
$r += $c['red'];
$g += $c['green'];
$b += $c['blue'];
$a++;
}
}
if($a) {
imagesetpixel($dst_img, $x, $y, imagecolorclosest($dst_img, $r / $a, $g / $a, $b / $a));
}
}
}
// apply the temp image over the returned image and use the destination x,y coordinates
imagecopy($dst_image, $dst_img, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h);
// we should return true since ImageCopyResampled/ImageCopyResized do it
return true;
}
/**
* Creates a bmp image ressource from a filename
* credit to alexander@alexauto.nl
* script found on http://www.php.net
*/
public static function imageCreateFromBmp($fileName)
{
// Load the image into a string
$file = fopen($fileName,"rb");
$read = fread($file,10);
while (!feof($file) && ($read<>"")) {
$read .= fread($file,1024);
}
$temp = unpack("H*", $read);
$hex = $temp[1];
$header = substr($hex, 0, 108);
// Process the header
// Structure: http://www.fastgraph.com/help/bmp_header_format.html
if (substr($header, 0, 4) == "424d") {
// Cut it in parts of 2 bytes
$header_parts = str_split($header, 2);
// Get the width 4 bytes
$width = hexdec($header_parts[19].$header_parts[18]);
// Get the height 4 bytes
$height = hexdec($header_parts[23].$header_parts[22]);
// Unset the header params
unset($header_parts);
}
// Define starting X and Y
$x = 0;
$y = 1;
// Create newimage
$image = imagecreatetruecolor($width,$height);
// Grab the body from the image
$body = substr($hex,108);
// Calculate if padding at the end-line is needed
// Divided by two to keep overview.
// 1 byte = 2 HEX-chars
$body_size = (strlen($body)/2);
$header_size = ($width * $height);
// Use end-line padding? Only when needed
$usePadding = ($body_size > ($header_size * 3) +4);
/**
* Using a for-loop with index-calculation instead of str_split
* to avoid large memory consumption
* Calculate the next DWORD-position in the body
*/
for ($i=0; $i < $body_size; $i += 3) {
// Calculate line-ending and padding
if ($x >= $width) {
// If padding needed, ignore image-padding
// Shift i to the ending of the current 32-bit-block
if ($usePadding) {
$i += $width%4;
}
// Reset horizontal position
$x = 0;
// Raise the height-position (bottom-up)
$y++;
// Reached the image-height? Break the for-loop
if ($y > $height) {
break;
}
}
// Calculation of the RGB-pixel (defined as BGR in image-data)
// Define $i_pos as absolute position in the body
$i_pos = $i*2;
$r = hexdec($body[$i_pos+4].$body[$i_pos+5]);
$g = hexdec($body[$i_pos+2].$body[$i_pos+3]);
$b = hexdec($body[$i_pos].$body[$i_pos+1]);
// Calculate and draw the pixel
$color = imagecolorallocate($image, $r, $g, $b);
imagesetpixel($image, $x, $height-$y, $color);
// Raise the horizontal position
$x++;
}
// Unset the body / free the memory
unset($body);
// Return image-object
return $image;
}
}
<?php
require_once('Gen/Image/Interface.php');
class Gen_Image_Gd implements Gen_Image_Interface
{
public static function getHeight($image)
{
$height = imagesy($image);
}
public static function getWidth($image)
{
$width = imagesx($image);
}
public static function getFormat($filePath)
{
$imageInfo = getimagesize($filePath);
if ($imageInfo === false) {
return false;
}
switch ($imageInfo['mime'])
{
case 'image/gif':
return 'gif';
break;
case 'image/jpeg':
return 'jpg';
break;
case 'image/png':
return 'png';
break;
}
return false;
}
public static function create($filePath)
{
if (!file_exists($filePath)) {
return false;
}
$imageInfo = getimagesize($filePath);
if ($imageInfo === false) {
return false;
}
switch ($imageInfo['mime']) {
case 'image/gif':
$image = imagecreatefromgif($filePath);
break;
case 'image/jpeg':
$image = imagecreatefromjpeg($filePath);
break;
case 'image/png':
$image = imagecreatefrompng($filePath);
break;
default:
throw new Exception('Unsupported image format in Gen_Image_Gd::create');
return false;
}
$exif = exif_read_data($filePath);
if (!empty($exif['Orientation'])) {
switch ($exif['Orientation']) {
case 3:
$image = imagerotate($image, 180, 0);
break;
case 6:
$image = imagerotate($image, -90, 0);
break;
case 8:
$image = imagerotate($image, 90, 0);
break;
}
}
return $image;
}
public static function write($image, $filePath, $format, $quality = 90, $destroy = true)
{
$result = false;
$dir = dirname($filePath);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
switch ($format) {
case 'jpg':
case 'jpeg':
/** flattern image on white background for PGN **/
$width = imagesx($image);
$height = imagesy($image);
$tmp = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($tmp, 255, 255, 255);
imagefill($tmp, 0, 0, $white);
imagecopyresampled($tmp, $image, 0, 0, 0, 0, $width, $height, $width, $height);
$result = imagejpeg($tmp, $filePath, $quality);
break;
case 'png':
$quality = round(9*(1 - $quality/100));
imagesavealpha($image,true);
$result = imagepng($image, $filePath, $quality);
break;
case 'gif':
$result = imagegif($image, $filePath);
break;
default:
throw new Exception('Unsupported image format in Gen_Image_Gd::create');
break;
}
if ($destroy) {
imageDestroy($image);
}
return $result;
}
public static function render($image, $format, $quality = 90)
{
switch ($format) {
case 'jpg':
case 'jpeg':
header('Content-Type: image/jpeg');
$result = imagejpeg($image, null, $quality);
break;
case 'png':
header('Content-Type: image/png');
$quality = round(9*(1 - $quality/100));
$result = imagepng($image, null, $quality);
break;
case 'gif':
header('Content-Type: image/gif');
$result = imagegif($image, null);
break;
default:
require_once('Gen/Log.php');
Gen_Log::log('Unsupported image format', 'Gen_Image_Gd::write', 'warning');
$result = false;
break;
}
imageDestroy($image);
return $result;
}
public static function destroy($image)
{
return imageDestroy($image);
}
public static function crop($image, $width, $height = null, $x = null, $y = null)
{
$height = ($height === null) ? $width : $height;
$sw = imagesx($image);
$sh = imagesy($image);
$sx = ($x === null) ? round(($sw - $width)/2) : $x;
$sy = ($y === null) ? round(($sh - $height)/2) : $y;
$dx = $dy = 0;
$crop = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($crop, 255, 255, 255);
imagefill($crop, 0, 0, $white);
imagecopyresampled($crop, $image, $dx, $dy, $sx, $sy, $width, $height, $width, $height);
return $crop;
}
public static function resize($image, $width, $height = null)
{
$sw = imagesx($image);
$sh = imagesy($image);
if($sh == 0 || $sw == 0) {
return false;
}
$sr = round($sh/$sw, 2);
$width = (int) $width;
$height = ($height === null) ? round($width * $sr) : $height;
$dr = round($height/$width, 2);
if($sr < $dr) {
$dw = $width;
$dh = round($sr * $dw);
$dy = round(($height - $dh) / 2);
$dx = 0;
} elseif($sr > $dr) {
$dh = $height;
$dw = round($dh / $sr);
$dx = round(($width - $dw) / 2);
$dy = 0;
} else {
$dx = $dy = 0;
$dw = $width;
$dh = $height;
}
$sx = $sy = 0;
$resize = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($resize, 255, 255, 255);
imagefill($resize, 0, 0, $white);
imagecopyresampled($resize, $image, $dx, $dy, $sx, $sy, $dw, $dh, $sw, $sh);
return $resize;
}
public static function thumb($image, $width, $height = null)
{
if(null === $height) {
$height = $width;
}
$dr = round($height/$width, 2);
$sw = imagesx($image);
$sh = imagesy($image);
if ($sw == 0) {
return false;
}
$sr = round($sh/$sw, 2);
$thumb = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($thumb, 255, 255, 255);
imagefill($thumb, 0, 0, $white);
if ($sr == $dr) {
$dx = $dy = 0;
$rw = $width;
$rh = $height;
} elseif ($sr > $dr) {
$rw = $width;
$rh = round($sr * $rw);
$dy = round(($height - $rh) / 2);
$dx = 0;
} else {
$rh = $height;
$rw = round($rh / $sr);
$dx = round(($width - $rw) / 2);
$dy = 0;
}
imagecopyresampled($thumb, $image, $dx, $dy, 0, 0, $rw, $rh, $sw, $sh);
return $thumb;
}
public static function createFromText($text, $width = 400, $height=null, $color=null)
{
$colors = array(
array('r' => 255, 'g' => 50, 'b' => 55), //'Youtube Red'
array('r' => 41, 'g' => 185, 'b' => 238), // Blue
array('r' => 255, 'g' => 238, 'b' => 98), // Yellow
array('r' => 180, 'g' => 255, 'b' => 0), // Green
array('r' => 240, 'g' => 28, 'b' => 228), // Purple
);
if($height === null) {
$height = $width;
}
if($color === null) {
$color = $colors[rand(0,count($colors)-1)];
}
/** clean text **/
$text = mb_strtoupper(str_replace(array(',', ':', ';', '-', '_'), ' ', $text));
$text = preg_replace('@ +@', ' ', $text);
/** params */
$font = realpath(dirname(__FILE__)).'/font/GothamBook.ttf';
$charCount = strlen($text);
$maxCharCount = round($width / round(sqrt($width * $height / $charCount)));
$xMargin = 0.05 * $width;
$yMargin = 0.05 * $height;
/** compute lines **/
$lines = array();
$line = '';
foreach(explode(' ', $text) as $word) {
$line .= ($line ? ' ' : '') . $word;
if(strlen($line) <= $maxCharCount) {
continue;
}
$lines[] = $line;
$line = '';
}
if($line != '') {$lines[] = $line;}
/** determine word width & height **/
$wordCount = count($lines);
$maxWordHeight = ($height - ($wordCount + 1) *$yMargin)/$wordCount;
$maxWordWidth = $width - 2 * $xMargin;
$defaultFontSize = $maxWordHeight/0.97; // default font fits height
$angle = 0;
$img = imagecreatetruecolor($width, $height);
$background_color = imagecolorallocate($img, $color['r'], $color['g'], $color['b']);
imagefill($img, 0, 0, $background_color);
$textColor = imagecolorallocate($img, 255, 255, 255);
$results = array();
$totalHeight = 0;
foreach($lines as $i => $word)
{
/** try width default font **/
$word = trim($word);
$box = @imageTTFBbox($defaultFontSize,$angle,$font,$word);
$textWidth = abs($box[2] - $box[0]);
$textHeight = abs($box[5] - $box[1]);
/** if the width is to large, resize **/
$fontSize = $defaultFontSize;
if($textWidth > $maxWordWidth) {
$fontSize = $defaultFontSize * $maxWordWidth / $textWidth;
$box = @imageTTFBbox($fontSize,$angle,$font,$word);
$textWidth = abs($box[2] - $box[0]);
$textHeight = abs($box[5] - $box[1]);
}
$x = ($width - $textWidth)/2; // center the word
$totalHeight += $yMargin + $textHeight; // keep track of height for next word
$results[] = array('x' => $x, 'width' => $textWidth, 'height' => $textHeight, 'font_size' => $fontSize, 'text' => $word);
}
//$borderColor = imagecolorallocate($img, 255, 0, 0);
$y = ($height - $totalHeight + $yMargin)/2;
foreach ($results as $i => $row) {
//imagerectangle($img, $row['x'], $y, $row['x'] + $row['width'], $y + $row['height'], $borderColor);
$y += $row['height'];
imagettftext($img, $row['font_size'], $angle, $row['x']-0.05*$row['font_size'], $y, $textColor, $font, $row['text']);
$y += $yMargin;
}
return $img;
}
}
<?php
require_once('Gen/Image/Interface.php');
class Gen_Image_Imagick implements Gen_Image_Interface
public static function getHeight($image)
{
return $image->getImageHeight();
}
public static function getWidth($image)
{
return $image->getImageWidth();
}
public static function create($filePath)
{
if (!file_exists($filePath)) {
return false;
}
$image = new Imagick();
$image->readImage($filePath);
return $image;
}
public static function write($image, $filePath, $format, $quality = 90, $destroy = true)
{
$dir = dirname($filePath);
if (!file_exists($dir)) {
mkdir($dir, 0777, true);
}
$image->setImageFormat(strtoupper($format));
if ($format == 'jpeg' || $format == 'jpg') {
$image->setImageCompression(Imagick::COMPRESSION_JPEG);
$image->setImageCompressionQuality($quality);
}
$result = $image->writeImage($filePath);
if ($destroy) {
$image->destroy();
}
return $result;
}
public static function render($image, $format, $quality = 90)
{
switch ($format) {
case 'jpg':
case 'jpeg':
header('Content-Type: image/jpeg');
echo $image;
break;
case 'png':
header('Content-Type: image/png');
echo $image;
break;
case 'gif':
header('Content-Type: image/gif');
echo $image;
break;
default:
require_once('Gen/Log.php');
Gen_Log::log('Unsupported image format', 'Gen_Image_Gd::write', 'warning');
$image->destroy();
return false;
break;
}
$image->destroy();
return true;
}
public static function destroy($image)
{
return $image->destroy();
}
public static function crop($image, $width, $height = null, $x = null, $y = null)
{
$height = (null === $height) ? $width : $height;
$sw = $image->getImageWidth();
$sh = $image->getImageHeight();
$x = ($x === null) ? intval(($sw - $width)/2) : $x;
$y = ($y === null) ? intval(($sh - $height)/2) : $y;
$result = $image->clone();
$result->cropImage($width, $height, $x, $y);
return $result;
}
public static function resize($image, $width, $height = null)
{
$height = (null === $height) ? $width : $height;
$result = $image->clone();
$result->resizeImage($width, $height);
return $result;
}
public static function thumb($image, $width, $height = null)
{
$height = (null === $height) ? $width : $height;
$result = $image->clone();
$result->cropThumbnailImage($width, $height);
return $result;
}
}
<?php
interface Gen_Image_Interface {
public static function getHeight($image);
public static function getWidth($image);
public static function create($filePath);
public static function write($image, $filePath, $format, $quality = 90, $destroy = true);
public static function destroy($image);
public static function thumb($image, $width, $height = null);
public static function crop($image, $width, $height = null, $x = null, $y = null);
public static function resize($image, $width, $height = null);
}
<?php
require_once ('Gen/Oauth/Consumer.php');
require_once ('Oauth/OAuth.php');
require_once ('Gen/Http/Request.php');
class Gen_Oauth_AlternOauth extends Gen_Oauth_Consumer{
/* @var OAuth object */
private $_consumer;
/* @var object OAuthSignatureMethod */
private $_signMethod;
/* @var string Contains the last HTTP status code returned. */
public $http_code;
/* @var string Contains the last HTTP headers returned. */
public $http_info;
/* Set timeout default. */
public $timeout = 30;
/* Set connect timeout. */
public $connecttimeout = 30;
/* Verify SSL Cert. */
public $ssl_verifypeer = FALSE;
/* Set the useragnet. */
public $useragent = 'genesis';
function __construct($consumerKey, $consumerSecret, $authType = self::PIMP_OAUTH_AUTH_TYPE_AUTHORIZATION){
if(!class_exists('OAuthConsumer'))
throw new Exception("La classe OAuthConsumer n'existe pas");
$this->_consumer = new OAuthConsumer($consumerKey,$consumerSecret);
}
public function setOauthVersion($version){
$this->oauthVersion = $version;
}
public function setNonce($nonce){
$this->nonce = $nonce;
}
public function setSignatureMethod($signatureMethod){
//manage the signature method;
switch ($signatureMethod) {
case self::PIMP_OAUTH_SIGN_METH_HMAC_SHA1:
$this->_signMethod = new OAuthSignatureMethod_HMAC_SHA1();
break;
case self::PIMP_OAUTH_SIGN_METH_PLAINTEXT:
$this->_signMethod = new OAuthSignatureMethod_RSA_SHA1();
break;
case self::PIMP_OAUTH_SIGN_METH_RSA_SHA1:
$this->_signMethod = new OAuthSignatureMethod_PLAINTEXT();
break;
default:
throw new OAuthException("Signature not known");
}
}
/**
* Get a request_token from Twitter
*
* @returns a key/value array containing oauth_token and oauth_token_secret
*/
public function getRequestToken($requestTokenUrl,$callbackUrl){
$parameters = array();
if (!empty($callbackUrl)) {
$parameters['oauth_callback'] = $callbackUrl;
}
$request = $this->oAuthRequest($requestTokenUrl, 'GET', NULL, $parameters);
$token = OAuthUtil::parse_parameters($request);
if($this->http_code != 200) {
throw new OAuthException(print_r(array($this->http_code,$token),true));
}
return $token;
}
/**
* Exchange request token and secret for an access token and
* secret, to sign API calls.
*
* @returns array("oauth_token" => "the-access-token",
* "oauth_token_secret" => "the-access-secret",
* "user_id" => "9436992",
* "screen_name" => "abraham")
*/
public function getAccessToken($accessTokenUrl,$requestToken,$requestTokenSecret,$verifiedToken){
$parameters = array();
if (!empty($verifiedToken)) {
$parameters['oauth_verifier'] = $verifiedToken;
}
$token = new OAuthConsumer($requestToken, $requestTokenSecret);
$request = $this->oAuthRequest($accessTokenUrl, 'GET', $token, $parameters);
$token = OAuthUtil::parse_parameters($request);
if($this->http_code != 200) {
throw new OAuthException(print_r(array($this->http_code,$token),true));
}
return $token;
}
/**
* get a OAuth protected resource
* Follow the REST definition of GET : http://en.wikipedia.org/wiki/Representational_State_Transfer
*/
public function fetch($action,$protectedResourceUrl,$accessToken,$accessTokenSecret,$properties=array()){
$token = new OAuthConsumer($accessToken, $accessTokenSecret);
$response = $this->oAuthRequest($protectedResourceUrl, $action, $token, $properties);
if($this->http_code != 200) {
throw new OAuthException(print_r(array($this->http_code,$response),true));
}
return $response;
}
public function disableSSLChecks(){
$this->ssl_verifypeer = false;
}
public function enableSSLChecks(){
$this->ssl_verifypeer = true;
}
/**
* Format and sign an OAuth / API request
*/
private function oAuthRequest($url, $method, $token, $parameters) {
$request = OAuthRequest::from_consumer_and_token($this->_consumer, $token, $method, $url, $parameters);
$request->sign_request($this->_signMethod, $this->_consumer, $token);
switch ($method) {
case 'GET':
$httpRequest = Gen_Http_Request::send($request->to_url(), 'GET', array(), $this->ssl_verifypeer);
break;
default:
$httpRequest = Gen_Http_Request::send($request->get_normalized_http_url(), $method, $request->to_postdata(), $this->ssl_verifypeer);
break;
}
$this->http_info = $httpRequest['info'];
$this->http_code = $httpRequest['status'];
return $httpRequest['response'];
}
}
<?php
/**
* interface for Oauth consumer.
*
* This interface defines the method used to fetch some oauth protected data.
* This interface is an abstraction of oauth consumer method.
* @author Anthony BARRE
*/
abstract class Gen_Oauth_Consumer{
/****************************************************************************************************
SIGNATURE METHOD
****************************************************************************************************/
/**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
*/
const PIMP_OAUTH_SIGN_METH_HMAC_SHA1 = "HMACSHA1";
/**
* PLAINTEXT method does not provide any security protection and SHOULD only be used
* over a secure channel such as HTTPS.
*/
const PIMP_OAUTH_SIGN_METH_PLAINTEXT = "PLAINTEXT";
/**
* The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in [RFC3447]
*/
const PIMP_OAUTH_SIGN_METH_RSA_SHA1 = "RSA-SHA1";
/****************************************************************************************************
AUTH TYPE
****************************************************************************************************/
/**
* Passe les paramètres OAuth dans l'entête HTTP Authorization.
*/
const PIMP_OAUTH_AUTH_TYPE_AUTHORIZATION = "AUTHORIZATION";
/**
* Ajoute les paramètres OAuth au corps de la requête HTTP POST.
*/
const PIMP_OAUTH_AUTH_TYPE_FORM = "FORM";
/**
* Ajoute les paramètres OAuth à l'URI.
*/
const PIMP_OAUTH_AUTH_TYPE_URI = "URI";
public $oauthVersion = "1.0";
public $nonce;
/****************************************************************************************************
TOKEN HANDLER
****************************************************************************************************/
abstract public function __construct($consumerKey, $consumerSecret,$authType = self::PIMP_OAUTH_AUTH_TYPE_AUTHORIZATION);
/**
* use for the first stage of the process
* @param URL requestTokenUrl is given by the data server.
* @param optional URL callbackURL is the url where the user is redirected after the authorization
*/
abstract public function getRequestToken($requestTokenUrl,$callbackUrl);
/**
* use for the second stage of the process
*/
public function getAuthorizeURL($authorizeUrl, $requestToken){
return $authorizeUrl . "?oauth_token={$requestToken}";
}
/**
* use for the third stage of the process
* URL $access_token_url [, string $auth_session_handle [, string $verifier_token ]]
* @param URL accessTokenUrl is given by the data server.
*/
abstract public function getAccessToken($accessTokenUrl,$requestToken,$requestTokenSecret,$verifiedToken);
/****************************************************************************************************
DATA HANDLER
****************************************************************************************************/
/**
* fetch a OAuth protected resource
* Follow the REST definition of GET : http://en.wikipedia.org/wiki/Representational_State_Transfer
*/
abstract public function fetch($action,$protectedResourceUrl,$accessToken,$accessTokenSecret,$properties=array());
abstract public function disableSSLChecks();
abstract public function enableSSLChecks();
abstract public function setSignatureMethod($signatureMethod);
abstract public function setNonce($nonce);
abstract public function setOauthVersion($version);
}
<?php
require_once ('Gen/Oauth/Consumer.php');
class Gen_Oauth_PeclOauth extends Gen_Oauth_Consumer{
const PIMP_OAUTH_SIGN_METH_HMAC_SHA1 = OAUTH_SIG_METHOD_HMACSHA1;
/****************************************************************************************************
AUTH TYPE
****************************************************************************************************/
const PIMP_OAUTH_AUTH_TYPE_AUTHORIZATION = OAUTH_AUTH_TYPE_AUTHORIZATION;
const PIMP_OAUTH_AUTH_TYPE_FORM = OAUTH_AUTH_TYPE_FORM;
const PIMP_OAUTH_AUTH_TYPE_URI = OAUTH_AUTH_TYPE_URI;
/**
* @var OAuth object
*/
private $_oauth;
function __construct($consumerKey, $consumerSecret,$authType = self::PIMP_OAUTH_AUTH_TYPE_AUTHORIZATION){
if(!class_exists('OAuth'))
throw new Exception("La classe OAuth n'existe pas");
//only HMAC_SHA1 is supported
$this->_oauth = new OAuth($consumerKey,$consumerSecret, self::PIMP_OAUTH_SIGN_METH_HMAC_SHA1, $authType);
}
public function setOauthVersion($version){
$this->_oauth->setVersion($version);
}
public function setNonce($nonce){
$this->_oauth->setNonce($nonce);
}
public function setSignatureMethod($signatureMethod){
//seul HMAC_SHA1 est supporté
//throw new Exception("SignatureMethod not implemented");
}
public function getRequestToken($requestTokenUrl,$callbackUrl){
$token = $this->_oauth->getRequestToken($requestTokenUrl,$callbackUrl);
$httpInfo = $this->_oauth->getLastResponseInfo();
if($httpInfo["http_code"] != 200) {
throw new OauthException("{$httpInfo["http_code"]} : Failed fetching request token, response was: " . $this->_oauth->getLastResponse());
}
return $token;
}
public function getAccessToken($accessTokenUrl,$requestToken,$requestTokenSecret,$verifiedToken){
$this->_oauth->setToken($requestToken,$requestTokenSecret);
if(!empty($verifiedToken))
$token = $this->_oauth->getAccessToken($accessTokenUrl,NULL,$verifiedToken);
else
$token = $this->_oauth->getAccessToken($accessTokenUrl);
$httpInfo = $this->_oauth->getLastResponseInfo();
if($httpInfo["http_code"] != 200) {
throw new OauthException("{$httpInfo["http_code"]} : Failed fetching request token, response was: " . $this->_oauth->getLastResponse());
}
return $token;
}
/**
* get a OAuth protected resource
* Follow the REST definition of GET : http://en.wikipedia.org/wiki/Representational_State_Transfer
*/
public function fetch($action,$protectedResourceUrl,$accessToken,$accessTokenSecret,$properties=array()){
$this->_oauth->setToken($accessToken,$accessTokenSecret);
$data = $this->_oauth->fetch($protectedResourceUrl, $properties, $action, array());
$httpInfo = $this->_oauth->getLastResponseInfo();
if($httpInfo["http_code"] != 200) {
throw new OauthException("{$httpInfo["http_code"]} :Failed fetching request token, response was: " . $this->_oauth->getLastResponse());
}
return $data;
}
public function disableSSLChecks(){
$this->_oauth->disableSSLChecks();
}
public function enableSSLChecks(){
$this->_oauth->enableSSLChecks();
}
}
<?php
/** @see Gen_Hash */
require_once('Gen/Hash.php');
/**
* @category Gen
* @package Gen_Session
*/
class Gen_Session
{
/**
* Constructor
*
* Instantiate using {@link getInstance()}; event handler is a singleton
* object.
*
* @return void
*/
protected function __construct()
{
}
/**
* Enforce singleton; disallow cloning
*
* @return void
*/
private function __clone()
{
}
/**
* Singleton instance
*
* @return Gen_Event_Handler
*/
public static function getInstance()
{
if (null === self::$_instance) {
require_once('Gen/Hash.php');
self::$_instance = new Gen_Hash($_SESSION);
}
return self::$_instance;
}
public static function start()
{
session_start();
}
}
<?php
class Gen_Session_Flash
{
protected static $_instance;
protected $_new;
protected $_old;
public function __construct()
{
}
/**
* Enforce singleton; disallow cloning
*
* @return void
*/
private function __clone()
{
}
/**
* Singleton instance
*
* @return Gen_Event_Handler
*/
public static function getInstance()
{
if (null === self::$_instance) {
self::$_instance = new self();
}
return self::$_instance;
}
public function getNew()
{
if (!isset($this->_new)) {
require_once('Gen/Hash.php');
$this->_new = new Gen_Hash();
}
return $this->_new;
}
public function getOld()
{
if (!isset($this->_old)) {
require_once('Gen/Hash.php');
$this->_old = new Gen_Hash();
}
return $this->_old;
}
public function get($key, $default = null) {
return $this->getOld()->get($key, $default);
}
public function set($key, $value)
{
$this->getNew()->set($key, $value);
return $this;
}
public function save()
{
if (isset($this->_new)) {
$_SESSION['Gen_Session_Flash'] = $this->_new->toArray();
}
return $this;
}
public function load()
{
if (isset($_SESSION['Gen_Session_Flash'])) {
$this->getOld()->update($_SESSION['Gen_Session_Flash']);
unset($_SESSION['Gen_Session_Flash']);
}
return $this;
}
}
<?php
require_once('Gen/Enum.php');
class Gen_Translate_Pattern extends Gen_Enum
{
const VIEW = 1;
const CONTROLLER = 2;
const FORM = 3;
const MODEL = 4;
const JAVASCRIPT = 5;
const FLASH = 6;
const CONTEXT = 7;
const PLURAL = 8;
const DATABASE = 9;
protected static $_data = array(
self::VIEW => array('key' => 'view', 'label' => "Vues", 'pattern' => '#_{1,2}t\("([^"\\\]*(?:\\\.[^"\\\]*)*)"#'),
self::CONTROLLER => array('key' => 'controller', 'label' => "Controllers", 'pattern' => '#(?:(?:\$this->setMessage)|(?:->addError)|(?:_{1,2}t))\("([^"\\\]*(?:\\\.[^"\\\]*)*)"#'),
self::FORM => array('key' => 'form', 'label' => "Formulaires", 'pattern' => '#(?:(?:->addError)|(?:->set(?:Label|Comment))|(?:_{1,2}t))\("([^"\\\]*(?:\\\.[^"\\\]*)*)"#'),
self::MODEL => array('key' => 'model', 'label' => "Constantes de classes", 'pattern' => '#"([^"\\\]*(?:\\\.[^"\\\]*)*)"#', 'condition' => 'extends Gen_Enum'),
self::JAVASCRIPT => array('key' => 'script', 'label' => "Javascript", 'pattern' => '#_t\("([^"\\\]*(?:\\\.[^"\\\]*)*)"#', 'extension' => 'js'),
self::FLASH => array('key' => 'flash', 'label' => "Flash", 'pattern' => '#key="([^"\\\]*(?:\\\.[^"\\\]*)*)"#', 'extension' => 'xml'),
self::CONTEXT => array('key' => 'context', 'label' => "Context", 'pattern' => '#_{1,2}ct\("([^"\\\]*(?:\\\.[^"\\\]*)*)"(?:[\s]*,[\s]*\'([a-zA-Z0-9-]+)\')#'),
self::PLURAL => array('key' => 'plural', 'label' => "Pluriel", 'pattern' => '#_{1,2}pt\("([^"\\\]*(?:\\\.[^"\\\]*)*)"(?:[\s]*,[\s]*"([^"\\\]*(?:\\\.[^"\\\]*)*)")#'),
self::DATABASE => array('key' => 'database', 'label' => "Base de données")
);
public static function getPatternById($id)
{
return static::getPropertyById($id, 'pattern');
}
public static function getExtensionById($id)
{
$extension = static::getPropertyById($id, 'extension');
return $extension ? $extension : 'php';
}
public static function getConditionById($id)
{
return static::getPropertyById($id, 'condition');
}
}
<?php
require_once('Gen/View/Helper.php');
require_once('Gen/Repository.php');
/**
* @category Gen
* @package Gen_View
*/
class Gen_View_Base
{
/**
* the base paths for view scripts
* @var string
*/
public static $defaultBaseDir = './app/view/';
protected $_baseDir;
/**
* the Path where layouts can be found
* @var string
*/
public static $layoutPath = 'layout';
/**
* Data provided to the template
* @var array
*/
protected $_data = array();
protected $_layout;
/**
* Options = array('action', 'controller', 'module', 'format');
* @var array
*/
protected $_options;
/**
* Block is used to redifine layout values inside a view
* @var string
*/
protected $_block;
/**
* Indicates wether the View is rendered or not
* @var bool
*/
protected $_isRendered = false;
public function getBaseDir()
{
if(null === $this->_baseDir) {
$this->_baseDir = self::$defaultBaseDir;
}
return $this->_baseDir;
}
public function setBaseDir($baseDir)
{
$this->_baseDir = $baseDir;
return $this;
}
public function assign($key, $value)
{
$this->_data[(string) $key] = $value;
}
public function getParam($key, $default = null)
{
return isset($this->_data[$key]) ? $this->_data[$key] : $default;
}
public function getData()
{
return $this->_data;
}
public function setLayout($layout)
{
$this->_layout = $layout;
return $this;
}
public function getLayout()
{
return $this->_layout;
}
public function resetLayout()
{
$layout = $this->_layout;
$this->_layout = null;
return $layout;
}
public function getOption($key)
{
return isset($this->_options[$key]) ? $this->_options[$key] : null;
}
public function getOptions()
{
return isset($this->_options) ? $this->_options : array();
}
public function setOptions(array $options)
{
$this->_options = $this->_checkOptions($options);
return $this;
}
public function buildOptions($options)
{
if (!is_array($options)) {
if(preg_match('#::#', $options)) {
$parts = preg_split('#::#', $options);
$action = array_pop($parts);
$options = array(
'controller' => implode('::', $parts),
'action' => $action
);
} else {
$action = (string) $options;
$options = $this->getOptions();
$options['action'] = $action;
}
}
$this->_checkOptions($options);
return $options;
}
protected function _checkOptions(array $options)
{
if (!isset($options['controller']) || !isset($options['action'])) {
require_once ('Gen/View/Exception.php');
throw new Gen_View_Exception("Missing Argument 'controller' or 'action' " . print_r($options, true) . ' in ' . __CLASS__);
}
return $options;
}
public function setRendered($isRendered)
{
$this->_isRendered = (bool) $isRendered;
return $this;
}
public function isRendered()
{
return $this->_isRendered;
}
public function setHeadMeta($key, $content, $equiv = null, $property = null, $charset = null, $URL = null)
{
Gen_Repository::getInstance('Gen_View_Head_Metas')->set($key, array(
'name'=> $key,
'content'=> $content,
'http-equiv' => $equiv,
'charset' => $charset,
'URL' => $URL,
'property' => $property
));
return $this;
}
public function getHeadMetas()
{
return Gen_Repository::getInstance('Gen_View_Head_Metas')->toArray();
}
public function addHeadLink($rel, $type, $href, $title = null)
{
$links = $this->getHeadLinks();
$links[$rel] = array(
'rel' => $rel,
'type' => $type,
'href' => $href,
'title' => $title
);
Gen_Repository::getInstance()->set('Gen_View_Head_Links', $links);
return $this;
}
public function addRss($url, $title = null)
{
return $this->addHeadLink('alternate', 'application/rss+xml', $url, $title);
}
public function addStyle($url)
{
return $this->addHeadLink('stylesheet', 'text/css', $url);
}
public function getHeadLinks()
{
return Gen_Repository::getInstance()->get('Gen_View_Head_Links', array());
}
public function block($name)
{
if(null !== $this->_block) {
require_once ('Gen/View/Exception.php');
throw new Gen_View_Exception('Can not call nested blocks in' . __CLASS__);
}
$this->_block = (string) $name;
ob_start();
}
public function endBlock()
{
if (null === $this->_block) {
require_once ('Gen/View/Exception.php');
throw new Gen_View_Exception('Can not call endBlock without calling block first in' . __CLASS__);
}
$this->setContentFor($this->_block, ob_get_clean());
$this->_block = null;
}
public function getContent($name = 'Gen_View_Default_Block', $default = null)
{
return Gen_Repository::getInstance('Gen_View_Block')->get($name, $default);
}
public function setContentFor($key, $value)
{
Gen_Repository::getInstance('Gen_View_Block')->set($key, $value);
}
public function setHeadTitle($title)
{
$this->setContentFor('head_title', $title);
return $this;
}
public function setInternalScript($script)
{
Gen_Repository::getInstance('Gen_View_Internal_Scripts')->add($script);
return $this;
}
public function getInternalScripts()
{
return array_unique(Gen_Repository::getInstance('Gen_View_Internal_Scripts')->toArray());
}
public function setExternalScript($script)
{
Gen_Repository::getInstance('Gen_View_External_Scripts')->add($script);
return $this;
}
public function getExternalScripts()
{
return array_unique(Gen_Repository::getInstance('Gen_View_External_Scripts')->toArray());
}
public function partial($options, array $params = array())
{
$options = $this->buildOptions($options);
$file = $this->_formatFileName($options);
$params = array_merge($this->_data, $params);
return $this->renderFile($file, $params);
}
public function render(array $options, $layout = null)
{
$this->setOptions($options);
if ($layout) $this->setLayout($layout);
$file = $this->_formatFileName($options);
return $this->loop($file);
}
public function loop($file) {
$content = $this->renderFile($file, $this->_data);
if ($layout = $this->resetLayout()) {
$options = $this->buildOptions($layout);
$this->setContentFor('Gen_View_Default_Block', $content);
return $this->loop($this->_formatFileName($options));
}
return $content;
}
// protected function _formatLayoutFileName($layout)
// {
// return $this->getBaseDir() . self::$layoutPath . '/' . $layout . '.php';
// }
protected function _formatFileName($options)
{
$module = isset($options['module']) ? $options['module'] . '/' : null;
$format = (isset($options['format']) && $options['format']) ? $options['format'] . '/' : null;
$controller = str_replace('::', '/', $options['controller']);
Gen_Log::log($options, 'Gen_View::_formatFileName');
return $this->getBaseDir() . $module . $controller . '/' . $format . $options['action'] . '.php';
}
public function renderFile($_file, array $_params = array())
{
if (file_exists($_file)) {
try {
Gen_Log::log($_file, 'Gen_View_Base::renderFile');
ob_start();
/** Enable to access the data directly using $ instead of $this-> in the template */
extract($_params);
/** Includes the template file */
include ($_file);
$_str = ob_get_clean();
return $_str;
} catch (Exception $e) {
ob_end_clean();
throw $e;
}
}
throw new Exception("Unknown file: $_file in " . __CLASS__);
}
}
<?php
/** Gen_Exception */
require_once ('Gen/Exception.php');
/**
* @category Gen
* @package Gen_View
*/
class Gen_View_Exception extends Gen_Exception
{
}
<?php
function _t($text, $params = null)
{
if ($params === null) {
return _sanitize(Gen_I18n::translate($text));
}
$params = (array) $params;
$text = _sanitize(Gen_I18n::translate($text));
foreach ($params as $key => $value) {
$text = @preg_replace('#{' . $key . '}#', $value, $text);
}
return $text;
}
function __t($text, $params = null)
{
echo _t($text, $params);
}
function _ct($text, $context, $params = null)
{
$token = '{context:' . $context . '}';
$text = _t($token . $text, $params);
return preg_replace('#' . $token . '#', '', $text);
}
function __ct($text, $context, $params = null)
{
echo _ct($text, $context, $params);
}
function _pt($text, $plural, $field, array $params)
{
if (!isset($params[$field]) || strip_tags($params[$field]) <= 1) {
return _t($text, $params);
}
return _t($plural, $params);
}
function __pt($text, $plural, $field, array $params)
{
echo _pt($text, $plural, $field, $params);
}
function __if($value, $true, $false = null) {
echo $value ? $true : $false;
}
function __isNull($value, $default = null) {
echo $value ? $value : $default;
}
function _sanitize($text)
{
if (is_array($text)) return array_map('_sanitize', $text);
else return htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
}
function __($text)
{
echo _sanitize($text);
}
function __include($action, $controller, array $params = array())
{
$file = Gen_View_Base::buildFile($controller . '/' . $action);
echo Gen_View_Base::merge($file, $params);
}
function _url($name = 'default', array $data = array(), $relative = true)
{
return Gen_Controller_Front::getInstance()
->getRouter()
->url($name, $data, $relative);
}
function __url($name = 'default', array $data = array(), $relative = true)
{
echo _url($name, $data, $relative);
}
function _currentUrl(array $data = array(), $relative = true)
{
$url_infos = parse_url($_SERVER['REQUEST_URI']);
$params = array();
if (isset($url_infos['query'])) {
parse_str($url_infos['query'], $params);
}
$params = array_merge($params, $data);
return ($relative ? '' : ('https://' . $_SERVER['HTTP_HOST'])) . $url_infos['path'] . (http_build_query($params) ? ('?' . http_build_query($params)) : '');
}
function __currentUrl(array $data = array(), $relative = true)
{
echo _currentUrl($data, $relative);
}
function _link($label, array $attributes = array())
{
if(!isset($attributes['href'])) {
$attributes['href'] = $label;
}
$attributes['target'] = '_blank';
return _tag('a', $label, $attributes);
}
function __link($label, array $attributes = array())
{
echo _link($label, $attributes);
}
function _email($email, array $attributes = array())
{
if($email === null) {
return null;
}
$attributes['href'] = 'mailto:'.$email;
return _link($email, $attributes);
}
function __email($email, array $attributes = array())
{
echo _email($email, $attributes);
}
function _menu($caption, $name, array $data = array(), array $attributes = array())
{
require_once('Gen/Html/Element.php');
$url = _url($name, $data);
$attributes['href'] = $url;
if($url == $_SERVER['REQUEST_URI']) {
$attributes['class'] = isset($attributes['class']) ? ($attributes['class'] . ' active') : 'active';
}
$link = new Gen_Html_Element('a', $attributes);
$link->append($caption);
return $link;
}
function __menu($caption, $name, array $data = array(), array $attributes = array())
{
echo _menu($caption, $name, $data, $attributes);
}
function _a($label, $route = null, $attributes = array())
{
if(is_array($route)) {
if(isset($route['name'])) {
$name = $route['name'];
$data = isset($route['data']) ? $route['data'] : array();
$relative = isset($route['relative']) ? $route['relative'] : true;
} else {
$name = $route[0];
$data = isset($route[1]) ? $route[1] : array();
$relative = isset($route[2]) ? $route[2] : true;
}
} elseif($route !== null) {
$name = $route;
$data = array();
$relative = true;
}
$url ="#";
if($route !== null) {
$url = _url($name, $data, $relative);
}
$attributes['href'] = $url;
if(($url == $_SERVER['REQUEST_URI']) || (isset($attributes['active']) && $attributes['active'] === true)) {
$activeCss = 'a-active';
if(isset($attributes['active_css'])) {
$activeCss = $attributes['active_css'];
unset($attributes['active_css']);
} elseif(isset($attributes['class'])) {
$activeCss = $attributes['class'] . '-active';
}
$attributes['class'] = isset($attributes['class']) ? ($attributes['class'] . ' ' . $activeCss) : $activeCss;
}
return _tag('a', _t($label), $attributes);
}
function __a($label, $route, $attributes = array()) { echo _a($label, $route, $attributes); }
function _btn($label, $route = null, $attributes = array())
{
$class = isset($attributes['class']) ? $attributes['class'] : null;
$attributes['class'] = 'btn ' . $class;
$attributes['rel'] = 'nofollow';
return _a($label, $route, $attributes);
}
function __btn($label, $route = null, $attributes = array()) { echo _btn($label, $route, $attributes); }
function _br($text, $sanitize = true)
{
if($sanitize) { $text = _sanitize($text); }
$dirty = preg_replace('/\r/', '', $text);
$clean = preg_replace('/\n{3,}/', '<br/><br/>', preg_replace('/\r/', '', $dirty));
return nl2br($clean);
}
function __br($text, $sanitize = true) { echo _br($text, $sanitize); }
function __thumb($file, $size = 100) { echo _thumb($file, $size); }
function _thumb($file, $size = 100) {
return _img(_url('image_thumb', array('file' => $file, 'width' => $size, 'height' => $size)));
}
function _text($text, $sanitize = true)
{
//$text = utf8_decode($text);
if($sanitize) { $text = _sanitize($text); }
$text = preg_replace('#\*([^*\n]*)\*#', '<b>$1</b>', $text);
$text = preg_replace('#"([^"\n]*)"#', '<i>$1</i>', $text);
$text = preg_replace('#\b__([^_\n]*)__\b#', '<u>$1</u>', $text);
$text = preg_replace('#\b(https?://[a-zA-Z0-9.?&=;\-_/%]*)#', '<a href="$1" target="_blank">$1</a>', $text);
$text = preg_replace('#\b((?<!http://)www.[a-zA-Z0-9.?&=;\-_/%]*)#', '<a href="http://$1" target="_blank">$1</a>', $text);
//return utf8_encode($text);
return _br($text, false);
}
function __desc($text, $limit = 400, $sanitize = true) { echo _desc($text, $limit, $sanitize); }
function _desc($text, $limit = 400, $sanitize = true) {
require_once('Gen/Str.php');
$text = _unmark($text, false);
$text = Gen_Str::shorten($text, $limit);
if($sanitize) { $text = _sanitize($text); }
return $text;
}
function __text($text, $sanitize = true) { echo _text($text, $sanitize); }
function _markdown($text, $sanitize = false)
{
if($sanitize) { $text = _sanitize($text); }
require_once('Gen/Markdown.php');
return Gen_Markdown::parse($text);
}
function __markdown($text, $sanitize = false) { echo _markdown($text, $sanitize); }
function __unmark($text, $sanitize = true) { echo _unmark($text, $sanitize); }
function _unmark($text, $sanitize = true)
{
if($sanitize) { $text = _sanitize($text); }
$text = preg_replace('@[\*_#\[\]!]@', '', $text);
return $text;
}
function _code($text, $language = 'php') {
require_once('Gen/Css.php');
require_once('Gen/Html.php');
$text = str_replace('[php]', '<?php', $text);
$text = str_replace('[/php]', '?>', $text);
$text = htmlentities((string) $text);
$patterns = array(
'php' => array(
'#\b('
.'(class)|(abstract)|(final)|(static )|(public)|(private)|(protected)'
.'|(function)|(extends)|(implements)|(parent)|(self)'
.'|(int)|(string)|(bool)|(float)|(null)|(array)|(const)|(instanceof)'
.'|(isset)|(foreach)|(while)|(as)|(if)|(else)|(return)|(endif)|(endforeach)'
.'|((include)|(require)(_once)?)|(echo)|(new)'
.'|(try)|(catch)|(throw)'
.')\b#',
'#(\$\w+)#',
"#((->[a-zA-Z0-9_]+)+)#",
"#('[^']*')#",
"#\b([0-9.]+)\b#",
"#(//.*)#",
'#((<[?]php)|(\?>))#',
),
'sql' => array(
'#\b((select)|(from)|(on)|((left|right)? *(inner|outer)? *join)'
.'|(where)|(groupby)|(limit)|(orderby)'
.')\b#',
),
'html' => array(
'#(</?('.implode('|', Gen_Html::$tags).')(.*)>)#',
),
'css' => array(
'#\.([a-z0-9_-]+)#',
'@(#[a-z0-9_-]+)\s*:@',
'#('. implode('|', Gen_Css::$properties) .')\s*:#',
'#:('. implode('|', Gen_Css::$pseudoClasses) .')#',
)
);
$replaces = array(
'php' => array(
'<span class="php-key">$1</span>',
'<span class="php-var">$1</span>',
'<span class="php-prop">$1</span>',
'<span class="php-string">$1</span>',
'<span class="php-int">$1</span>',
'<span class="comment">$1</span>',
'<span class="php-tag">$1</span>',
),
'sql' => array(
'<span class="sql">$1</span>',
),
'html' => array(
'<span class="html-tag">$1</span>',
),
'css' => array(
'.<span class="css-class">$1</span>:',
'<span class="css-id">$1</span>',
'<span class="css-prop">$1</span>:',
':<span class="css-pseudo">$1</span>:',
)
);
$text = preg_replace($patterns[$language], $replaces[$language], $text);
$text = preg_replace('#(/\*[a-z0-9\w\s:()@<>="/*$\.-_]*\*/)#m', '<span class="comment">$1</span>', $text);
return '<pre class="code">'.$text.'</pre>';
}
function __code($text, $language = 'php') { echo _code($text, $language); }
function _paginate($name = 'default', array $data = array(), $total, $current_page, $adj=3)
{
$prev = $current_page - 1; // numéro de la page précédente
$next = $current_page + 1; // numéro de la page suivante
$n2l = $total - 1; // numéro de l'avant-dernière page (n2l = next to last)
$url = _url($name, $data);
/* Initialisation : s'il n'y a pas au moins deux pages, l'affichage reste vide */
$pagination = '';
/* Sinon ... */
if ($total > 1) {
/* Concaténation du <div> d'ouverture à $pagination */
$pagination .= '<ul class="pagination">';
/* previous */
if ($current_page == 2) {
$pagination .= '<li><a href="'.$url.'" title="' . _t("previous page") .'">«</a></li>';
} elseif ($current_page > 2) {
$data['page'] = $prev;
$prev_url = _url($name, $data);
$pagination .= '<li><a href="'.$prev_url.'" title="'. _t("page précédente") .'">«</a></li>';
} else {
$pagination .= '<li class="disabled"><span>«</span></li>';
}
/* ///////////////
Début affichage des pages, l'exemple reprend le cas de 3 numéros de pages adjacents (par défaut) de chaque côté du numéro courant
- CAS 1 : il y a au plus 12 pages, insuffisant pour faire une troncature
- CAS 2 : il y a au moins 13 pages, on effectue la troncature pour afficher 11 numéros de pages au total
/////////////// */
/* CAS 1 */
if ($total < 5 + ($adj * 2))
{
/* Ajout de la page 1 : on la traite en dehors de la boucle pour n'avoir que index.php au lieu de index.php?p=1 et ainsi éviter le duplicate content */
$pagination .= ($current_page == 1) ? '<li class="active"><span>1</span></li>' : '<li><a href="'.$url.'">1</a></li>';
/* Pour les pages restantes on utilise une boucle for */
for ($i = 2; $i<=$total; $i++)
{
if ($i == $current_page) {
$pagination .= '<li class="active"><span>'.$i.'</span>';
} else {
$data['page'] = $i;
$page_url = _url($name, $data);
$pagination .= '<li><a href="'.$page_url.'">'.$i.'</a>';
}
}
}
/* CAS 2 : au moins 13 pages, troncature */
else
{
/*
Troncature 1 : on se situe dans la partie proche des premières pages, on tronque donc la fin de la pagination.
l'affichage sera de neuf numéros de pages à gauche ... deux à droite (cf figure 1)
*/
if ($current_page < 2 + ($adj * 2))
{
/* Affichage du numéro de page 1 */
$pagination .= ($current_page == 1) ? '<li class="active"><span>1</span></li>' : '<li><a href="'.$url.'">1</a></li>';
/* puis des huit autres suivants */
for ($i = 2; $i < 4 + ($adj * 2); $i++)
{
if ($i == $current_page)
$pagination .= "<li class=\"active\"><span>{$i}</span></li>";
else {
$data['page'] = $i;
$page_url = _url($name, $data);
$pagination .= "<li><a href=\"{$page_url}\">{$i}</a></li>";
}
}
/* ... pour marquer la troncature */
$pagination .= '<li class="disabled"><span>...</span></li>';
/* et enfin les deux derniers numéros */
$data['page'] = $n2l;
$n2l_url = _url($name, $data);
$pagination .= "<li><a href=\"{$n2l_url}\">{$n2l}</a></li>";
$data['page'] = $total;
$total_url = _url($name, $data);
$pagination .= "<li><a href=\"{$total_url}\">{$total}</a></li>";
}
/*
Troncature 2 : on se situe dans la partie centrale de notre pagination, on tronque donc le début et la fin de la pagination.
l'affichage sera deux numéros de pages à gauche ... sept au centre ... deux à droite (cf figure 2)
*/
elseif ( (($adj * 2) + 1 < $current_page) && ($current_page < $total - ($adj * 2)) )
{
/* Affichage des numéros 1 et 2 */
$pagination .= "<li><a href=\"{$url}\">1</a></li>";
$data['page'] = 2;
$second_url = _url($name, $data);
$pagination .= "<li><a href=\"{$second_url}\">2</a></li>";
$pagination .= '<li class="disabled"><span>...</span></li>';
/* les septs du milieu : les trois précédents la page courante, la page courante, puis les trois lui succédant */
for ($i = $current_page - $adj; $i <= $current_page + $adj; $i++)
{
if ($i == $current_page)
$pagination .= "<li class=\"active\"><span>{$i}</span></li>";
else {
$data['page'] = $i;
$page_url = _url($name, $data);
$pagination .= "<li><a href=\"{$page_url}\">{$i}</a></li>";
}
}
$pagination .= '<li class="disabled"><span>...</span></li>';
/* et les deux derniers numéros */
$data['page'] = $n2l;
$n2l_url = _url($name, $data);
$pagination .= "<li><a href=\"{$n2l_url}\">{$n2l}</a></li>";
$data['page'] = $total;
$total_url = _url($name, $data);
$pagination .= "<li><a href=\"{$total_url}\">{$total}</a></li>";
}
/*
Troncature 3 : on se situe dans la partie de droite, on tronque donc le début de la pagination.
l'affichage sera deux numéros de pages à gauche ... neuf à droite (cf figure 3)
*/
else
{
/* Affichage des numéros 1 et 2 */
$pagination .= "<li><a href=\"{$url}\">1</a></li>";
$data['page'] = 2;
$second_url = _url($name, $data);
$pagination .= "<li><a href=\"{$second_url}\">2</a></li>";
$pagination .= '<li class="disabled"><span>...</span></li>';
/* puis des neufs dernières */
for ($i = $total - (2 + ($adj * 2)); $i <= $total; $i++)
{
if ($i == $current_page)
$pagination .= "<li class=\"active\"><span>{$i}</span></li>";
else {
$data['page'] = $i;
$page_url = _url($name, $data);
$pagination .= "<li><a href=\"{$page_url}\">{$i}</a></li>";
}
}
}
}
/* Fin affichage des pages */
/* next page */
if ($current_page == $total)
$pagination .= "<li class=\"disabled\"><span title=\"" . _t("next page") . "\">»</span></li>\n";
else {
$data['page'] = $next;
$next_url = _url($name, $data);
$pagination .= "<li><a href=\"{$next_url}\" title=\"" . _t("next page") . "\">»</a></li>\n";
}
/* Fin affichage du bouton [suivant] */
/* </ul> de fermeture */
$pagination .= "</ul>\n";
}
/* Fin de la fonction, renvoi de $pagination au programme */
return ($pagination);
}
function __paginate($name = 'default', array $data = array(), $total, $current_page, $adj=3)
{
echo _paginate($name, $data, $total, $current_page, $adj);
}
function __f(&$first, $separator = ' ') {
echo $first ? $separator . $first : '';
$first = false;
}
function _tag($tag, $content = null, array $attributes = array())
{
$str = '<' . $tag;
foreach($attributes as $name => $value) {
$str .= ' ' . $name . '="' . htmlspecialchars($value, ENT_COMPAT, 'UTF-8') . '"';
}
if(null === $content) {
$str .= '/>';
} else {
$str.= '>'
. implode("\n", (array) $content)
. '</' . $tag . '>';
}
return $str;
}
function __tag($tag, $content = null, array $attributes = array())
{
echo _tag($tag, $content, $attributes);
}
function _input($type, $name = null, $attributes = array())
{
$attributes['type'] = $type;
return _tag('input', null, $attributes);
}
function __input($type, $name = null, $attributes = array()) { echo _input($type, $name, $attributes); }
function _p($txt)
{
return _tag('pre', print_r($txt, true));
}
function __p($txt) { echo _p($txt); }
function _date($date, $format = 'smart_date', $timezone = false, $lang = null) {
if(null === $date) {
return '';
} elseif($date instanceof Gen_Entity_Date) {
return $date->format($format);
}
require_once('Gen/Date.php');
if($format == 'smart_date') {
return Gen_Date::smartDate($date);
}
return Gen_Date::format($date, $format, $timezone, $lang);
}
function __date($date, $format = 'smart_date', $timezone = false, $lang = null) { echo _date($date, $format, $timezone, $lang); }
function _time($time, $format = 'H:i', $timezone = false, $lang = null) {
if(null === $time) {
return '';
} elseif ($time instanceof Gen_Entity_Date) {
return $time->format($format);
}
return Gen_Date::format($time, $format, $timezone, $lang);
}
function __time($time, $format = 'H:i', $timezone = false, $lang = null) { echo _time($time, $format, $timezone, $lang); }
function _dasherize($text) {
require_once('Gen/Str.php');
return Gen_Str::urlDasherize($text);
}
function _img($src, array $attributes = array()) {
$defaults = array(
'loading' => 'lazy',
'decoding' => 'async',
'alt' => ''
);
$attributes = array_merge($defaults, $attributes);
$attributes['src'] = $src;
return _tag('img', null, $attributes);
}
function __img($src, array $attributes = array()) { echo _img($src, $attributes); }
function _select($name, array $data, array $attributes = array())
{
$labelAttribute = null;
if(isset($attributes['label_attribute'])) {
$labelAttribute = $attributes['label_attribute'];
unset($attributes['label_attribute']);
}
require_once('Gen/Form/Select.php');
$select = new Gen_Form_Select($attributes);
$select->setName($name);
if($labelAttribute !== null) {
$select->setLabelAttribute($labelAttribute);
}
$select->setDatasource($data);
return $select;
}
function __select($name, array $data, array $attributes = array()) { echo _select($name, $data, $attributes); }
function __amount($amount, $decimals = null) { echo _amount($amount, $decimals); }
function _amount($amount, $decimals = null)
{
$decimals = ($decimals === null) ? ((abs($amount) >= 1000) ? 0 : 2) : $decimals;
return number_format($amount, $decimals, ',', ' ');
}
function __percentage($amount, $decimals = null) { echo _percentage($amount, $decimals); }
function _percentage($amount, $decimals = null)
{
$amount = $amount * 100;
$decimals = ($decimals === null) ? ((abs($amount) >= 10) ? 0 : 2) : $decimals;
return _amount($amount, $decimals).'%';
}
function __check($bool = true) { echo _check($bool); }
function _check($bool = true)
{
if($bool) {
return '<i class="fas fa-check"></i>';
}
return false;
}
function __toggle($bool = true) { echo _toggle($bool); }
function _toggle($bool = true)
{
return '<i class="fas fa-lg fa-toggle-'.($bool ? 'on' : 'off').'"></i>';
}