PageRenderTime 61ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/caelum/classes/toolbox/Util.class.php

https://github.com/nemiah/projectMankind
PHP | 1320 lines | 1079 code | 149 blank | 92 comment | 147 complexity | bb2ea2426f7ab10e4e7deb0745fe73ed MD5 | raw file
Possible License(s): LGPL-2.1, GPL-3.0
  1. <?php
  2. /*
  3. * This file is part of phynx.
  4. * phynx is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. * phynx is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. * GNU General Public License for more details.
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. *
  15. * 2007 - 2012, Rainer Furtmeier - Rainer@Furtmeier.de
  16. */
  17. class Util {
  18. public static function getCloudHost(){
  19. if($_SERVER["HTTP_HOST"] == "*")
  20. return null;
  21. $h = "CloudHost".str_replace(array(":", "-"), "_", implode("", array_map("ucfirst", explode(".", $_SERVER["HTTP_HOST"]))));
  22. try {
  23. $c = new $h();
  24. return $c;
  25. } catch (ClassNotFoundException $e){
  26. return null;
  27. }
  28. }
  29. /**
  30. * Created fixed-size string
  31. *
  32. * @param string $string
  33. * @param int $width
  34. * @param int $pad_type STR_PAD_RIGHT OR STR_PAD_LEFT
  35. */
  36. public static function utf8_str_col($string, $width, $pad_string = " ", $pad_type = STR_PAD_RIGHT){
  37. preg_match_all("/./su", $string, $ar);
  38. $ar = array_slice($ar[0], 0, $width);
  39. switch($pad_type){
  40. case STR_PAD_RIGHT:
  41. while(count($ar) < $width)
  42. $ar[] = $pad_string[0];
  43. break;
  44. case STR_PAD_LEFT:
  45. while(count($ar) < $width)
  46. array_unshift($ar, $pad_string[0]);
  47. break;
  48. }
  49. return implode("", $ar);
  50. }
  51. public static function getAppServerClient($auth = true){
  52. try {
  53. $AppServer = mUserdata::getGlobalSettingValue("AppServer", "");
  54. if($AppServer != ""){
  55. $CU = Session::currentUser();
  56. $uri = $AppServer."/plugins/AppServer/AppServer.php";
  57. if($CU != null AND $auth){
  58. $c = Session::currentUser()->getA();
  59. return new SoapClient(null, array(
  60. "location" => $uri,
  61. "uri" => $uri,
  62. #"trace" => 1,
  63. "login" => $c->username,
  64. "password" => $c->SHApassword));
  65. } else {
  66. return new SoapClient(null, array(
  67. "location" => $uri,
  68. "uri" => $uri/*,
  69. "trace" => 1*/));
  70. }
  71. #$user = $S->getUser($username, $password);
  72. }
  73. } catch (Exception $e){}
  74. return null;
  75. }
  76. public static function getAppClient($App, $local = false, $username = null, $password = null){
  77. $host = "";
  78. if(!$local){
  79. $S = self::getAppServerClient($username != null);
  80. if($S == null)
  81. throw new Exception("Es steht kein AppServer zur Verfügung!");
  82. $Apps = $S->getApplications();
  83. $host = $Apps[$App][0];
  84. } else
  85. $host = AppProvider::getAppHost($App);
  86. if($host == "" OR $host == null)
  87. throw new Exception("Es steht keine Installation von $App zur Verfügung!");
  88. $uri = $host."/$App/ExtConn/ExtConn.php";
  89. if($username != null)
  90. $S2 = new SoapClient(null, array(
  91. "location" => $uri,
  92. "uri" => $uri,
  93. "login" => $username,
  94. "password" => $password/*,
  95. "trace" => 1*/));
  96. else
  97. $S2 = new SoapClient(null, array(
  98. "location" => $uri,
  99. "uri" => $uri/*,
  100. "trace" => 1*/));
  101. return $S2;
  102. }
  103. public static function getCountryAddressFormat($ISOCountry){
  104. $r = "";
  105. switch($ISOCountry){
  106. case "GB":
  107. $r .= "{firma}\n";
  108. $r .= "{position}{vorname}{nachname}\n";
  109. $r .= "{zusatz1}\n";
  110. $r .= "{nr}{strasse}\n";
  111. $r .= "{ort}\n";
  112. $r .= "{plz}\n";
  113. $r .= "{land}";
  114. break;
  115. default:
  116. $r .= "{firma}\n";
  117. $r .= "{vorname}{nachname}\n";
  118. $r .= "{strasse}{nr}\n";
  119. $r .= "{plz}{ort}\n";
  120. $r .= "{land}";
  121. break;
  122. }
  123. // <editor-fold defaultstate="collapsed" desc="Aspect:jP">
  124. return Aspect::joinPoint("after", null, __METHOD__, $r);
  125. // </editor-fold>
  126. }
  127. public static function getMaxUpload(){
  128. $badFormat = ini_get("upload_max_filesize");
  129. $maxSize = 0;
  130. if(stripos($badFormat, "m") !== false)
  131. $maxSize = substr($badFormat, 0, strlen($badFormat)-1)*1024*1024;
  132. if(stripos($badFormat, "k") !== false)
  133. $maxSize = substr($badFormat, 0, strlen($badFormat)-1)*1024;
  134. if(stripos($badFormat, "g") !== false)
  135. $maxSize = substr($badFormat, 0, strlen($badFormat)-1)*1024*1024*1024;
  136. return $maxSize;
  137. }
  138. public static function getRootPath(){
  139. return str_replace("classes".DIRECTORY_SEPARATOR."toolbox".DIRECTORY_SEPARATOR."Util.class.php","",__FILE__);
  140. }
  141. public static function PostToHostCustom($host, $port = 80, $path = "/", $data = "", array $headers = null){
  142. $fp = fsockopen($host, $port);
  143. fputs($fp, "POST $path HTTP/1.1\r\n");
  144. fputs($fp, "Host: $host:$port\r\n");
  145. foreach($headers AS $k => $v)
  146. fputs($fp, "$k:$v\r\n");
  147. if(!isset($headers["Content-type"]))
  148. fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
  149. fputs($fp, "Content-length: ". strlen($data) ."\r\n");
  150. fputs($fp, "Connection: close\r\n\r\n");
  151. fputs($fp, $data);
  152. $res = "";
  153. while(!feof($fp))
  154. $res .= fgets($fp, 128);
  155. #printf("Done!\n");
  156. fclose($fp);
  157. return $res;
  158. }
  159. /**
  160. * Setzt einen Post-Request auf Port 80 ab
  161. *
  162. * Kopiert von http://www.php-faq.de/q-code-post.html
  163. *
  164. * @param string $host z.B. "www.linux.com"
  165. * @param string $path z.B. "/polls/index.phtml"
  166. * @param string $referer z.B. "http://www.linux.com/polls/index.phtml?pid=14"
  167. * @param string $data_to_send z.B. "pid=14&poll_vote_number=2"
  168. * @return string
  169. */
  170. public static function PostToHost($host, $port = 80, $path = "", $referer = "", $data_to_send = "", $user = null, $pass = null, $contentType = "application/x-www-form-urlencoded") {
  171. $fp = fsockopen($host, $port);
  172. #printf("Open!\n");
  173. fputs($fp, "POST $path HTTP/1.1\r\n");
  174. fputs($fp, "Host: $host:$port\r\n");
  175. fputs($fp, "Referer: $referer\r\n");
  176. if($user != null AND $pass != null){
  177. $string = base64_encode("$user:$pass");
  178. fputs($fp, "Authorization: Basic ".$string."\r\n");
  179. }
  180. fputs($fp, "Content-type: $contentType\r\n");
  181. fputs($fp, "Content-length: ". strlen($data_to_send) ."\r\n");
  182. fputs($fp, "Connection: close\r\n\r\n");
  183. fputs($fp, $data_to_send);
  184. #printf("Sent!\n");
  185. $res = "";
  186. while(!feof($fp))
  187. $res .= fgets($fp, 128);
  188. #printf("Done!\n");
  189. fclose($fp);
  190. return $res;
  191. }
  192. public static function isWindowsHost(){
  193. return stripos(getenv("OS"), "Windows") !== false;
  194. }
  195. /**
  196. * Formatiert eine Zahl $number nach Sprache $language
  197. * Wenn $digits angegeben wird, so wird die Einstellung der Sprache überschrieben
  198. * $digits kann auch das Format "max2" haben. In diesem Fall werden Nullen am Ende
  199. * abgeschnitten bei maximal 2 Nachkommastellen
  200. */
  201. public static function formatNumber($language, $number, $digits = "default", $showZero = true, $endingZeroes = true, $thousandSeparator = true){
  202. $format = Util::getLangNumbersFormat($language);
  203. $ren = false;
  204. if(strstr($digits, "max")) {
  205. $ren = true;
  206. $digits = str_replace("max","",$digits) * 1;
  207. }
  208. $float = Util::parseFloat($language, $number);
  209. $stringNumber = number_format($float, ($digits === "default" ? $format[1] : $digits), $format[0], $thousandSeparator ? $format[2] : "")."";
  210. if($ren){
  211. for($i = 0; $i < $digits; $i++){
  212. if($stringNumber{strlen($stringNumber) - 1 - $i} == "0") $stringNumber{strlen($stringNumber) - 1 - $i} = " ";
  213. else break;
  214. }
  215. $stringNumber = trim($stringNumber);
  216. if($stringNumber{strlen($stringNumber) - 1} == $format[0]) {
  217. $stringNumber{strlen($stringNumber) - 1} = " ";
  218. $stringNumber = trim($stringNumber);
  219. }
  220. }
  221. if(!$showZero AND $stringNumber == "0") $stringNumber = "";
  222. if(!$endingZeroes)
  223. $stringNumber = str_replace($format[0].str_pad("",($digits == "default" ? $format[1] : $digits),"0"),"",$stringNumber);
  224. return $stringNumber;
  225. }
  226. public static function CLFormatNumber($number, $digits = "default", $showZero = true, $endingZeroes = true, $thousandSeparator = true){
  227. return Util::formatNumber($_SESSION["S"]->getUserLanguage(), $number, $digits, $showZero, $endingZeroes, $thousandSeparator);
  228. }
  229. /**
  230. * Formatiert einen String oder eine Zahl als Währung
  231. * $number sollte entweder in der Sprache vorliegen, in der die Währung ausgegeben wird
  232. * oder als float oder int
  233. */
  234. public static function formatCurrency($language, $number, $withSymbol = false, $dezimalstellen = null){
  235. $format = Util::getLangCurrencyFormat($language);
  236. $float = Util::parseFloat($language, $number);
  237. $float *= Util::getLangCurrencyFactor($language);
  238. $negative = false;
  239. if($float < 0) $negative = true;
  240. $float = abs($float);
  241. if($dezimalstellen != null) $format[4] = $dezimalstellen;
  242. $stringCurrency = number_format(Util::kRound($float, $format[4]), $format[4], $format[3], $format[5]);
  243. $stringCurrency = str_replace("n", $stringCurrency, $negative ? $format[2] : $format[1]);
  244. if(!$withSymbol) $stringCurrency = str_replace($format[0], "", $stringCurrency);
  245. return $stringCurrency;
  246. }
  247. public static function getLangCurrencyFactor($language){
  248. if(!Session::isPluginLoaded("mSprache")) return 1;
  249. $Sprache = anyC::getFirst("Sprache", "SpracheIdentifier", $language);
  250. if($Sprache == null)
  251. return 1;
  252. return $Sprache->A("SpracheWaehrungFaktor") * 1;
  253. }
  254. public static function CLFormatCurrency($number, $withSymbol = false){
  255. return Util::formatCurrency($_SESSION["S"]->getUserLanguage(), $number, $withSymbol);
  256. }
  257. public static function CLNumberParser($number, $l = "load"){
  258. if($l == "load") return Util::formatNumber($_SESSION["S"]->getUserLanguage(), $number * 1, 0, true, false);
  259. if($l == "store") return Util::parseFloat($_SESSION["S"]->getUserLanguage(), $number);
  260. }
  261. public static function CLTimeParser($time, $l = "load"){
  262. if($l == "load") return Util::formatTime($_SESSION["S"]->getUserLanguage(), $time);
  263. if($l == "store") return Util::parseTime($_SESSION["S"]->getUserLanguage(), $time);
  264. }
  265. public static function CLTimeParserE($time, $l = "load"){
  266. if($l == "load" AND $time == "-1") return "";
  267. if($l == "store" AND $time == "") return "-1";
  268. return self::CLTimeParser($time, $l);
  269. }
  270. public static function CLNumberParserZ($number, $l = "load"){
  271. if($l == "load") {
  272. $n = Util::formatNumber($_SESSION["S"]->getUserLanguage(), $number * 1, 3, true, true);
  273. $l = strlen($n) - 1;
  274. if($n[$l] == "0") $n = substr($n, 0, $l);
  275. return $n;
  276. }
  277. if($l == "store") return Util::parseFloat($_SESSION["S"]->getUserLanguage(), $number);
  278. }
  279. public static function formatAnrede($language, Adresse $Adresse, $shortmode = false){
  280. switch($Adresse->A("anrede")){
  281. case "2":
  282. if($shortmode) $A = "Herr";
  283. else $A = "Sehr geehrter Herr ".$Adresse->A("nachname");
  284. break;
  285. case "1":
  286. if($shortmode) $A = "Frau";
  287. else $A = "Sehr geehrte Frau ".$Adresse->A("nachname");
  288. break;
  289. case "3":
  290. if($shortmode) $A = "";
  291. else $A = "Sehr geehrte Damen und Herren";
  292. break;
  293. case "4":
  294. if($shortmode) $A = "Familie";
  295. else $A = "Sehr geehrte Familie ".$Adresse->A("nachname");
  296. break;
  297. default:
  298. if($shortmode) $A = "";
  299. else $A = "Sehr geehrte Damen und Herren";
  300. break;
  301. }
  302. $args = func_get_args();
  303. return Aspect::joinPoint("alterAnrede", null, __METHOD__, $args, $A);
  304. }
  305. public static function CLFormatDate($timeStamp = -1, $long = false){
  306. return self::formatDate($_SESSION["S"]->getUserLanguage(), $timeStamp, $long);
  307. }
  308. public static function formatDate($language, $timeStamp = -1, $long = false){
  309. if($timeStamp == -1) $timeStamp = time();
  310. $format = Util::getLangDateFormat($language);
  311. if(!$long) $format = $format[0];
  312. else $format = $format[2];
  313. $weekdayNames = util::getLangWeekdayNames($language);
  314. $monthNames = util::getLangMonthNames($language);
  315. $date = date($format, $timeStamp);
  316. $date = str_replace(date("l", $timeStamp), $weekdayNames[date("w", $timeStamp)], $date);
  317. $date = str_replace(date("F", $timeStamp), $monthNames[date("m", $timeStamp)*1], $date);
  318. return $date;
  319. }
  320. public static function CLMonthName($number){
  321. $monthNames = util::getLangMonthNames($_SESSION["S"]->getUserLanguage());
  322. return $monthNames[$number*1];
  323. }
  324. public static function CLWeekdayName($number){
  325. $weekdayNames = util::getLangWeekdayNames($_SESSION["S"]->getUserLanguage());
  326. return $weekdayNames[$number*1];
  327. }
  328. public static function CLDateParser($date, $l = "load"){
  329. if($l == "load") return Util::formatDate($_SESSION["S"]->getUserLanguage(), $date);
  330. if($l == "store") return Util::parseDate($_SESSION["S"]->getUserLanguage(), $date);
  331. }
  332. public static function CLDateTimeParser($dateTime, $l = "load"){
  333. if($dateTime == "0" AND $l == "load") return "";
  334. if($dateTime == "" AND $l == "store") return "0";
  335. if($l == "load") return Util::CLDateParser($dateTime)." ".Util::CLTimeParser($dateTime);
  336. if($l == "store") {
  337. $ex = explode(" ", $dateTime);
  338. return Util::CLDateParser($ex[0], "store")-60+Util::CLTimeParser($ex[1], "store");
  339. }
  340. }
  341. public static function CLDateParserE($date, $l = "load"){
  342. if($date == "0" AND $l == "load") return "";
  343. if($date == "" AND $l == "store") return "0";
  344. if($l == "load") return Util::formatDate($_SESSION["S"]->getUserLanguage(), $date);
  345. if($l == "store") return Util::parseDate($_SESSION["S"]->getUserLanguage(), $date);
  346. }
  347. public static function CLDateParserL($date, $l = "load"){
  348. if($l == "load") return Util::formatDate($_SESSION["S"]->getUserLanguage(), $date, true);
  349. return "mode $l not supported";
  350. }
  351. public static function formatTime($language, $seconds, $showSeconds = false){
  352. $format = Util::getLangTimeFormat($language);
  353. if(!$showSeconds) $f = $format[1];
  354. else $f = $format[0];
  355. return date($f, $seconds - ($seconds <= 3600 * 24 * 7 ? 3600 : 0));
  356. }
  357. public static function parseTime($language, $time){
  358. $format = Util::getLangTimeFormat($language);
  359. $s = explode($format[2], $time);
  360. $r = explode($format[2], $format[0]);
  361. return mktime(
  362. $s[array_search("H", $r)] * 1,
  363. $s[array_search("i", $r)] * 1,
  364. (isset($s[array_search("s", $r)]) ?
  365. $s[array_search("s", $r)] * 1 :
  366. 0),
  367. 1, 1, 1970)
  368. + 3600;
  369. }
  370. /**
  371. * Formatiert eine Zahl als (k, M, G, ...)Byte mit Einheit
  372. */
  373. public static function formatByte($byte, $digits = 0){
  374. $unit = "B";
  375. if($byte > 1024){
  376. $byte /= 1024;
  377. $unit = "kB";
  378. }
  379. if($byte > 1024){
  380. $byte /= 1024;
  381. $unit = "MB";
  382. }
  383. if($byte > 1024){
  384. $byte /= 1024;
  385. $unit = "GB";
  386. }
  387. if($byte > 1024){
  388. $byte /= 1024;
  389. $unit = "PB";
  390. }
  391. if($byte > 1024){
  392. $byte /= 1024;
  393. $unit = "EB";
  394. }
  395. if($byte > 1024){
  396. $byte /= 1024;
  397. $unit = "ZB";
  398. }
  399. if($byte > 1024){
  400. $byte /= 1024;
  401. $unit = "YB";
  402. }
  403. return round($byte,$digits).$unit;
  404. }
  405. public static function parseDate($language, $date){
  406. $format = Util::getLangDateFormat($language);
  407. $split = explode($format[1],$date);
  408. $refer = explode($format[1],$format[0]);
  409. if(count($split) != 3) return -1;
  410. if($split[0] < 1 OR $split[0] > 31) return -1;
  411. if($split[1] < 1 OR $split[1] > 12) return -1;
  412. $monat = $split[array_search("m",$refer)];
  413. $tag = $split[array_search("d",$refer)];
  414. $jahr = $split[array_search("Y",$refer)];
  415. return mktime(0, 1, 0, $monat,$tag,$jahr);
  416. }
  417. /**
  418. * Parst einen String, der eine Zahl in der Sprache $language enthält, als float oder int
  419. * $stringNumber darf nur Ziffern und Separatoren enthalten ansonsten wird null zurückgegeben
  420. */
  421. public static function parseFloat($language, $stringNumber){
  422. if(is_float($stringNumber) OR is_int($stringNumber)) return $stringNumber;
  423. $format = Util::getLangNumbersFormat($language);
  424. $stringNumber = str_replace($format[2], "", stripslashes($stringNumber));
  425. $stringNumber = str_replace($format[0], ".", $stringNumber);
  426. $number = $stringNumber * 1;
  427. for($i = 0; $i < strlen($stringNumber); $i++) {
  428. if(!strstr($stringNumber, ".")) break;
  429. if($stringNumber{strlen($stringNumber) - 1 - $i} == "0" OR $stringNumber{strlen($stringNumber) - 1 - $i} == ".")
  430. $stringNumber{strlen($stringNumber) - 1 - $i} = " ";
  431. else break;
  432. }
  433. $stringNumber = trim($stringNumber);
  434. if(strcmp($number."", $stringNumber) != 0) return null;
  435. return $number;
  436. }
  437. /**
  438. * Rundet kaufmännisch, auch negative Werte
  439. * Also ab 0.5 aufwärts
  440. */
  441. public static function kRound($nummer, $stellen = 2){
  442. $negative = false;
  443. if($nummer < 0) $negative = true;
  444. return round(abs($nummer) + 0.0000000001, $stellen) * ($negative ? -1 : 1);
  445. }
  446. public static function getLangNumbersFormat($languageTag = null){
  447. if($languageTag == null)
  448. $languageTag = Session::getLanguage();
  449. /* array(
  450. * Decimal symbol,
  451. * # digits after decimal,
  452. * Digit grouping symbol);
  453. */
  454. switch($languageTag) {
  455. case "de_DE":
  456. return array(",",2,".");
  457. break;
  458. case "de_CH":
  459. return array(".",2,"'");
  460. break;
  461. case "en_US":
  462. return array(".",2,",");
  463. break;
  464. case "en_GB":
  465. return array(".",2,",");
  466. break;
  467. default:
  468. return array(",",2,".");
  469. break;
  470. }
  471. }
  472. public static function getLangCurrencyFormat($languageTag = null){
  473. if($languageTag == null)
  474. $languageTag = Session::getLanguage();
  475. /* array(
  476. * Currency symbol,
  477. * positive number Format,
  478. * negative number Format,
  479. * Decimal symbol,
  480. * # digits after decimal,
  481. * Digit grouping symbol);
  482. */
  483. switch($languageTag) {
  484. case "de_DE":
  485. return array("€", "n€", "-n€", ",", 2, ".");
  486. break;
  487. case "de_DE_EUR":
  488. return array(" EUR", "n EUR", "-n EUR", ",", 2, ".");
  489. break;
  490. case "de_CH":
  491. return array("SFr.", "SFr. n", "SFr. -n", ".", 2, "'");
  492. break;
  493. case "en_US":
  494. return array("$", "\$n", "\$(n)", ".", 2, ",");
  495. break;
  496. case "en_GB":
  497. return array("£", "£n", "-£n", ".", 2, ",");
  498. break;
  499. case "en_NO":
  500. return array(" NOK", "n NOK", "-n NOK", ".", 2, ",");
  501. break;
  502. default:
  503. return array("€", "n€", "-n€", ",", 2, ".");
  504. break;
  505. }
  506. }
  507. public static function getLangTimeFormat($languageTag){
  508. /* array(
  509. * Time format,
  510. * Time format without seconds,
  511. * Time separator,
  512. * AM symbol,
  513. * PM symbol);
  514. */
  515. switch($languageTag) {
  516. case "de_DE":
  517. return array("H:i:s","H:i",":","","");
  518. break;
  519. case "de_CH":
  520. return array("H:i:s","H:i",":","","");
  521. break;
  522. case "en_GB":
  523. return array("H:i:s","H:i",":","AM","PM");
  524. break;
  525. default:
  526. return array("H:i:s","H:i",":","","");
  527. break;
  528. }
  529. }
  530. public static function getLangDateFormat($languageTag){
  531. /* array(
  532. * Short date format,
  533. * Date separator,
  534. * Long date Format);
  535. */
  536. switch($languageTag) {
  537. case "de_DE":
  538. case "de_CH":
  539. case "ru_RU":
  540. return array("d.m.Y",".", "l, d. F Y");
  541. break;
  542. case "en_GB":
  543. return array("m/d/Y","/", "l, d. F Y");
  544. break;
  545. case "it_IT":
  546. case "es_ES":
  547. return array("d/m/Y","/", "l, d. F Y");
  548. break;
  549. default:
  550. return array("d.m.Y",".", "l, d. F Y");
  551. break;
  552. }
  553. }
  554. public static function getLangWeekdayNames($languageTag){
  555. switch($languageTag) {
  556. case "de_DE":
  557. return Datum::getGerWeekArray();
  558. break;
  559. default:
  560. return Datum::getGerWeekArray();
  561. break;
  562. }
  563. }
  564. public static function getLangMonthNames($languageTag){
  565. switch($languageTag) {
  566. case "de_DE":
  567. return Datum::getGerMonthArray();
  568. break;
  569. default:
  570. return Datum::getGerMonthArray();
  571. break;
  572. }
  573. }
  574. public static function base64Parser($w, $mode = "store"){
  575. if($mode == "load") return base64_encode($w);
  576. return base64_decode($w);
  577. }
  578. public static function nothingParser($w, $mode = "store"){
  579. return $w;
  580. }
  581. public static function fillStdClassWithAssocArray($class, $values){
  582. $a = PMReflector::getAttributesArray($class);
  583. for($i = 0;$i < count($a);$i++)
  584. if(isset($values[$a[$i]])) $class->$a[$i] = str_replace("\$","\\$", $values[$a[$i]]);
  585. return $class;
  586. }
  587. public static function usePDFViewer(){
  588. return ($_SESSION["S"]->getAgent() == "IE" OR is_writable("../system/IECache/"));
  589. }
  590. public static function makeOptions($keys, $values){
  591. $html = "";
  592. foreach($keys AS $k => $v)
  593. $html .= "<option value=\"{$v}\">{$values[$k]}</option>";
  594. return $html;
  595. }
  596. public static function checkIsEmail($email){
  597. if(preg_match("/^[a-z0-9]+[a-z0-9_\.-]+@[a-z0-9]+([-_\.]?[a-z0-9])+\.[a-z]{2,12}$/", strtolower(trim($email))))
  598. return true;
  599. else
  600. return false;
  601. }
  602. /**
  603. * Generates an encryption key to encrypt and decrypt data
  604. */
  605. public static function getEncryptionKey(){
  606. return sha1(mt_rand(100, 100000000)).sha1(mt_rand(100, 100000000));
  607. }
  608. public static function conv_euro($text){
  609. $text = str_replace("€", chr(128), $text);
  610. $text = str_replace("£", chr(163), $text);
  611. return $text;
  612. }
  613. public static function conv_euro8($text){
  614. $text = str_replace("€", utf8_encode(chr(128)), $text);
  615. $text = str_replace("£", utf8_encode(chr(163)), $text);
  616. return $text;
  617. }
  618. public static function countUmlaute($text){
  619. $us = 0;
  620. $us += substr_count($text, "ä");
  621. $us += substr_count($text, "ü");
  622. $us += substr_count($text, "ö");
  623. $us += substr_count($text, "Ä");
  624. $us += substr_count($text, "Ü");
  625. $us += substr_count($text, "Ö");
  626. $us += substr_count($text, "ß");
  627. return $us;
  628. }
  629. public static function formatSeconds($seconds){
  630. $h = ($seconds / 3600);
  631. $hours = floor($h);
  632. $minutes = floor(($seconds - $hours * 3600) / 60);
  633. $sec = $seconds - $hours * 3600 - $minutes * 60;
  634. if($sec < 10) $sec = "0".$sec;
  635. $minutes = ($minutes < 10 ? "0" : "").$minutes;
  636. return $hours.":".$minutes.":".$sec;
  637. }
  638. /**
  639. * returns true if the running php version is greater OR equal $version
  640. */
  641. public static function phpVersionGEThen($version) {
  642. return version_compare(phpversion(), $version, ">=");
  643. }
  644. public static function versionCheck($version1, $version2, $op = ">") {
  645. $version1 = str_replace("a",".1", $version1);
  646. $version2 = str_replace("a",".1", $version2);
  647. $version1 = str_replace("b",".2", $version1);
  648. $version2 = str_replace("b",".2", $version2);
  649. $version1 = str_replace("c",".3", $version1);
  650. $version2 = str_replace("c",".3", $version2);
  651. $version1 = str_replace("d",".4", $version1);
  652. $version2 = str_replace("d",".4", $version2);
  653. $version1 = str_replace("e",".5", $version1);
  654. $version2 = str_replace("e",".5", $version2);
  655. $version1 = str_replace("f",".6", $version1);
  656. $version2 = str_replace("f",".6", $version2);
  657. $version1 = str_replace(".","", $version1);
  658. $version2 = str_replace(".","", $version2);
  659. $version1 = str_pad($version1, 5, "0", STR_PAD_RIGHT) * 1;
  660. $version2 = str_pad($version2, 5, "0", STR_PAD_RIGHT) * 1;
  661. if($op == ">") return $version1 > $version2;
  662. if($op == "<") return $version1 < $version2;
  663. if($op == "==") return $version1 == $version2;
  664. if($op == "!=") return $version1 != $version2;
  665. #return version_compare($version1, $version2, $op);
  666. }
  667. public function hidePHPErrors(){
  668. if(!isset($_SESSION["HideErrors"])) $_SESSION["HideErrors"] = true;
  669. else $_SESSION["HideErrors"] = !$_SESSION["HideErrors"];
  670. }
  671. public function showPHPErrors(){
  672. #echo "<pre style=\"font-size:8px;width:300px;\">";
  673. $m = "";
  674. if(isset($_SESSION["phynx_errors"]))
  675. foreach($_SESSION["phynx_errors"] AS $value){
  676. $m .= "<b>FehlerTyp:</b> ".$value[0]."\n";
  677. $m .= "<b>FehlerNachricht:</b> ".$value[1]."\n";
  678. $m .= "<b>FehlerDatei:</b> ".$value[2]." ($value[3])\n\n";
  679. }
  680. echo Util::getBasicHTMLText($m, "PHP-Fehler");
  681. #echo "</pre>";
  682. }
  683. public function deletePHPErrors(){
  684. unset($_SESSION["phynx_errors"]);
  685. }
  686. public static function replaceNonURLChars($string){
  687. $string = str_replace(" ", "_", $string);
  688. $string = str_replace("ä", "ae", $string);
  689. $string = str_replace("ü", "ue", $string);
  690. $string = str_replace("ö", "oe", $string);
  691. $string = str_replace("Ä", "Ae", $string);
  692. $string = str_replace("Ü", "Ue", $string);
  693. $string = str_replace("Ö", "Oe", $string);
  694. $string = str_replace("ß", "ss", $string);
  695. $string = str_replace("&", "+", $string);
  696. $string = str_replace("/", "", $string);
  697. return $string;
  698. }
  699. public static function makeFilename($string){
  700. $filename = Util::replaceNonURLChars($string);
  701. $filename = str_replace(array("Á","À","Â","Ã","á","à","â","ã"), array("A","A","A","A","a","a","a","a"), $filename);
  702. $filename = str_replace(array("Ç","ç","É","È","Ê","é","è","ê", "ë", "Č"), array("C","c","E","E","E","e","e","e", "e", "C"), $filename);
  703. $filename = str_replace(array("Í","Ì","í","ì","Õ","Ô","Ó"), array("I","I","i","i","O","O","O"), $filename);
  704. $filename = str_replace(array("õ","ô","ó","Ú","ú"), array("o","o","o","U","u"), $filename);
  705. $filename = str_replace(array(":", "–", "\n", "'", "?", "(", ")"), array("_", "-", "", "", "", "", ""), $filename);
  706. return $filename;
  707. }
  708. public static function PDFViewer($filename){
  709. if(!strstr($filename, "IECache")) {
  710. $_SESSION["BPS"]->registerClass("showPDF");
  711. $_SESSION["BPS"]->setACProperty("filename","$filename");
  712. echo "<html><script>document.location='./showPDF.php';</script></html>";
  713. } else echo "<html><script>document.location='../system/IECache/".$_SESSION["S"]->getCurrentUser()->getID()."/".basename($filename)."?rand=".rand(100, 1000000)."';</script></html>";
  714. }
  715. public static function showPDF($object, $callbackFunction){
  716. if(Util::usePDFViewer()){
  717. $filename = $object->$callbackFunction(true);
  718. Util::PDFViewer($filename);
  719. } else $object->$callbackFunction(false);
  720. }
  721. public static function genPassword($length=8) {
  722. $pass = chr(mt_rand(65,90));
  723. for($k=0; $k < $length - 1; $k++) {
  724. $probab = mt_rand(1,10);
  725. if($probab <= 8)
  726. $pass .= chr(mt_rand(97,122));
  727. else
  728. $pass .= chr(mt_rand(48, 57));
  729. }
  730. return $pass;
  731. }
  732. public static function encrypt($input){
  733. if(!isset($_SESSION["MCryptKey"])) return null;
  734. if($input == "") return "";
  735. $td = mcrypt_module_open(MCRYPT_TWOFISH, '', MCRYPT_MODE_ECB, '');
  736. $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  737. mcrypt_generic_init($td, $_SESSION["MCryptKey"], $iv);
  738. $encrypted = mcrypt_generic($td, $input);
  739. mcrypt_generic_deinit($td);
  740. mcrypt_module_close($td);
  741. return $encrypted;
  742. }
  743. public static function decrypt($input){
  744. if(!isset($_SESSION["MCryptKey"])) return null;
  745. if($input == "") return "";
  746. $td = mcrypt_module_open(MCRYPT_TWOFISH, '', MCRYPT_MODE_ECB, '');
  747. $iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
  748. mcrypt_generic_init($td, $_SESSION["MCryptKey"], $iv);
  749. $decrypted = mdecrypt_generic($td, $input);
  750. mcrypt_generic_deinit($td);
  751. mcrypt_module_close($td);
  752. return trim($decrypted);
  753. }
  754. public static function dencryptParser($w, $l){
  755. if($l == "load")
  756. return Util::decrypt(base64_decode($w, true));
  757. return base64_encode(Util::encrypt($w));
  758. }
  759. public static function PDFCurrencyParser($w, $l = "load"){
  760. return Util::conv_euro(Util::CLFormatCurrency($w * 1, true));
  761. }
  762. public static function getTempDir(){
  763. $dirtouse = Util::getRootPath()."system/IECache/";
  764. if(!is_writable($dirtouse)) {
  765. $file = tempnam(":\n\\/?><","");
  766. $dirtouse = dirname($file);
  767. unlink($file);
  768. }
  769. else Util::clearIECache($dirtouse);
  770. $subdir = (isset($_SESSION["S"]) AND $_SESSION["S"]->getCurrentUser() != null) ? $_SESSION["S"]->getCurrentUser()->getID() : "info";
  771. $dirtouse .= ($dirtouse[strlen($dirtouse) -1] != "/" ? "/" : "").$subdir."/";
  772. if(!is_dir($dirtouse)) {
  773. mkdir($dirtouse, 0777);
  774. chmod($dirtouse, 0777);
  775. }
  776. return $dirtouse;
  777. }
  778. public static function getTempFilename($filename = null, $suffix = "pdf"){
  779. $dirtouse = self::getTempDir();
  780. if($filename == null) $filename = "TempFile";
  781. $filename = $dirtouse.$filename.".$suffix";
  782. #if($filename != null) {
  783. # $tmpfname = $dirtouse.$filename.".pdf";
  784. $handle = fopen($filename, "w+");
  785. fclose($handle);
  786. #} else {
  787. # $file = tempnam($dirtouse, "GRLBM_");
  788. # $tmpfname .= ".pdf";
  789. # unlink($file);
  790. #}
  791. chmod($filename, 0777);
  792. return $filename;
  793. }
  794. public static function clearIECache($dir, $filename = ""){
  795. if(!strstr($dir,"IECache")) return;
  796. if(!is_dir($dir)) return;
  797. $subdir = (isset($_SESSION["S"]) AND $_SESSION["S"]->getCurrentUser() != null) ? $_SESSION["S"]->getCurrentUser()->getID() : "info";
  798. $dir .= ($dir[strlen($dir) -1] != "/" ? "/" : "").$subdir."/";
  799. if(!file_exists($dir)) return;
  800. $fp = opendir($dir);
  801. while(($file = readdir($fp)) !== false) {
  802. if(is_dir("$dir/$file")) continue;
  803. if(time() - filemtime($dir."/".$file) > 180) unlink ("$dir/$file");
  804. }
  805. if($filename != "")
  806. if(file_exists("$dir/$filename")) unlink("$dir/$filename");
  807. }
  808. public static function catchParser($w, $l = "load", $p = ""){
  809. if(!is_array($p))
  810. $p = HTMLGUI::getArrayFromParametersString($p);
  811. else
  812. unset($p[0]);
  813. return $w == 1 ? "<img ".(isset($p[0]) ? "title=\"$p[0]\"" : "")." src=\"./images/i2/ok.gif\" />" : "<img ".(isset($p[1]) ? "title=\"$p[1]\"" : "")." src=\"./images/i2/notok.gif\" />";
  814. }
  815. public static function httpTestAndLoad($url, $timeout = 10) {
  816. $timeout = (int)round($timeout/2+0.00000000001);
  817. $return = array();
  818. $query = Aspect::joinPoint("query", null, __METHOD__);
  819. ### 1 ###
  820. $inf = parse_url($url.($query != null ? "?q=$query" : ""));
  821. if (!isset($inf['scheme']) or $inf['scheme'] !== 'http')
  822. return array('status' => -1);
  823. if (!isset($inf['host']))
  824. return array('status' => -2);
  825. $host = $inf['host'];
  826. if (!isset($inf['path']))
  827. return array('status' => -3);
  828. $path = $inf['path'];
  829. if (isset($inf['query'])) $path .= '?'.$inf['query'];
  830. if (isset($inf['port']))
  831. $port = $inf['port'];
  832. else $port = 80;
  833. ### 2 ###
  834. $pointer = fsockopen($host, $port, $errno, $errstr, $timeout);
  835. if (!$pointer)
  836. return array('status' => -4, 'errstr' => $errstr, 'errno' => $errno);
  837. socket_set_timeout($pointer, $timeout);
  838. ### 3 ###
  839. $head =
  840. 'GET '.$path.' HTTP/1.1'."\r\n".
  841. 'Host: '.$host."\r\n";
  842. if (isset($inf['user']))
  843. $head .= 'Authorization: Basic '.base64_encode($inf['user'].':'.(isset($inf['pass']) ? $inf['pass'] : ''))."\r\n";
  844. if (func_num_args() > 2) {
  845. for ($i = 2; $i < func_num_args(); $i++) {
  846. $arg = func_get_arg($i);
  847. if (strpos($arg, ':') !== false and strpos($arg, "\r") === false and strpos($arg, "\n") === false)
  848. $head .= $arg."\r\n";
  849. }
  850. }
  851. #else
  852. $head .= 'User-Agent: phynx Version checker'."\r\n";
  853. $head .= "X-Application: ".$_SESSION["applications"]->getActiveApplication()."\r\n";
  854. $head .= "X-Version: ".$_SESSION["applications"]->getRunningVersion()."\r\n";
  855. $head .= 'Connection: close'."\r\n"."\r\n";
  856. ### 4 ###
  857. fputs($pointer, $head);
  858. $response = '';
  859. $status = socket_get_status($pointer);
  860. while (!$status['timed_out'] && !$status['eof']) {
  861. $response .= fgets($pointer);
  862. $status = socket_get_status($pointer);
  863. }
  864. fclose($pointer);
  865. if ($status['timed_out'])
  866. return array('status' => -5, '_request' => $head);
  867. ### 5 ###
  868. $res = str_replace("\r\n", "\n", $response);
  869. $res = str_replace("\r", "\n", $res);
  870. $res = str_replace("\t", ' ', $res);
  871. $ares = explode("\n", $res);
  872. $first_line = explode(' ', array_shift($ares), 3);
  873. $return['status'] = trim($first_line[1]);
  874. $return['reason'] = trim($first_line[2]);
  875. foreach ($ares as $line) {
  876. $temp = explode(':', $line, 2);
  877. if (isset($temp[0]) and isset($temp[1]))
  878. $return[strtolower(trim($temp[0]))] = trim($temp[1]);
  879. }
  880. $return['_response'] = $response;
  881. $return['_request'] = $head;
  882. return $return;
  883. }
  884. /*
  885. * Die folgende Funktion ist von
  886. * Christian Seiler
  887. * http://aktuell.de.selfhtml.org/artikel/php/httpsprache/
  888. * self@christian-seiler.de
  889. */
  890. public static function lang_getfrombrowser($allowed_languages, $default_language, $lang_variable = null, $strict_mode = true) {
  891. // $_SERVER['HTTP_ACCEPT_LANGUAGE'] verwenden, wenn keine Sprachvariable mitgegeben wurde
  892. if ($lang_variable === null) {
  893. $lang_variable = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
  894. }
  895. // wurde irgendwelche Information mitgeschickt?
  896. if (empty($lang_variable)) {
  897. // Nein? => Standardsprache zurückgeben
  898. return $default_language;
  899. }
  900. // Den Header auftrennen
  901. $accepted_languages = preg_split('/,\s*/', $lang_variable);
  902. // Die Standardwerte einstellen
  903. $current_lang = $default_language;
  904. $current_q = 0;
  905. // Nun alle mitgegebenen Sprachen abarbeiten
  906. foreach ($accepted_languages as $accepted_language) {
  907. // Alle Infos über diese Sprache rausholen
  908. $res = preg_match ('/^([a-z]{1,8}(?:-[a-z]{1,8})*)'.
  909. '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches);
  910. // war die Syntax gültig?
  911. if (!$res) {
  912. // Nein? Dann ignorieren
  913. continue;
  914. }
  915. // Sprachcode holen und dann sofort in die Einzelteile trennen
  916. $lang_code = explode ('-', $matches[1]);
  917. // Wurde eine Qualität mitgegeben?
  918. if (isset($matches[2])) {
  919. // die Qualität benutzen
  920. $lang_quality = (float)$matches[2];
  921. } else {
  922. // Kompabilitätsmodus: Qualität 1 annehmen
  923. $lang_quality = 1.0;
  924. }
  925. // Bis der Sprachcode leer ist...
  926. while (count ($lang_code)) {
  927. // mal sehen, ob der Sprachcode angeboten wird
  928. if (in_array (strtolower (join ('-', $lang_code)), $allowed_languages)) {
  929. // Qualität anschauen
  930. if ($lang_quality > $current_q) {
  931. // diese Sprache verwenden
  932. $current_lang = strtolower (join ('-', $lang_code));
  933. $current_q = $lang_quality;
  934. // Hier die innere while-Schleife verlassen
  935. break;
  936. }
  937. }
  938. // Wenn wir im strengen Modus sind, die Sprache nicht versuchen zu minimalisieren
  939. if ($strict_mode) {
  940. // innere While-Schleife aufbrechen
  941. break;
  942. }
  943. // den rechtesten Teil des Sprachcodes abschneiden
  944. array_pop ($lang_code);
  945. }
  946. }
  947. // die gefundene Sprache zurückgeben
  948. if($current_lang == "de") $current_lang .= "_DE";
  949. if($current_lang == "en") $current_lang .= "_US";
  950. if($current_lang == "it") $current_lang .= "_IT";
  951. return $current_lang;
  952. }
  953. private $statusMessagesLog = array();
  954. public function logStatusMessages($columns, $class, $method, $parameters = null){
  955. if(!is_array($columns)) $columns = array($columns);
  956. ob_start();
  957. $message = "";
  958. #$class->$method();
  959. try {
  960. $R = new ReflectionMethod($class, $method);
  961. $R->invokeArgs($class, $parameters);
  962. } catch(Exception $e){
  963. $message = $e->getMessage();
  964. }
  965. $ob = ob_get_contents();
  966. $out = array();
  967. $out[0] = "";
  968. if($ob != "")
  969. $out[0] .= "<script type=\"text/javascript\">Interface.translateStatusMessage(\"$ob\",\"replacementMessage".count($this->statusMessagesLog)."\");</script><span id=\"replacementMessage".count($this->statusMessagesLog)."\"></span>";
  970. elseif($message != ""){
  971. $out[0] .= "<span style=\"color:red;\">$message</span>";
  972. } else $out[0] .= "<span style=\"color:green;\">OK</span>";
  973. $this->statusMessagesLog[] = array_merge($columns, $out);
  974. }
  975. public function getStatusMessagesLog($tableColumns = 1, $tableName = ""){
  976. if($tableName != "") $tab = new HTMLTable($tableColumns, $tableName);
  977. else $tab = new HTMLTable($tableColumns);
  978. foreach($this->statusMessagesLog AS $k => $v)
  979. $tab->addRow($v);
  980. return $tab;
  981. }
  982. public static function getBasicHTMLText($message, $title){
  983. $lines = explode("\n",trim($message));
  984. foreach($lines as $k => $v)
  985. $lines[$k] = str_pad(($k + 1),5, " ", STR_PAD_LEFT).": ";
  986. $html = "<pre class=\"backgroundColor2\" style=\"font-size:9px;float:left;\">".implode("\n",$lines)."</pre><pre class=\"backgroundColor0\" style=\"font-size:9px;margin-left:40px;\">".$message."</pre>";
  987. return Util::getBasicHTML($html, $title);
  988. }
  989. /*
  990. public static function getEmoHTMLError($excuse, $message, $title){
  991. $message = "<style type=\"text/css\">
  992. p {
  993. padding:5px;
  994. }
  995. div {
  996. padding:10px;
  997. }
  998. </style><div class=\"backgroundColor0\"><img src=\"./images/big/notice.png\" style=\"float:left;margin-right:15px;\" /><h1>$excuse</h1><p>".$message."</p></div>";
  999. return Util::getBasicHTML($message, $title);
  1000. }*/
  1001. public static function getBasicHTMLError($message, $title){
  1002. $message = "<style type=\"text/css\">
  1003. p {
  1004. padding:5px;
  1005. }
  1006. </style><p class=\"backgroundColor0\">".$message."</p>";
  1007. return Util::getBasicHTML($message, $title);
  1008. }
  1009. public static function getBasicHTML($content, $title, $js = true){
  1010. #header("Content-Type: text/html; charset=utf-8");
  1011. return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  1012. <html xmlns="http://www.w3.org/1999/xhtml">
  1013. <head>
  1014. <title>'.$title.'</title>
  1015. '.($js ? '
  1016. <script type="text/javascript" src="../libraries/jquery/jquery-1.7.1.min.js"></script>
  1017. <script type="text/javascript" src="../libraries/jquery/jquery-ui-1.8.17.custom.min.js"></script>
  1018. <script type="text/javascript" src="../javascript/P2J.js"></script>
  1019. <script type="text/javascript" src="../javascript/handler.js"></script>
  1020. <script type="text/javascript" src="../javascript/contentManager.js"></script>
  1021. <script type="text/javascript" src="../javascript/Interface.js"></script>
  1022. <script type="text/javascript" src="../javascript/Overlay.js"></script>
  1023. <script type="text/javascript" src="../libraries/webtoolkit.base64.js"></script>' : "").'
  1024. <link rel="stylesheet" type="text/css" href="../styles/'.(isset($_COOKIE["phynx_color"])? $_COOKIE["phynx_color"] : "standard").'/colors.css"></link>
  1025. <link rel="stylesheet" type="text/css" href="../styles/standard/general.css"></link>
  1026. </head>
  1027. <body>
  1028. '.$content.'
  1029. </body>
  1030. </html>';
  1031. }
  1032. public static function eK(){
  1033. return mUserdata::getGlobalSettingValue(implode("", array_map("chr", array(0 => 101, 1 => 110, 2 => 99, 3 => 114, 4 => 121, 5 => 112, 6 => 116, 7 => 105, 8 => 111, 9 => 110, 10 => 75, 11 => 101, 12 => 121))));
  1034. }
  1035. public static function newObject($className){
  1036. $c = new $className(-1);
  1037. $a = $c->newAttributes();
  1038. $arg_list = func_get_args();
  1039. $i = 1;
  1040. foreach($a as $k => $v){
  1041. if($k == $className."ID") continue;
  1042. if(isset($arg_list[$i]))
  1043. $a->$k = $arg_list[$i];
  1044. $i++;
  1045. }
  1046. $c->setA($a);
  1047. $c->newMe();
  1048. }
  1049. public static function calcNettoPreis($preis, $mwst){
  1050. $p = Util::parseFloat($_SESSION["S"]->getUserLanguage(), $preis);
  1051. $m = $mwst * 1;#Util::parseFloat($_SESSION["S"]->getUserLanguage(), $mwst);
  1052. $netto = $p / (100 + $m) * 100;
  1053. echo Util::formatCurrency($_SESSION["S"]->getUserLanguage(), $netto, false);
  1054. }
  1055. public static function invokeStaticMethod($class, $method, $parameters){
  1056. $R = new ReflectionMethod($class, $method);
  1057. if(!is_array($parameters)) $parameters = array($parameters);
  1058. return $R->invokeArgs(null, $parameters);
  1059. }
  1060. }
  1061. ?>