Ejemplo n.º 1
0
 /**
  * Initialize the config for database(s)
  */
 public static function init()
 {
     if (static::$config === null) {
         static::$config = Application::getConfig('database');
         $keys = array_keys(static::$config);
         static::$defaultKey = $keys[0];
     }
 }
Ejemplo n.º 2
0
 /**
  * Initialize, load config and etc.
  */
 private static function init()
 {
     if (static::$writers === null) {
         static::$writers = array();
         $configs = Application::getConfig('application', 'log');
         $count = 0;
         foreach ($configs as $config) {
             if ($config['enabled']) {
                 // if the config is enabled, then make new instance
                 $writer = $config['writer_class'];
                 static::$writers[$count] = new $writer($config['options']);
                 if (!static::$writers[$count] instanceof AbstractLogWriter) {
                     throw new Exception("Log driver {$writer} must extend AbstractLogWriter");
                 }
                 $count++;
             }
         }
         register_shutdown_function(function () {
             \Koldy\Log::shutdown();
         });
     }
 }
Ejemplo n.º 3
0
 /**
  * Initialize the application :)
  * 
  * @throws Exception
  */
 protected static function init()
 {
     // second, check all requirements
     if (!function_exists('spl_autoload_register')) {
         throw new Exception('SPL is missing! Can not register autoload function');
     }
     // set the error reporting in development mode
     if (static::inDevelopment()) {
         error_reporting(E_ALL | E_STRICT);
     }
     $config = static::getConfig('application');
     // this is just shorthand for Directory Separator
     defined('DS') || define('DS', DIRECTORY_SEPARATOR);
     date_default_timezone_set($config['timezone']);
     // Register Autoload function
     spl_autoload_register(function ($className) {
         $classes = \Koldy\Application::$classAliases;
         if (isset($classes[$className])) {
             class_alias($classes[$className], $className);
         } else {
             $classPath = str_replace('\\', DS, $className);
             $path = "{$classPath}.php";
             include $path;
         }
     });
     // set the include path to the framework folder (to Koldy and any other
     // framework(s) located in framework folder with same namespacing style)
     $includePaths = array(substr(dirname(__FILE__), 0, -6));
     $basePath = static::getApplicationPath();
     // auto registering modules if there are any defined
     if (isset($config['auto_register_modules'])) {
         if (!is_array($config['auto_register_modules'])) {
             throw new Exception('Invalid config for auto_register_modules in config/application.php');
         }
         foreach ($config['auto_register_modules'] as $moduleName) {
             $includePaths[] = $basePath . 'modules' . DS . $moduleName . DS . 'controllers';
             $includePaths[] = $basePath . 'modules' . DS . $moduleName . DS . 'models';
             $includePaths[] = $basePath . 'modules' . DS . $moduleName . DS . 'library';
         }
     }
     // adding additional include paths if there are any
     if (isset($config['additional_include_path'])) {
         if (!is_array($config['additional_include_path'])) {
             throw new Exception('Invalid config for additional_include_path in config/application.php');
         }
         // so, we need to include something more
         foreach ($config['additional_include_path'] as $path) {
             $includePaths[] = $path;
         }
     }
     // register include path of application itself
     $includePaths[] = $basePath . 'controllers';
     $includePaths[] = $basePath . 'library';
     $includePaths[] = $basePath . 'models';
     // set the include path
     set_include_path(implode(PATH_SEPARATOR, $includePaths) . PATH_SEPARATOR . get_include_path());
     // set the error handler
     if (isset($config['error_handler']) && $config['error_handler'] instanceof \Closure) {
         set_error_handler($config['error_handler']);
     } else {
         set_error_handler(function ($errno, $errstr, $errfile, $errline) {
             if (!(error_reporting() & $errno)) {
                 // This error code is not included in error_reporting
                 return;
             }
             switch ($errno) {
                 case E_USER_ERROR:
                     \Koldy\Log::error("PHP [{$errno}] {$errstr} in file {$errfile}:{$errline}");
                     break;
                 case E_USER_WARNING:
                 case E_DEPRECATED:
                 case E_STRICT:
                     \Koldy\Log::warning("PHP [{$errno}] {$errstr} in file {$errfile}:{$errline}");
                     break;
                 case E_USER_NOTICE:
                     \Koldy\Log::notice("PHP [{$errno}] {$errstr} in file {$errfile}:{$errline}");
                     break;
                 default:
                     \Koldy\Log::error("PHP Uknown [{$errno}] {$errstr} in file {$errfile}:{$errline}");
                     break;
             }
             /* Don't execute PHP internal error handler */
             return true;
         });
     }
     // register PHP fatal errors
     register_shutdown_function(function () {
         if (!defined('KOLDY_FATAL_ERROR_HANDLER')) {
             define('KOLDY_FATAL_ERROR_HANDLER', true);
             // to prevent possible recursion if you run into problems with logger
             $fatalError = error_get_last();
             if ($fatalError !== null && $fatalError['type'] == E_ERROR) {
                 $errno = E_ERROR;
                 $errstr = $fatalError['message'];
                 $errfile = $fatalError['file'];
                 $errline = $fatalError['line'];
                 $config = \Koldy\Application::getConfig('application');
                 if (isset($config['error_handler']) && $config['error_handler'] instanceof \Closure) {
                     call_user_func($config['error_handler'], $errno, $errstr, $errfile, $errline);
                 } else {
                     \Koldy\Log::error("PHP [{$errno}] Fatal error: {$errstr} in {$errfile} on line {$errline}");
                 }
             }
         }
     });
     // all execeptions will be caught in run() method
 }
