PageRenderTime 67ms CodeModel.GetById 25ms app.highlight 35ms RepoModel.GetById 1ms app.codeStats 0ms

/src/classes/helpers.class.php

https://github.com/CharlesTati/Minicraft
PHP | 861 lines | 699 code | 123 blank | 39 comment | 95 complexity | ad2c3fc36c29daabe01187fb46a206a6 MD5 | raw file
  1<?php
  2
  3class Helpers {
  4  public static $icon_collapse = 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAEJGlDQ1BJQ0MgUHJvZmlsZQAAOBGFVd9v21QUPolvUqQWPyBYR4eKxa9VU1u5GxqtxgZJk6XtShal6dgqJOQ6N4mpGwfb6baqT3uBNwb8AUDZAw9IPCENBmJ72fbAtElThyqqSUh76MQPISbtBVXhu3ZiJ1PEXPX6yznfOec7517bRD1fabWaGVWIlquunc8klZOnFpSeTYrSs9RLA9Sr6U4tkcvNEi7BFffO6+EdigjL7ZHu/k72I796i9zRiSJPwG4VHX0Z+AxRzNRrtksUvwf7+Gm3BtzzHPDTNgQCqwKXfZwSeNHHJz1OIT8JjtAq6xWtCLwGPLzYZi+3YV8DGMiT4VVuG7oiZpGzrZJhcs/hL49xtzH/Dy6bdfTsXYNY+5yluWO4D4neK/ZUvok/17X0HPBLsF+vuUlhfwX4j/rSfAJ4H1H0qZJ9dN7nR19frRTeBt4Fe9FwpwtN+2p1MXscGLHR9SXrmMgjONd1ZxKzpBeA71b4tNhj6JGoyFNp4GHgwUp9qplfmnFW5oTdy7NamcwCI49kv6fN5IAHgD+0rbyoBc3SOjczohbyS1drbq6pQdqumllRC/0ymTtej8gpbbuVwpQfyw66dqEZyxZKxtHpJn+tZnpnEdrYBbueF9qQn93S7HQGGHnYP7w6L+YGHNtd1FJitqPAR+hERCNOFi1i1alKO6RQnjKUxL1GNjwlMsiEhcPLYTEiT9ISbN15OY/jx4SMshe9LaJRpTvHr3C/ybFYP1PZAfwfYrPsMBtnE6SwN9ib7AhLwTrBDgUKcm06FSrTfSj187xPdVQWOk5Q8vxAfSiIUc7Z7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3ZcnOWWing6noonSInvi0/Ex+IzAreevPhe+CawpgP1/pMTMDo64G0sTCXIM+KdOnFWRfQKdJvQzV1+Bt8OokmrdtY2yhVX2a+qrykJfMq4Ml3VR4cVzTQVz+UoNne4vcKLoyS+gyKO6EHe+75Fdt0Mbe5bRIf/wjvrVmhbqBN97RD1vxrahvBOfOYzoosH9bq94uejSOQGkVM6sN/7HelL4t10t9F4gPdVzydEOx83Gv+uNxo7XyL/FtFl8z9ZAHF4bBsrEwAAAPxJREFUWAljZACCnW5ussycnF1MTEz2QK4kSIyG4Pm/f/8O/v3+vcx9167HjCDLWbm4LjIwMgrS0FIMo//9///u77dvBiwgn9PbcpBrmBgZhRggoQ4OdgwX0kMAFOVMQItoHef4/CIJcsCAAhZybXdav54RWe++wMD/yHxi2QMeAqMOGA2B0RBgxJV/0fM5sfkalzpc9oxGwYCHAM40gCsuYeLoaQRXHMPU46IHPARGHTAaAqMhQHY5gCtfkyo+KKLgOamupqL650ygjiIVDSTJKJDdTKBeKqijSJJOKigGd06BdjOBusigXirQNSuA5tIjOkDd8xUgO0F2AwDAIFg55NaPHAAAAABJRU5ErkJggg==';
  7  
  8  // Bolt - http://bolt.cm
  9  public static function htmlentities($str, $preserve_encoded_entities = false) {
 10    if ($preserve_encoded_entities) {
 11      $translation_table          = get_html_translation_table(HTML_ENTITIES, ENT_QUOTES);
 12      $translation_table[chr(38)] = '&';
 13      return preg_replace('#&(?![A-Za-z]{0,4}\w{2,3};|\#[0-9]{2,3};)#', '&amp;', strtr($str, $translation_table));
 14    } else {
 15      return htmlentities($str, ENT_QUOTES);
 16    }
 17  }
 18  
 19  // http://stackoverflow.com/a/3349792
 20  public static function removeDirectory($path) {
 21    if (is_dir($path)) {
 22      if (substr($path, strlen($pth) - 1, 1) != '/') {
 23        $dirPath .= '/';
 24      }
 25      $files = glob($path . '*', GLOB_MARK);
 26      foreach ($files as $file) {
 27        if (is_dir($file)) {
 28          self::removeDirectory($file);
 29        } else {
 30          unlink($file);
 31        }
 32      }
 33      $result = rmdir($path);
 34    }
 35    
 36    return $result;
 37  }
 38  
 39  public static function camelCase($str) {
 40    $str = lcfirst(str_replace(' ', '', ucwords(str_replace(array(
 41      '-',
 42      '_'
 43    ), ' ', $str))));
 44    
 45    return $str;
 46  }
 47  
 48  public static function underscoreCase($str) {
 49    return strtolower(preg_replace('#([a-z])([A-Z])#', '$1_$2', $str));
 50  }
 51  
 52  static function generateSlug($str, $replace = array('\''), $delimiter = '-', $limit = 64, $css_mode = false) {
 53    // Replaces some characters (such as apostrophes) with spaces
 54    if (!empty($replace)) {
 55      $str = str_replace((array) $replace, ' ', $str);
 56    }
 57    
 58    // Transforms unknown characters into a similar letter
 59    $clean = self::removeAccents($str);
 60    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $clean);
 61    $clean = preg_replace('#[^a-zA-Z0-9/_|+ -]#', '', $clean);
 62    $clean = strtolower(trim($clean, '-'));
 63    $clean = preg_replace('#[/_|+ -]+#', $delimiter, $clean);
 64    
 65    // Smart trim
 66    if (strlen($clean) > $limit) {
 67      $clean  = substr($clean, 0, $limit);
 68      $hyphen = strrpos($clean, '-');
 69      $clean  = substr($clean, 0, $hyphen);
 70    }
 71    
 72    if ($css_mode) {
 73      $digits = array(
 74        'zero',
 75        'one',
 76        'two',
 77        'three',
 78        'four',
 79        'five',
 80        'six',
 81        'seven',
 82        'eight',
 83        'nine'
 84      );
 85      
 86      if (is_numeric(substr($clean, 0, 1))) {
 87        $clean = $digits[substr($slug, 0, 1)] . substr($clean, 1);
 88      }
 89    }
 90    
 91    return $clean;
 92  }
 93  
 94  // Bolt - http://bolt.cm
 95  public static function generateExtract($str, $length = 64, $append = '…') {
 96    $ret        = substr($str, 0, $length);
 97    $last_space = strrpos($ret, ' ');
 98    
 99    if ($last_space and $str != $ret) {
100      $ret = substr($ret, 0, $last_space);
101    }
102    
103    if ($ret != $str) {
104      $ret .= $append;
105    }
106    
107    return $ret;
108  }
109  
110  public static function addHTTP($url) {
111    return preg_match("#^(?:f|ht)tps?://#i", $url) ? $url : 'http://' . $url;
112  }
113  
114  // Bolt - http://bolt.cm
115  public static function getClientIp($trust_proxy_headers = false) {
116    if (!$trust_proxy_headers) {
117      return ip2long($_SERVER['REMOTE_ADDR']);
118    } elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
119      return ip2long($_SERVER['HTTP_CLIENT_IP']);
120    } else if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
121      return ip2long($_SERVER['HTTP_X_FORWARDED_FOR']);
122    } else {
123      return ip2long($_SERVER['REMOTE_ADDR']);
124    }
125  }
126  
127  public static function tooShort($str, $min) {
128    return strlen($str) < $min;
129  }
130  
131  public static function tooLong($str, $max) {
132    return strlen($str) > $max;
133  }
134  
135  public static function usernameIsValid($username) {
136    $regex_username = '#^(?![_-])(?!.*[_-]{2})([\wàáâãäåçèéêëìíîïðòóôõöùúûüýÿñ-]+)(?<![_-])$#';
137    return preg_match($regex_username, $username);
138  }
139  
140  public static function emailIsValid($email) {
141    if (function_exists('idn_to_ascii')) {
142      $parts  = explode('@', $email);
143      $user   = $parts[0];
144      $domain = idn_to_ascii($parts[1]);
145      $email  = $user . '@' . $domain;
146    }
147    
148    return filter_var($email, FILTER_VALIDATE_EMAIL);
149  }
150  
151  public static function setFlash($type, $message) {
152    $_SESSION['MinicraftFlash'] = array(
153      'type' => $type,
154      'message' => $message
155    );
156  }
157  
158  // Générer une clé
159  public static function randomKey($length = 32) {
160    return substr(sha1(uniqid(rand(), true)), 0, $length > 40 ? 40 : $length);
161  }
162  
163  /* ========== */
164  
165  // Wordpress - https://wordpress.org
166  public static function removeAccents($str) {
167    if (!preg_match('/[\x80-\xff]/', $str)) {
168      return $str;
169    }
170    
171    if (self::seemsUtf8($str)) {
172      $chars = array(
173        // Decompositions for Latin-1 Supplement
174        chr(194) . chr(170) => 'a',
175        chr(194) . chr(186) => 'o',
176        chr(195) . chr(128) => 'A',
177        chr(195) . chr(129) => 'A',
178        chr(195) . chr(130) => 'A',
179        chr(195) . chr(131) => 'A',
180        chr(195) . chr(132) => 'A',
181        chr(195) . chr(133) => 'A',
182        chr(195) . chr(134) => 'AE',
183        chr(195) . chr(135) => 'C',
184        chr(195) . chr(136) => 'E',
185        chr(195) . chr(137) => 'E',
186        chr(195) . chr(138) => 'E',
187        chr(195) . chr(139) => 'E',
188        chr(195) . chr(140) => 'I',
189        chr(195) . chr(141) => 'I',
190        chr(195) . chr(142) => 'I',
191        chr(195) . chr(143) => 'I',
192        chr(195) . chr(144) => 'D',
193        chr(195) . chr(145) => 'N',
194        chr(195) . chr(146) => 'O',
195        chr(195) . chr(147) => 'O',
196        chr(195) . chr(148) => 'O',
197        chr(195) . chr(149) => 'O',
198        chr(195) . chr(150) => 'O',
199        chr(195) . chr(153) => 'U',
200        chr(195) . chr(154) => 'U',
201        chr(195) . chr(155) => 'U',
202        chr(195) . chr(156) => 'U',
203        chr(195) . chr(157) => 'Y',
204        chr(195) . chr(158) => 'TH',
205        chr(195) . chr(159) => 's',
206        chr(195) . chr(160) => 'a',
207        chr(195) . chr(161) => 'a',
208        chr(195) . chr(162) => 'a',
209        chr(195) . chr(163) => 'a',
210        chr(195) . chr(164) => 'a',
211        chr(195) . chr(165) => 'a',
212        chr(195) . chr(166) => 'ae',
213        chr(195) . chr(167) => 'c',
214        chr(195) . chr(168) => 'e',
215        chr(195) . chr(169) => 'e',
216        chr(195) . chr(170) => 'e',
217        chr(195) . chr(171) => 'e',
218        chr(195) . chr(172) => 'i',
219        chr(195) . chr(173) => 'i',
220        chr(195) . chr(174) => 'i',
221        chr(195) . chr(175) => 'i',
222        chr(195) . chr(176) => 'd',
223        chr(195) . chr(177) => 'n',
224        chr(195) . chr(178) => 'o',
225        chr(195) . chr(179) => 'o',
226        chr(195) . chr(180) => 'o',
227        chr(195) . chr(181) => 'o',
228        chr(195) . chr(182) => 'o',
229        chr(195) . chr(184) => 'o',
230        chr(195) . chr(185) => 'u',
231        chr(195) . chr(186) => 'u',
232        chr(195) . chr(187) => 'u',
233        chr(195) . chr(188) => 'u',
234        chr(195) . chr(189) => 'y',
235        chr(195) . chr(190) => 'th',
236        chr(195) . chr(191) => 'y',
237        chr(195) . chr(152) => 'O',
238        
239        // Decompositions for Latin Extended-A
240        chr(196) . chr(128) => 'A',
241        chr(196) . chr(129) => 'a',
242        chr(196) . chr(130) => 'A',
243        chr(196) . chr(131) => 'a',
244        chr(196) . chr(132) => 'A',
245        chr(196) . chr(133) => 'a',
246        chr(196) . chr(134) => 'C',
247        chr(196) . chr(135) => 'c',
248        chr(196) . chr(136) => 'C',
249        chr(196) . chr(137) => 'c',
250        chr(196) . chr(138) => 'C',
251        chr(196) . chr(139) => 'c',
252        chr(196) . chr(140) => 'C',
253        chr(196) . chr(141) => 'c',
254        chr(196) . chr(142) => 'D',
255        chr(196) . chr(143) => 'd',
256        chr(196) . chr(144) => 'D',
257        chr(196) . chr(145) => 'd',
258        chr(196) . chr(146) => 'E',
259        chr(196) . chr(147) => 'e',
260        chr(196) . chr(148) => 'E',
261        chr(196) . chr(149) => 'e',
262        chr(196) . chr(150) => 'E',
263        chr(196) . chr(151) => 'e',
264        chr(196) . chr(152) => 'E',
265        chr(196) . chr(153) => 'e',
266        chr(196) . chr(154) => 'E',
267        chr(196) . chr(155) => 'e',
268        chr(196) . chr(156) => 'G',
269        chr(196) . chr(157) => 'g',
270        chr(196) . chr(158) => 'G',
271        chr(196) . chr(159) => 'g',
272        chr(196) . chr(160) => 'G',
273        chr(196) . chr(161) => 'g',
274        chr(196) . chr(162) => 'G',
275        chr(196) . chr(163) => 'g',
276        chr(196) . chr(164) => 'H',
277        chr(196) . chr(165) => 'h',
278        chr(196) . chr(166) => 'H',
279        chr(196) . chr(167) => 'h',
280        chr(196) . chr(168) => 'I',
281        chr(196) . chr(169) => 'i',
282        chr(196) . chr(170) => 'I',
283        chr(196) . chr(171) => 'i',
284        chr(196) . chr(172) => 'I',
285        chr(196) . chr(173) => 'i',
286        chr(196) . chr(174) => 'I',
287        chr(196) . chr(175) => 'i',
288        chr(196) . chr(176) => 'I',
289        chr(196) . chr(177) => 'i',
290        chr(196) . chr(178) => 'IJ',
291        chr(196) . chr(179) => 'ij',
292        chr(196) . chr(180) => 'J',
293        chr(196) . chr(181) => 'j',
294        chr(196) . chr(182) => 'K',
295        chr(196) . chr(183) => 'k',
296        chr(196) . chr(184) => 'k',
297        chr(196) . chr(185) => 'L',
298        chr(196) . chr(186) => 'l',
299        chr(196) . chr(187) => 'L',
300        chr(196) . chr(188) => 'l',
301        chr(196) . chr(189) => 'L',
302        chr(196) . chr(190) => 'l',
303        chr(196) . chr(191) => 'L',
304        chr(197) . chr(128) => 'l',
305        chr(197) . chr(129) => 'L',
306        chr(197) . chr(130) => 'l',
307        chr(197) . chr(131) => 'N',
308        chr(197) . chr(132) => 'n',
309        chr(197) . chr(133) => 'N',
310        chr(197) . chr(134) => 'n',
311        chr(197) . chr(135) => 'N',
312        chr(197) . chr(136) => 'n',
313        chr(197) . chr(137) => 'N',
314        chr(197) . chr(138) => 'n',
315        chr(197) . chr(139) => 'N',
316        chr(197) . chr(140) => 'O',
317        chr(197) . chr(141) => 'o',
318        chr(197) . chr(142) => 'O',
319        chr(197) . chr(143) => 'o',
320        chr(197) . chr(144) => 'O',
321        chr(197) . chr(145) => 'o',
322        chr(197) . chr(146) => 'OE',
323        chr(197) . chr(147) => 'oe',
324        chr(197) . chr(148) => 'R',
325        chr(197) . chr(149) => 'r',
326        chr(197) . chr(150) => 'R',
327        chr(197) . chr(151) => 'r',
328        chr(197) . chr(152) => 'R',
329        chr(197) . chr(153) => 'r',
330        chr(197) . chr(154) => 'S',
331        chr(197) . chr(155) => 's',
332        chr(197) . chr(156) => 'S',
333        chr(197) . chr(157) => 's',
334        chr(197) . chr(158) => 'S',
335        chr(197) . chr(159) => 's',
336        chr(197) . chr(160) => 'S',
337        chr(197) . chr(161) => 's',
338        chr(197) . chr(162) => 'T',
339        chr(197) . chr(163) => 't',
340        chr(197) . chr(164) => 'T',
341        chr(197) . chr(165) => 't',
342        chr(197) . chr(166) => 'T',
343        chr(197) . chr(167) => 't',
344        chr(197) . chr(168) => 'U',
345        chr(197) . chr(169) => 'u',
346        chr(197) . chr(170) => 'U',
347        chr(197) . chr(171) => 'u',
348        chr(197) . chr(172) => 'U',
349        chr(197) . chr(173) => 'u',
350        chr(197) . chr(174) => 'U',
351        chr(197) . chr(175) => 'u',
352        chr(197) . chr(176) => 'U',
353        chr(197) . chr(177) => 'u',
354        chr(197) . chr(178) => 'U',
355        chr(197) . chr(179) => 'u',
356        chr(197) . chr(180) => 'W',
357        chr(197) . chr(181) => 'w',
358        chr(197) . chr(182) => 'Y',
359        chr(197) . chr(183) => 'y',
360        chr(197) . chr(184) => 'Y',
361        chr(197) . chr(185) => 'Z',
362        chr(197) . chr(186) => 'z',
363        chr(197) . chr(187) => 'Z',
364        chr(197) . chr(188) => 'z',
365        chr(197) . chr(189) => 'Z',
366        chr(197) . chr(190) => 'z',
367        chr(197) . chr(191) => 's',
368        
369        // Decompositions for Latin Extended-B
370        chr(200) . chr(152) => 'S',
371        chr(200) . chr(153) => 's',
372        chr(200) . chr(154) => 'T',
373        chr(200) . chr(155) => 't',
374        
375        // Euro Sign
376        chr(226) . chr(130) . chr(172) => 'E',
377        // GBP (Pound) Sign
378        chr(194) . chr(163) => ''
379      );
380      
381      $str = strtr($str, $chars);
382    } else {
383      // Assume ISO-8859-1 if not UTF-8
384      $chars['in'] = chr(128) . chr(131) . chr(138) . chr(142) . chr(154) . chr(158) . chr(159) . chr(162) . chr(165) . chr(181) . chr(192) . chr(193) . chr(194) . chr(195) . chr(196) . chr(197) . chr(199) . chr(200) . chr(201) . chr(202) . chr(203) . chr(204) . chr(205) . chr(206) . chr(207) . chr(209) . chr(210) . chr(211) . chr(212) . chr(213) . chr(214) . chr(216) . chr(217) . chr(218) . chr(219) . chr(220) . chr(221) . chr(224) . chr(225) . chr(226) . chr(227) . chr(228) . chr(229) . chr(231) . chr(232) . chr(233) . chr(234) . chr(235) . chr(236) . chr(237) . chr(238) . chr(239) . chr(241) . chr(242) . chr(243) . chr(244) . chr(245) . chr(246) . chr(248) . chr(249) . chr(250) . chr(251) . chr(252) . chr(253) . chr(255);
385      
386      $chars['out'] = 'EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy';
387      
388      $str = strtr($str, $chars['in'], $chars['out']);
389      
390      $double_chars['in'] = array(
391        chr(140),
392        chr(156),
393        chr(198),
394        chr(208),
395        chr(222),
396        chr(223),
397        chr(230),
398        chr(240),
399        chr(254)
400      );
401      
402      $double_chars['out'] = array(
403        'OE',
404        'oe',
405        'AE',
406        'DH',
407        'TH',
408        'ss',
409        'ae',
410        'dh',
411        'th'
412      );
413      
414      $str = str_replace($double_chars['in'], $double_chars['out'], $str);
415    }
416    
417    return $str;
418  }
419  
420  // Bolt - http://bolt.cm
421  public static function seemsUtf8($str) {
422    if (function_exists('mb_check_encoding')) {
423      // If mbstring is available, this is significantly faster than
424      // using PHP regexps.
425      return mb_check_encoding($str, 'UTF-8');
426    }
427    
428    $regex = '/(
429      | [\xF8-\xFF] # Invalid UTF-8 Bytes
430      | [\xC0-\xDF](?![\x80-\xBF]) # Invalid UTF-8 Sequence Start
431      | [\xE0-\xEF](?![\x80-\xBF]{2}) # Invalid UTF-8 Sequence Start
432      | [\xF0-\xF7](?![\x80-\xBF]{3}) # Invalid UTF-8 Sequence Start
433      | (?<=[\x0-\x7F\xF8-\xFF])[\x80-\xBF] # Invalid UTF-8 Sequence Middle
434      | (?<![\xC0-\xDF]|[\xE0-\xEF]|[\xE0-\xEF][\x80-\xBF]|[\xF0-\xF7]|[\xF0-\xF7][\x80-\xBF]|[\xF0-\xF7][\x80-\xBF]{2})[\x80-\xBF] # Overlong Sequence
435      | (?<=[\xE0-\xEF])[\x80-\xBF](?![\x80-\xBF]) # Short 3 byte sequence
436      | (?<=[\xF0-\xF7])[\x80-\xBF](?![\x80-\xBF]{2}) # Short 4 byte sequence
437      | (?<=[\xF0-\xF7][\x80-\xBF])[\x80-\xBF](?![\x80-\xBF]) # Short 4 byte sequence (2)
438      )/x';
439    
440    return !preg_match($regex, $str);
441  }
442  
443  // Bolt - http://bolt.cm
444  public static function forceDownload($filename, $content = false) {
445    if (!headers_sent()) {
446      // Required for some browsers
447      if (ini_get('zlib.output_compression')) {
448        @ini_set('zlib.output_compression', 'Off');
449      }
450      
451      header('Pragma: public');
452      header('Expires: 0');
453      header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
454      
455      // Required for certain browsers
456      header('Cache-Control: private', false);
457      
458      header('Content-Disposition: attachment; filename="' . basename(str_replace('"', '', $filename)) . '";');
459      header('Content-Type: application/force-download');
460      header('Content-Transfer-Encoding: binary');
461      
462      if ($content) {
463        header('Content-Length: ' . strlen($content));
464      }
465      
466      ob_clean();
467      flush();
468      
469      if ($content) {
470        echo $content;
471      }
472      
473      return true;
474    } else {
475      return false;
476    }
477  }
478  
479  // Bolt - http://bolt.cm
480  public static function randomString($length = 32, $human_friendly = true, $include_symbols = false, $no_duplicate_chars = false) {
481    $nice_chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefhjkmnprstuvwxyz23456789';
482    $all_an     = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
483    $symbols    = '!@#$%^&*()~_-=+{}[]|:;<>,.?/"\'\\`';
484    $str        = '';
485    
486    // Determines the pool of available characters based on the given parameters
487    if ($human_friendly) {
488      $pool = $nice_chars;
489    } else {
490      $pool = $all_an;
491      
492      if ($include_symbols) {
493        $pool .= $symbols;
494      }
495    }
496    
497    // Don't allow duplicate letters to be disabled if the length is longer than the available characters
498    if ($no_duplicate_chars and strlen($pool) < $length) {
499      throw new LengthException('$length exceeds the size of the pool and $no_duplicate_chars is enabled');
500    }
501    
502    // Converts the pool of characters into an array of characters and shuffle the array
503    $pool = str_split($pool);
504    shuffle($pool);
505    
506    // Generates the string
507    for ($i = 0; $i < $length; $i++) {
508      if ($no_duplicate_chars) {
509        $str .= array_shift($pool);
510      } else {
511        $str .= $pool[0];
512        shuffle($pool);
513      }
514    }
515    
516    return $str;
517  }
518  
519  public static function getGravatar($email, $size = 32) {
520    return 'http://www.gravatar.com/avatar/' . md5($email) . '?s=' . self::absint($size);
521  }
522  
523  // Bolt - http://bolt.cm
524  public static function absint($maybeint) {
525    return abs(intval($maybeint));
526  }
527  
528  // Bolt - http://bolt.cm
529  function emailIsValidAlt($email) {
530    if (!empty($email) or is_string($email)) {
531      $mail_array = explode('@', $email);
532    }
533    
534    if (!is_array($mail_array)) {
535      return false;
536    }
537    
538    if (count($mail_array) == 2) {
539      $localpart    = $mail_array[0];
540      $domain_array = explode('.', $mail_array[1]);
541    } else {
542      return false;
543    }
544    
545    if (!is_array($domain_array)) {
546      return false;
547    }
548    
549    if (count($domain_array) == 1) {
550      return false;
551    }
552    
553    $domain_toplevel = array_pop($domain_array);
554    
555    if (is_string($domain_toplevel) and (strlen($domain_toplevel) > 1)) {
556      $domain_array[] = $domain_toplevel;
557      $domain         = implode('', $domain_array);
558      $domain         = preg_replace('/[a-z0-9]/i', '', $domain);
559      $domain         = preg_replace('/[-|\_]/', '', $domain);
560      $localpart      = preg_replace('/[a-z0-9]/i', '', $localpart);
561      $localpart      = preg_replace('#[-.|\!|\#|\$|\%|\&|\'|\*|\+|\/|\=|\? |\^|\_|\`|\{|\or\}|\~]#', '', $localpart);
562      
563      // If there are no characters left in localpart or domain, the email address is valid
564      return (empty($domain) and empty($localpart));
565    }
566    
567    return false;
568  }
569  
570  public static function blockAccess() {
571    if (!in_array(@$_SERVER['REMOTE_ADDR'], array(
572      '127.0.0.1',
573      '::1'
574    ))) {
575      header('HTTP/1.0 403 Forbidden');
576      die('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Unauthorized access</title></head><body><h1>Unauthorized access</h1><p>You can\'t see this page.</p></body></html>');
577    }
578  }
579  
580  // Bolt - http://bolt.cm
581  public static function var_dump($var, $return = false) {
582    $html = '<pre style="margin: 0 0 10px;' . 'background: #373b41;' . 'padding: 9.5px;' . 'border: 1px solid #1d1f21;' . 'border-radius: 4px;' . 'display: block;' . 'font-size: 13px;' . 'white-space: pre-wrap;' . 'word-wrap: break-word;' . 'word-break: break-all;' . 'color: #c5c8c6;' . 'text-align: left;' . 'line-height: 1.42857143;' . 'page-break-inside: avoid;' . 'max-height: 340px;' . 'overflow-y: scroll;' . 'font-family: Menlo, Monaco, Consolas, "Courier New", monospace;">';
583    $html .= self::var_dump_plain($var, true);
584    $html .= '</pre>';
585    
586    if (!$return) {
587      echo $html;
588    } else {
589      return $html;
590    }
591  }
592  
593  // Bolt - http://bolt.cm
594  public static function var_dump_plain($var, $traversedeeper = false) {
595    $html = '';
596    
597    if (is_bool($var)) {
598      $html .= '<span style="color:#81a2be;">boo</span><span style="color:#c5c8c6;">(</span><span style="color: #cc6666;">' . (($var) ? 'true' : 'false') . '</span><span style="color:#c5c8c6;">)</span>';
599    } else if (is_int($var)) {
600      $html .= '<span style="color:#81a2be;">int</span><span style="color:#c5c8c6;">(</span><span style="color: #cc6666;">' . $var . '</span><span style="color:#c5c8c6;">)</span>';
601    } else if (is_float($var)) {
602      $html .= '<span style="color:#81a2be;">flo</span><span style="color:#c5c8c6;">(</span><span style="color: #cc6666;">' . $var . '</span><span style="color:#c5c8c6;">)</span>';
603    } else if (is_string($var)) {
604      $html .= '<span style="color:#81a2be;">str</span><span style="color:#c5c8c6;">(</span><span style="color: #cc6666;">' . strlen($var) . '</span><span style="color:#c5c8c6;">)</span>"<span style="color: #df9f4f;">' . self::htmlentities($var) . '</span>"';
605    } else if (is_null($var)) {
606      $html .= 'NULL';
607    } else if (is_resource($var)) {
608      $html .= '<span style="color:#81a2be;">res</span>("' . get_resource_type($var) . '") "' . $var;
609    } else if (is_array($var)) {
610      $uuid = uniqid('include-php-', true);
611      
612      $html .= '<span style="color:#81a2be;">arr</span>(<span style="color: #cc6666;">' . count($var) . '</span>)';
613      
614      if (!empty($var)) {
615        $html .= ' <img id="' . $uuid . '" data-collapse="data:image/png;base64,' . self::$icon_collapse . '" style="position:relative;cursor:pointer;width:16px!important;height:16px!important;" src="data:image/png;base64,' . self::$icon_expand . '"> <span id="' . $uuid . '-collapsable" style="display: none;">[<br>';
616        
617        $indent      = 2;
618        $longest_key = 0;
619        
620        foreach ($var as $key => $value) {
621          if (is_string($key)) {
622            $longest_key = max($longest_key, strlen($key) + 2);
623          } else {
624            $longest_key = max($longest_key, strlen($key));
625          }
626        }
627        
628        foreach ($var as $key => $value) {
629          if (is_numeric($key)) {
630            $html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, '_');
631          } else {
632            $html .= str_repeat(' ', $indent) . str_pad('"<span style="color: #8abeb7;">' . self::htmlentities($key) . '</span>"', $longest_key, ' ');
633          }
634          
635          $html .= ' => ';
636          
637          $value = explode('<br>', self::var_dump_plain($value));
638          
639          foreach ($value as $line => $val) {
640            if ($line != 0) {
641              $value[$line] = str_repeat(' ', $indent * 2) . $val;
642            }
643          }
644          
645          $html .= implode('<br>', $value) . '<br>';
646        }
647        
648        $html .= ']</span>';
649        
650        $html .= preg_replace('/ +/', ' ', '<script type="text/javascript">(function() {
651          var img = document.getElementById("' . $uuid . '");
652          img.onclick = function() {
653            if ( document.getElementById("' . $uuid . '-collapsable").style.display == "none" ) {
654              document.getElementById("' . $uuid . '-collapsable").style.display = "inline";
655              img.setAttribute( "data-expand", img.getAttribute("src") );
656              img.src = img.getAttribute("data-collapse");
657              var previousSibling = document.getElementById("' . $uuid . '-collapsable").previousSibling;
658            } else {
659              document.getElementById("' . $uuid . '-collapsable").style.display = "none";
660              img.src = img.getAttribute("data-expand");
661              var previousSibling = document.getElementById("' . $uuid . '-collapsable").previousSibling;
662            }
663          };
664        })();
665        </script>');
666      }
667      
668    } else if (is_object($var)) {
669      $uuid = uniqid('include-php-', true);
670      
671      $html .= '<span style="color:#81a2be;">object</span>(' . get_class($var) . ') <img id="' . $uuid . '" data-collapse="data:image/png;base64,' . self::$icon_collapse . '" style="position:relative;vertical-align:middle;cursor:pointer;width:16px!important;height:16px!important;" src="data:image/png;base64,' . self::$icon_expand . '"> <span id="' . $uuid . '-collapsable" style="display: none;">[<br>';
672      
673      $original = $var;
674      $var      = (array) $var;
675      
676      $indent      = 2;
677      $longest_key = 0;
678      
679      foreach ($var as $key => $value) {
680        if (substr($key, 0, 2) == "\0*") {
681          unset($var[$key]);
682          $key       = 'protected:' . substr($key, 2);
683          $var[$key] = $value;
684        } else if (substr($key, 0, 1) == "\0") {
685          unset($var[$key]);
686          $key       = 'private:' . substr($key, 1, strpos(substr($key, 1), "\0")) . ':' . substr($key, strpos(substr($key, 1), "\0") + 1);
687          $var[$key] = $value;
688        }
689        
690        if (is_string($key)) {
691          $longest_key = max($longest_key, strlen($key) + 2);
692        } else {
693          $longest_key = max($longest_key, strlen($key));
694        }
695      }
696      
697      foreach ($var as $key => $value) {
698        if (is_numeric($key)) {
699          $html .= str_repeat(' ', $indent) . str_pad($key, $longest_key, ' ');
700        } else {
701          $html .= str_repeat(' ', $indent) . str_pad('"<span style="color: #8abeb7;">' . self::htmlentities($key) . '</span>"', $longest_key, ' ');
702        }
703        
704        $html .= ' => ';
705        
706        $value = explode('<br>', self::var_dump_plain($value));
707        
708        foreach ($value as $line => $val) {
709          if ($line != 0) {
710            $value[$line] = str_repeat(' ', $indent * 2) . $val;
711          }
712        }
713        
714        $html .= implode('<br>', $value) . '<br>';
715      }
716      
717      $html .= ']</span>';
718      
719      $html .= preg_replace('/ +/', ' ', '<script type="text/javascript">(function() {
720        var img = document.getElementById("' . $uuid . '");
721        img.onclick = function() {
722          if ( document.getElementById("' . $uuid . '-collapsable").style.display == "none" ) {
723            document.getElementById("' . $uuid . '-collapsable").style.display = "inline";
724            img.setAttribute( "data-expand", img.getAttribute("src") );
725            img.src = img.getAttribute("data-collapse");
726            var previousSibling = document.getElementById("' . $uuid . '-collapsable").previousSibling;
727          } else {
728            document.getElementById("' . $uuid . '-collapsable").style.display = "none";
729            img.src = img.getAttribute("data-expand");
730            var previousSibling = document.getElementById("' . $uuid . '-collapsable").previousSibling;
731          }
732        };
733      })();
734      </script>');
735    }
736    
737    return $html;
738  }
739  
740  public static function isHttps() {
741    return isset($_SERVER['HTTPS']) and !empty($_SERVER['HTTPS']) and $_SERVER['HTTPS'] != 'off';
742  }
743  
744  function checkVersion($currentversion, $requiredversion) {
745    return version_compare($currentversion, $requiredversion) > -1;
746  }
747  
748  public static function generateUniqueId() {
749    $data = $_SERVER['REQUEST_TIME'];
750    $data .= $_SERVER['HTTP_USER_AGENT'];
751    $data .= $_SERVER['LOCAL_ADDR'];
752    $data .= $_SERVER['LOCAL_PORT'];
753    $data .= $_SERVER['REMOTE_ADDR'];
754    $data .= $_SERVER['REMOTE_PORT'];
755    $hash = sha1($data);
756  }
757  
758  // Bolt - http://bolt.cm
759  function generateToken() {
760    $seed  = $_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $_SESSION['Minicraft'];
761    $token = substr(md5($seed), 0, 8);
762    
763    return $token;
764  }
765  
766  // Bolt - http://bolt.cm
767  function checkToken($token = '') {
768    return $token === generateToken();
769  }
770  
771  //Bolt
772  function stripTrailingSlash($path) {
773    if (substr($path, -1, 1) == '/') {
774      $path = substr($path, 0, -1);
775    }
776    
777    return $path;
778  }
779  
780  // Bolt - http://bolt.cm
781  function getExtension($filename) {
782    $pos = strrpos($filename, '.');
783    if ($pos === false) {
784      return '';
785    } else {
786      $ext = substr($filename, $pos + 1);
787      
788      return $ext;
789    }
790  }
791  
792  // Bolt - http://bolt.cm
793  function isHtml($html) {
794    $len = strlen($html);
795    
796    $trimlen = strlen(strip_tags($html));
797    
798    $factor = $trimlen / $len;
799    
800    if ($factor < 0.97) {
801      return true;
802    } else {
803      return false;
804    }
805    
806  }
807  
808  // http://stackoverflow.com/a/2606638
809  function strReplaceFirst($search, $replace, $subject) {
810    $pos = strpos($subject, $search);
811    if ($pos !== false) {
812      $subject = substr_replace($subject, $replace, $pos, strlen($search));
813    }
814    return $subject;
815  }
816  
817  // Bolt - http://bolt.cm
818  public static function createDirectory($path) {
819    if (file_exists($path)) {
820      return true;
821    }
822    
823    if (dirname($path) != '.') {
824      $success = makeDir(dirname($path));
825      if (!$success) {
826        return false;
827      }
828    }
829    
830    $mode_dec = octdec('0777');
831    $oldumask = umask(0);
832    $success  = @mkdir($path, $mode_dec);
833    @chmod($name, $mode_dec);
834    umask($oldumask);
835    
836    return $success;
837  }
838  
839  public static function throw404($twig, $config, $user) {
840    header('HTTP/1.0 404 Not Found');
841    die($twig->render('misc/404.twig', array(
842      'pageTitle' => '404',
843      'config' => $config,
844      'user' => $user,
845      'flash' => new Flash
846    )));
847  }
848  
849  public static function redirect($router, $page, $args = array()) {
850    $url = $router->getController($page)->getUrl();
851    
852    if (!empty($args)) {
853      for ($i = 0; $i < count($args); $i++) {
854        $url = preg_replace('#%m' . ($i + 1) . '%#', $args[$i], $url);
855      }
856    }
857    
858    header('Location: ' . URL . '/' . $url);
859    die();
860  }
861}