PageRenderTime 59ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/system/library/functions.php

https://github.com/nicksp/rainframework
PHP | 961 lines | 414 code | 191 blank | 356 comment | 88 complexity | b0556dadaa7743b095c3931685352291 MD5 | raw file
Possible License(s): MIT, LGPL-2.1
  1. <?php
  2. /**
  3. * RainFramework
  4. * -------------
  5. * Realized by Federico Ulfo & maintained by the Rain Team
  6. * Distributed under MIT license http://www.opensource.org/licenses/mit-license.php
  7. */
  8. /**
  9. * Functions divided in categories
  10. */
  11. //-------------------------------------------------------------
  12. //
  13. // INPUT FUNCTIONS
  14. //
  15. //-------------------------------------------------------------
  16. // disable register globals
  17. if( ini_get( "register_globals" ) && isset( $_REQUEST ) ) foreach ($_REQUEST as $k => $v) unset($GLOBALS[$k]);
  18. /**
  19. * Get GET input
  20. */
  21. function get( $key = null, $filter = FILTER_SANITIZE_MAGIC_QUOTES ){
  22. if( !$key )
  23. return $filter ? filter_input_array( INPUT_GET, $filter ) : $_GET;
  24. if( isset($_GET[$key]) )
  25. return $filter ? filter_input(INPUT_GET, $key, $filter ) : $_GET[$key];
  26. }
  27. /**
  28. * Get POST input
  29. */
  30. function post( $key = null, $filter = FILTER_SANITIZE_MAGIC_QUOTES ){
  31. if( !$key )
  32. return $filter ? filter_input_array( INPUT_POST, $filter ) : $_POST;
  33. if( isset($_POST[$key]) )
  34. return $filter ? filter_input(INPUT_POST, $key, $filter ) : $_POST[$key];
  35. }
  36. /**
  37. * Get GET_POST input
  38. */
  39. function get_post( $key = null, $filter = FILTER_SANITIZE_MAGIC_QUOTES ){
  40. if( !isset($GLOBALS['_GET_POST'] ) )
  41. $GLOBALS['_GET_POST'] = $_GET + $_POST;
  42. if( !$key )
  43. return $filter ? filter_input_array( $GLOBALS['_GET_POST'], $filter ) : $GLOBALS['_GET_POST'];
  44. if( isset($GLOBALS['_GET_POST'][$key] ) )
  45. return $filter ? filter_var($GLOBALS['_GET_POST'][$key], $filter ) : $GLOBALS['_GET_POST'][$key];
  46. }
  47. /**
  48. * Get COOKIE input
  49. */
  50. function cookie( $key = null, $filter = FILTER_SANITIZE_MAGIC_QUOTES ){
  51. if( isset($_COOKIE[$key]) )
  52. return $filter ? filter_input(INPUT_COOKIE, $key, $filter ) : $_COOKIE[$key];
  53. }
  54. //-------------------------------------------------------------
  55. //
  56. // BENCHMARK/DEBUG FUNCTIONS
  57. //
  58. //-------------------------------------------------------------
  59. /**
  60. * Useful for debug, print the variable $mixed and die
  61. */
  62. function dump( $mixed, $exit = 1 ){
  63. echo "<pre>dump \n---------------------- \n\n" . print_r( $mixed, true ) . "\n----------------------<pre>";
  64. if( $exit ) exit;
  65. }
  66. /**
  67. * Save the memory used at this point
  68. */
  69. function memory_usage_start( $memName = "execution_time" ){
  70. return $GLOBALS['memoryCounter'][$memName] = memory_get_usage();
  71. }
  72. /**
  73. * Get the memory used
  74. */
  75. function memory_usage( $memName = "execution_time", $byte_format = true ){
  76. $totMem = memory_get_usage() - $GLOBALS['memoryCounter'][ $memName ];
  77. return $byte_format ? byte_format($totMem) : $totMem;
  78. }
  79. //-------------------------------------------------------------
  80. //
  81. // TIME FUNCTIONS
  82. //
  83. //-------------------------------------------------------------
  84. /**
  85. * Start the timer
  86. */
  87. function timer_start( $timeName = "execution_time" ){
  88. $stimer = explode( ' ', microtime( ) );
  89. $GLOBALS['timeCounter'][$timeName] = $stimer[ 1 ] + $stimer[ 0 ];
  90. }
  91. /**
  92. * Get the time passed
  93. */
  94. function timer( $timeName = "execution_time", $precision = 6 ){
  95. $etimer = explode( ' ', microtime( ) );
  96. $timeElapsed = $etimer[ 1 ] + $etimer[ 0 ] - $GLOBALS['timeCounter'][ $timeName ];
  97. return substr( $timeElapsed, 0, $precision );
  98. }
  99. /**
  100. * Transform timestamp to readable time format
  101. *
  102. * @param int $time unix timestamp
  103. * @param string format of time (use the constant fdate_format or ftime_format)
  104. */
  105. function time_format( $time=null, $format=DATE_FORMAT ){
  106. return strftime( $format, $time );
  107. }
  108. /**
  109. * Transform timestamp to readable time format as elapsed time e.g. 3 days ago, or 5 minutes ago to a maximum of a week ago
  110. *
  111. * @param int $time unix timestamp
  112. * @param string format of time (use the constant fdate_format or ftime_format)
  113. */
  114. function time_elapsed( $time = null, $format ){
  115. $diff = TIME - $time;
  116. if( $diff < MINUTE )
  117. return $diff . " " . get_msg('seconds_ago');
  118. elseif( $diff < HOUR )
  119. return ceil($diff/60) . " " . get_msg('minutes_ago');
  120. elseif( $diff < 12*HOUR )
  121. return ceil($diff/3600) . " " . get_msg('hours_ago');
  122. elseif( $diff < DAY )
  123. return get_msg('today') . " " . strftime( TIME_FORMAT, $time );
  124. elseif( $diff < DAY*2 )
  125. return get_msg('yesterday') . " " . strftime( TIME_FORMAT, $time );
  126. elseif( $diff < WEEK )
  127. return ceil($diff/DAY) . " " . get_msg('days_ago') . " " . strftime( TIME_FORMAT, $time );
  128. else
  129. return strftime( $format, $time );
  130. }
  131. /**
  132. * Convert seconds to hh:ii:ss
  133. */
  134. function sec_to_hms($sec) {
  135. $hours = intval(intval($sec) / 3600);
  136. $hms = str_pad($hours, 2, "0", STR_PAD_LEFT). ':';
  137. $minutes = intval(($sec / 60) % 60);
  138. $hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ':';
  139. $seconds = intval($sec % 60);
  140. $hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
  141. return $hms;
  142. }
  143. /**
  144. * Convert seconds to string, eg. "2 minutes", "1 hour", "16 seconds"
  145. */
  146. function sec_to_string($sec) {
  147. $str = null;
  148. if( $hours = intval(intval($sec) / 3600) )
  149. $str .= $hours > 1 ? $hours . " " . get_msg('hours') : $hours . " " . get_msg('hour');
  150. if( $minutes = intval(($sec / 60) % 60) )
  151. $str .= $minutes > 1 ? $minutes . " " . get_msg('minutes') : $minutes . " " . get_msg('minute');
  152. if( $seconds = intval($sec % 60) )
  153. $str .= $seconds > 1 ? $seconds . " " . get_msg('seconds') : $seconds . " " . get_msg('second');
  154. return $str;
  155. }
  156. //-------------------------------------------------------------
  157. //
  158. // STRING FUNCTIONS
  159. //
  160. //-------------------------------------------------------------
  161. /**
  162. * Cut html
  163. * text, length, ending, tag allowed, $remove_image true / false, $exact true=the ending words are not cutted
  164. * Note: I get this functions from web but I don't remember the source. It should be from cakePHP.
  165. */
  166. function cut_html( $text, $length = 100, $ending = '...', $allowed_tags = '<b><i>', $remove_image = true, $exact = false ) {
  167. if( !$remove_image )
  168. $allowed_tags .= '<img>';
  169. $text = strip_tags($text, $allowed_tags );
  170. if (strlen(preg_replace('/<.*?>/', '', $text)) <= $length)
  171. return $text;
  172. // splits all html-tags to scanable lines
  173. preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
  174. $total_length = strlen($ending);
  175. $open_tags = array();
  176. $truncate = '';
  177. foreach ($lines as $line_matchings) {
  178. // if there is any html-tag in this line, handle it and add it (uncounted) to the output
  179. if (!empty($line_matchings[1])) {
  180. // if it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>)
  181. if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
  182. // do nothing
  183. // if tag is a closing tag (f.e. </b>)
  184. } else if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
  185. // delete tag from $open_tags list
  186. $pos = array_search($tag_matchings[1], $open_tags);
  187. if ($pos !== false) {
  188. unset($open_tags[$pos]);
  189. }
  190. // if tag is an opening tag (f.e. <b>)
  191. } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $line_matchings[1], $tag_matchings)) {
  192. // add tag to the beginning of $open_tags list
  193. array_unshift($open_tags, strtolower($tag_matchings[1]));
  194. }
  195. // add html-tag to $truncate'd text
  196. $truncate .= $line_matchings[1];
  197. }
  198. // calculate the length of the plain text part of the line; handle entities as one character
  199. $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
  200. if ($total_length+$content_length> $length) {
  201. // the number of characters which are left
  202. $left = $length - $total_length;
  203. $entities_length = 0;
  204. // search for html entities
  205. if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
  206. // calculate the real length of all entities in the legal range
  207. foreach ($entities[0] as $entity) {
  208. if ($entity[1]+1-$entities_length <= $left) {
  209. $left--;
  210. $entities_length += strlen($entity[0]);
  211. } else {
  212. // no more characters left
  213. break;
  214. }
  215. }
  216. }
  217. $truncate .= substr($line_matchings[2], 0, $left+$entities_length);
  218. // maximum lenght is reached, so get off the loop
  219. break;
  220. } else {
  221. $truncate .= $line_matchings[2];
  222. $total_length += $content_length;
  223. }
  224. // if the maximum length is reached, get off the loop
  225. if($total_length>= $length)
  226. break;
  227. }
  228. // don't cut the last words
  229. if (!$exact && $spacepos = strrpos($truncate, ' ') )
  230. $truncate = substr($truncate, 0, $spacepos);
  231. $truncate .= $ending;
  232. foreach ($open_tags as $tag)
  233. $truncate .= '</' . $tag . '>';
  234. return $truncate;
  235. }
  236. /**
  237. * Cut string and add ... at the end
  238. * useful to cut noHTML text, for example to cut the title of an article
  239. */
  240. function cut( $string, $length, $ending = "..." ){
  241. if( strlen( $string ) > $length )
  242. return $string = substr( $string, 0, $length ) . $ending;
  243. else
  244. return $string = substr( $string, 0, $length );
  245. }
  246. /**
  247. * Return a random string
  248. */
  249. function rand_str($length = 5, $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890'){
  250. $chars_length = (strlen($chars) - 1);
  251. $string = $chars{rand(0, $chars_length)};
  252. for ($i = 1; $i < $length; $i = strlen($string)){
  253. $r = $chars{rand(0, $chars_length)};
  254. if ($r != $string{$i - 1}) $string .= $r;
  255. }
  256. return $string;
  257. }
  258. //-------------------------------------------------------------
  259. //
  260. // NUMBER FUNCTIONS
  261. //
  262. //-------------------------------------------------------------
  263. /**
  264. * Convert byte to more readable format, like "1 KB" instead of "1024".
  265. * cut_zero, remove the 0 after comma ex: 10,00 => 10 14,30 => 14,3
  266. */
  267. function byte_format( $size ){
  268. if( $size > 0 ){
  269. $unim = array("B","KB","MB","GB","TB","PB");
  270. for( $i=0; $size >= 1024; $i++ )
  271. $size = $size / 1024;
  272. return number_format($size,$i?2:0, DEC_POINT, THOUSANDS_SEP )." ".$unim[$i];
  273. }
  274. }
  275. /**
  276. * Format the money in the current format. If add_currency is true the function add the currency configured into the language
  277. */
  278. function format_money( $number, $add_currency = false ){
  279. return ( $add_currency && CURRENCY_SIDE == 0 ? CURRENCY . " " : "" ) . number_format($number,2,DEC_POINT,THOUSANDS_SEP) . ( $add_currency && CURRENCY_SIDE == 1 ? " " . CURRENCY : "" );
  280. }
  281. //-------------------------------------------------------------
  282. //
  283. // EMAIL FUNCTIONS
  284. //
  285. //-------------------------------------------------------------
  286. /**
  287. * Return true if the email is valid else false
  288. */
  289. function is_email( $email ){
  290. return preg_match('|^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$|i', $email );
  291. }
  292. /**
  293. * Send an email
  294. * @param $to
  295. */
  296. function email_send( $to, $subject, $body, $from = null, $from_name = null, $attachment = null, $embed_images = false ){
  297. // TO DO: use the email class
  298. }
  299. /**
  300. * Send an email with selected template
  301. */
  302. function email_tpl_send( $template = "generic/email", $to, $subject, $body, $from = null, $from_name = null, $attachment = null){
  303. $tpl = new TPL();
  304. $tpl->assign("body", $body );
  305. $body = $tpl->draw( $template, true );
  306. return emailSend( $to, $subject, $body, $from, $from_name, $attachment );
  307. }
  308. //-------------------------------------------------------------
  309. //
  310. // FILE FUNCTIONS
  311. //
  312. //-------------------------------------------------------------
  313. /**
  314. * Return list of dir and files without . ..
  315. *
  316. * @param string $d directory
  317. */
  318. function dir_scan($dir){
  319. if( is_dir($dir) && $dh = opendir($dir) ){ $f=array(); while ($fn = readdir($dh)) { if($fn!='.'&&$fn!='..') $f[] = $fn; } return $f; }
  320. }
  321. /**
  322. * Get the list of files filtered by extension ($ext)
  323. *
  324. * @param string $d directory
  325. * @param string $ext extension filter, example ".jpg"
  326. */
  327. function file_list($dir,$ext=null){
  328. if( $dl=dir_scan($dir) ){ $l=array(); foreach( $dl as $f ) if( is_file($dir.'/'.$f) && ($ext?preg_match('/\.'.$ext.'$/',$f):1) ) $l[]=$f; return $l; }
  329. }
  330. /**
  331. * Get the list of directory
  332. *
  333. * @param string $dir directory
  334. */
  335. function dir_list($dir){
  336. if( $dl=dir_scan($dir) ){ $l=array(); foreach($dl as $f)if(is_dir($dir.'/'.$f))$l[]=$f; return $l; }
  337. }
  338. /**
  339. * File extension
  340. *
  341. * @param string $file filename
  342. */
  343. function file_ext($filename){
  344. return substr(strrchr($filename, '.'),1);
  345. }
  346. /**
  347. * Get the name without extension
  348. *
  349. * @param string $f filename
  350. */
  351. function file_name($filename){
  352. if( ($filename = basename($filename) ) && ( $dot_pos = strrpos( $filename , "." ) ) )
  353. return substr( $filename, 0, $dot_pos );
  354. }
  355. /**
  356. * Delete dir and contents
  357. *
  358. * @param string $dir directory
  359. */
  360. function dir_del($dir) {
  361. if( $l=dir_scan($dir) ){ foreach($l as $f) if (is_dir($dir."/".$f)) dir_del($dir.'/'.$f); else unlink($dir."/".$f); return rmdir($dir); }
  362. }
  363. /**
  364. * Copy all the content of a directory
  365. *
  366. * @param string $s source directory
  367. * @param string $d destination directory
  368. */
  369. function dir_copy( $source, $dest) {
  370. if (is_file($source)){
  371. copy($source, $dest);
  372. chmod($dest, fileperms($source) );
  373. }
  374. else{
  375. mkdir( $dest, 0777 );
  376. if( $l=dir_scan($source) ){ foreach( $l as $f ) dir_copy("$source/$f", "$dest/$f"); }
  377. }
  378. }
  379. /**
  380. * Upload one file selected with $file. Use it when you pass only one file with a form.
  381. * The file is saved into UPLOADS_DIR, the name created as "md5(time()) . file_extension"
  382. * it return the filename
  383. *
  384. * @return string uploaded filename
  385. */
  386. function upload_file($file){
  387. if( $_FILES[$file]["tmp_name"] ){
  388. $upload_filepath = UPLOADS_DIR . ( $filename = md5(time()).".".( strtolower( file_ext($_FILES[$file]['name'] ) ) ) );
  389. move_uploaded_file( $_FILES[$file]["tmp_name"], $upload_filepath );
  390. return $filename;
  391. }
  392. }
  393. /**
  394. * Upload an image file and create a thumbnail
  395. *
  396. * @param string $file
  397. * @param string $UPLOADS_DIR
  398. * @param string $thumb_prefix Prefisso della thumbnail
  399. * @param int $max_width
  400. * @param int $max_height
  401. * @param bool $square
  402. * @return string Nome del file generato
  403. */
  404. function upload_image( $file, $thumb_prefix = null, $max_width = 128, $max_height = 128, $square = false ){
  405. if( $filename = upload_file( $file ) ){
  406. image_resize( UPLOADS_DIR . $filename, UPLOADS_DIR . $thumb_prefix . $filename, $max_width, $max_height, $square );
  407. return $filename;
  408. //try to create the thumbnail
  409. if( $thumb_prefix && !image_resize( UPLOADS_DIR . $filename, UPLOADS_DIR . $thumb_prefix . $filename, $max_width, $max_height, $square ) ){
  410. unlink( UPLOADS_DIR . $filename );
  411. return false;
  412. }
  413. return $filename;
  414. }
  415. }
  416. function reduce_path( $path ){
  417. $path = str_replace( "://", "@not_replace@", $path );
  418. $path = preg_replace( "#(/+)#", "/", $path );
  419. $path = preg_replace( "#(/\./+)#", "/", $path );
  420. $path = str_replace( "@not_replace@", "://", $path );
  421. while( preg_match( '#\.\./#', $path ) ){
  422. $path = preg_replace('#\w+/\.\./#', '', $path );
  423. }
  424. return $path;
  425. }
  426. //-------------------------------------------------------------
  427. //
  428. // IMAGE FUNCTIONS
  429. //
  430. //-------------------------------------------------------------
  431. /**
  432. * resize
  433. */
  434. function image_resize($source, $dest, $new_width, $new_height, $quality) {
  435. if( $memory_limit = get_setting('memory_limit') ){
  436. $old_memory_limit = ini_get('memory_limit');
  437. ini_set('memory_limit', $memory_limit );
  438. }
  439. // increase the memory limit for resizing the image
  440. switch ($ext = file_ext($source)) {
  441. case 'jpg':
  442. case 'jpeg': $source_img = imagecreatefromjpeg($source);
  443. break;
  444. case 'png': $source_img = imagecreatefrompng($source);
  445. break;
  446. case 'gif': $source_img = imagecreatefromgif($source);
  447. break;
  448. default:
  449. return false;
  450. }
  451. list($width, $height) = getimagesize($source);
  452. // create a new true color image
  453. $dest_img = imagecreatetruecolor($new_width, $new_height);
  454. imagealphablending($dest_img, false);
  455. $origin_x = $origin_y = 0;
  456. $dest_canvas_color = 'ffffff';
  457. $dest_img_color_R = hexdec(substr($dest_canvas_color, 0, 2));
  458. $dest_img_color_G = hexdec(substr($dest_canvas_color, 2, 2));
  459. $dest_img_color_B = hexdec(substr($dest_canvas_color, 2, 2));
  460. // Create a new transparent color for image
  461. $color = imagecolorallocatealpha($dest_img, $dest_img_color_R, $dest_img_color_G, $dest_img_color_B, 127);
  462. // Completely fill the background of the new image with allocated color.
  463. imagefill($dest_img, 0, 0, $color);
  464. // Restore transparency blending
  465. imagesavealpha($dest_img, true);
  466. $src_x = $src_y = 0;
  467. $src_w = $width;
  468. $src_h = $height;
  469. $cmp_x = $width / $new_width;
  470. $cmp_y = $height / $new_height;
  471. // calculate x or y coordinate and width or height of source
  472. if ($cmp_x > $cmp_y) {
  473. $src_w = round($width / $cmp_x * $cmp_y);
  474. $src_x = round(($width - ($width / $cmp_x * $cmp_y)) / 2);
  475. } else if ($cmp_y > $cmp_x) {
  476. $src_h = round($height / $cmp_y * $cmp_x);
  477. $src_y = round(($height - ($height / $cmp_y * $cmp_x)) / 2);
  478. }
  479. imagecopyresampled($dest_img, $source_img, $origin_x, $origin_y, $src_x, $src_y, $new_width, $new_height, $src_w, $src_h);
  480. switch ($ext) {
  481. case 'png': imagepng($dest_img, $dest, ceil($quality / 10));
  482. break;
  483. case 'gif': imagegif($dest_img, $dest, $quality);
  484. break;
  485. default: imagejpeg($dest_img, $dest, $quality);
  486. }
  487. imagedestroy($source_img);
  488. imagedestroy($dest_img);
  489. if( !$memory_limit )
  490. ini_set( 'memory_limit', $old_memory_limit );
  491. return true;
  492. }
  493. //-------------------------------------------------------------
  494. //
  495. // HOOKS FUNCTIONS
  496. //
  497. //-------------------------------------------------------------
  498. /**
  499. * Hooks allows to load files, execute classes or execute functions,
  500. * defined into globals $hooks variable. You can set the code you want to execute
  501. * by calling hooks_add_file, hooks_add_function, hooks_add_class
  502. *
  503. * @param string $name Name of the hooks
  504. *
  505. function hooks($name){
  506. global $hooks;
  507. if( isset($hooks[$name]) && is_array( $hooks[$name] ) ){
  508. foreach( $hooks[$name] as $hook ){
  509. $file = $hook['file'];
  510. $class = $hook['class'];
  511. $function = $hook['function'];
  512. $params = $hook['params'];
  513. if( $file ){
  514. if( file_exists($file) ){
  515. if( $class or $function )
  516. require_once $file;
  517. else
  518. require $file;
  519. }
  520. else
  521. trigger_error('HOOKS: FILE NOT FOUND',E_WARNING);
  522. }
  523. if( $class ){
  524. if( class_exists($class) ){
  525. for($i=0,$n=count($params),$param="";$i<$n;$i++)
  526. $param .= $i>0 ? ',$params['.$i.']' : '$params['.$i.']';
  527. if( !$function or $function==$class )
  528. eval( '$obj = new $class('.$param.')' );
  529. else{
  530. $obj = new $class;
  531. if( is_callable(array($obj,$function) ) )
  532. eval( '$obj->$function( ' . $param . ' );' );
  533. else
  534. trigger_error("HOOKS: METHOD NOT FOUND OR NOT CALLABLE",E_WARNING);
  535. }
  536. }
  537. else
  538. trigger_error('HOOKS: CLASS NOT FOUND',E_WARNING);
  539. }elseif( $function ){
  540. if( function_exists($function) )
  541. $function($params);
  542. else
  543. trigger_error('HOOKS: FUNCTION NOT FOUND',E_WARNING);
  544. }
  545. }
  546. }
  547. }
  548. /**
  549. * You can add a function or a method
  550. *
  551. function hooks_add_function($name,$function,$params=null,$file=null){
  552. global $hooks;
  553. $hooks[$name][] = array( 'file'=>$file,'class'=>null, 'function'=>$function, 'params'=>$params );
  554. }
  555. /**
  556. * You can add a method
  557. *
  558. function hooks_add_class($name,$class,$function=null,$params=null,$file=null){
  559. global $hooks;
  560. $hooks[$name][] = array( 'file'=>$file,'class'=>$class,'function'=>$function, 'params'=>$params );
  561. }
  562. /**
  563. * It add a file to hooks, HTML or PHP is ok.
  564. *
  565. function hooks_add_file($name,$file){
  566. global $hooks;
  567. $hooks[$name][] = array( 'file'=>$file,'class'=>null,'function'=>null,'params'=>null );
  568. }
  569. */
  570. //-------------------------------------------------------------
  571. //
  572. // Settings
  573. //
  574. //-------------------------------------------------------------
  575. function get_setting( $key = null ){
  576. global $settings;
  577. if( !$key )
  578. return $settings;
  579. if( isset( $settings[$key] ) )
  580. return $settings[$key];
  581. }
  582. //-------------------------------------------------------------
  583. //
  584. // Language
  585. //
  586. //-------------------------------------------------------------
  587. /**
  588. * Get the translated string if in language dictionary, return the string if not
  589. *
  590. * @param string $msg Msg to translate
  591. * @param string $modifier You can choose a modifier from: strtoupper, strtolower, ucwords, ucfirst
  592. * @return translated string
  593. */
  594. function get_msg( $msg, $modifier = null ){
  595. global $lang;
  596. if( isset($lang[$msg]))
  597. $msg = $lang[$msg];
  598. return $modifier ? $modifier($msg) : $msg;
  599. }
  600. function get_lang(){
  601. return LANG_ID;
  602. }
  603. function load_lang( $file ){
  604. require_once LANGUAGE_DIR . get_lang() . "/" . $file . ".php";
  605. }
  606. function get_installed_language(){
  607. return dir_list(LANGUAGE_DIR);
  608. }
  609. // draw a message styled as SUCCESS, WARNING, ERROR or INFO. See .box in style.css for the style
  610. function draw_msg( $msg, $type = SUCCESS, $close = false, $autoclose = 0 ){
  611. add_script("jquery.min.js", JQUERY_DIR );
  612. add_style( "box.css", CSS_DIR );
  613. $box_id = rand(0,9999) . "_" . time();
  614. if( $close )
  615. $close = '<div class="close"><a onclick="$(\'#box_'.$box_id.'\').slideUp();">x</a></div>';
  616. if($autoclose)
  617. add_javascript( 'setTimeout("$(\'#box_'.$box_id.'\').slideUp();", "'.($autoclose*1000).'")', $onload=true );
  618. switch( $type ){
  619. case SUCCESS: $class = 'success'; break;
  620. case WARNING: $class = 'warning'; break;
  621. case ERROR: $class = 'error'; break;
  622. case INFO: $class = 'info'; break;
  623. }
  624. // style defined in style.css as .box
  625. return '<div class="box box_'.$class.'" id="box_'.$box_id.'">'.$close.$msg.'</div>';
  626. }
  627. //-------------------------------------------------------------
  628. //
  629. // Javascript & CSS
  630. //
  631. //-------------------------------------------------------------
  632. //style sheet and javascript
  633. global $style, $script, $javascript, $javascript_onload;
  634. $style = $script = array();
  635. $javascript = $javascript_onload = "";
  636. //add style sheet
  637. function add_style( $file, $dir = CSS_DIR, $url = null ){
  638. if( !$url )
  639. $url = URL . $dir;
  640. $GLOBALS['style'][$dir . $file] = $url . $file;
  641. }
  642. //add javascript file
  643. function add_script( $file, $dir = JAVASCRIPT_DIR, $url = null ){
  644. if( !$url )
  645. $url = URL . $dir;
  646. $GLOBALS['script'][$dir . $file] = $url . $file;
  647. }
  648. //add javascript code
  649. function add_javascript( $javascript, $onload = false ){
  650. if( !$onload )
  651. $GLOBALS['javascript'] .= "\n".$javascript."\n";
  652. else
  653. $GLOBALS['javascript_onload'] .= "\n".$javascript."\n";
  654. }
  655. /**
  656. * get javascript
  657. */
  658. function get_javascript( $compression = false ){
  659. global $script, $javascript, $javascript_onload;
  660. $html = "";
  661. if( $script ){
  662. if( $compression ){
  663. $js_file = "";
  664. foreach( $script as $file => $url)
  665. $js_file .= "$url,";
  666. $html = '<script src="/js.php?'.$js_file.'" type="text/javascript"></script>' . "\n";
  667. }
  668. else{
  669. foreach( $script as $s )
  670. $html .= '<script src="'.$s.'" type="text/javascript"></script>' . "\n";
  671. }
  672. }
  673. if( $javascript_onload ) $javascript .= "\n" . "$(function(){" . "\n" . " $javascript_onload" . "\n" . "});" . "\n";
  674. if( $javascript ) $html .= "<script type=\"text/javascript\">" . "\n" .$javascript . "\n" . "</script>";
  675. return $html;
  676. }
  677. /**
  678. * get the style
  679. */
  680. function get_style( $compression = false ){
  681. global $style;
  682. $html = "";
  683. if( $style ){
  684. if( $compression ){
  685. $css_file = "";
  686. foreach( $style as $file => $url)
  687. $css_file .= "$url,";
  688. $html = ' <link rel="stylesheet" href="/css.php?'.$css_file.'" type="text/css" />' . "\n";
  689. }
  690. else{
  691. foreach( $style as $file => $url)
  692. $html .= ' <link rel="stylesheet" href="'.$url.'" type="text/css" />' . "\n";
  693. }
  694. }
  695. return $html;
  696. }
  697. //-------------------------------------------------------------
  698. //
  699. // LOCALIZATION FUNCTIONS
  700. //
  701. //-------------------------------------------------------------
  702. function get_ip(){
  703. if( !defined("IP") ){
  704. $ip = getenv( "HTTP_X_FORWARDED_FOR" ) ? getenv( "HTTP_X_FORWARDED_FOR" ) : getenv( "REMOTE_ADDR" );
  705. if( !preg_match("^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}^", $ip ) ) $ip = null;
  706. define( "IP", $ip );
  707. }
  708. return IP;
  709. }
  710. /**
  711. * Return true if $ip is a valid ip
  712. */
  713. function is_ip($ip){
  714. return preg_match("^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}^", $ip );
  715. }
  716. /**
  717. * Return the array with all geolocation info of user selected by IP
  718. * ip = your IP
  719. * assoc = true if you want the result as array
  720. */
  721. if( !defined("IPINFODB_KEY" ) )
  722. define( "IPINFODB_KEY", "YOUR_KEY" );
  723. function ip_to_location( $ip = IP, $assoc = true ){
  724. // if ip is correct and it can access to the URL it will get the array with all the user localization info
  725. if( is_ip( $ip ) && file_exists( $url = "http://api.ipinfodb.com/v2/ip_query.php?key=".IPINFODB_KEY."&ip={$ip}&output=json&timezone=true" ) && ($json = file_get_contents( $url ) ) )
  726. return json_decode( $json, $assoc );
  727. }
  728. /**
  729. * Return the browser information of the logged user
  730. */
  731. function get_browser_info(){
  732. if( !isset( $GLOBALS['rain_browser_info'] ) ){
  733. $known = array('msie', 'firefox', 'safari', 'webkit', 'opera', 'netscape', 'konqueror', 'gecko');
  734. preg_match( '#(' . join('|', $known) . ')[/ ]+([0-9]+(?:\.[0-9]+)?)#', strtolower($_SERVER['HTTP_USER_AGENT']), $br );
  735. preg_match_all( '#\((.*?);#', $_SERVER['HTTP_USER_AGENT'], $os );
  736. global $rain_browser_info;
  737. $rain_browser_info['lang_id'] = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2);
  738. $rain_browser_info['browser'] = isset( $br[1][1] ) ? $br[1][1] : null;
  739. $rain_browser_info['version'] = isset( $br[2][1] ) ? $br[2][1] : null;
  740. $rain_browser_info['os'] = $od[1][0];
  741. }
  742. return $GLOBALS['rain_browser_info'];
  743. }
  744. //-------------------------------------------------------------
  745. //
  746. // URL FUNCTIONS
  747. //
  748. //-------------------------------------------------------------
  749. // alias for redirect
  750. function reindex( $url ){
  751. redirect( $url );
  752. }
  753. function redirect( $url ){
  754. header( "location: $url" );
  755. }
  756. // -- end