Functions.class.php 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. <?php
  2. /**
  3. * Tool library wich provide many common functions to ease your life :)
  4. *
  5. * @author Idleman
  6. * @category Tools
  7. * @license cc by nc sa
  8. */
  9. class Functions
  10. {
  11. private $id;
  12. public $debug=0;
  13. /**
  14. * Secure client var
  15. * #### Example
  16. * ```php
  17. * Functions::secure($_GET['nonThrustedInput']);
  18. * ```
  19. * @param mixed var to secure
  20. * @return mixed secured var
  21. */
  22. public static function secure($var){
  23. if(is_array($var)){
  24. $array = array();
  25. foreach($var as $key=>$value):
  26. $array[self::secure($key)] = self::secure($value);
  27. endforeach;
  28. return $array;
  29. } else {
  30. return str_replace('&amp;','&',htmlspecialchars($var, ENT_NOQUOTES, "UTF-8"));
  31. }
  32. }
  33. /**
  34. * Get client IP
  35. * #### Example
  36. * ```php
  37. * Functions::getIP();
  38. * ```
  39. * @return string client ip
  40. */
  41. public static function getIP(){
  42. if(isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
  43. $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];}
  44. elseif(isset($_SERVER['HTTP_CLIENT_IP'])){
  45. $ip = $_SERVER['HTTP_CLIENT_IP'];}
  46. else{ $ip = $_SERVER['REMOTE_ADDR'];}
  47. return $ip;
  48. }
  49. /**
  50. * Truncate string after 'x' characters and add '...'
  51. * #### Example
  52. * ```php
  53. * echo Functions::truncate('This is incredibly long !!',5);
  54. * ```
  55. * @param string String to truncate
  56. * @param int Max length before truncate
  57. * @return string truncated string
  58. */
  59. public static function truncate($msg,$limit){
  60. if(mb_strlen($msg)>$limit){
  61. $fin='…' ;
  62. $nb=$limit-mb_strlen($fin) ;
  63. }else{
  64. $nb=mb_strlen($msg);
  65. $fin='';
  66. }
  67. return mb_substr($msg, 0, $nb).$fin;
  68. }
  69. /**
  70. * Get script base url (require calling file path in parameter)
  71. * #### Example
  72. * ```php
  73. * echo Functions::getBaseUrl('action.php');
  74. * ```
  75. * @param string calling file path
  76. * @return string base url
  77. */
  78. public static function getBaseUrl($from){
  79. $protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  80. $split = explode('/'.$from,$_SERVER['REQUEST_URI']);
  81. return $protocol.$_SERVER['HTTP_HOST'].$split[0];
  82. }
  83. /**
  84. * Definis si la chaine fournie est existante dans la reference fournie ou non
  85. * @TODO delete that after verifying that is not used by plugin or core!
  86. * @param unknown_type $string
  87. * @param unknown_type $reference
  88. * @return false si aucune occurence du string, true dans le cas contraire
  89. */
  90. public static function contain($string,$reference){
  91. $return = true;
  92. $pos = strpos($reference,$string);
  93. if ($pos === false) {
  94. $return = false;
  95. }
  96. return strtolower($return);
  97. }
  98. /**
  99. * @TODO delete that after verifying that is not used by plugin or core!
  100. * Définis si la chaine passée en parametre est une url ou non
  101. */
  102. public static function isUrl($url){
  103. $return =false;
  104. if (preg_match('/^(http|https|ftp)://([A-Z0-9][A-Z0-9_-]*(?:.[A-Z0-9][A-Z0-9_-]*)+):?(d+)?/?/i', $url)) {
  105. $return =true;
  106. }
  107. return $return;
  108. }
  109. /**
  110. * @TODO delete that after verifying that is not used by plugin or core!
  111. * Définis si la chaine passée en parametre est une couleur héxadécimale ou non
  112. */
  113. public static function isColor($color){
  114. $return =false;
  115. if (preg_match('/^#(?:(?:[a-fd]{3}){1,2})$/i', $color)) {
  116. $return =true;
  117. }
  118. return $return;
  119. }
  120. /**
  121. * @TODO delete that after verifying that is not used by plugin or core!
  122. * Définis si la chaine passée en parametre est un mail ou non
  123. */
  124. public static function isMail($mail){
  125. $return =false;
  126. if (filter_var($mail, FILTER_VALIDATE_EMAIL)) {
  127. $return =true;
  128. }
  129. return $return;
  130. }
  131. /**
  132. * @TODO delete that after verifying that is not used by plugin or core!
  133. * Définis si la chaine passée en parametre est une IP ou non
  134. */
  135. public static function isIp($ip){
  136. $return =false;
  137. if (preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',$ip)) {
  138. $return =true;
  139. }
  140. return $return;
  141. }
  142. public static function makeCookie($name, $value,$expire) {
  143. setcookie($name,$value,$expire,'/');
  144. }
  145. public static function destroyCookie($name){
  146. setcookie(COOKIE_NAME, "", time()-3600,"/");
  147. }
  148. public static function convertFileSize($bytes)
  149. {
  150. if($bytes<1024){
  151. return round(($bytes / 1024), 2).' o';
  152. }elseif(1024<$bytes && $bytes<1048576){
  153. return round(($bytes / 1024), 2).' ko';
  154. }elseif(1048576<$bytes && $bytes<1073741824){
  155. return round(($bytes / 1024)/1024, 2).' Mo';
  156. }elseif(1073741824<$bytes){
  157. return round(($bytes / 1024)/1024/1024, 2).' Go';
  158. }
  159. }
  160. //Calcul une adresse relative en fonction de deux adresse absolues
  161. public static function relativePath($from, $to, $ps = '/') {
  162. $arFrom = explode($ps, rtrim($from, $ps));
  163. $arTo = explode($ps, rtrim($to, $ps));
  164. while(count($arFrom) && count($arTo) && ($arFrom[0] == $arTo[0])) {
  165. array_shift($arFrom);
  166. array_shift($arTo);
  167. }
  168. return str_pad("", count($arFrom) * 3, '..'.$ps).implode($ps, $arTo);
  169. }
  170. //Transforme une date en timestamp
  171. public static function totimestamp($date,$delimiter='/')
  172. {
  173. $explode=explode($delimiter,$date);
  174. return strtotime($explode[1].'/'.$explode[0].'/'.$explode[2]);
  175. }
  176. public static function goback($page,$section="",$param="")
  177. {
  178. if ($section == "")
  179. {
  180. header('location:'.$page.'.php '.$param);
  181. }
  182. else
  183. {
  184. header('location:'.$page.'.php?section='.$section.$param);
  185. }
  186. }
  187. public static function rmFullDir($path){
  188. $files = array_diff(scandir($path), array('.','..'));
  189. foreach ($files as $file) {
  190. (is_dir("$path/$file")) ? Functions::rmFullDir("$path/$file") : unlink("$path/$file");
  191. }
  192. return rmdir($path);
  193. }
  194. public static function log($message,$type = 'notice'){
  195. $message = date('d-m-Y H:i:s').' - ['.$type.'] :'.$message.PHP_EOL;
  196. if(!file_exists(LOG_FILE)) touch(LOG_FILE);
  197. $linecount = 0;
  198. $handle = fopen(LOG_FILE, "r");
  199. while(fgets($handle)!=false){
  200. $linecount++;
  201. }
  202. fclose($handle);
  203. if($linecount>1000) unlink(LOG_FILE);
  204. file_put_contents(LOG_FILE,$message,FILE_APPEND);
  205. }
  206. public static function alterBase($versions,$current){
  207. $manager = new User();
  208. foreach($versions as $version){
  209. if($version['version'] <= $current) continue;
  210. set_error_handler('Functions::alterBaseError');
  211. foreach($version['sql'] as $command){
  212. $sql = str_replace(array('{PREFIX}'), array(MYSQL_PREFIX), $command);
  213. Functions::log('Execute alter base query: '.$sql);
  214. $manager->customQuery($sql);
  215. }
  216. restore_error_handler();
  217. }
  218. }
  219. public static function alterBaseError($errno, $errstr, $errfile, $errline){
  220. self::log("Erreur update sql : [$errno] $errstr L$errline dans le fichier $errfile");
  221. }
  222. public static function array_rand($array){
  223. return $array[array_rand($array)];
  224. }
  225. public static function tail($filepath, $lines = 1, $adaptive = true) {
  226. $f = @fopen($filepath, "rb");
  227. if ($f === false) return false;
  228. if (!$adaptive) $buffer = 4096;
  229. else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));
  230. fseek($f, -1, SEEK_END);
  231. if (fread($f, 1) != "\n") $lines -= 1;
  232. $output = '';
  233. $chunk = '';
  234. while (ftell($f) > 0 && $lines >= 0) {
  235. $seek = min(ftell($f), $buffer);
  236. fseek($f, -$seek, SEEK_CUR);
  237. $output = ($chunk = fread($f, $seek)) . $output;
  238. fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);
  239. $lines -= substr_count($chunk, "\n");
  240. }
  241. while ($lines++ < 0) {
  242. $output = substr($output, strpos($output, "\n") + 1);
  243. }
  244. fclose($f);
  245. return trim($output);
  246. }
  247. public static function htmlAlert($type,$message){
  248. switch ($type) {
  249. case 'error':
  250. echo '<div class="alert alert-error"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Erreur!</strong> ';
  251. break;
  252. case 'info':
  253. echo '<div class="alert alert-notice"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Info</strong> ';
  254. break;
  255. case 'success':
  256. echo '<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Yeah!</strong> ';
  257. break;
  258. default:
  259. echo '<div class="alert"><button type="button" class="close" data-dismiss="alert">&times;</button><strong>Erreur!</strong> ';
  260. break;
  261. }
  262. echo $message.'</div>';
  263. }
  264. static public function slugify($text)
  265. {
  266. // replace non letter or digits by -
  267. $text = preg_replace('~[^\\pL\.\d]+~u', '-', $text);
  268. // trim
  269. $text = trim($text, '-');
  270. // transliterate
  271. $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
  272. // lowercase
  273. $text = strtolower($text);
  274. // remove unwanted characters
  275. $text = preg_replace('~[^-\.\w]+~', '', $text);
  276. if (empty($text))
  277. return 'n-a';
  278. return $text;
  279. }
  280. }
  281. ?>