V.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  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 'object':
  96. case 'array':
  97. if (is_scalar($from) || is_array($from) || is_object($from)) {
  98. $ret = $from;
  99. settype($ret, $type);
  100. }
  101. break;
  102. case 'int_array':
  103. if (is_scalar($from) || is_array($from) || is_object($from)) {
  104. $ret = array();
  105. $arr = $from;
  106. settype($arr, 'array');
  107. foreach ($arr as $v) {
  108. $v = V::convert($v, 'int');
  109. $ret[] = $v;
  110. }
  111. }
  112. break;
  113. case 'uint_array':// uncigned int array
  114. if (is_scalar($from) || is_array($from) || is_object($from)) {
  115. $ret = array();
  116. $arr = $from;
  117. settype($arr, 'array');
  118. foreach ($arr as $v) {
  119. $v = V::convert($v, 'int');
  120. if ($v <= 0) continue;
  121. $ret[] = $v;
  122. }
  123. }
  124. break;
  125. case 'float_array':// uncigned int array
  126. if (is_scalar($from) || is_array($from) || is_object($from)) {
  127. $ret = array();
  128. $arr = $from;
  129. settype($arr, 'array');
  130. foreach ($arr as $v) {
  131. $v = V::convert($v, 'float');
  132. $ret[] = $v;
  133. }
  134. }
  135. break;
  136. default:
  137. $fun = 'func_type_convert_'.$type;
  138. if (function_exists($fun)) {
  139. $ret = $fun($from);
  140. }
  141. break;
  142. }
  143. return $ret;
  144. }
  145. /**
  146. * Merge the contents of two objects/array.
  147. *
  148. * array V::extend(mixed $defaults, mixed $params);
  149. * @see http://api.jquery.com/jQuery.extend/
  150. * is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  151. */
  152. public static function extend($defaults, $params) {
  153. $ret = array();
  154. $d = (is_array($defaults))? $defaults : (array)$defaults;
  155. $p = (is_array($params))? $params : (array)$params;
  156. foreach ($d as $k => $v) {
  157. $ret[$k] = $v;
  158. }
  159. foreach ($p as $k => $v) {
  160. if (array_key_exists($k, $ret) && (is_array($ret[$k]) || is_object($ret[$k])) && (is_array($v) || is_object($v))) {
  161. $ret[$k] = V::extend($ret[$k], $v);
  162. } else {
  163. $ret[$k] = $v;
  164. }
  165. }
  166. return $ret;
  167. }
  168. public static function json_encode_latin2($o, $force_object = false) {
  169. if ($o === '') {
  170. return '""';
  171. }
  172. else if (!$o) {
  173. return 'null';
  174. }
  175. else if (is_array($o)) {
  176. $arr = '';
  177. if ($force_object) {
  178. foreach ($o as $k => $v) {
  179. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  180. }
  181. return '{'.implode(',',$arr).'}';
  182. }
  183. else {
  184. foreach ($o as $k => $v) {
  185. if (is_string($k)) $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  186. else $arr[] = V::json_encode_latin2($v);
  187. }
  188. return '['.implode(',',$arr).']';
  189. }
  190. }
  191. else if (is_object($o)) {
  192. $arr = '';
  193. foreach (get_object_vars($o) as $k => $v) {
  194. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  195. }
  196. return '{'.implode(',',$arr).'}';
  197. }
  198. else if (is_string($o)) {
  199. return '"'.addslashes(str_replace(array("\n","\r"), array('\n',''), $o)).'"';
  200. }
  201. else if (is_numeric($o)) {
  202. return ''.$o.'';
  203. }
  204. else if (is_bool($o)) {
  205. return ''.(($o)? 'true' : 'false').'';
  206. }
  207. }
  208. public static function copy($o) {
  209. $null = null;
  210. if (!$o) {
  211. return $null;
  212. }
  213. else if (is_array($o)) {
  214. $ret = array();
  215. foreach ($o as $k => $v) {
  216. $ret[$k] = $v;
  217. }
  218. return $ret;
  219. }
  220. else if (is_object($o)) {
  221. $ret = new stdClass();
  222. foreach (get_object_vars($o) as $k => $v) {
  223. $ret->$k = $v;
  224. }
  225. return $ret;
  226. }
  227. else {
  228. $ret = $o;
  229. return $ret;
  230. }
  231. }
  232. public static function make_link($prefix = '', $params = array()) {
  233. $ret = '';
  234. if ($prefix) {
  235. $ret = $prefix;
  236. }
  237. if (!empty($params)) {
  238. $ret_arr = array();
  239. foreach ($params as $k => $v) {
  240. $ret_arr[] = $k . "=" . $v;
  241. }
  242. $ret .= "?" . implode("&", $ret_arr);
  243. }
  244. return $ret;
  245. }
  246. public static function strShort($label, $maxLength = 10, $suffix = ' ...') {
  247. if (strlen($label) > $maxLength) {
  248. $pos = strpos($label, ' - ');
  249. if ($pos > $maxLength || $pos < 5) {
  250. $label = substr($label, 0, $pos) . $suffix;
  251. } else {
  252. $label = substr($label, 0, $pos);
  253. }
  254. }
  255. return $label;
  256. }
  257. public static function strShortUtf8($label, $maxLength = 10, $suffix = ' ...') {
  258. if (mb_strlen($label, 'utf-8') > $maxLength) {
  259. $pos = mb_strpos($label, ' - ', 0, 'utf-8');
  260. if ($pos > $maxLength || $pos < 5) {
  261. $label = mb_substr($label, 0, $maxLength, 'utf-8') . $suffix;
  262. } else {
  263. $label = mb_substr($label, 0, $pos, 'utf-8');
  264. }
  265. }
  266. return $label;
  267. }
  268. public static function filter($array, $filterCallback) {
  269. if (!is_callable($filterCallback)) {
  270. throw new Exception("callback is not callable '" . ((is_array($filterCallback))? implode('.', $filterCallback) : $filterCallback) . "'");
  271. }
  272. return array_filter($array, $filterCallback);
  273. }
  274. public static function filterNotEmpty($value) {
  275. return !empty($value);
  276. }
  277. public static function filterInteger($value) {// An integer or string with integer value
  278. if (is_int($value)) {
  279. return true;
  280. } else if (is_string($value)) {
  281. if ((string)(int)$value === $value) {
  282. return true;
  283. }
  284. }
  285. return false;
  286. }
  287. public static function filterNegativeInteger($value) {// An integer containing only negative values (..,-2,-1)
  288. if (V::filterInteger($value)) {
  289. if (intval($value) < 0) {
  290. return true;
  291. }
  292. }
  293. return false;
  294. }
  295. public static function filterNonNegativeInteger($value) {// An integer containing only non-negative values (0,1,2,..)
  296. if (V::filterInteger($value)) {
  297. if (intval($value) >= 0) {
  298. return true;
  299. }
  300. }
  301. return false;
  302. }
  303. public static function filterNonPositiveInteger($value) {// An integer containing only non-positive values (..,-2,-1,0)
  304. if (V::filterInteger($value)) {
  305. if (intval($value) <= 0) {
  306. return true;
  307. }
  308. }
  309. return false;
  310. }
  311. public static function filterPositiveInteger($value) {// An integer containing only positive values (1,2,..)
  312. if (V::filterInteger($value)) {
  313. if (intval($value) > 0) {
  314. return true;
  315. }
  316. }
  317. return false;
  318. }
  319. public static function validate($argName, $args, $params) {
  320. //$what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  321. $argValue = V::get($argName, null, $args);
  322. $fldLabel = V::get('fld_label', $argName, $params);
  323. if (array_key_exists('not_empty', $params) && true == $params['not_empty']) {
  324. if (!array_key_exists($argName, $args) || empty($args[$argName])) throw new Exception("Field {$fldLabel} not set.");
  325. }
  326. $params['fld_label'] = $fldLabel;
  327. return V::validateValue($argValue, $params);
  328. }
  329. public static function validateValue($value, $params) {
  330. $fldLabel = V::get('fld_label', '', $params);
  331. $maxLength = V::get('max_length', 0, $params);
  332. if ($maxLength > 0) {
  333. if (strlen($value) > $maxLength) throw new Exception("'{$fldLabel}' cannot be longer then {$maxLength}.");
  334. }
  335. $allowedValues = V::get('values', null, $params);
  336. if (is_array($allowedValues) && !empty($allowedValues)) {
  337. if (!in_array($value, $allowedValues)) throw new Exception("'{$fldLabel}' value is not allowed");
  338. }
  339. $type = V::get('type', null, $params);
  340. if ($type != null) {
  341. if ('word' == $type) {
  342. if (!is_scalar($value) || !preg_match('/^[a-zA-Z_-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  343. } else {
  344. throw new Exception("Unimplemented type to validate: '{$type}'");
  345. }
  346. }
  347. if (array_key_exists('equal', $params)) {
  348. if ($value != $params['equal']) throw new Exception(V::get('error_msg_equal', "'{$fldLabel}' must be equal to '{$params['equal']}'", $params));
  349. }
  350. if (array_key_exists('equalStrict', $params)) {
  351. if ($value !== $params['equalStrict']) throw new Exception(V::get('error_msg_equalStrict', "'{$fldLabel}' must be strict equal to '{$params['equal']}'", $params));
  352. }
  353. return $value;
  354. }
  355. public static function exec($cmd, &$out, &$ret) {
  356. $out = null;
  357. $ret = null;
  358. exec($cmd, $out, $ret);
  359. return $ret;
  360. }
  361. public static function execRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  362. $out = null;
  363. $ret = null;
  364. $pass = $password;
  365. $pass = str_replace('!', '\!', $pass);
  366. $sshPort = (22 != $port)? "-p {$port}" : '';
  367. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  368. 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/
  369. '.$command.'
  370. EOF';
  371. exec($cmd, $out, $ret);
  372. return $ret;
  373. }
  374. public static function execRootRemote($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. sudo -n su -
  382. 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/
  383. '.$command.'
  384. EOF';
  385. exec($cmd, $out, $ret);
  386. return $ret;
  387. }
  388. public static function cloneArray($arr) {
  389. return $arr;
  390. }
  391. public function humanFileSize($bytes) {
  392. $bytes = intval($bytes);
  393. $arBytes = array(
  394. 0 => array("UNIT" => "TB", "VALUE" => pow(1024, 4)),
  395. 1 => array("UNIT" => "GB", "VALUE" => pow(1024, 3)),
  396. 2 => array("UNIT" => "MB", "VALUE" => pow(1024, 2)),
  397. 3 => array("UNIT" => "KB", "VALUE" => 1024),
  398. 4 => array("UNIT" => "B", "VALUE" => 1)
  399. );
  400. foreach($arBytes as $arItem) {
  401. if ($bytes >= $arItem["VALUE"]) {
  402. $result = $bytes / $arItem["VALUE"];
  403. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  404. break;
  405. }
  406. }
  407. return $result;
  408. }
  409. }