V.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  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 - case insensitive
  10. */
  11. public static function geti($name, $default, $from, $type = '', $filterCallback = null) {
  12. $lowerFrom = array();
  13. if (!is_object($from) && !is_array($from)) throw new Exception("Bad param - from must be array or object");
  14. foreach ((array)$from as $fieldName => $value) {
  15. $lowerFrom[ strtolower($fieldName) ] = $value;
  16. }
  17. return V::get(strtolower($name), $default, $lowerFrom, $type, $filterCallback);
  18. }
  19. /**
  20. * Get variable from array or object.
  21. */
  22. public static function get($name, $default, $from, $type = '', $filterCallback = null) {
  23. if (empty($name)) return null;
  24. $ret = null;
  25. if (is_bool($name)) $name = (int)$name;
  26. if (!is_string($name) && !is_numeric($name)) {
  27. //var_dump($name);
  28. //echo'<pre>';print_r(debug_backtrace());echo'</pre>';
  29. throw new Exception("Error name is not scalar! '{$name}'");
  30. }
  31. if (is_array($from)) {
  32. if (array_key_exists($name, $from)) {
  33. $ret = $from[$name];
  34. }
  35. }
  36. else if (is_object($from)) {
  37. if (isset($from->$name)) {
  38. $ret = $from->$name;
  39. }
  40. }
  41. if (isset($ret) && $type != '') {
  42. $ret = V::convert($ret, $type);
  43. }
  44. if (!empty($filterCallback)) {
  45. if ($type == 'array' && is_array($ret) && !empty($ret)) {
  46. $ret = V::filter($ret, $filterCallback);
  47. }
  48. }
  49. $ret = (null !== $ret)? $ret : $default;
  50. return $ret;
  51. }
  52. /**
  53. * Convert variable type.
  54. * @usage: V::convert($from, 'url');
  55. */
  56. public static function convert($from, $type = 'string') {
  57. switch ($type) {
  58. case 'minOccurs':
  59. case 'maxOccurs': // The default values for minOccurs and maxOccurs are 1 - @return int or 'unbounded', default is 1
  60. if (!is_scalar($from)) return null;
  61. if (!strlen($from)) return 1;
  62. if ("unbounded" === $from) return "unbounded";
  63. return (int)$from;
  64. }
  65. $type = strtolower($type);
  66. // is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  67. $ret = null;
  68. switch ($type) {
  69. case 'string':
  70. if (is_scalar($from)) {
  71. $ret = $from;
  72. settype($ret, $type);
  73. }
  74. return $ret;
  75. case 'word':
  76. if (is_scalar($from)) {
  77. $ret = $from;
  78. settype($ret, 'string');
  79. $ret = trim($ret);
  80. if (false !== ($pos = strpos($ret, ' '))) {
  81. $ret = substr($ret, 0, $pos);
  82. }
  83. }
  84. return $ret;
  85. case 'login':// [a-zA-Z.-_]
  86. if (is_scalar($from)) {
  87. $ret = $from;
  88. settype($ret, 'string');
  89. $ret = trim($ret);
  90. if (!preg_match("/^[a-zA-Z.-_]*$/", $ret, $matches)) {
  91. $ret = null;
  92. }
  93. }
  94. return $ret;
  95. case 'url':// [a-zA-Z0-9_-]
  96. if (is_scalar($from)) {
  97. $ret = $from;
  98. settype($ret, 'string');
  99. $ret = trim($ret);
  100. $pl_letters = array('ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż', 'Ą', 'Ć', 'Ę', 'Ł', 'Ń', 'Ó', 'Ś', 'Ź', 'Ż');
  101. $en_letters = array('a', 'c', 'e', 'l', 'n', 'o', 's', 'z', 'z', 'A', 'C', 'E', 'L', 'N', 'O', 'S', 'Z', 'Z');
  102. $ret = str_replace($pl_letters, $en_letters, $ret);
  103. $ret = preg_replace('/[^a-zA-Z0-9_-]+/', '_', $ret);
  104. }
  105. return $ret;
  106. case 'int':
  107. case 'integer':
  108. if (is_scalar($from)) {
  109. $ret = $from;
  110. settype($ret, $type);
  111. }
  112. return $ret;
  113. case 'float':
  114. case 'double':
  115. if (is_scalar($from)) {
  116. $ret = str_replace(',', '.', $from);
  117. settype($ret, $type);
  118. }
  119. return $ret;
  120. case 'price':// 0.00 - decimal(n, 2)
  121. if (is_scalar($from)) {
  122. $ret = str_replace(',', '.', $from);
  123. settype($ret, 'float');
  124. $ret = round($ret, 2);
  125. }
  126. return $ret;
  127. case 'object':
  128. case 'array':
  129. if (is_scalar($from) || is_array($from) || is_object($from)) {
  130. $ret = $from;
  131. settype($ret, $type);
  132. }
  133. return $ret;
  134. case 'int_array':
  135. if (is_scalar($from) || is_array($from) || is_object($from)) {
  136. $ret = array();
  137. $arr = $from;
  138. settype($arr, 'array');
  139. foreach ($arr as $v) {
  140. $v = V::convert($v, 'int');
  141. $ret[] = $v;
  142. }
  143. }
  144. return $ret;
  145. case 'uint_array':// unsigned int array
  146. if (is_scalar($from) || is_array($from) || is_object($from)) {
  147. $ret = array();
  148. $arr = $from;
  149. settype($arr, 'array');
  150. foreach ($arr as $v) {
  151. $v = V::convert($v, 'int');
  152. if ($v <= 0) continue;
  153. $ret[] = $v;
  154. }
  155. }
  156. return $ret;
  157. case 'float_array':// uncigned int array
  158. if (is_scalar($from) || is_array($from) || is_object($from)) {
  159. $ret = array();
  160. $arr = $from;
  161. settype($arr, 'array');
  162. foreach ($arr as $v) {
  163. $v = V::convert($v, 'float');
  164. $ret[] = $v;
  165. }
  166. }
  167. return $ret;
  168. case 'bool':
  169. case 'boolean': return (bool)$from;
  170. default:
  171. $fun = 'func_type_convert_'.$type;
  172. return (function_exists($fun)) ? $fun($from) : null;
  173. }
  174. }
  175. /**
  176. * Merge the contents of two objects/array.
  177. *
  178. * array V::extend(mixed $defaults, mixed $params);
  179. * @see http://api.jquery.com/jQuery.extend/
  180. * is_scalar($from) - return TRUE if int,float,string,bool, FALSE if array,object,resource, ...
  181. */
  182. public static function extend($defaults, $params) {
  183. $ret = array();
  184. $d = (is_array($defaults))? $defaults : (array)$defaults;
  185. $p = (is_array($params))? $params : (array)$params;
  186. foreach ($d as $k => $v) {
  187. $ret[$k] = $v;
  188. }
  189. foreach ($p as $k => $v) {
  190. if (array_key_exists($k, $ret) && (is_array($ret[$k]) || is_object($ret[$k])) && (is_array($v) || is_object($v))) {
  191. $ret[$k] = V::extend($ret[$k], $v);
  192. } else {
  193. $ret[$k] = $v;
  194. }
  195. }
  196. return $ret;
  197. }
  198. public static function json_encode_latin2($o, $force_object = false) {
  199. if ($o === '') {
  200. return '""';
  201. }
  202. else if (!$o) {
  203. return 'null';
  204. }
  205. else if (is_array($o)) {
  206. $arr = '';
  207. if ($force_object) {
  208. foreach ($o as $k => $v) {
  209. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  210. }
  211. return '{'.implode(',',$arr).'}';
  212. }
  213. else {
  214. foreach ($o as $k => $v) {
  215. if (is_string($k)) $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  216. else $arr[] = V::json_encode_latin2($v);
  217. }
  218. return '['.implode(',',$arr).']';
  219. }
  220. }
  221. else if (is_object($o)) {
  222. $arr = '';
  223. foreach (get_object_vars($o) as $k => $v) {
  224. $arr[] = '"'.$k.'":'.V::json_encode_latin2($v, $force_object);
  225. }
  226. return '{'.implode(',',$arr).'}';
  227. }
  228. else if (is_string($o)) {
  229. return '"'.addslashes(str_replace(array("\n","\r"), array('\n',''), $o)).'"';
  230. }
  231. else if (is_numeric($o)) {
  232. return ''.$o.'';
  233. }
  234. else if (is_bool($o)) {
  235. return ''.(($o)? 'true' : 'false').'';
  236. }
  237. }
  238. public static function copy($o) {
  239. $null = null;
  240. if (!$o) {
  241. return $null;
  242. }
  243. else if (is_array($o)) {
  244. $ret = array();
  245. foreach ($o as $k => $v) {
  246. $ret[$k] = $v;
  247. }
  248. return $ret;
  249. }
  250. else if (is_object($o)) {
  251. $ret = new stdClass();
  252. foreach (get_object_vars($o) as $k => $v) {
  253. $ret->$k = $v;
  254. }
  255. return $ret;
  256. }
  257. else {
  258. $ret = $o;
  259. return $ret;
  260. }
  261. }
  262. public static function make_link($prefix = '', $params = array()) {
  263. $ret = '';
  264. if ($prefix) {
  265. $ret = $prefix;
  266. }
  267. if (!empty($params)) {
  268. $ret_arr = array();
  269. foreach ($params as $k => $v) {
  270. $ret_arr[] = $k . "=" . $v;
  271. }
  272. $ret .= "?" . implode("&", $ret_arr);
  273. }
  274. return $ret;
  275. }
  276. public static function strShort($label, $maxLength = 10, $suffix = ' ...') {
  277. if (strlen($label) > $maxLength) {
  278. $pos = strpos($label, ' - ');
  279. if ($pos > $maxLength || $pos < 5) {
  280. $label = substr($label, 0, $maxLength) . $suffix;
  281. } else {
  282. $label = substr($label, 0, $pos);
  283. }
  284. }
  285. return $label;
  286. }
  287. public static function strShortUtf8($label, $maxLength = 10, $suffix = ' ...') {
  288. if (mb_strlen($label, 'utf-8') > $maxLength) {
  289. $pos = mb_strpos($label, ' - ', 0, 'utf-8');
  290. if ($pos > $maxLength || $pos < 5) {
  291. $label = mb_substr($label, 0, $maxLength, 'utf-8') . $suffix;
  292. } else {
  293. $label = mb_substr($label, 0, $pos, 'utf-8');
  294. }
  295. }
  296. return $label;
  297. }
  298. public static function filter($array, $filterCallback) {
  299. if (!is_callable($filterCallback)) {
  300. throw new Exception("callback is not callable '" . ((is_array($filterCallback))? implode('.', $filterCallback) : $filterCallback) . "'");
  301. }
  302. return array_filter($array, $filterCallback);
  303. }
  304. public static function filterNotEmpty($value) {
  305. return !empty($value);
  306. }
  307. public static function filterInteger($value) {// An integer or string with integer value
  308. if (is_int($value)) {
  309. return true;
  310. } else if (is_string($value)) {
  311. if ((string)(int)$value === $value) {
  312. return true;
  313. }
  314. }
  315. return false;
  316. }
  317. public static function filterNegativeInteger($value) {// An integer containing only negative values (..,-2,-1)
  318. if (V::filterInteger($value)) {
  319. if (intval($value) < 0) {
  320. return true;
  321. }
  322. }
  323. return false;
  324. }
  325. public static function filterNonNegativeInteger($value) {// An integer containing only non-negative values (0,1,2,..)
  326. if (V::filterInteger($value)) {
  327. if (intval($value) >= 0) {
  328. return true;
  329. }
  330. }
  331. return false;
  332. }
  333. public static function filterNonPositiveInteger($value) {// An integer containing only non-positive values (..,-2,-1,0)
  334. if (V::filterInteger($value)) {
  335. if (intval($value) <= 0) {
  336. return true;
  337. }
  338. }
  339. return false;
  340. }
  341. public static function filterPositiveInteger($value) {// An integer containing only positive values (1,2,..)
  342. if (V::filterInteger($value)) {
  343. if (intval($value) > 0) {
  344. return true;
  345. }
  346. }
  347. return false;
  348. }
  349. public static function validate($argName, $args, $params) {
  350. //$what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  351. $argValue = V::get($argName, null, $args);
  352. $fldLabel = V::get('fld_label', $argName, $params);
  353. if (array_key_exists('not_empty', $params) && true == $params['not_empty']) {
  354. if (!array_key_exists($argName, $args) || empty($args[$argName])) throw new Exception("Field {$fldLabel} not set.");
  355. }
  356. $params['fld_label'] = $fldLabel;
  357. return V::validateValue($argValue, $params);
  358. }
  359. public static function validateValue($value, $params) {
  360. $fldLabel = V::get('fld_label', '', $params);
  361. $maxLength = V::get('max_length', 0, $params);
  362. if ($maxLength > 0) {
  363. if (strlen($value) > $maxLength) throw new Exception("'{$fldLabel}' cannot be longer then {$maxLength}.");
  364. }
  365. $allowedValues = V::get('values', null, $params);
  366. if (is_array($allowedValues) && !empty($allowedValues)) {
  367. if (!in_array($value, $allowedValues)) throw new Exception("'{$fldLabel}' value is not allowed");
  368. }
  369. $type = V::get('type', null, $params);
  370. if ($type != null) {
  371. if ('word' == $type) {
  372. if (!is_scalar($value) || !preg_match('/^[a-zA-Z_-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  373. } else if ('login' == $type) {
  374. if (!is_scalar($value) || !preg_match('/^[a-zA-Z\._-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  375. } else {
  376. throw new Exception("Unimplemented type to validate: '{$type}'");
  377. }
  378. }
  379. if (array_key_exists('equal', $params)) {
  380. if ($value != $params['equal']) throw new Exception(V::get('error_msg_equal', "'{$fldLabel}' must be equal to '{$params['equal']}'", $params));
  381. }
  382. if (array_key_exists('equalStrict', $params)) {
  383. if ($value !== $params['equalStrict']) throw new Exception(V::get('error_msg_equalStrict', "'{$fldLabel}' must be strict equal to '{$params['equal']}'", $params));
  384. }
  385. return $value;
  386. }
  387. public static function exec($cmd, &$out, &$ret) {
  388. $out = null;
  389. $ret = null;
  390. // NOTE: SourceGuardian requires file: "${HOME}/.config/SourceGuardian/"
  391. $cmd = implode("\n", [
  392. "PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/local/bin:/opt/local/lib/mysql55/bin:/Applications/Server.app/Contents/ServerRoot/usr/bin:/Applications/Server.app/Contents/ServerRoot/usr/sbin:/Users/pl/programy/bin",
  393. "export HOME='/Library/WebServer'",
  394. $cmd
  395. ]);
  396. exec($cmd, $out, $ret);
  397. return $ret;
  398. }
  399. public static function execRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  400. $out = null;
  401. $ret = null;
  402. $pass = $password;
  403. $pass = str_replace('!', '\!', $pass);
  404. $sshPort = (22 != $port)? "-p {$port}" : '';
  405. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  406. 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/
  407. '.$command.'
  408. EOF';
  409. exec($cmd, $out, $ret);
  410. return $ret;
  411. }
  412. public static function execRootRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  413. $out = null;
  414. $ret = null;
  415. $pass = $password;
  416. $pass = str_replace('!', '\!', $pass);
  417. $sshPort = (22 != $port)? "-p {$port}" : '';
  418. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  419. sudo -n su -
  420. 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/
  421. '.$command.'
  422. EOF';
  423. exec($cmd, $out, $ret);
  424. return $ret;
  425. }
  426. public static function quoteBashEcho($string) {
  427. return str_replace([ '"', '$' ], [ '\"', '\$' ], $string);
  428. }
  429. public static function cloneArray($arr) {
  430. return $arr;
  431. }
  432. public static function humanFileSize($bytes) {
  433. $bytes = intval($bytes);
  434. $arBytes = array(
  435. 0 => array("UNIT" => "TB", "VALUE" => pow(1024, 4)),
  436. 1 => array("UNIT" => "GB", "VALUE" => pow(1024, 3)),
  437. 2 => array("UNIT" => "MB", "VALUE" => pow(1024, 2)),
  438. 3 => array("UNIT" => "KB", "VALUE" => 1024),
  439. 4 => array("UNIT" => "B", "VALUE" => 1)
  440. );
  441. foreach($arBytes as $arItem) {
  442. if ($bytes >= $arItem["VALUE"]) {
  443. $result = $bytes / $arItem["VALUE"];
  444. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  445. break;
  446. }
  447. }
  448. return $result;
  449. }
  450. public static function kwotaSlownie($kwota = 0, $waluta = "PLN") {
  451. if (!preg_match("/^[[:digit:]]*(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Błędna liczba");
  452. if (!preg_match("/^[[:digit:]]{0,48}(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Zbyt duża liczba");
  453. $waluty = array(
  454. 'PLN' => array('złoty','złotych','złote'),
  455. 'USD' => array('dolar','dolarów','dolary')
  456. );
  457. $jednosci = array('zero','jeden','dwa','trzy','cztery','pięć','sześć','siedem','osiem','dziewięć','dziesięć','jedenaście',
  458. 'dwanaście','trzynaście','czternaście','piętnaście','szesnaście','siednaście','osiemnaście','dziewiętnaście');
  459. $dziesiatki = array('','','dwadzieścia','trzydzieści','czterdzieści','pięćdziesiąt','sześćdziesiąt','siedemdziesiąt','osiemdziesiąt','dziewięćdziesiąt');
  460. $setki = array('','sto','dwieście','trzysta','czterysta','pięćset','sześćset','siedemset','osiemset','dziewięćset');
  461. if (!isset($waluty[$waluta])) $tysiace[] = array($waluta,$waluta,$waluta);
  462. else $tysiace[] = $waluty[$waluta];
  463. $tysiace[] = array('tysiąc','tysięcy','tysiące');
  464. $tysiace[] = array('milion','milionów','miliony');
  465. $tysiace[] = array('miliard','miliardów','miliardy');
  466. $tysiace[] = array('bilion','bilionów','bilony');
  467. $tysiace[] = array('biliard','biliardów','biliardy');
  468. $tysiace[] = array('trylion','trylionów','tryliony');
  469. $tysiace[] = array('tryliard','tryliardów','tryliardy');
  470. $tysiace[] = array('kwadrylion','kwadrylionów','kwadryliony');
  471. $tysiace[] = array('kwadryliard','kwadryliardów','kwaryliardy');
  472. $tysiace[] = array('kwintylion','kwintylionów','kwintyliony');
  473. $tysiace[] = array('kwintyliard','kwintyliardów','kwintyliardy');
  474. $tysiace[] = array('sekstylion','sekstylionów','sepstyliony');
  475. $tysiace[] = array('sekstyliard','sekstyliardów','sekstyliardy');
  476. $tysiace[] = array('septylion','septylionów','septyliony');
  477. $tysiace[] = array('septyliard','septyliardów','septyliardy');
  478. $kwota = (!substr_count($kwota, '.')) ? $kwota.'.00' : $kwota;
  479. list($zlote, $grosze) = explode('.', $kwota);
  480. $zlote = ltrim($zlote, '0');
  481. if ($zlote == '') $zlote = '0';
  482. if (strlen($grosze) == 1) $grosze .= "0";
  483. elseif (strlen($grosze) > 2) $grosze = round(substr($grosze, 0, 2).".".substr($grosze, 2), 0);
  484. $zlote = strrev(wordwrap(strrev($zlote), 3, '.', true));
  485. $zloteArr = explode('.', $zlote);
  486. foreach ($zloteArr as $i => $l) {
  487. $tysiac = count($zloteArr) - $i - 1;
  488. $setka = $setki[floor($l/100)];
  489. $dziesiatka = $dziesiatki[floor(($l%100)/10)];
  490. $jednosc = $dziesiatka ? $jednosci[$l%10] : $jednosci[$l%100];
  491. if ($l == 1 and ($tysiac > 0 or count($zloteArr) == 1)) $odmiana = 0;
  492. elseif (floor($l%100/10) != 1 and $l%10 >= 2 and $l%10 <= 4) $odmiana = 2;
  493. else $odmiana = 1;
  494. if ($setka) $resultArr[] = $setka;
  495. if ($dziesiatka) $resultArr[] = $dziesiatka;
  496. if ($jednosc == $jednosci[0] && $zlote != '0') $jednosc = '';
  497. if ($jednosc) $resultArr[] = $jednosc;
  498. if ($setka || $dziesiatka || $jednosc || $tysiac == 0) $resultArr[] = $tysiace[$tysiac][$odmiana];
  499. }
  500. $resultArr[] = $grosze . "/100";
  501. return implode(" ", $resultArr);
  502. }
  503. public static function nettoOdBrutto($brutto = 0, $vat = "23") {
  504. if ($vat < 0) throw new Exception("Stawka VAT nie może być liczbą ujemną!");
  505. $netto = round($brutto/(1+$vat/100),2);
  506. if (round($netto*(1+$vat/100),2) > $brutto) $netto -= 0.01;
  507. return $netto;
  508. }
  509. public static function makePick($fieldName, $default = '', $type = null) {
  510. return function ($item) use ($fieldName, $default, $type) {
  511. return V::get($fieldName, $default, $item, $type);
  512. };
  513. }
  514. public static function pickSimgleValue($items, $fieldName) {
  515. return array_map(
  516. function ($row) use ($fieldName) {
  517. return V::get($fieldName, '', $row);
  518. }
  519. , $items
  520. );
  521. }
  522. public static function pickArrayValues($items, $fieldNames) {
  523. return $items;
  524. }
  525. public static function arrayToXML($array, $formatOutput = false, $root = "root") {
  526. $arrayToXML_rec = function($data, $dom, $node, $parent = null) use (&$arrayToXML_rec) {
  527. $child = $dom->createElement($node);
  528. if (!$parent) $parent = $dom;
  529. if (is_array($data)) {
  530. if ($data) {
  531. foreach ($data as $key => $value) {
  532. if ((string)$key === '@attributes') {
  533. foreach ($value as $attrName => $attrValue) {
  534. $attr = $dom->createAttribute($attrName);
  535. $attr->value = $attrValue;
  536. $child->appendChild($attr);
  537. }
  538. } else {
  539. if (is_numeric($key)) $arrayToXML_rec($value, $dom, $node, $parent);
  540. else $arrayToXML_rec($value, $dom, $key, $child);
  541. }
  542. }
  543. } else $parent->appendChild($child);
  544. } else {
  545. if ($data) {
  546. if ($data == htmlspecialchars($data)) $child->nodeValue = $data;
  547. else $child->appendChild($dom->createCDATASection($data));
  548. } else $parent->appendChild($child);
  549. }
  550. if ($child->hasChildNodes() || $child->hasAttributes()) $parent->appendChild($child);
  551. };
  552. if (!is_array($array)) throw new Exception("First argument need to be an array");
  553. $dom = new DOMDocument('1.0', 'UTF-8');
  554. $dom->preserveWhiteSpace = false;
  555. $dom->formatOutput = $formatOutput;
  556. $arrayToXML_rec($array, $dom, $root);
  557. return $dom->saveXML();
  558. }
  559. // date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
  560. // a: '2017-07-25 13:06:15.59124',
  561. // b: '2017-07-25 13:06:15.56161',
  562. // result: '0.02963'
  563. public static function milisecondsStringDiff($a, $b) {
  564. if (25 != strlen($a)) return "Wrong length in 1st arg";
  565. if (25 != strlen($b)) return "Wrong length in 2nd arg";
  566. $aTime = array_sum([
  567. intVal(substr($a, 11, 2)) * 100000 * 60 * 60, // hour
  568. intVal(substr($a, 14, 2)) * 100000 * 60, // min
  569. intVal(substr($a, 17, 2)) * 100000, // sec
  570. intVal(substr($a, 20, 5)), // mili sec (5 digits)
  571. ]);
  572. $bTime = array_sum([
  573. intVal(substr($b, 11, 2)) * 100000 * 60 * 60, // hour
  574. intVal(substr($b, 14, 2)) * 100000 * 60, // min
  575. intVal(substr($b, 17, 2)) * 100000, // sec
  576. intVal(substr($b, 20, 5)), // mili sec (5 digits)
  577. ]);
  578. return sprintf("%0.5f", abs($aTime - $bTime) / 100000);
  579. }
  580. public static function isNip($nip) {
  581. if (!(is_numeric($nip) && preg_match('/^[[:digit:]]{10}$/', $nip))) return false;
  582. $waga = [6, 5, 7, 2, 3, 4, 5, 6, 7];
  583. $c = 0;
  584. for ($i = 0; $i < 9; $i++) $c += $nip[$i] * $waga[$i];
  585. $c = ($c % 11) % 10;
  586. return ($nip[9] == $c);
  587. }
  588. public static function isRegon($regon) {
  589. if (!(is_numeric($regon) && preg_match('/^[[:digit:]]{9}$/', $regon))) return false;
  590. $waga = [8, 9, 2, 3, 4, 5, 6, 7];
  591. $c = 0;
  592. for ($i = 0; $i < 8; $i++) $c += $regon[$i] * $waga[$i];
  593. $c = ($c % 11) % 10;
  594. return ($regon[8] == $c);
  595. }
  596. static function stripInvalidXmlChars($value = "") {
  597. return array_reduce(str_split((string)$value), function ($ret, $char) {
  598. $charCode = ord($char);
  599. if (
  600. (0x9 === $charCode)
  601. || (0xA === $charCode)
  602. || (0xD === $charCode)
  603. || (($charCode >= 0x20) && ($charCode <= 0xD7FF))
  604. || (($charCode >= 0xE000) && ($charCode <= 0xFFFD))
  605. || (($charCode >= 0x10000) && ($charCode <= 0x10FFFF))
  606. ) {
  607. return $ret . $char;
  608. }
  609. return $ret;
  610. }, "");
  611. }
  612. static function deleteWholeDirectory($dir, $returnFiles = false, $doDelete = true) {
  613. if (!is_dir($dir)) throw new Exception("{$dir} must be a directory");
  614. $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
  615. $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  616. if ($doDelete) {
  617. $rmdir = 'rmdir';
  618. $unlink = 'unlink';
  619. } else {
  620. $rmdir = 'is_string';
  621. $unlink = 'is_string';
  622. }
  623. if ($returnFiles) {
  624. $return = [];
  625. foreach ($files as $file) {
  626. if ($file->isDir()) $return['dirs'][$file->getRealPath()] = @$rmdir($file->getRealPath());
  627. else $return['files'][$file->getRealPath()] = @$unlink($file->getRealPath());
  628. }
  629. $return['dirs'][$dir] = @$rmdir($dir);
  630. return $return;
  631. } else {
  632. foreach ($files as $file) {
  633. if ($file->isDir()) @$rmdir($file->getRealPath());
  634. else @$unlink($file->getRealPath());
  635. }
  636. @$rmdir($dir);
  637. }
  638. }
  639. }