PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/pluf-v1.0/src/Pluf/Utils.php

#
PHP | 308 lines | 188 code | 16 blank | 104 comment | 16 complexity | 1a522a43cf430a0d5c54bad2a80d3b48 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause
  1. <?php
  2. /* -*- tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
  3. /*
  4. # ***** BEGIN LICENSE BLOCK *****
  5. # This file is part of Plume Framework, a simple PHP Application Framework.
  6. # Copyright (C) 2001-2007 Loic d'Anterroches and contributors.
  7. #
  8. # Plume Framework is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU Lesser General Public License as published by
  10. # the Free Software Foundation; either version 2.1 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # Plume Framework is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU Lesser General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU Lesser General Public License
  19. # along with this program; if not, write to the Free Software
  20. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  21. #
  22. # ***** END LICENSE BLOCK ***** */
  23. /**
  24. * This file contains several utility classes.
  25. * These classes have only static methods.
  26. */
  27. class Pluf_Utils
  28. {
  29. /**
  30. * Produces a random string.
  31. *
  32. * @param int Length of the random string to be generated.
  33. * @return string Random string
  34. */
  35. static function getRandomString($len=35)
  36. {
  37. $string = '';
  38. $chars = '0123456789abcdefghijklmnopqrstuvwxyz'
  39. .'ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%&*()+=-_}{[]><?/';
  40. $lchars = strlen($chars);
  41. $i = 0;
  42. while ($i<$len) {
  43. $string .= substr($chars, mt_rand(0, $lchars-1), 1);
  44. $i++;
  45. }
  46. return $string;
  47. }
  48. /**
  49. * Produces a random password.
  50. *
  51. * The random password generator avoid characters that can be
  52. * confused like 0,O,o,1,l,I.
  53. *
  54. * @param int Length of the password (8)
  55. * @return string Password
  56. */
  57. static function getPassword($len=8)
  58. {
  59. $string = '';
  60. $chars = '23456789abcdefghijkmnpqrstuvwxyz'
  61. .'ABCDEFGHJKLMNPQRSTUVWXYZ';
  62. $lchars = strlen($chars);
  63. $i = 0;
  64. while ($i<$len) {
  65. $string .= substr($chars, mt_rand(0, $lchars-1), 1);
  66. $i++;
  67. }
  68. return $string;
  69. }
  70. /**
  71. * Clean the name of a file to only have alphanumeric characters.
  72. *
  73. * @param string Name
  74. * @return string Clean name
  75. */
  76. static function cleanFileName($name)
  77. {
  78. return mb_ereg_replace("/\015\012|\015|\012|\s|[^A-Za-z0-9\.\-\_]/", '_', $name);
  79. }
  80. static function prettySize($size)
  81. {
  82. switch (strtolower(substr($size, -1))) {
  83. case 'k':
  84. $size = substr($size, 0, -1) * 1000;
  85. break;
  86. case 'm':
  87. $size = substr($size, 0, -1) * 1000*1000;
  88. break;
  89. case 'g':
  90. $size = substr($size, 0, -1) * 1000*1000*1000;
  91. break;
  92. }
  93. if ($size > (1000*1000*1000)) {
  94. $mysize = sprintf('%01.2f', $size/(1000*1000*1000)).' '. __('GB');
  95. } elseif ($size > (1000*1000)) {
  96. $mysize = sprintf('%01.2f', $size/(1000*1000)).' '. __('MB');
  97. } elseif ($size >= 1000) {
  98. $mysize = sprintf('%01.2f', $size/1000).' '.__('kB');
  99. } else {
  100. $mysize = sprintf(_n('%d byte', '%d bytes', $size), $size);
  101. }
  102. return $mysize;
  103. }
  104. /**
  105. * RFC(2)822 Email Parser
  106. *
  107. * By Cal Henderson <cal@iamcal.com>
  108. * This code is licensed under a Creative Commons
  109. * Attribution-ShareAlike 2.5 License
  110. * http://creativecommons.org/licenses/by-sa/2.5/
  111. * Revision 5 - http://www.iamcal.com/publish/articles/php/parsing_email/
  112. *
  113. * Comments were stripped, check the source for the way this
  114. * parser is built. It is a very interesting reading.
  115. *
  116. * @param string Email
  117. * @return bool Is email
  118. */
  119. static function isValidEmail($email)
  120. {
  121. $email = trim($email);
  122. $n = explode(' ', $email);
  123. if (count($n) > 1) {
  124. return false;
  125. }
  126. $no_ws_ctl = "[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]";
  127. $alpha = "[\\x41-\\x5a\\x61-\\x7a]";
  128. $digit = "[\\x30-\\x39]";
  129. $cr = "\\x0d";
  130. $lf = "\\x0a";
  131. $crlf = "($cr$lf)";
  132. $obs_char = "[\\x00-\\x09\\x0b\\x0c\\x0e-\\x7f]";
  133. $obs_text = "($lf*$cr*($obs_char$lf*$cr*)*)";
  134. $text = "([\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f]|$obs_text)";
  135. $obs_qp = "(\\x5c[\\x00-\\x7f])";
  136. $quoted_pair = "(\\x5c$text|$obs_qp)";
  137. $wsp = "[\\x20\\x09]";
  138. $obs_fws = "($wsp+($crlf$wsp+)*)";
  139. $fws = "((($wsp*$crlf)?$wsp+)|$obs_fws)";
  140. $ctext = "($no_ws_ctl|[\\x21-\\x27\\x2A-\\x5b\\x5d-\\x7e])";
  141. $ccontent = "($ctext|$quoted_pair)";
  142. $comment = "(\\x28($fws?$ccontent)*$fws?\\x29)";
  143. $cfws = "(($fws?$comment)*($fws?$comment|$fws))";
  144. $cfws = "$fws*";
  145. $atext = "($alpha|$digit|[\\x21\\x23-\\x27\\x2a\\x2b\\x2d\\x2f\\x3d\\x3f\\x5e\\x5f\\x60\\x7b-\\x7e])";
  146. $atom = "($cfws?$atext+$cfws?)";
  147. $qtext = "($no_ws_ctl|[\\x21\\x23-\\x5b\\x5d-\\x7e])";
  148. $qcontent = "($qtext|$quoted_pair)";
  149. $quoted_string = "($cfws?\\x22($fws?$qcontent)*$fws?\\x22$cfws?)";
  150. $word = "($atom|$quoted_string)";
  151. $obs_local_part = "($word(\\x2e$word)*)";
  152. $obs_domain = "($atom(\\x2e$atom)*)";
  153. $dot_atom_text = "($atext+(\\x2e$atext+)*)";
  154. $dot_atom = "($cfws?$dot_atom_text$cfws?)";
  155. $dtext = "($no_ws_ctl|[\\x21-\\x5a\\x5e-\\x7e])";
  156. $dcontent = "($dtext|$quoted_pair)";
  157. $domain_literal = "($cfws?\\x5b($fws?$dcontent)*$fws?\\x5d$cfws?)";
  158. $local_part = "($dot_atom|$quoted_string|$obs_local_part)";
  159. $domain = "($dot_atom|$domain_literal|$obs_domain)";
  160. $addr_spec = "($local_part\\x40$domain)";
  161. $done = 0;
  162. while(!$done){
  163. $new = preg_replace("!$comment!", '', $email);
  164. if (strlen($new) == strlen($email)){
  165. $done = 1;
  166. }
  167. $email = $new;
  168. }
  169. return preg_match("!^$addr_spec$!", $email) ? true : false;
  170. }
  171. /**
  172. * Validate an url.
  173. * Only the structure is checked, no check of availability of the
  174. * url is performed. It is a really basic validation.
  175. */
  176. static function isValidUrl($url)
  177. {
  178. $ip = '(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.'
  179. .'(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}';
  180. $dom = '([a-z0-9\.\-]+)';
  181. return (preg_match('!^(http|https|ftp|gopher)\://('.$ip.'|'.$dom.')!i', $url)) ? true : false;
  182. }
  183. /**
  184. * Convert a whatever separated list of items and returns an array
  185. * of them.
  186. *
  187. * @param string Items.
  188. * @param string Separator (',')
  189. * @return array Items.
  190. */
  191. static function itemsToArray($items, $sep=',')
  192. {
  193. $_t = explode($sep, $items);
  194. $res = array();
  195. foreach ($_t as $item) {
  196. $item = trim($item);
  197. if (strlen($item) > 0) {
  198. $res[] = $item;
  199. }
  200. }
  201. return $res;
  202. }
  203. /**
  204. * Run an external program capturing both stdout and stderr.
  205. *
  206. * @credits dk at brightbyte dot de
  207. * @source http://www.php.net/manual/en/function.shell-exec.php
  208. * @see proc_open
  209. *
  210. * @param string Command to run (will be passed to proc_open)
  211. * @param &int Return code of the command
  212. * @return mixed false in case of error or output string
  213. */
  214. public static function runExternal($cmd, &$code)
  215. {
  216. $descriptorspec = array(
  217. // stdin is a pipe that the child will read from
  218. 0 => array('pipe', 'r'),
  219. // stdout is a pipe that the child will write to
  220. 1 => array('pipe', 'w'),
  221. // stderr is a file to write to
  222. 2 => array('pipe', 'w'));
  223. $pipes= array();
  224. $process = proc_open($cmd, $descriptorspec, $pipes);
  225. $output= '';
  226. if (!is_resource($process)) return false;
  227. fclose($pipes[0]); //close child's input imidiately
  228. stream_set_blocking($pipes[1], false);
  229. stream_set_blocking($pipes[2], false);
  230. $todo = array($pipes[1], $pipes[2]);
  231. while (true) {
  232. $read = array();
  233. if(!feof($pipes[1])) $read[] = $pipes[1];
  234. if(!feof($pipes[2])) $read[] = $pipes[2];
  235. if (!$read) break;
  236. $write = $ex = array();
  237. $ready= stream_select($read, $write, $ex, 2);
  238. if ($ready === false) {
  239. break; // should never happen - something died
  240. }
  241. foreach ($read as $r) {
  242. $s = fread($r,1024);
  243. $output .= $s;
  244. }
  245. }
  246. fclose($pipes[1]);
  247. fclose($pipes[2]);
  248. $code = proc_close($process);
  249. return $output;
  250. }
  251. /**
  252. * URL safe base 64 encoding.
  253. *
  254. * Compatible with python base64's urlsafe methods.
  255. *
  256. * @link http://www.php.net/manual/en/function.base64-encode.php#63543
  257. */
  258. public static function urlsafe_b64encode($string)
  259. {
  260. return str_replace(array('+','/','='),
  261. array('-','_',''),
  262. base64_encode($string));
  263. }
  264. /**
  265. * URL safe base 64 decoding.
  266. */
  267. public static function urlsafe_b64decode($string)
  268. {
  269. $data = str_replace(array('-','_'),
  270. array('+','/'),
  271. $string);
  272. $mod4 = strlen($data) % 4;
  273. if ($mod4) {
  274. $data .= substr('====', $mod4);
  275. }
  276. return base64_decode($data);
  277. }
  278. /**
  279. * Flatten an array.
  280. *
  281. * @param array $array The array to flatten.
  282. * @return array
  283. */
  284. public static function flattenArray($array)
  285. {
  286. $result = array();
  287. foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array)) as $value) {
  288. $result[] = $value;
  289. }
  290. return $result;
  291. }
  292. }