V.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. <?php
  2. /**
  3. * @see http://pl2.php.net/manual/en/book.var.php
  4. *
  5. * Define Your own convert function: var func_type_convert_{$type}($var);
  6. */
  7. class V {
  8. /**
  9. * Get variable from array or object.
  10. */
  11. public static function get($name, $default, $from, $type = '', $filterCallback = null) {
  12. if (empty($name)) return null;
  13. $ret = null;
  14. if (is_bool($name)) $name = (int)$name;
  15. if (!is_string($name) && !is_numeric($name)) {
  16. //var_dump($name);
  17. //echo'<pre>';print_r(debug_backtrace());echo'</pre>';
  18. throw new Exception("Error name is not scalar! '{$name}'");
  19. }
  20. if (is_array($from)) {
  21. if (array_key_exists($name, $from)) {
  22. $ret = $from[$name];
  23. }
  24. }
  25. else if (is_object($from)) {
  26. if (isset($from->$name)) {
  27. $ret = $from->$name;
  28. }
  29. }
  30. if (isset($ret) && $type != '') {
  31. $ret = V::convert($ret, $type);
  32. }
  33. if (!empty($filterCallback)) {
  34. if ($type == 'array' && is_array($ret) && !empty($ret)) {
  35. $ret = V::filter($ret, $filterCallback);
  36. }
  37. }
  38. $ret = (null !== $ret)? $ret : $default;
  39. return $ret;
  40. }
  41. /**
  42. * Convert variable type.
  43. * @usage: V::convert($from, 'url');
  44. */
  45. public static function convert($from, $type = 'string') {
  46. $type = strtolower($type);
  47. // is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  48. $ret = null;
  49. switch ($type) {
  50. case 'string':
  51. if (is_scalar($from)) {
  52. $ret = $from;
  53. settype($ret, $type);
  54. }
  55. break;
  56. case 'word':
  57. if (is_scalar($from)) {
  58. $ret = $from;
  59. settype($ret, 'string');
  60. $ret = trim($ret);
  61. if (false !== ($pos = strpos($ret, ' '))) {
  62. $ret = substr($ret, 0, $pos);
  63. }
  64. }
  65. break;
  66. case 'login':// [a-zA-Z.-_]
  67. if (is_scalar($from)) {
  68. $ret = $from;
  69. settype($ret, 'string');
  70. $ret = trim($ret);
  71. if (!preg_match("/^[a-zA-Z.-_]*$/", $ret, $matches)) {
  72. $ret = null;
  73. }
  74. }
  75. break;
  76. case 'url':// [a-zA-Z0-9_-]
  77. if (is_scalar($from)) {
  78. $ret = $from;
  79. settype($ret, 'string');
  80. $ret = trim($ret);
  81. $pl_letters = array('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż', 'Ą', 'Ć', 'Ę', 'Ł', 'Ń', 'Ó', 'Ś', 'Ź', 'Ż');
  82. $en_letters = array('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', 'A', 'C', 'E', 'L', 'N', 'O', 'S', 'Z', 'Z');
  83. $ret = str_replace($pl_letters, $en_letters, $ret);
  84. $ret = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $ret);
  85. }
  86. break;
  87. case 'int':
  88. case 'integer':
  89. if (is_scalar($from)) {
  90. $ret = $from;
  91. settype($ret, $type);
  92. }
  93. break;
  94. case 'float':
  95. case 'double':
  96. if (is_scalar($from)) {
  97. $ret = str_replace(',', '.', $from);
  98. settype($ret, $type);
  99. }
  100. break;
  101. case 'price':// 0.00 - decimal(n, 2)
  102. if (is_scalar($from)) {
  103. $ret = str_replace(',', '.', $from);
  104. settype($ret, 'float');
  105. $ret = round($ret, 2);
  106. }
  107. break;
  108. case 'object':
  109. case 'array':
  110. if (is_scalar($from) || is_array($from) || is_object($from)) {
  111. $ret = $from;
  112. settype($ret, $type);
  113. }
  114. break;
  115. case 'int_array':
  116. if (is_scalar($from) || is_array($from) || is_object($from)) {
  117. $ret = array();
  118. $arr = $from;
  119. settype($arr, 'array');
  120. foreach ($arr as $v) {
  121. $v = V::convert($v, 'int');
  122. $ret[] = $v;
  123. }
  124. }
  125. break;
  126. case 'uint_array':// uncigned int array
  127. if (is_scalar($from) || is_array($from) || is_object($from)) {
  128. $ret = array();
  129. $arr = $from;
  130. settype($arr, 'array');
  131. foreach ($arr as $v) {
  132. $v = V::convert($v, 'int');
  133. if ($v <= 0) continue;
  134. $ret[] = $v;
  135. }
  136. }
  137. break;
  138. case 'float_array':// uncigned int array
  139. if (is_scalar($from) || is_array($from) || is_object($from)) {
  140. $ret = array();
  141. $arr = $from;
  142. settype($arr, 'array');
  143. foreach ($arr as $v) {
  144. $v = V::convert($v, 'float');
  145. $ret[] = $v;
  146. }
  147. }
  148. break;
  149. default:
  150. $fun = 'func_type_convert_'.$type;
  151. if (function_exists($fun)) {
  152. $ret = $fun($from);
  153. }
  154. break;
  155. }
  156. return $ret;
  157. }
  158. /**
  159. * Merge the contents of two objects/array.
  160. *
  161. * array V::extend(mixed $defaults, mixed $params);
  162. * @see http://api.jquery.com/jQuery.extend/
  163. * is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  164. */
  165. public static function extend($defaults, $params) {
  166. $ret = array();
  167. $d = (is_array($defaults))? $defaults : (array)$defaults;
  168. $p = (is_array($params))? $params : (array)$params;
  169. foreach ($d as $k => $v) {
  170. $ret[$k] = $v;
  171. }
  172. foreach ($p as $k => $v) {
  173. if (array_key_exists($k, $ret) && (is_array($ret[$k]) || is_object($ret[$k])) && (is_array($v) || is_object($v))) {
  174. $ret[$k] = V::extend($ret[$k], $v);
  175. } else {
  176. $ret[$k] = $v;
  177. }
  178. }
  179. return $ret;
  180. }
  181. public static function json_encode_latin2($o, $force_object = false) {
  182. if ($o === '') {
  183. return '""';
  184. }
  185. else if (!$o) {
  186. return 'null';
  187. }
  188. else if (is_array($o)) {
  189. $arr = '';
  190. if ($force_object) {
  191. foreach ($o as $k => $v) {
  192. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  193. }
  194. return '{'.implode(',',$arr).'}';
  195. }
  196. else {
  197. foreach ($o as $k => $v) {
  198. if (is_string($k)) $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  199. else $arr[] = V::json_encode_latin2($v);
  200. }
  201. return '['.implode(',',$arr).']';
  202. }
  203. }
  204. else if (is_object($o)) {
  205. $arr = '';
  206. foreach (get_object_vars($o) as $k => $v) {
  207. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  208. }
  209. return '{'.implode(',',$arr).'}';
  210. }
  211. else if (is_string($o)) {
  212. return '"'.addslashes(str_replace(array("\n","\r"), array('\n',''), $o)).'"';
  213. }
  214. else if (is_numeric($o)) {
  215. return ''.$o.'';
  216. }
  217. else if (is_bool($o)) {
  218. return ''.(($o)? 'true' : 'false').'';
  219. }
  220. }
  221. public static function copy($o) {
  222. $null = null;
  223. if (!$o) {
  224. return $null;
  225. }
  226. else if (is_array($o)) {
  227. $ret = array();
  228. foreach ($o as $k => $v) {
  229. $ret[$k] = $v;
  230. }
  231. return $ret;
  232. }
  233. else if (is_object($o)) {
  234. $ret = new stdClass();
  235. foreach (get_object_vars($o) as $k => $v) {
  236. $ret->$k = $v;
  237. }
  238. return $ret;
  239. }
  240. else {
  241. $ret = $o;
  242. return $ret;
  243. }
  244. }
  245. public static function make_link($prefix = '', $params = array()) {
  246. $ret = '';
  247. if ($prefix) {
  248. $ret = $prefix;
  249. }
  250. if (!empty($params)) {
  251. $ret_arr = array();
  252. foreach ($params as $k => $v) {
  253. $ret_arr[] = $k . "=" . $v;
  254. }
  255. $ret .= "?" . implode("&", $ret_arr);
  256. }
  257. return $ret;
  258. }
  259. public static function strShort($label, $maxLength = 10, $suffix = ' ...') {
  260. if (strlen($label) > $maxLength) {
  261. $pos = strpos($label, ' - ');
  262. if ($pos > $maxLength || $pos < 5) {
  263. $label = substr($label, 0, $pos) . $suffix;
  264. } else {
  265. $label = substr($label, 0, $pos);
  266. }
  267. }
  268. return $label;
  269. }
  270. public static function strShortUtf8($label, $maxLength = 10, $suffix = ' ...') {
  271. if (mb_strlen($label, 'utf-8') > $maxLength) {
  272. $pos = mb_strpos($label, ' - ', 0, 'utf-8');
  273. if ($pos > $maxLength || $pos < 5) {
  274. $label = mb_substr($label, 0, $maxLength, 'utf-8') . $suffix;
  275. } else {
  276. $label = mb_substr($label, 0, $pos, 'utf-8');
  277. }
  278. }
  279. return $label;
  280. }
  281. public static function filter($array, $filterCallback) {
  282. if (!is_callable($filterCallback)) {
  283. throw new Exception("callback is not callable '" . ((is_array($filterCallback))? implode('.', $filterCallback) : $filterCallback) . "'");
  284. }
  285. return array_filter($array, $filterCallback);
  286. }
  287. public static function filterNotEmpty($value) {
  288. return !empty($value);
  289. }
  290. public static function filterInteger($value) {// An integer or string with integer value
  291. if (is_int($value)) {
  292. return true;
  293. } else if (is_string($value)) {
  294. if ((string)(int)$value === $value) {
  295. return true;
  296. }
  297. }
  298. return false;
  299. }
  300. public static function filterNegativeInteger($value) {// An integer containing only negative values (..,-2,-1)
  301. if (V::filterInteger($value)) {
  302. if (intval($value) < 0) {
  303. return true;
  304. }
  305. }
  306. return false;
  307. }
  308. public static function filterNonNegativeInteger($value) {// An integer containing only non-negative values (0,1,2,..)
  309. if (V::filterInteger($value)) {
  310. if (intval($value) >= 0) {
  311. return true;
  312. }
  313. }
  314. return false;
  315. }
  316. public static function filterNonPositiveInteger($value) {// An integer containing only non-positive values (..,-2,-1,0)
  317. if (V::filterInteger($value)) {
  318. if (intval($value) <= 0) {
  319. return true;
  320. }
  321. }
  322. return false;
  323. }
  324. public static function filterPositiveInteger($value) {// An integer containing only positive values (1,2,..)
  325. if (V::filterInteger($value)) {
  326. if (intval($value) > 0) {
  327. return true;
  328. }
  329. }
  330. return false;
  331. }
  332. public static function validate($argName, $args, $params) {
  333. //$what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  334. $argValue = V::get($argName, null, $args);
  335. $fldLabel = V::get('fld_label', $argName, $params);
  336. if (array_key_exists('not_empty', $params) && true == $params['not_empty']) {
  337. if (!array_key_exists($argName, $args) || empty($args[$argName])) throw new Exception("Field {$fldLabel} not set.");
  338. }
  339. $params['fld_label'] = $fldLabel;
  340. return V::validateValue($argValue, $params);
  341. }
  342. public static function validateValue($value, $params) {
  343. $fldLabel = V::get('fld_label', '', $params);
  344. $maxLength = V::get('max_length', 0, $params);
  345. if ($maxLength > 0) {
  346. if (strlen($value) > $maxLength) throw new Exception("'{$fldLabel}' cannot be longer then {$maxLength}.");
  347. }
  348. $allowedValues = V::get('values', null, $params);
  349. if (is_array($allowedValues) && !empty($allowedValues)) {
  350. if (!in_array($value, $allowedValues)) throw new Exception("'{$fldLabel}' value is not allowed");
  351. }
  352. $type = V::get('type', null, $params);
  353. if ($type != null) {
  354. if ('word' == $type) {
  355. if (!is_scalar($value) || !preg_match('/^[a-zA-Z_-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  356. } else {
  357. throw new Exception("Unimplemented type to validate: '{$type}'");
  358. }
  359. }
  360. if (array_key_exists('equal', $params)) {
  361. if ($value != $params['equal']) throw new Exception(V::get('error_msg_equal', "'{$fldLabel}' must be equal to '{$params['equal']}'", $params));
  362. }
  363. if (array_key_exists('equalStrict', $params)) {
  364. if ($value !== $params['equalStrict']) throw new Exception(V::get('error_msg_equalStrict', "'{$fldLabel}' must be strict equal to '{$params['equal']}'", $params));
  365. }
  366. return $value;
  367. }
  368. public static function exec($cmd, &$out, &$ret) {
  369. $out = null;
  370. $ret = null;
  371. exec($cmd, $out, $ret);
  372. return $ret;
  373. }
  374. public static function execRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  375. $out = null;
  376. $ret = null;
  377. $pass = $password;
  378. $pass = str_replace('!', '\!', $pass);
  379. $sshPort = (22 != $port)? "-p {$port}" : '';
  380. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  381. declare PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin/:/Applications/Server.app/Contents/ServerRoot/usr/sbin/
  382. '.$command.'
  383. EOF';
  384. exec($cmd, $out, $ret);
  385. return $ret;
  386. }
  387. public static function execRootRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  388. $out = null;
  389. $ret = null;
  390. $pass = $password;
  391. $pass = str_replace('!', '\!', $pass);
  392. $sshPort = (22 != $port)? "-p {$port}" : '';
  393. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  394. sudo -n su -
  395. declare PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin/:/Applications/Server.app/Contents/ServerRoot/usr/sbin/
  396. '.$command.'
  397. EOF';
  398. exec($cmd, $out, $ret);
  399. return $ret;
  400. }
  401. public static function cloneArray($arr) {
  402. return $arr;
  403. }
  404. public static function humanFileSize($bytes) {
  405. $bytes = intval($bytes);
  406. $arBytes = array(
  407. 0 => array("UNIT" => "TB", "VALUE" => pow(1024, 4)),
  408. 1 => array("UNIT" => "GB", "VALUE" => pow(1024, 3)),
  409. 2 => array("UNIT" => "MB", "VALUE" => pow(1024, 2)),
  410. 3 => array("UNIT" => "KB", "VALUE" => 1024),
  411. 4 => array("UNIT" => "B", "VALUE" => 1)
  412. );
  413. foreach($arBytes as $arItem) {
  414. if ($bytes >= $arItem["VALUE"]) {
  415. $result = $bytes / $arItem["VALUE"];
  416. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  417. break;
  418. }
  419. }
  420. return $result;
  421. }
  422. }