Ejemplo n.º 4
0
 /**
  * (non-PHPdoc)
  * @see \Koldy\Application\Route\AbstractRoute::href()
  */
 public function href($controller = null, $action = null, array $params = null)
 {
     if ($controller !== null && strpos($controller, '/') !== false) {
         throw new \InvalidArgumentException('Slash is not allowed in controller name');
     }
     if ($action !== null && strpos($action, '/') !== false) {
         throw new \InvalidArgumentException('Slash is not allowed in action name');
     }
     $config = Application::getConfig();
     if ($controller === null) {
         $controller = '';
     }
     $url = $config['site_url'];
     $url .= '/' . $controller;
     if ($action !== null) {
         $url .= '/' . $action;
     }
     if ($params !== null && count($params) > 0) {
         $q = array();
         foreach ($params as $key => $value) {
             if (is_numeric($key)) {
                 $url .= '/' . $value;
             } else {
                 $q[$key] = $value;
             }
         }
         if (sizeof($q) > 0) {
             $url .= '?';
             foreach ($q as $key => $value) {
                 $url .= "{$key}={$value}&";
             }
             $url = substr($url, 0, -1);
         }
     }
     return $url;
 }
Ejemplo n.º 5
0
 /**
  * Send e-mail report if system detected that e-mail should be sent
  * 
  * @return boolean|null true if mail was sent and null if mail shouldn't be sent
  */
 protected function sendEmailReport()
 {
     if ($this->emailReport === true && $this->config['email'] !== null) {
         $body = implode('', $this->messages);
         /* this doesn't have sense any more :::
         			$body .= "\n\n---------- debug_backtrace:\n";
         
         			foreach (debug_backtrace() as $r) {
         				if (isset($r['file']) && isset($r['line'])) {
         					$body .= "{$r['file']}:{$r['line']} ";
         				}
         
         				if (isset($r['function'])) {
         					$body .= "{$r['function']} ";
         				}
         
         				if (isset($r['args'])) {
         					$body .= implode(', ', $r['args']);
         				}
         
         				$body .= "\n";
         			}
         			*/
         $body .= "\n----------\n";
         $body .= sprintf("server: %s (%s)\n", Request::serverIp(), Request::hostName());
         if (PHP_SAPI != 'cli') {
             $body .= 'URI: ' . $_SERVER['REQUEST_METHOD'] . '=' . Application::getConfig('application', 'site_url') . Application::getUri() . "\n";
             $body .= sprintf("User IP: %s (%s)%s", Request::ip(), Request::host(), Request::hasProxy() ? sprintf(" via %s for %s\n", Request::proxySignature(), Request::httpXForwardedFor()) : "\n");
             $body .= sprintf("UAS: %s\n", isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : 'no user agent set');
         } else {
             $body .= 'CLI Name: ' . Application::getCliName() . "\n";
             $body .= 'CLI Script: ' . Application::getCliScript() . "\n";
             $params = Cli::getParameters();
             if (count($params) > 0) {
                 $body .= 'CLI Params: ' . print_r($params, true) . "\n";
             }
         }
         $body .= sprintf("Server load: %s\n", Server::getServerLoad());
         $peak = memory_get_peak_usage(true);
         $memoryLimit = ini_get('memory_limit');
         $body .= sprintf("Memory: %s; peak: %s; limit: %s; spent: %s%%\n", Convert::bytesToString(memory_get_usage(true)), Convert::bytesToString($peak), $memoryLimit, $memoryLimit !== false && $memoryLimit > 0 ? round($peak * 100 / Convert::stringToBytes($memoryLimit), 2) : 'null');
         $body .= sprintf("included files: %s\n", print_r(get_included_files(), true));
         $mail = Mail::create();
         $mail->from('alert@' . Request::hostName(), Request::hostName())->subject('Log report')->body($body);
         if (!is_array($this->config['email']) && strpos($this->config['email'], ',') !== false) {
             $this->config['email'] = explode(',', $this->config['email']);
         }
         if (is_array($this->config['email'])) {
             foreach ($this->config['email'] as $toEmail) {
                 $mail->to(trim($toEmail));
             }
         } else {
             $mail->to(trim($this->config['email']));
         }
         if (!$mail->send()) {
             $this->error("Can not send alert mail to {$this->config['email']}: {$mail->getError()}\n{$mail->getException()->getTraceAsString()}");
             return false;
         }
         return true;
     }
     return null;
 }
