V.php 23 KB

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