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