V.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  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 filterInteger($value) {// An integer or string with integer value
  312. if (is_int($value)) {
  313. return true;
  314. } else if (is_string($value)) {
  315. if ((string)(int)$value === $value) {
  316. return true;
  317. }
  318. }
  319. return false;
  320. }
  321. public static function filterNegativeInteger($value) {// An integer containing only negative values (..,-2,-1)
  322. if (V::filterInteger($value)) {
  323. if (intval($value) < 0) {
  324. return true;
  325. }
  326. }
  327. return false;
  328. }
  329. public static function filterNonNegativeInteger($value) {// An integer containing only non-negative values (0,1,2,..)
  330. if (V::filterInteger($value)) {
  331. if (intval($value) >= 0) {
  332. return true;
  333. }
  334. }
  335. return false;
  336. }
  337. public static function filterNonPositiveInteger($value) {// An integer containing only non-positive values (..,-2,-1,0)
  338. if (V::filterInteger($value)) {
  339. if (intval($value) <= 0) {
  340. return true;
  341. }
  342. }
  343. return false;
  344. }
  345. public static function filterPositiveInteger($value) {// An integer containing only positive values (1,2,..)
  346. if (V::filterInteger($value)) {
  347. if (intval($value) > 0) {
  348. return true;
  349. }
  350. }
  351. return false;
  352. }
  353. public static function validate($argName, $args, $params) {
  354. //$what = V::validate('what', $args, array('type'=>'word', 'not_empty'=>true, 'max_length'=>'255', 'values'=>$when_values));
  355. $argValue = V::get($argName, null, $args);
  356. $fldLabel = V::get('fld_label', $argName, $params);
  357. if (array_key_exists('not_empty', $params) && true == $params['not_empty']) {
  358. if (!array_key_exists($argName, $args) || empty($args[$argName])) throw new Exception("Field {$fldLabel} not set.");
  359. }
  360. $params['fld_label'] = $fldLabel;
  361. return V::validateValue($argValue, $params);
  362. }
  363. public static function validateValue($value, $params) {
  364. $fldLabel = V::get('fld_label', '', $params);
  365. $maxLength = V::get('max_length', 0, $params);
  366. if ($maxLength > 0) {
  367. if (strlen($value) > $maxLength) throw new Exception("'{$fldLabel}' cannot be longer then {$maxLength}.");
  368. }
  369. $allowedValues = V::get('values', null, $params);
  370. if (is_array($allowedValues) && !empty($allowedValues)) {
  371. if (!in_array($value, $allowedValues)) throw new Exception("'{$fldLabel}' value is not allowed");
  372. }
  373. $type = V::get('type', null, $params);
  374. if ($type != null) {
  375. if ('word' == $type) {
  376. if (!is_scalar($value) || !preg_match('/^[a-zA-Z_-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  377. } else if ('login' == $type) {
  378. if (!is_scalar($value) || !preg_match('/^[a-zA-Z\._-]*$/', $value)) throw new Exception("required type '{$type}' ({$fldLabel})");
  379. } else {
  380. throw new Exception("Unimplemented type to validate: '{$type}'");
  381. }
  382. }
  383. if (array_key_exists('equal', $params)) {
  384. if ($value != $params['equal']) throw new Exception(V::get('error_msg_equal', "'{$fldLabel}' must be equal to '{$params['equal']}'", $params));
  385. }
  386. if (array_key_exists('equalStrict', $params)) {
  387. if ($value !== $params['equalStrict']) throw new Exception(V::get('error_msg_equalStrict', "'{$fldLabel}' must be strict equal to '{$params['equal']}'", $params));
  388. }
  389. return $value;
  390. }
  391. public static function exec($cmd, &$out, &$ret) {
  392. $out = null;
  393. $ret = null;
  394. // NOTE: SourceGuardian requires file: "${HOME}/.config/SourceGuardian/"
  395. $cmd = implode("\n", [
  396. "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",
  397. "export HOME='/Library/WebServer'",
  398. $cmd
  399. ]);
  400. exec($cmd, $out, $ret);
  401. return $ret;
  402. }
  403. public static function execRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  404. $out = null;
  405. $ret = null;
  406. $pass = $password;
  407. $pass = str_replace('!', '\!', $pass);
  408. $sshPort = (22 != $port)? "-p {$port}" : '';
  409. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  410. 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/
  411. '.$command.'
  412. EOF';
  413. exec($cmd, $out, $ret);
  414. return $ret;
  415. }
  416. public static function execRootRemote($host, $login, $password, $command, &$out, &$ret, $port = 22) {
  417. $out = null;
  418. $ret = null;
  419. $pass = $password;
  420. $pass = str_replace('!', '\!', $pass);
  421. $sshPort = (22 != $port)? "-p {$port}" : '';
  422. $cmd = '/opt/local/bin/sshpass -p ' . $pass . ' ssh -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ConnectTimeout=99999 ' . $sshPort . ' ' . $login . '@' . $host . ' -t <<EOF
  423. sudo -n su -
  424. 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/
  425. '.$command.'
  426. EOF';
  427. exec($cmd, $out, $ret);
  428. return $ret;
  429. }
  430. public static function quoteBashEcho($string) {
  431. return str_replace([ '"', '$' ], [ '\"', '\$' ], $string);
  432. }
  433. public static function cloneArray($arr) {
  434. return $arr;
  435. }
  436. public static function humanFileSize($bytes) {
  437. $bytes = intval($bytes);
  438. $arBytes = array(
  439. 0 => array("UNIT" => "TB", "VALUE" => pow(1024, 4)),
  440. 1 => array("UNIT" => "GB", "VALUE" => pow(1024, 3)),
  441. 2 => array("UNIT" => "MB", "VALUE" => pow(1024, 2)),
  442. 3 => array("UNIT" => "KB", "VALUE" => 1024),
  443. 4 => array("UNIT" => "B", "VALUE" => 1)
  444. );
  445. foreach($arBytes as $arItem) {
  446. if ($bytes >= $arItem["VALUE"]) {
  447. $result = $bytes / $arItem["VALUE"];
  448. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  449. break;
  450. }
  451. }
  452. return $result;
  453. }
  454. public static function kwotaSlownie($kwota = 0, $waluta = "PLN") {
  455. if (!preg_match("/^[[:digit:]]*(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Błędna liczba");
  456. if (!preg_match("/^[[:digit:]]{0,48}(\.[[:digit:]]+)?$/",$kwota)) throw new Exception("Zbyt duża liczba");
  457. $waluty = array(
  458. 'PLN' => array('złoty','złotych','złote'),
  459. 'USD' => array('dolar','dolarów','dolary')
  460. );
  461. $jednosci = array('zero','jeden','dwa','trzy','cztery','pięć','sześć','siedem','osiem','dziewięć','dziesięć','jedenaście',
  462. 'dwanaście','trzynaście','czternaście','piętnaście','szesnaście','siednaście','osiemnaście','dziewiętnaście');
  463. $dziesiatki = array('','','dwadzieścia','trzydzieści','czterdzieści','pięćdziesiąt','sześćdziesiąt','siedemdziesiąt','osiemdziesiąt','dziewięćdziesiąt');
  464. $setki = array('','sto','dwieście','trzysta','czterysta','pięćset','sześćset','siedemset','osiemset','dziewięćset');
  465. if (!isset($waluty[$waluta])) $tysiace[] = array($waluta,$waluta,$waluta);
  466. else $tysiace[] = $waluty[$waluta];
  467. $tysiace[] = array('tysiąc','tysięcy','tysiące');
  468. $tysiace[] = array('milion','milionów','miliony');
  469. $tysiace[] = array('miliard','miliardów','miliardy');
  470. $tysiace[] = array('bilion','bilionów','bilony');
  471. $tysiace[] = array('biliard','biliardów','biliardy');
  472. $tysiace[] = array('trylion','trylionów','tryliony');
  473. $tysiace[] = array('tryliard','tryliardów','tryliardy');
  474. $tysiace[] = array('kwadrylion','kwadrylionów','kwadryliony');
  475. $tysiace[] = array('kwadryliard','kwadryliardów','kwaryliardy');
  476. $tysiace[] = array('kwintylion','kwintylionów','kwintyliony');
  477. $tysiace[] = array('kwintyliard','kwintyliardów','kwintyliardy');
  478. $tysiace[] = array('sekstylion','sekstylionów','sepstyliony');
  479. $tysiace[] = array('sekstyliard','sekstyliardów','sekstyliardy');
  480. $tysiace[] = array('septylion','septylionów','septyliony');
  481. $tysiace[] = array('septyliard','septyliardów','septyliardy');
  482. $kwota = (!substr_count($kwota, '.')) ? $kwota.'.00' : $kwota;
  483. list($zlote, $grosze) = explode('.', $kwota);
  484. $zlote = ltrim($zlote, '0');
  485. if ($zlote == '') $zlote = '0';
  486. if (strlen($grosze) == 1) $grosze .= "0";
  487. elseif (strlen($grosze) > 2) $grosze = round(substr($grosze, 0, 2).".".substr($grosze, 2), 0);
  488. $zlote = strrev(wordwrap(strrev($zlote), 3, '.', true));
  489. $zloteArr = explode('.', $zlote);
  490. foreach ($zloteArr as $i => $l) {
  491. $tysiac = count($zloteArr) - $i - 1;
  492. $setka = $setki[floor($l/100)];
  493. $dziesiatka = $dziesiatki[floor(($l%100)/10)];
  494. $jednosc = $dziesiatka ? $jednosci[$l%10] : $jednosci[$l%100];
  495. if ($l == 1 and ($tysiac > 0 or count($zloteArr) == 1)) $odmiana = 0;
  496. elseif (floor($l%100/10) != 1 and $l%10 >= 2 and $l%10 <= 4) $odmiana = 2;
  497. else $odmiana = 1;
  498. if ($setka) $resultArr[] = $setka;
  499. if ($dziesiatka) $resultArr[] = $dziesiatka;
  500. if ($jednosc == $jednosci[0] && $zlote != '0') $jednosc = '';
  501. if ($jednosc) $resultArr[] = $jednosc;
  502. if ($setka || $dziesiatka || $jednosc || $tysiac == 0) $resultArr[] = $tysiace[$tysiac][$odmiana];
  503. }
  504. $resultArr[] = $grosze . "/100";
  505. return implode(" ", $resultArr);
  506. }
  507. public static function nettoOdBrutto($brutto = 0, $vat = "23") {
  508. if ($vat < 0) throw new Exception("Stawka VAT nie może być liczbą ujemną!");
  509. $netto = round($brutto/(1+$vat/100),2);
  510. if (round($netto*(1+$vat/100),2) > $brutto) $netto -= 0.01;
  511. return $netto;
  512. }
  513. public static function makePick($fieldName, $default = '', $type = null) {
  514. return function ($item) use ($fieldName, $default, $type) {
  515. return V::get($fieldName, $default, $item, $type);
  516. };
  517. }
  518. public static function pickSimgleValue($items, $fieldName) {
  519. return array_map(
  520. function ($row) use ($fieldName) {
  521. return V::get($fieldName, '', $row);
  522. }
  523. , $items
  524. );
  525. }
  526. public static function pickArrayValues($items, $fieldNames) {
  527. return $items;
  528. }
  529. static function addSingleQuotes($str) {
  530. return "'{$str}'";
  531. }
  532. public static function arrayToXML($array, $formatOutput = false, $root = "root") {
  533. $arrayToXML_rec = function($data, $dom, $node, $parent = null) use (&$arrayToXML_rec) {
  534. $child = $dom->createElement($node);
  535. if (!$parent) $parent = $dom;
  536. if (is_array($data)) {
  537. if ($data) {
  538. foreach ($data as $key => $value) {
  539. if ((string)$key === '@attributes') {
  540. foreach ($value as $attrName => $attrValue) {
  541. $attr = $dom->createAttribute($attrName);
  542. $attr->value = $attrValue;
  543. $child->appendChild($attr);
  544. }
  545. } else {
  546. if (is_numeric($key)) $arrayToXML_rec($value, $dom, $node, $parent);
  547. else $arrayToXML_rec($value, $dom, $key, $child);
  548. }
  549. }
  550. } else $parent->appendChild($child);
  551. } else {
  552. if ($data) {
  553. if ($data == htmlspecialchars($data)) $child->nodeValue = $data;
  554. else $child->appendChild($dom->createCDATASection($data));
  555. } else $parent->appendChild($child);
  556. }
  557. if ($child->hasChildNodes() || $child->hasAttributes()) $parent->appendChild($child);
  558. };
  559. if (!is_array($array)) throw new Exception("First argument need to be an array");
  560. $dom = new DOMDocument('1.0', 'UTF-8');
  561. $dom->preserveWhiteSpace = false;
  562. $dom->formatOutput = $formatOutput;
  563. $arrayToXML_rec($array, $dom, $root);
  564. return $dom->saveXML();
  565. }
  566. // date("Y-m-d H:i:s") . substr((string)microtime(), 1, 6),
  567. // a: '2017-07-25 13:06:15.59124',
  568. // b: '2017-07-25 13:06:15.56161',
  569. // result: '0.02963'
  570. public static function milisecondsStringDiff($a, $b) {
  571. if (25 != strlen($a)) return "Wrong length in 1st arg";
  572. if (25 != strlen($b)) return "Wrong length in 2nd arg";
  573. $aTime = array_sum([
  574. intVal(substr($a, 11, 2)) * 100000 * 60 * 60, // hour
  575. intVal(substr($a, 14, 2)) * 100000 * 60, // min
  576. intVal(substr($a, 17, 2)) * 100000, // sec
  577. intVal(substr($a, 20, 5)), // mili sec (5 digits)
  578. ]);
  579. $bTime = array_sum([
  580. intVal(substr($b, 11, 2)) * 100000 * 60 * 60, // hour
  581. intVal(substr($b, 14, 2)) * 100000 * 60, // min
  582. intVal(substr($b, 17, 2)) * 100000, // sec
  583. intVal(substr($b, 20, 5)), // mili sec (5 digits)
  584. ]);
  585. return sprintf("%0.5f", abs($aTime - $bTime) / 100000);
  586. }
  587. public static function isNip($nip) {
  588. if (!(is_numeric($nip) && preg_match('/^[[:digit:]]{10}$/', $nip))) return false;
  589. $waga = [6, 5, 7, 2, 3, 4, 5, 6, 7];
  590. $c = 0;
  591. for ($i = 0; $i < 9; $i++) $c += $nip[$i] * $waga[$i];
  592. $c = ($c % 11) % 10;
  593. return ($nip[9] == $c);
  594. }
  595. public static function isRegon($regon) {
  596. if (!(is_numeric($regon) && preg_match('/^[[:digit:]]{9}$/', $regon))) return false;
  597. $waga = [8, 9, 2, 3, 4, 5, 6, 7];
  598. $c = 0;
  599. for ($i = 0; $i < 8; $i++) $c += $regon[$i] * $waga[$i];
  600. $c = ($c % 11) % 10;
  601. return ($regon[8] == $c);
  602. }
  603. static function stripInvalidXmlChars($value = "") {
  604. return array_reduce(str_split((string)$value), function ($ret, $char) {
  605. $charCode = ord($char);
  606. if (
  607. (0x9 === $charCode)
  608. || (0xA === $charCode)
  609. || (0xD === $charCode)
  610. || (($charCode >= 0x20) && ($charCode <= 0xD7FF))
  611. || (($charCode >= 0xE000) && ($charCode <= 0xFFFD))
  612. || (($charCode >= 0x10000) && ($charCode <= 0x10FFFF))
  613. ) {
  614. return $ret . $char;
  615. }
  616. return $ret;
  617. }, "");
  618. }
  619. static function deleteWholeDirectory($dir, $returnFiles = false, $doDelete = true) {
  620. if (!is_dir($dir)) throw new Exception("{$dir} must be a directory");
  621. $it = new RecursiveDirectoryIterator($dir, RecursiveDirectoryIterator::SKIP_DOTS);
  622. $files = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  623. if ($doDelete) {
  624. $rmdir = 'rmdir';
  625. $unlink = 'unlink';
  626. } else {
  627. $rmdir = 'is_string';
  628. $unlink = 'is_string';
  629. }
  630. if ($returnFiles) {
  631. $return = [];
  632. foreach ($files as $file) {
  633. if ($file->isDir()) $return['dirs'][$file->getRealPath()] = @$rmdir($file->getRealPath());
  634. else $return['files'][$file->getRealPath()] = @$unlink($file->getRealPath());
  635. }
  636. $return['dirs'][$dir] = @$rmdir($dir);
  637. return $return;
  638. } else {
  639. foreach ($files as $file) {
  640. if ($file->isDir()) @$rmdir($file->getRealPath());
  641. else @$unlink($file->getRealPath());
  642. }
  643. @$rmdir($dir);
  644. }
  645. }
  646. }