V.php 12 KB

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