Ejemplo n.º 6
0
 /**
  * Get path to the cache file by $key
  * 
  * @param string $key
  * @return string
  */
 protected function getPath($key)
 {
     return $this->path . $key . '_' . md5($key . Application::getConfig('application', 'key'));
 }
Ejemplo n.º 7
0
 /**
  * (non-PHPdoc)
  * @see \Koldy\Application\Route\AbstractRoute::href()
  */
 public function href($controller = null, $action = null, array $params = null)
 {
     if ($controller !== null && strpos($controller, '/') !== false) {
         throw new Exception('Slash is not allowed in controller name');
     }
     if ($action !== null && strpos($action, '/') !== false) {
         throw new Exception('Slash is not allowed in action name');
     }
     $config = Application::getConfig();
     if ($controller === null) {
         $controller = '';
     }
     $url = $config['site_url'] . '/?';
     $url .= "{$this->config['controller_param']}={$controller}";
     if ($action !== null) {
         $url .= "&{$this->config['action_param']}={$action}";
     }
     if ($params !== null) {
         foreach ($params as $key => $value) {
             $url .= "&{$key}={$value}";
         }
     }
     return $url;
 }
Ejemplo n.º 8
0
 /**
  * Generate link to the resource file on CDN domain if CDN is set, otherwise
  * this acts the same as link() method
  * 
  * @param string $path
  * @return string
  */
 public function cdn($path)
 {
     // if you pass the full URL that contains "://" part, then it will be immediately
     // returned without any kind of building or parsing it
     $pos = strpos($path, '://');
     if ($pos !== false && $pos < 10) {
         return $path;
     }
     $config = Application::getConfig();
     $cdnUrl = $config['cdn_url'] === null ? $config['site_url'] : $config['cdn_url'];
     if ($path[0] != '/') {
         $path = '/' . $path;
     }
     if (substr($path, 0, 2) == '//') {
         return $path;
     }
     return $cdnUrl . $path;
 }