/fruml/library/lib.library.php
PHP | 1044 lines | 616 code | 77 blank | 351 comment | 103 complexity | 78fd898e703491ba5b12906abf96c85b MD5 | raw file
Possible License(s): LGPL-3.0, LGPL-2.1, GPL-2.0, BSD-2-Clause
- <?php
- /**
- * Library: general helper tools
- *
- * Library gives access to a number of often used tools.
- * A number of Library's methods can be called globally, e.g. Library::dbg()
- * can also be called as dbg()
- *
- * @author Alex Butter <alex.butter@gmail.com>
- * @license Fruml License 1.0
- *
- * @package Library
- * @version
- */
- /**
- * Library
- *
- * The main Libary class
- *
- * @package Library
- */
- class Library {
-
- /**
- * pretty print the contents of passed variables
- *
- * @param mixed $data,...
- * @return void
- * @access public
- * @static
- * @return void
- */
- public static function dbg() {
- if(Library::ajax() || IS_FLASH) {
- $output = array();
- $output['success'] = false;
- $output['debug'] = true;
- $args = func_get_args();
- $output['data_display'] = '';
- foreach($args as $arg) {
- $output['data'][] = $arg;
- $output['data_display'] .= '<pre>'.Library::encode(print_r($arg, 1)).'</pre>';
- }
- echo Library::json($output);
- die();
- }
-
- if(defined('IS_CLI') && IS_CLI) {
- foreach(func_get_args() as $arg) {
- var_dump($arg);
- }
- return;
- }
-
- $trace = $orig_trace = debug_backtrace();
- $caller = array_shift($trace);
- while(empty($caller['file']) || realpath(Library::formatPath($caller['file']))==realpath(Library::formatPath(__FILE__))) {
- $caller = array_shift($trace);
- }
- $function = $caller['function'];
- $class = isset($caller['class']) ? $caller['class'].'::' : '' ;
- $header = $class.$function.'()';
- $header .= !empty($caller['file']) ? ' @ '.self::formatPath($caller['file']) : '' ;
- $header .= !empty($caller['line']) ? ', line '.$caller['line'] : '' ;
-
- echo chr(10).'<div style="border: 1px solid #eee; margin: 5px;">'.chr(10);
- echo chr(9).'<div style="background-color: #eee; color: #333; font-family: Arial, Helv, Sans; font-size: 12px; padding: 3px;">';
- echo ' '.$header.'</div>'.chr(10);
- if(func_num_args()) {
- foreach(func_get_args() as $arg) {
- echo chr(9).'<div style="background: white; color: #333; font-family: Arial, Helv, Sans; font-size: 12px; padding: 3px;">'.chr(10);
- $dump = Library::prettyPrint($arg);
- echo $dump;
- }
- echo chr(9).'</div>'.chr(10);
- } else {
- echo chr(9).'<div style="color: #333; font-family: Arial, Helv, Sans; font-size: 12px; padding: 3px;">'.chr(10);
- echo 'No parameters passed, nothing to '.$function.'().'.chr(10);
- echo chr(9).'</div>'.chr(10);
- }
- echo '</div>'.chr(10).chr(10);
- }
-
- /**
- * Output the contents of the passed variables, and stops script executions
- *
- * @return void
- * @access public
- * @static
- */
- public static function dbgd() {
- $args = func_get_args();
- call_user_func_array(array('Library', 'dbg'), $args);
- die();
- }
-
- /**
- * Returns pretty-printable version of $data.
- *
- * @return string $data
- * @access public
- * @static
- */
- static public function prettyPrint($data) {
- // set html_errors to 1 just in case xdebug's installed. It'll give pretty colours :)
- $html_errors = ini_get('html_errors');
- ini_set('html_errors', 1);
- ob_start();
- echo '<pre>';
- var_dump($data);
- echo '</pre>';
- ini_set('html_errors', $html_errors);
- return ob_get_clean();
- }
-
- /**
- * Cleans a (file) path and replaces backslashes with forward slashes
- *
- * @param string $path
- * @return string
- * @access public
- * @static
- */
- public static function formatPath($path) {
- $path = str_replace('\\', '/', $path);
- $path = str_replace('///', '/', $path);
- $path = str_replace('//', '/', $path);
- $path = str_replace('../', '/', $path); // stop directory traversal?
- return $path;
- }
- /**
- * Instantiates and returns a dwoo
- *
- * @return object Dwoo
- * @access public
- * @static
- */
- public static function getDwoo() {
- self::loadDwoo();
- return new Dwoo(CACHE_PATH.'template/', CACHE_PATH.'data/');
- }
- /**
- * Loads the Dwoo autoloader
- *
- * @return void
- * @access public
- * @static
- */
- public static function loadDwoo() {
- if(!class_exists('Dwoo', false)) {
- require_once VENDOR_PATH.'dwoo/dwooAutoload.php';
- }
- }
-
- /**
- * Loads the a BB Code parser
- *
- * @return void
- * @access public
- * @static
- */
- public static function getBBCodeParser() {
- if(!class_exists('ubbParser', false)) {
- require_once VENDOR_PATH.'ubbparser/class.ubbparser.php';
- }
- return new ubbParser();
- }
-
-
- /**
- * Parses a string for BB Code
- * @return string The parsed string
- * @access public
- * @static
- */
- private static $bbcodeParser = false;
- public static function parseBBCode($string) {
- Library::disableErrorHandling();
- if(!self::$bbcodeParser) self::$bbcodeParser = self::getBBCodeParser();
- $string = self::$bbcodeParser->parse($string);
- Library::enableErrorHandling();
- return $string;
- }
- /**
- * Checks if an incoming request is an AJAX request.
- *
- * @return boolean
- * @access public
- * @static
- */
- public static function ajax() {
- $ajax = false;
- $ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest' ? true : $ajax ;
- $ajax = IS_FLASH ? true : $ajax ;
- $ajax = defined('FORCE_HTML') && FORCE_HTML==true ? false : $ajax;
- return $ajax;
- }
- /**
- * Force HTML output, even if it's an AJAX request. Useful for getting properly formatted
- * dbg and error messages when using something like jQuery's .load() function.
- *
- * @return void
- * @access public
- * @static
- */
- public static function forceHTML() {
- if(!defined('FORCE_HTML')) {
- define('FORCE_HTML', true);
- }
- }
-
- /**
- * Does a redirect.
- *
- * @return void
- * @access public
- * @static
- */
- public static function redirect($target) {
- header('Location: '.$target);
- die();
- }
- /**
- * Escapes single quotes, but not double quotes.
- *
- * @return string
- * @access public
- * @static
- */
- public static function escapequotes($string) {
- return str_replace('\"', '"', addslashes($string));
- }
-
- /**
- * json_encode() wrapper, also skips debug output and sends headers
- *
- * @return string
- * @access public
- * @static
- */
- static function json($data) {
- if(!defined('SKIP_DEBUG')) define('SKIP_DEBUG', true);
- header('Content-Type: application/json');
- return json_encode($data);
- }
-
- /**
- * Writes an entry to the audit log
- *
- * @return void
- * @access public
- * @static
- */
- static public function audit($message, $item_id = NULL, $type = 'info', $data = NULL) {
- if(!is_array($data)) {
- $data = array();
- }
- $data['_ip'] = self::getIP();
- DB::getInstance()->query("INSERT INTO %tp%log SET
- user_id = ?,
- type = ?,
- controller = ?,
- action = ?,
- message = ?,
- item_id = ?,
- data = ?,
- log_date = NOW()",
- (User::getId()!==false ? User::getId() : NULL),
- $type,
- CONTROLLER,
- ACTION,
- $message,
- (is_numeric($item_id) ? $item_id : NULL),
- serialize($data)
- );
- }
- /**
- * Recursive stripslashes function.
- *
- * @return mixed
- * @access public
- * @static
- */
- static function stripslashesDeep($value) {
- $value = is_array($value) ? array_map(array('Library', 'stripslashesDeep'), $value) : stripslashes($value) ;
- return $value;
- }
-
- /**
- * Store a message in the session to display on next page load.
- *
- * @return void
- * @access public
- * @static
- */
- static function notify($message) {
- Session::save('fruml_dashboard_notification', $message);
- }
-
- /**
- * Retrieve a message from the session store.
- *
- * @return string $message
- * @access public
- * @static
- */
- static function getNotification() {
- $message = Session::get('fruml_dashboard_notification');
- Session::delete('fruml_dashboard_notification');
- return $message;
- }
- /**
- * Store a message in the session to display in an allert on next page load.
- *
- * @return void
- * @access public
- * @static
- */
- static function notifyAlert($message) {
- Session::save('fruml_dashboard_alert', $message);
- }
-
- /**
- * Retrieve a message from the session to display in an alert.
- *
- * @return string $message
- * @access public
- * @static
- */
- static function getAlertNotification() {
- $message = Session::get('fruml_dashboard_alert');
- Session::delete('fruml_dashboard_alert');
- return $message;
- }
-
- /**
- * Retrieves the IP address.
- *
- * @return string IP Address
- * @access public
- * @static
- */
- static function getIP() {
- if(!empty($_SERVER['HTTP_CLIENT_IP'])) {
- $ip = $_SERVER['HTTP_CLIENT_IP'];
- } elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
- $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
- } else {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- return $ip;
- }
- /**
- * Works out a file's mimetype. Tries to do so the nice way (by using finfo). If that fails,
- * tries to get the mimetype using a slightly less nice way (by using mime_content_type) and
- * if that fails, uses a very dirty lookup table using the file's extension.
- *
- * @return string $mime
- * @access public
- * @static
- */
- static function getMimeType($file) {
- $mime = false;
- //if(class_exists('finfo', false) && file_exists($file)) {
- // $finfo = new finfo(FILEINFO_MIME);
- // $fres = $finfo->file($file);
- // if (is_string($fres) && !empty($fres)) {
- // $mime = $fres;
- // }
- //} elseif(function_exists('mime_content_type') && file_exists($file)) {
- // $mime = mime_content_type($file);
- //} else {
- $mime_types = array(
- 'txt' => 'text/plain',
- 'htm' => 'text/html',
- 'html' => 'text/html',
- 'php' => 'text/html',
- 'css' => 'text/css',
- 'js' => 'application/javascript',
- 'json' => 'application/json',
- 'xml' => 'application/xml',
- 'swf' => 'application/x-shockwave-flash',
- 'flv' => 'video/x-flv',
- 'png' => 'image/png',
- 'jpe' => 'image/jpeg',
- 'jpeg' => 'image/jpeg',
- 'jpg' => 'image/jpeg',
- 'gif' => 'image/gif',
- 'bmp' => 'image/bmp',
- 'ico' => 'image/vnd.microsoft.icon',
- 'tiff' => 'image/tiff',
- 'tif' => 'image/tiff',
- 'svg' => 'image/svg+xml',
- 'svgz' => 'image/svg+xml',
- 'zip' => 'application/zip',
- 'rar' => 'application/x-rar-compressed',
- 'exe' => 'application/x-msdownload',
- 'msi' => 'application/x-msdownload',
- 'cab' => 'application/vnd.ms-cab-compressed',
- 'mp3' => 'audio/mpeg',
- 'qt' => 'video/quicktime',
- 'mov' => 'video/quicktime',
- 'pdf' => 'application/pdf',
- 'psd' => 'image/vnd.adobe.photoshop',
- 'ai' => 'application/postscript',
- 'eps' => 'application/postscript',
- 'ps' => 'application/postscript',
- 'doc' => 'application/msword',
- 'rtf' => 'application/rtf',
- 'xls' => 'application/vnd.ms-excel',
- 'ppt' => 'application/vnd.ms-powerpoint',
- 'odt' => 'application/vnd.oasis.opendocument.text',
- 'ods' => 'application/vnd.oasis.opendocument.spreadsheet',
- );
- $ext = Library::getExtension($file);
- if(isset($mime_types[$ext])) {
- return $mime_types[$ext];
- }
- //}
- if($mime===false) {
- $mime = 'application/octet-stream';
- }
- return $mime;
- }
- /**
- * Returns the extension on a file (or other string)
- *
- * @param string $string
- * @return string $ext
- * @access public
- * @static
- */
- static function getExtension($string) {
- return substr(strrchr($string, "."), 1);
- }
-
- /**
- * Returns a string's length.
- *
- * @param $data The string to get the length of.
- * @return int The length of the string.
- */
- static function length($data) {
- if(function_exists('mb_strlen')) {
- return mb_strlen($data, 'utf-8');
- } else {
- return strlen(utf8_decode($data));
- }
- }
- /**
- * Cleans up a filename. Don't supply a file path, as that will be cleaned up beyond all recognition (cubar?).
- *
- * @param $string The string to sanitize.
- * @return string The sanitized file name.
- */
- static function sanitizeFilename($string) {
- $extension = Library::getExtension($string);
- $simple = str_replace('.'.$extension, '', $string);
- $simple = trim($simple);
- $simple = str_replace(" ", "-", $simple);
- $simple = str_replace("--", "-", $simple);
- $string = htmlentities($string);
- $string = preg_replace("/&([a-z])[a-z]+;/i", "$1", $string);
- $simple = preg_replace("/[^a-zA-Z0-9_-]/", "", $simple);
- if($extension != '') {
- $simple .= '.'.$extension;
- }
- return strtolower($simple);
- }
- /**
- * Works out the max upload size for files based on ini settings.
- * @param boolean $as_int Indicates whether the max upload size should be returned as integer.
- * @return string The max possible upload size.
- */
- static function getMaxUploadSize($as_int=false) {
- $post_max_size = ini_get('post_max_size');
- $unit = strtoupper(substr($post_max_size, -1));
- $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
- $post_size = $multiplier*(int)$post_max_size;
- $upload_max_size = ini_get('upload_max_filesize');
- $unit = strtoupper(substr($upload_max_size, -1));
- $multiplier = ($unit == 'M' ? 1048576 : ($unit == 'K' ? 1024 : ($unit == 'G' ? 1073741824 : 1)));
- $upload_size = $multiplier*(int)$upload_max_size;
-
- $max_size = min($post_size, $upload_size);
- if($as_int) {
- return $max_size;
- } else {
- return strtoupper(Library::humanSize($max_size, '%1.0f'));
- }
- }
-
- /**
- * Formats a bytecount to be readable for humans
- * @param $size
- * @param $unit
- * @param $retstring
- * @param $si
- * @author Aidan Lister <aidan@php.net>
- * @link http://aidanlister.com/repos/v/function.rmdirr.php
- * @author Fruml (slight modifications)
- * @return unknown_type
- */
- static function sizeReadable($size, $unit = NULL, $retstring = NULL, $si = true) {
- $sizes = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
- $mod = 1024;
- $ii = count($sizes) - 1;
- $unit = array_search((string) $unit, $sizes);
- if ($unit === NULL || $unit === false) {
- $unit = $ii;
- }
- if ($retstring === NULL) {
- $retstring = '%2.1f';
- }
- $i = 0;
- while ($unit != $i && $size >= 1024 && $i < $ii) {
- $size /= $mod;
- $i++;
- }
- return array(sprintf($retstring, $size), $sizes[$i]);
- }
-
- /**
- * @function humanSize
- * Wrapper for sizeReadable, returns a single string.
- */
- static function humanSize($size, $retstring = NULL) {
- $size = Library::sizeReadable($size, NULL, $retstring, NULL);
- return $size[0].' '.$size[1];
- }
- /**
- * @function incrementFileName
- * Checks to see if a file name contains a counter, and if so, increases it
- */
- static function incrementFilename($file) {
- // split the filename up
- $ext_only = false;
- $file = explode('/', Library::formatPath($file));
- $file_name = array_pop($file);
- $ext = Library::getExtension($file_name);
- $ext = !empty($ext) ? '.'.$ext : '';
- $file_name = str_replace($ext, '', $file_name);
- if(empty($file_name)) {
- $ext_only = true;
- $file_name = $ext;
- }
- $base_path = implode('/', $file).'/';
- // split the file name up using the counter separator (-)
- $file_name_parts = explode('-', $file_name);
- if(count($file_name_parts)==1) {
- $file_name_parts[] = '0';
- }
- // does the file already have an increment counter?
- if(preg_match('/(?<digit>\d+)/', $file_name_parts[count($file_name_parts)-1], $matches)) {
- $counter = $matches[0];
- $new_counter = $counter + 1;
- $file_name_parts[count($file_name_parts)-1] = $new_counter;
- $file_name = implode('-', $file_name_parts);
- } else {
- $file_name .= '-1';
- }
- $path = $base_path.$file_name;
- if(!$ext_only) {
- $path .= $ext;
- }
- return $path;
- }
- /**
- * @function moveTempFile
- * moves a file from it's temp to it's permament location
- */
- public static function moveTempFile($path) {
- if(strpos(Library::formatPath(UPLOAD_PATH.$path), Library::formatPath(UPLOAD_PATH.'/temp/'))!==false) {
- $filename = basename($path);
- $source = Library::formatPath(UPLOAD_PATH.$path);
- $destination = Library::formatPath(UPLOAD_PATH.strtolower($filename[0]).'/');
- if(!ini_get('safe_mode')) {
- if(!file_exists($destination)) {
- $old_umask = umask(0);
- mkdir($destination, 0777);
- umask($old_umask);
- }
- } else {
- $destination = Library::formatPath(UPLOAD_PATH.'/');
- }
- $destination .= $filename;
- while(file_exists($destination)) {
- $destination = Library::incrementFileName($destination);
- }
- Library::disableErrorHandling();
- $res = rename($source, $destination);
- Library::enableErrorHandling();
- if($res===false) {
- Error::raise(trans('could.not.move.uploaded.file'));
- } else {
- return str_replace(UPLOAD_PATH, '', $destination);
- }
- } else {
- return $path;
- }
- }
-
- /**
- * @function disableErrorHandling
- * Turn off error handling
- */
- static function disableErrorHandling() {
- error_reporting(0);
- $old_error_handling = restore_error_handler();
- }
-
- /**
- * @function enableErrorHandling
- * Turn error handling back on again
- */
- static function enableErrorHandling() {
- error_reporting(E_ALL);
- if(!IS_CLI) set_error_handler('catch_errors');
- }
- /**
- * @function loadChains
- * Loads the image chains.
- */
- static $imageChains = array();
- static function loadChains() {
- if(empty(self::$imageChains)) {
- self::$imageChains = Cache::get('imagechains');
- if(is_null(self::$imageChains)) {
- include_once Library::formatPath(APP_PATH.'include/include.image-chains.php');
- $db = DB::getInstance();
- $chains = $db->query("SELECT * FROM %tp%transformation AS t LEFT JOIN %tp%transformation_step AS s ON s.t_id=t.id ORDER BY s.t_id, s.`order` ASC;")->fetchAll();
- foreach($chains as $chain) {
- if(!empty($chain['type'])) {
- self::$imageChains[$chain['name']][] = array($chain['type'], unserialize($chain['parameters']), $chain['id']);
- } else {
- self::$imageChains[$chain['name']] = array();
- }
- }
- Cache::write('imagechains', self::$imageChains);
- }
- }
- }
- /**
- * @function isImage
- * Checks a file's extension to see if it's an image.
- */
- static function isImage($path) {
- $ext = strtolower(self::getExtension($path));
- $images = array('png', 'jpg', 'jpeg', 'gif');
- return in_array($ext, $images);
- }
- /**
- * @function getChain
- * Returns an image chain
- */
- static function getChain($name, $default = true) {
- self::loadChains();
- if(isset(self::$imageChains[$name])) {
- return self::$imageChains[$name];
- } elseif($default) {
- return self::$imageChains['default'];
- } else {
- return false;
- }
- }
- static function updateImagePath($data) {
- $data['path'] = BASE.str_replace(ROOT_PATH, '', $data['path']);
- return $data;
- }
-
- /**
- * Encodes $data for display in a form, uses htmlspeciarchars().
- * @param $data The data to encode.
- * @param $quote_type Quote type to use when encoding, defaults to ENT_QUOTES.
- * @return unknown_type
- */
- static function encode($data, $quote_type=ENT_QUOTES) {
- return htmlspecialchars($data, $quote_type, 'UTF-8');
- }
-
- /**
- * Recursively delete a directory and it's contents
- * @author Aidan Lister <aidan@php.net>
- * @link http://aidanlister.com/repos/v/function.rmdirr.php
- * @param $dirname
- * @return Boolean indicating success at deleting the directory.
- */
- static function rmdirr($dirname) {
- if (!file_exists($dirname)) {
- return false;
- }
- if (is_file($dirname) || is_link($dirname)) {
- return unlink($dirname);
- }
- $dir = dir($dirname);
- while (false !== $entry = $dir->read()) {
- if ($entry == '.' || $entry == '..') {
- continue;
- }
- Library::rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
- }
- $dir->close();
- return rmdir($dirname);
- }
- /**
- * Tells Fruml not to output debug information.
- * @return void
- */
- public static function skipDebug() {
- if(!defined('SKIP_DEBUG')) {
- define('SKIP_DEBUG', true);
- }
- }
-
- /**
- * Pads a string.
- * @param $value The string to pad.
- * @param $len The length to pad the string to.
- * @param $char The character to pad with.
- * @return The padded string.
- */
- static function stringPad($value, $len=2, $char = '0') {
- return str_pad($value, $len, $char, STR_PAD_LEFT);
- }
-
- /**
- * Loads a widget class file and returns the name of the actual widget class.
- * @param $name The id of the widget (e.g. weather).
- * @return String representing the widget's class name (e.g. WeatherWidget).
- */
- static function loadWidget($name) {
- $widget_path = WIDGET_PATH . strtolower($name) . '/widget.' . strtolower($name) . '.php';
- $widget_name = ucfirst($name).'Widget';
- if(class_exists($widget_name, false)) {
- return $widget_name;
- }
- if(file_exists($widget_path)) {
- require_once $widget_path;
- return $widget_name;
- } else {
- return false;
- }
- }
-
- /**
- * Simple wrapper for retrieving remote files. Wrapped here for error_reporting issues. Tries to use cURL if available.
- * @param $url The URL to retrieve.
- * @return The contents of the remote file or false in case of failure (dns, timeout, bad url etc).
- */
- static function getRemoteFile($url, $convert_utf8 = false) {
- self::disableErrorHandling();
- if(function_exists('curl_init')) {
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- curl_setopt($ch, CURLOPT_HEADER, 0);
- curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
- curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
- $res = curl_exec($ch);
- $response = curl_getinfo($ch);
- curl_close($ch);
- if($convert_utf8 && isset($response['content_type'])) {
- $ct = $response['content_type'];
- preg_match('#charset=(.*)#i', $ct, $m);
- if(isset($m[1])) {
- switch (strtolower($m[1])) {
- case 'utf-8':
- break;
- case 'iso-8859-1':
- $res = utf8_encode($res);
- break;
- default:
- $res = iconv($m[1], 'utf-8', $res);
- }
- }
- }
- } else {
- $res = file_get_contents($url);
- foreach ($http_response_header as $header) {
- if (preg_match('#charset=(.*)#i', $header, $m)) {
- switch (strtolower($m[1])) {
- case 'utf-8':
- break;
- case 'iso-8859-1':
- $res = utf8_encode($res);
- break;
- default:
- $res = iconv($m[1], 'utf-8', $res);
- }
- break;
- }
- }
- }
- self::enableErrorHandling();
- return $res;
- }
- /**
- * Pretty-formats the contents of a file. If GeSHi has been installed, it will be used, otherwise the file's contents are wrapped in a <pre> tag.
- * @param $path The file containing the code to highlight
- * @return String containing the highlighted code.
- */
- static function syntaxHighlight($path, $lines = false, $strict = 'maybe') {
- if(file_exists(VENDOR_PATH.'geshi/geshi.php') && filesize($path) < 10240) {
- require_once VENDOR_PATH.'geshi/geshi.php';
- $geshi = new GeSHi('', 'php');
- $geshi->set_header_type(GESHI_HEADER_DIV);
- $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
- $geshi->enable_keyword_links(false);
- $geshi->set_tab_width(4);
- $geshi->load_from_file($path);
- if($strict=='maybe') $strict = GESHI_MAYBE;
- $geshi->enable_strict_mode($strict);
- $geshi->set_overall_class('code-container');
- $geshi->enable_classes();
- if($lines!==false) {
- $geshi->highlight_lines_extra($lines);
- $geshi->set_highlight_lines_extra_style('background-color: #FFDDDD');
- }
- Library::disableErrorHandling();
- $ret = array('code' => $geshi->parse_code(), 'css' => $geshi->get_stylesheet());
- Library::enableErrorHandling();
- return $ret;
- } else {
- return array('code' => '<pre class="code-container">'.htmlentities(file_get_contents($path)).'</pre>', 'css' => '');
- }
- }
-
- /**
- * Pretty-formats the passed string. If GeSHi has been installed, it will be used, otherwise the passed string is wrapped in a <pre> tag.
- * @param $code The code to highlight
- * @return String containing the highlighted code.
- */
- static function syntaxHighlightCode($code, $type='php', $lines = false, $strict = 'maybe', $start = 0) {
- if(file_exists(VENDOR_PATH.'geshi/geshi.php') && Library::length($code) < 10240) {
- require_once VENDOR_PATH.'geshi/geshi.php';
- $geshi = new GeSHi($code, $type);
- $geshi->set_header_type(GESHI_HEADER_DIV);
- $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
- $geshi->enable_keyword_links(false);
- $geshi->set_tab_width(4);
- if($strict=='maybe') $strict = GESHI_MAYBE;
- $geshi->enable_strict_mode($strict);
- $geshi->set_overall_class('code-container');
- $geshi->enable_classes();
- if($lines!==false) {
- $geshi->highlight_lines_extra($lines);
- $geshi->start_line_numbers_at($start);
- $geshi->set_highlight_lines_extra_style('background-color: #FFDDDD');
- }
- Library::disableErrorHandling();
- $ret = array('code' => $geshi->parse_code(), 'css' => $geshi->get_stylesheet());
- Library::enableErrorHandling();
- return $ret;
- } else {
- return array('code' => '<pre class="code-container">'.htmlentities(file_get_contents($code)).'</pre>', 'css' => '');
- }
- }
-
-
- /**
- * Removes empty entries in an array.
- * @param $array The array to unempty.
- * @return Array containingno empty entries.
- */
- static function unempty(Array $array) {
- $res = array();
- foreach($array as $key => $value) {
- if(!empty($value)) {
- $res[$key] = $value;
- }
- }
- return $res;
- }
-
- /**
- * Shortens a string, adds dots
- * @param $string The string to shorten
- * @param $chars The number of characters to keep
- * @param $dots Whether to add dots to the truncated string
- * @return String containing the shortened string.
- */
- static function truncate($string, $chars=30, $dots=true) {
- if(strlen($string)>$chars) {
- $string = substr($string, 0, $chars);
- if($dots) {
- $string .= '...';
- }
- }
- return $string;
- }
- /**
- * Pauses execution for a while.
- * @param $pause The number of seconds to pause
- * @param $debug_only Only pause is DEBUG is set to true
- * @return void
- */
- static function pause($pause=2, $debug_only=true) {
- if(($debug_only==true && DEBUG) || !$debug_only) {
- sleep($pause);
- }
- }
- /**
- * Attempts to change the mode of a file or directory.
- * @param $path The path to change the mode of
- * @param $mode The mode to apply
- * @return Boolean true on success, false on failure
- */
- static function chmod($path, $mode=0666) {
- if(file_exists($path) && is_writable($path)) {
- if(function_exists('chmod') && self::is_enabled('chmod')) {
- self::disableErrorHandling();
- $res = chmod($path, $mode);
- self::enableErrorHandling();
- return $res;
- }
- }
- return false;
- }
-
- /**
- * Checks the disable_functions ini parameter to see if a function is disabled
- * @param $function The function to test for
- * @return Boolean true on success, false on failure
- */
- static function is_enabled($function) {
- $disabled_functions = explode(',', ini_get('disable_functions'));
- return !in_array($function, $disabled_functions);
- }
- /**
- * Loads a library
- * @param $name The name of the library to load
- * @return An instantiated library of type 'name'
- */
- static function loadLibrary($name) {
- $path = LIB_PATH.'lib.'.strtolower($name).'.php';
- if(file_exists($path)) {
- include_once $path;
- return new $name();
- } else {
- Error::raise(sprintf(trans('Cannot load library `%s` - the library file cannot be found.'), $name));
- }
- }
- }
- /**
- * Alias of {@link Libary::dbg()}
- *
- * @param mixed $data,...
- *
- * @see Library::dbg()
- */
- function dbg() {
- $args = func_get_args();
- call_user_func_array(array('Library', 'dbg'), $args);
- }
- /**
- * Alias of {@link Libary::dbgd()}
- *
- * @param mixed $data,...
- * @see Library::dbgd()
- */
- function dbgd() {
- $args = func_get_args();
- call_user_func_array(array('Library', 'dbgd'), $args);
- }
- if(!IS_CLI) {
- function catch_errors($errno, $errstr, $errfile, $errline) {
- Error::raise('<strong>'.$errstr . '</strong><br /><span class="mono">'.$errfile.':'.$errline.'</span>', $errtype='PHP', $errno, $errfile, $errline);
- }
- set_error_handler('catch_errors');
- // base function for unhandled (eep!) exceptions
- function unhandled_exception_handler($exception) {
- Error::raise('Unhandled Exception: '.$exception->getMessage(), $errtype='PHP', $exception->getCode(), $exception->getFile(), $exception->getLine());
- }
- set_exception_handler('unhandled_exception_handler');
- }
- /**
- * Check for question mark or ampersand in url.
- * @return Returns a question mark or an ampersand, depending on NICE_URLS setting
- */
- function qamp($entity = true) {
- if(NICE_URLS) {
- return '?';
- } else {
- return $entity ? '&' : '&' ;
- }
- }
- // translation functions
- $GLOBALS['trans_bound_domains'] = array();
- function trans($string) {
- return T_($string);
- }
- function p_trans($domain, $string) {
- if(!in_array($domain, $GLOBALS['trans_bound_domains'])) {
- T_bindtextdomain($domain, I18N_PATH);
- T_bind_textdomain_codeset($domain, 'utf8');
- $GLOBALS['trans_bound_domains'][] = $domain;
- }
-
- return T_dgettext($domain, $string);
- }