PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/tools/bike/bright/Br.php

https://bitbucket.org/englishextra/shimansky.biz
PHP | 839 lines | 716 code | 108 blank | 15 comment | 81 complexity | 5d47346e69907a45db0501efc3efcc71 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, CC-BY-SA-3.0, GPL-2.0, LGPL-3.0, GPL-3.0, CC-BY-3.0
  1. <?php
  2. /**
  3. * Project: Bright framework
  4. * Author: Jager Mesh (jagermesh@gmail.com)
  5. *
  6. * @version 1.1.0.0
  7. * @package Bright Core
  8. */
  9. require_once(__DIR__.'/BrSingleton.php');
  10. require_once(__DIR__.'/BrException.php');
  11. function br($array = null, $name = null, $default = null) {
  12. if (func_num_args() === 0) {
  13. return Br::getInstance();
  14. } else
  15. if (func_num_args() === 1) {
  16. if (is_array($array)) {
  17. require_once(__DIR__ . '/BrArray.php');
  18. return new BrArray($array);
  19. } else {
  20. // if (is_string($array)) {
  21. require_once(__DIR__ . '/BrString.php');
  22. return new BrString($array);
  23. }
  24. } else {
  25. if (is_array($array) && is_array($name)) {
  26. $result = null;
  27. foreach($name as $oneName) {
  28. $result = br($array, $oneName);
  29. if (strlen($result)) {
  30. return $result;
  31. }
  32. }
  33. if (!strlen($result)) {
  34. return $default;
  35. }
  36. } else {
  37. return ( is_array($array) &&
  38. strlen($name) &&
  39. array_key_exists($name, $array) &&
  40. ($array[$name] || is_bool($array[$name]) || (is_scalar($array[$name]) && strlen($array[$name])))
  41. )
  42. ? $array[$name]
  43. : $default;
  44. }
  45. }
  46. }
  47. if (!function_exists('debug')) {
  48. function debug() {
  49. $args = func_get_args();
  50. foreach($args as $var) {
  51. br()->log()->writeLn($var, 'DBG');
  52. $message = print_r($var, true);
  53. if (br()->isConsoleMode()) {
  54. // echo($message);
  55. // echo("\n");
  56. } else
  57. if (br()->request()->isLocalHost()) {
  58. include(__DIR__.'/templates/DebugMessage.html');
  59. }
  60. }
  61. }
  62. }
  63. if (!function_exists('callstack')) {
  64. function callStack() {
  65. br()->log()->callStack();
  66. }
  67. }
  68. if (!function_exists('logme')) {
  69. function logme() {
  70. $args = func_get_args();
  71. foreach($args as $var) {
  72. br()->log()->writeLn($var);
  73. }
  74. }
  75. }
  76. class Br extends BrSingleton {
  77. private $processId = null;
  78. function __construct() {
  79. $this->frameWorkPath = str_replace('\\', '/', rtrim(__DIR__, '/').'/');
  80. $this->processId = null;
  81. parent::__construct();
  82. }
  83. public function __call($name, $arguments) {
  84. $className = 'Br' . ucwords($name);
  85. $classFile = __DIR__ . '/' . $className . '.php';
  86. if (file_exists($classFile)) {
  87. require_once($classFile);
  88. // ARGH HOW UGLY!!!
  89. if (!count($arguments)) {
  90. return $className::getInstance();
  91. } else
  92. if (count($arguments) == 1) {
  93. return $className::getInstance($arguments[0]);
  94. } else
  95. if (count($arguments) == 2) {
  96. return $className::getInstance($arguments[0], $arguments[1]);
  97. } else
  98. if (count($arguments) == 3) {
  99. return $className::getInstance($arguments[0], $arguments[1], $arguments[2]);
  100. } else
  101. if (count($arguments) == 4) {
  102. return $className::getInstance($arguments[0], $arguments[1], $arguments[2], $arguments[3]);
  103. }
  104. } else {
  105. throw new Exception('Call to unknown method - ' . $name);
  106. }
  107. }
  108. function log() {
  109. require_once(__DIR__.'/BrLog.php');
  110. $log = BrLog::getInstance();
  111. $args = func_get_args();
  112. foreach($args as $var) {
  113. $log->writeLn($var);
  114. }
  115. return $log;
  116. }
  117. function config($name = null, $defaultValue = null) {
  118. require_once(__DIR__.'/BrConfig.php');
  119. $config = BrConfig::getInstance();
  120. if ($name) {
  121. return $config->get($name, $defaultValue);
  122. } else {
  123. return $config;
  124. }
  125. }
  126. function fs() {
  127. return $this->FileSystem();
  128. }
  129. function db($name = null) {
  130. return $this->DataBase($name);
  131. }
  132. private $scriptName = null;
  133. private $basePath = null;
  134. private $appPath = null;
  135. private $APIPath = null;
  136. private $frameWorkPath = null;
  137. private $application = null;
  138. function saveCallerScript($scriptPath) {
  139. $this->basePath = $this->fs()->filePath($scriptPath);
  140. $this->scriptName = $this->fs()->fileName($scriptPath);
  141. $this->appPath = $this->basePath.'app/';
  142. $this->APIPath = $this->basePath.'api/';
  143. $this->setTemplatesPath($this->basePath.'templates/');
  144. }
  145. function scriptName() {
  146. return $this->scriptName;
  147. }
  148. function atBasePath($path) {
  149. return $this->basePath.ltrim($path, '/');
  150. }
  151. function basePath() {
  152. return $this->basePath;
  153. }
  154. function atAppPath($path) {
  155. return $this->appPath.ltrim($path, '/');
  156. }
  157. function atAPIPath($path) {
  158. return $this->APIPath.ltrim($path, '/');
  159. }
  160. function setTemplatesPath($templatesPath) {
  161. $this->templatesPath = $templatesPath;
  162. }
  163. function templatesPath() {
  164. return $this->templatesPath;
  165. }
  166. function atTemplatesPath($path) {
  167. return $this->templatesPath.ltrim($path, '/');
  168. }
  169. function atFrameWorkPath($path) {
  170. return $this->frameWorkPath.$path;
  171. }
  172. function removeEmptyKeys($array) {
  173. $result = array();
  174. foreach($array as $key => $value) {
  175. $go = false;
  176. if (is_array($value)) {
  177. $value = br()->RemoveEmptyKeys($value);
  178. $go = $value;
  179. } else {
  180. $go = strlen($value);
  181. }
  182. if ($go) {
  183. $result[$key] = $value;
  184. }
  185. }
  186. return $result;
  187. }
  188. function isMultiArray($array) {
  189. $rv = array_filter($array, 'is_array');
  190. return (count($rv) > 0);
  191. }
  192. function isRegularArray($array) {
  193. if ($this->isMultiArray($array)) {
  194. return false;
  195. } else {
  196. $prior = -1;
  197. foreach($array as $idx => $value) {
  198. if (!is_numeric($idx) || (abs($idx - $prior) != 1)) {
  199. return false;
  200. }
  201. $prior = $idx;
  202. }
  203. return true;
  204. }
  205. }
  206. function loadFile($fileName) {
  207. $result = null;
  208. if (file_exists($fileName)) {
  209. if ($f = @fopen($fileName, 'r')) {
  210. while (!feof($f)) {
  211. $result .= fread($f, 4096);
  212. }
  213. fclose($f);
  214. }
  215. }
  216. return $result;
  217. }
  218. function isConsoleMode() {
  219. return (!array_key_exists('REQUEST_METHOD', $_SERVER));
  220. }
  221. function getMicrotime(){
  222. list($usec, $sec) = explode(" ",microtime());
  223. return ((float)$usec + (float)$sec);
  224. }
  225. function placeholder() {
  226. $args = func_get_args();
  227. $tmpl = array_shift($args);
  228. $result = $this->placeholderEx($tmpl, $args, $error);
  229. if ($result === false)
  230. return 'ERROR:'.$error;
  231. else
  232. return $result;
  233. }
  234. function assert($value, $error = null) {
  235. if (!$value) {
  236. // if ($error && br()->isConsoleMode()) {
  237. // echo($error . "\n");
  238. // } else {
  239. throw new BrAssertException($error ? $error : 'Assertion error');
  240. // }
  241. }
  242. }
  243. function importAtBasePath($fileName) {
  244. $this->import($this->atBasePath($fileName));
  245. }
  246. function importLib($FileName) {
  247. $FileName = 'Br'.$FileName.'.php';
  248. require_once(__DIR__ . '/' . $FileName);
  249. }
  250. function importDataSource($name) {
  251. require_once(__DIR__ . '/datasources/' . $name. '.php');
  252. }
  253. function import($FileName) {
  254. if (!preg_match('/[.]php$/', $FileName)) {
  255. $FileName = $FileName . '.php';
  256. }
  257. if (file_exists($FileName)) {
  258. require_once($FileName);
  259. return true;
  260. } else {
  261. return false;
  262. }
  263. }
  264. function formatDuration($duration) {
  265. $secs = $mins = $hrs = 0;
  266. if ($duration < 60) {
  267. $secs = $duration;
  268. } else
  269. if ($duration < 60*60) {
  270. $mins = floor($duration/60);
  271. $secs = $duration - $mins*60;
  272. } else {
  273. $hrs = floor($duration/60/60);
  274. $mins = ($duration - $hrs*60*60)/60;
  275. $secs = $duration - $hrs*60*60 - $mins*60;
  276. }
  277. $result = '';
  278. if ($secs) {
  279. $result = number_format($secs, 3);
  280. }
  281. if ($mins) {
  282. $result = $mins.($result?':'.$result:'');
  283. }
  284. if ($hrs) {
  285. $result = $hrs.($result?':'.$result:'');
  286. }
  287. return trim($result);
  288. }
  289. function durationToString($duration) {
  290. $secs = $mins = $hrs = 0;
  291. if ($duration < 60) {
  292. $secs = $duration;
  293. } else
  294. if ($duration < 60*60) {
  295. $mins = floor($duration/60);
  296. $secs = $duration - $mins*60;
  297. } else {
  298. $hrs = floor($duration/60/60);
  299. $mins = ($duration - $hrs*60*60)/60;
  300. $secs = $duration - $hrs*60*60 - $mins*60;
  301. }
  302. $result = '';
  303. if ($secs) {
  304. $result = number_format($secs, 3).' '.'secs';
  305. }
  306. if ($mins) {
  307. $result = $mins.' '.'mins'.' '.$result;
  308. }
  309. if ($hrs) {
  310. $result = $hrs.' '.'hrs'.' '.$result;
  311. }
  312. return trim($result);
  313. }
  314. private function placeholderCompile($tmpl) {
  315. $compiled = array();
  316. $p = 0;
  317. $i = 0;
  318. $has_named = false;
  319. while (false !== ($start = $p = strpos($tmpl, "?", $p))) {
  320. switch ($c = substr($tmpl, ++$p, 1)) {
  321. case '&':
  322. case '%':
  323. case '@':
  324. case '#':
  325. $type = $c;
  326. ++$p;
  327. break;
  328. default:
  329. $type = '';
  330. break;
  331. }
  332. if (preg_match('/^((?:[^\s[:punct:]]|_)+)/', substr($tmpl, $p), $pock)) {
  333. $key = $pock[1];
  334. if ($type != '#')
  335. $has_named = true;
  336. $p += strlen($key);
  337. } else {
  338. $key = $i;
  339. if ($type != '#')
  340. $i++;
  341. }
  342. $compiled[] = array($key, $type, $start, $p - $start);
  343. }
  344. return array($compiled, $tmpl, $has_named);
  345. }
  346. function placeholderEx($tmpl, $args, &$errormsg) {
  347. if (is_array($tmpl)) {
  348. $compiled = $tmpl;
  349. } else {
  350. $compiled = $this->placeholderCompile($tmpl);
  351. }
  352. list ($compiled, $tmpl, $has_named) = $compiled;
  353. if ($has_named)
  354. $args = @$args[0];
  355. $p = 0;
  356. $out = '';
  357. $error = false;
  358. foreach ($compiled as $num=>$e) {
  359. list ($key, $type, $start, $length) = $e;
  360. $out .= substr($tmpl, $p, $start - $p);
  361. $p = $start + $length;
  362. $repl = '';
  363. $errmsg = '';
  364. do {
  365. if (!isset($args[$key]))
  366. $args[$key] = "";
  367. if ($type === '#') {
  368. $repl = @constant($key);
  369. if (NULL === $repl)
  370. $error = $errmsg = "UNKNOWN_CONSTANT_$key";
  371. break;
  372. }
  373. if (!isset($args[$key])) {
  374. $error = $errmsg = "UNKNOWN_PLACEHOLDER_$key";
  375. break;
  376. }
  377. $a = $args[$key];
  378. if ($type === '&') {
  379. if (strlen($a) === 0) {
  380. $repl = "null";
  381. } else {
  382. $repl = "'".addslashes($a)."'";
  383. }
  384. break;
  385. } else
  386. if ($type === '') {
  387. if (is_array($a)) {
  388. $error = $errmsg = "NOT_A_SCALAR_PLACEHOLDER_$key";
  389. break;
  390. } else
  391. if (strlen($a) === 0) {
  392. $repl = "null";
  393. } else {
  394. $repl = (preg_match('#^[-]?([1-9][0-9]*|[0-9])($|[.,][0-9]+$)#', $a)) ? str_replace(',', '.', $a) : "'".addslashes($a)."'";
  395. }
  396. break;
  397. }
  398. if (!is_array($a)) {
  399. $error = $errmsg = "NOT_AN_ARRAY_PLACEHOLDER_$key";
  400. break;
  401. }
  402. if ($type === '@') {
  403. foreach ($a as $v) {
  404. $repl .= ($repl===''? "" : ",").(preg_match('#^[-]?([1-9][0-9]*|[0-9])($|[.,][0-9]+$)#', $v) ? str_replace(',', '.', $v):"'".$v."'");
  405. }
  406. } else
  407. if ($type === '%') {
  408. $lerror = array();
  409. foreach ($a as $k=>$v) {
  410. if (!is_string($k)) {
  411. $lerror[$k] = "NOT_A_STRING_KEY_{$k}_FOR_PLACEHOLDER_$key";
  412. } else {
  413. $k = preg_replace('/[^a-zA-Z0-9_]/', '_', $k);
  414. }
  415. $repl .= ($repl===''? "" : ", ").$k."='".@addslashes($v)."'";
  416. }
  417. if (count($lerror)) {
  418. $repl = '';
  419. foreach ($a as $k=>$v) {
  420. if (isset($lerror[$k])) {
  421. $repl .= ($repl===''? "" : ", ").$lerror[$k];
  422. } else {
  423. $k = preg_replace('/[^a-zA-Z0-9_-]/', '_', $k);
  424. $repl .= ($repl===''? "" : ", ").$k."=?";
  425. }
  426. }
  427. $error = $errmsg = $repl;
  428. }
  429. }
  430. } while (false);
  431. if ($errmsg)
  432. $compiled[$num]['error'] = $errmsg;
  433. if (!$error)
  434. $out .= $repl;
  435. }
  436. $out .= substr($tmpl, $p);
  437. if ($error) {
  438. $out = '';
  439. $p = 0;
  440. foreach ($compiled as $num=>$e) {
  441. list ($key, $type, $start, $length) = $e;
  442. $out .= substr($tmpl, $p, $start - $p);
  443. $p = $start + $length;
  444. if (isset($e['error'])) {
  445. $out .= $e['error'];
  446. } else {
  447. $out .= substr($tmpl, $start, $length);
  448. }
  449. }
  450. $out .= substr($tmpl, $p);
  451. $errormsg = $out;
  452. return false;
  453. } else {
  454. $errormsg = false;
  455. return $out;
  456. }
  457. }
  458. function panic($error = null) {
  459. throw new BrAppException($error ? $error : "Critical error");
  460. }
  461. function halt($check, $error = null) {
  462. if (!$error) {
  463. $error = $check;
  464. $check = false;
  465. }
  466. if (!$check) {
  467. throw new BrAppException($error ? $error : "Critical error");
  468. }
  469. }
  470. function fromJSON($json, $default = null) {
  471. $result = json_decode($json, true);
  472. if (!$result) {
  473. $result = $default;
  474. }
  475. return $result;
  476. }
  477. function toJSON($data) {
  478. return json_encode($data);
  479. }
  480. public function defaultConfig() {
  481. }
  482. function html2text($html) {
  483. return $this->HTML()->toText($html);
  484. }
  485. function text2html($html) {
  486. return $this->HTML()->fromText($html);
  487. }
  488. function guid() {
  489. // The field names refer to RFC 4122 section 4.1.2
  490. return sprintf('%04x%04x-%04x-%03x4-%04x-%04x%04x%04x',
  491. mt_rand(0, 65535), mt_rand(0, 65535), // 32 bits for "time_low"
  492. mt_rand(0, 65535), // 16 bits for "time_mid"
  493. mt_rand(0, 4095), // 12 bits before the 0100 of (version) 4 for "time_hi_and_version"
  494. bindec(substr_replace(sprintf('%016b', mt_rand(0, 65535)), '01', 6, 2)),
  495. // 8 bits, the last two of which (positions 6 and 7) are 01, for "clk_seq_hi_res"
  496. // (hence, the 2nd hex digit after the 3rd hyphen can only be 1, 5, 9 or d)
  497. // 8 bits for "clk_seq_low"
  498. mt_rand(0, 65535), mt_rand(0, 65535), mt_rand(0, 65535) // 48 bits for "node"
  499. );
  500. }
  501. function encryptInt($num) {
  502. $rand1 = rand(100, 999);
  503. $rand2 = rand(100, 999);
  504. $key1 = ($num + $rand1) * $rand2;
  505. $key2 = ($num + $rand2) * $rand1;
  506. $result = $rand1.$rand2.$key1.$key2;
  507. $rand1_len = chr(ord('A') + strlen($rand1));
  508. $rand2_len = chr(ord('D') + strlen($rand2));
  509. $key1_len = chr(ord('G') + strlen($key1));
  510. $rand1_pos = rand(0, floor(strlen($result)/3));
  511. $result1 = substr_replace($result, $rand1_len, $rand1_pos, 0);
  512. $rand2_pos = rand($rand1_pos + 1, floor(2*strlen($result1)/3));
  513. $result2 = substr_replace($result1, $rand2_len, $rand2_pos, 0);
  514. $key1_pos = rand($rand2_pos + 1, strlen($result2)-1);
  515. $result3 = substr_replace($result2, $key1_len, $key1_pos, 0);
  516. return $result3;
  517. }
  518. function decryptInt($num) {
  519. if (preg_match('/([A-Z]).*([A-Z]).*([A-Z])/', $num, $matches)) {
  520. $rand1_len = ord($matches[1]) - ord('A');
  521. $rand2_len = ord($matches[2]) - ord('D');
  522. $key1_len = ord($matches[3]) - ord('G');
  523. $num = str_replace($matches[1], '', $num);
  524. $num = str_replace($matches[2], '', $num);
  525. $num = str_replace($matches[3], '', $num);
  526. $rand1 = substr($num, 0, $rand1_len);
  527. $rand2 = substr($num, $rand1_len, $rand2_len);
  528. $key1 = substr($num, $rand1_len + $rand2_len, $key1_len);
  529. $key2 = substr($num, $rand1_len + $rand2_len + $key1_len);
  530. if (($rand1 > 0) && ($rand2 > 0)) {
  531. $num1 = $key1 / $rand2 - $rand1;
  532. $num2 = $key2 / $rand1 - $rand2;
  533. if ($num1 == $num2) {
  534. return $num1;
  535. } else {
  536. return null;
  537. }
  538. } else {
  539. return null;
  540. }
  541. } else {
  542. return null;
  543. }
  544. }
  545. function sendMail($email, $subject, $body, $params = array()) {
  546. if (!class_exists('PHPMailer')) {
  547. require_once(__DIR__.'/3rdparty/phpmailer/class.phpmailer.php');
  548. }
  549. $mail = new PHPMailer(true);
  550. $mail->CharSet = 'UTF-8';
  551. $mail->AddAddress($email);
  552. if ($from = br($params, 'sender', br()->config()->get('br/mail/sender', br()->config()->get('br/mail/from', br()->config()->get('br/Br/sendMail/from'))))) {
  553. $mail->AddReplyTo($from);
  554. $mail->SetFrom($from);
  555. }
  556. if (($mailer = br($params, 'mailer', br()->config()->get('br/mail/mailer'))) == 'smtp') {
  557. $mail->Mailer = $mailer;
  558. $mail->Host = br($params, 'hostname', br()->config()->get('br/mail/SMTP/hostname'));
  559. if ($port = br($params, 'port', br()->config()->get('br/mail/SMTP/port'))) {
  560. $mail->Port = $port;
  561. }
  562. if ($username = br($params, 'username', br()->config()->get('br/mail/SMTP/username'))) {
  563. $mail->Username = $username;
  564. $mail->Password = br($params, 'password', br()->config()->get('br/mail/SMTP/password'));
  565. $mail->SMTPAuth = true;
  566. }
  567. if ($secure = br($params, 'secure', br()->config()->get('br/mail/SMTP/secure'))) {
  568. $mail->SMTPSecure = $secure;
  569. }
  570. } else {
  571. $mail->Mailer = 'mail';
  572. $mail->SMTPSecure = '';
  573. }
  574. $mail->Subject = $subject;
  575. $mail->MsgHTML($body);
  576. br()->log()->writeLn('Sending mail to ' . $email);
  577. if ($mail->Send()) {
  578. br()->log()->writeLn('Sent');
  579. } else {
  580. throw new Exception('Mail was not sent because of unknown error');
  581. }
  582. return true;
  583. }
  584. function inc(&$var, $secondVar, $glue = ', ') {
  585. if (is_integer($var)) {
  586. $var = $var + $secondVar;
  587. } else {
  588. $var = $var . ($var ? $glue : '') . $secondVar;
  589. }
  590. }
  591. function stripSlashes(&$element) {
  592. if (is_array($element)) {
  593. foreach($element as $key => $value) {
  594. $this->stripSlashes($element[$key]);
  595. }
  596. } else {
  597. $element = stripslashes($element);
  598. }
  599. }
  600. // utils
  601. function formatBytes($size) {
  602. if ($size > 0) {
  603. $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
  604. return @round($size/pow(1024,($i=floor(log($size,1024)))),2).' '.$unit[$i];
  605. } else {
  606. return '0 b';
  607. }
  608. }
  609. function formatTraffic($size) {
  610. return $this->formatBytes($size);
  611. }
  612. function getMemoryUsage() {
  613. return $this->formatTraffic(memory_get_usage(true));
  614. }
  615. function getProcessId() {
  616. if ($this->processId === null) {
  617. $this->processId = getmypid();
  618. }
  619. return $this->processId;
  620. }
  621. function trn($phrase) {
  622. $translation = br()->config()->get('translation');
  623. return br($translation, $phrase, $phrase);
  624. }
  625. }