示例#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];
     }
 }
 public function debugSessionAction()
 {
     if (Application::inDevelopment()) {
         Session::start();
         return '<pre>' . print_r($_SESSION, true) . '</pre>';
     } else {
         return Redirect::temporary('/');
     }
 }
 public function versionsAjax()
 {
     $packageId = (int) Input::post('package_id');
     if ($packageId <= 0) {
         Application::throwError(400, 'Bad request');
     }
     $resultSet = new Package\ResultSet\Version();
     $resultSet->setPackageId($packageId, Input::post('last'));
     $timeFrom = $resultSet->getFromTime();
     return BootstrapUI::tableRemoteResponse()->primaryKey('package_version_id')->column('total', function ($value, $row) {
         return \Bootstrap::label($value)->color('red');
     })->column('name')->column('action', function ($value, $row) use($packageId, $timeFrom) {
         return \Bootstrap::anchor(\Bootstrap::icon('search'), \Koldy\Url::href('reports', 'search', array('package_version_id' => $row['package_version_id'], 'date_from' => \Misc::userDate('Y-m-d H:i:s', strtotime($timeFrom)))))->title('Find reports with this package version')->asButton()->size('xs')->color('red');
     })->resultSet($resultSet)->handle();
 }
示例#4
0
 /**
  * (non-PHPdoc)
  * @see SessionHandlerInterface::open()
  */
 public function open($save_path, $sessionid)
 {
     // we'll ignore $save_path because we have our own path from config
     if (isset($this->config['session_save_path'])) {
         $this->savePath = $this->config['session_save_path'];
     } else {
         $this->savePath = Application::getStoragePath() . 'session';
     }
     if (!is_dir($this->savePath)) {
         if (!Directory::mkdir($this->savePath, 0777)) {
             throw new Exception('Can not create directory for session storage');
         }
     }
     if (substr($this->savePath, -1) != DS) {
         $this->savePath .= DS;
     }
     return true;
 }
示例#5
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();
         });
     }
 }
 /**
  * Show the page with user edit form
  */
 public function editUserAction()
 {
     $id = (int) Url::getVar(2);
     $user = User::fetchOne($id);
     if ($user === false) {
         Application::throwError(404, "Can not find user");
     }
     $title = "Edit user {$user->username}";
     $elements = array(\Bootstrap::h(1, $title), \Bootstrap::panel("User #{$id}", $this->getUserForm($user->getData()))->color('blue'));
     if ($user->last_login !== null) {
         $info = \Bootstrap::alert('User logged in last time at ' . Misc::userDate('Y-m-d H:i:s', $user->last_login) . " from {$user->last_login_ip}")->color('info');
         $elements[] = $info;
     }
     $content[] = Bootstrap::row()->add(8, $elements, 2);
     return View::create('base')->with('title', $title)->with('content', $content);
 }
示例#7
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
 }
示例#8
0
 /**
  * (non-PHPdoc)
  * @see \Koldy\Application\Route\AbstractRoute::exec()
  */
 public function exec()
 {
     if (method_exists($this->controllerInstance, 'before')) {
         $response = $this->controllerInstance->before();
         // if "before" method returns anything, then we should not continue
         if ($response !== null) {
             return $response;
         }
     }
     $method = $this->getActionMethod();
     if (method_exists($this->controllerInstance, $method) || method_exists($this->controllerInstance, '__call')) {
         // get the return value of your method (json, xml, view object, download, string or nothing)
         return $this->controllerInstance->{$method}();
     } else {
         // the method we need doesn't exists, so, there is nothing we can do about it any more
         Log::notice("Can not find method={$method} in class={$this->getControllerClass()} on path={$this->controllerPath} for URI=" . Application::getUri());
         static::error(404);
     }
 }
示例#9
0
 /**
  * get the time difference text
  * @param int $compareTo OPTIONAL
  * @return string
  */
 public function get($compareTo = null)
 {
     if ($compareTo === null) {
         if ($this->compareTo === null) {
             \Koldy\Application::error(500, 'Can not calculate time difference with non-existing time');
         } else {
             $compareTo = $this->compareTo;
         }
     }
     $difference = $compareTo - $this->referenceDate;
     if ($difference < 10) {
         return static::$translation['just-now'];
     }
     $measure = null;
     if ($difference < 60) {
         $diff = $difference;
         $measure = "seconds";
     }
     if ($measure === null && $difference < 150) {
         //
         $diff = 1;
         $measure = "1minute";
     }
     if ($measure === null && $difference < 3600) {
         // 60*60
         $diff = floor($difference / 60);
         $measure = "minutes";
     }
     if ($measure === null && $difference < 7200) {
         // 60*60 + 3600
         $diff = 1;
         $measure = "1hour";
     }
     if ($measure === null && $difference < 86400) {
         // 60*60*24
         $diff = floor($difference / 3600);
         // 60*60
         $measure = "hours";
     }
     if ($measure === null && $difference < 172800) {
         // 60*60*24 + 60*60*24
         $diff = 1;
         $measure = "1day";
     }
     if ($measure === null && $difference < 2592000) {
         // 60*60*24*30
         $diff = floor($difference / 86400);
         // 3600 * 24
         $measure = "days";
     }
     if ($measure === null && $difference < 5184000) {
         // 60*60*24*30 + 3600*24*30
         $diff = 1;
         $measure = "1month";
     }
     if ($measure === null && $difference < 10368000) {
         // 60*60*24*30*4
         $diff = floor($difference / 2592000);
         // 60*60*24*30
         $measure = "months";
     }
     if ($measure === null) {
         // TODO: Implement date translation/localization here
         return date("Y-m-d H:i:s", strtotime($compareTo));
     }
     $text = static::$format;
     $text = str_replace("{before}", static::$translation['before'], $text);
     $text = str_replace("{difference}", $diff, $text);
     $text = str_replace("{measure}", static::$translation[$measure], $text);
     $text = str_replace("{ago}", static::$translation['ago'], $text);
     return $text;
 }
示例#10
0
 /**
  * (non-PHPdoc)
  * @see \Koldy\Log\Writer\AbstractLogWriter::processExtendedReports()
  */
 protected function processExtendedReports()
 {
     if (!isset($this->config['dump'])) {
         return;
     }
     $dump = $this->config['dump'];
     // 'speed', 'included_files', 'include_path', 'whitespace'
     if (in_array('speed', $dump)) {
         $method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] . '=' . Application::getUri() : 'CLI=' . Application::getCliName();
         $executedIn = Application::getRequestExecutionTime();
         $this->logMessage('notice', $method . ' LOADED IN ' . $executedIn . 'ms, ' . count(get_included_files()) . ' files');
     }
     if (in_array('included_files', $dump)) {
         $this->logMessage('notice', print_r(get_included_files(), true));
     }
     if (in_array('include_path', $dump)) {
         $this->logMessage('notice', print_r(explode(':', get_include_path()), true));
     }
     if (in_array('whitespace', $dump)) {
         $this->logMessage('notice', "----------\n\n\n");
     }
 }
示例#11
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'));
 }
示例#12
0
					</p>
					<?php 
if (strlen($message) > 0) {
    ?>
					<p>
						<code><?php 
    echo $message;
    ?>
</code>
					</p>
					<?php 
}
?>
					
					<?php 
if (isset($exception) && class_exists('\\Koldy\\Application') && \Koldy\Application::inDevelopment()) {
    ?>
						<pre class="text-danger"><?php 
    echo $exception->getTraceAsString();
    ?>
</pre>
					<?php 
}
?>
					<p>
						<a class="btn btn-success btn-lg" role="button" href="/"><span class="glyphicon glyphicon-home"></span> Go home</a>
						<button class="btn btn-success btn-lg" onclick="window.location.reload()"><span class="glyphicon glyphicon-refresh"></span> Retry</button>
					</p>
				</div>
				
			</div><!-- /row -->
 public function viewAction()
 {
     $id = Url::getVar(1);
     // todo: ubaciti ovo u cache i odatle cupat van
     $cacheKey = "report-{$id}";
     $crash = CrashArchive::fetchOne($id);
     if ($crash === false) {
         Application::throwError(404, 'Can not find crash report ' . $id);
     }
     $title = "Crash Report #{$id}";
     $content = array();
     $panel = Bootstrap::panel($title)->color('blue')->addHeaderElement(Bootstrap::button('Back')->setAttribute('onclick', 'window.history.back()')->color('red')->size('xs'));
     $table = Bootstrap::table();
     $table->column('id', '')->column('value', '');
     // time
     $table->row(array('id' => 'time', 'value' => Misc::userDate('Y-m-d H:i:s', $crash->created_at) . ' (' . $this->user['timezone'] . ')'));
     // package
     $e = $crash->getPackage();
     $v = $crash->getPackageVersion();
     $table->row(array('id' => 'package and version', 'value' => implode(' ', array($e !== null ? "{$this->getSearchLink('package_id', $e->id, $e->name)} {$this->getLabel($e->total)}" : 'unknown', $v !== null ? "{$this->getSearchLink('package_version_id', $v->id, $v->value)} {$this->getLabel($v->total)}" : 'unknown'))));
     // device
     $value = '';
     $e = $crash->getBrand();
     if ($e === null) {
         $value .= 'unknown brand<br/>';
     } else {
         $value .= "{$this->getSearchLink('brand_id', $e->id, $e->name)} {$this->getLabel($e->total)}<br/>";
     }
     $e = $crash->getPhoneModel();
     if ($e === null) {
         $value .= 'unknown phone model<br/>';
     } else {
         $value .= "{$this->getSearchLink('model_id', $e->id, $e->name)} {$this->getLabel($e->total)}<br/>";
     }
     $table->row(array('id' => 'device', 'value' => substr($value, 0, -5)));
     // product
     $e = $crash->getProduct();
     if ($e !== null) {
         $table->row(array('id' => 'product name', 'value' => "{$this->getSearchLink('product_id', $e->id, $e->name)} {$this->getLabel($e->total)}"));
     }
     // os
     $e = $crash->getOsVersion();
     $table->row(array('id' => 'OS', 'value' => $e === null ? 'unknown' : "{$this->getSearchLink('os_version_id', $e->id, "{$e->os} {$e->name}")} {$this->getLabel($e->total)}"));
     // user comment
     if ($crash->user_comment !== null && trim($crash->user_comment) != '') {
         $table->row(array('id' => 'user comment', 'value' => $crash->user_comment));
     }
     // user email
     if ($crash->user_email !== null && trim($crash->user_email) != '') {
         $table->row(array('id' => 'user email', 'value' => $crash->user_email));
     }
     // app lifetime
     if ($crash->user_app_start_date !== null && $crash->user_crash_date !== null) {
         $table->row(array('id' => 'app lifetime', 'value' => "{$crash->user_app_start_date}<br/>{$crash->user_crash_date} (duration: {$this->duration($crash->user_app_start_date, $crash->user_crash_date)})"));
     }
     // memory usage
     $table->row(array('id' => 'available / total memory size', 'value' => Convert::bytesToString($crash->available_mem_size) . ' / ' . Convert::bytesToString($crash->total_mem_size)));
     // country
     if ($crash->country_id !== null) {
         $country = Country::fetchOne($crash->country_id);
         $table->row(array('id' => 'country', 'value' => "<img src=\"" . Url::link("img/flag/{$country->tld}.png") . "\" /> <a href=\"" . Url::href('reports', 'search', array('country_id' => $crash->country_id)) . "\">{$country->country} (" . strtoupper($country->tld) . ")</a> " . Bootstrap::label($country->total)->color('red')));
     }
     // provider
     if ($crash->provider_id !== null) {
         $e = Provider::fetchOne($crash->provider_id);
         $table->row(array('id' => 'internet provider', 'value' => "{$this->getSearchLink('provider_id', $e->id, $e->name)} {$this->getLabel($e->total)}"));
     }
     $metas = $crash->getMetas();
     $toTabs = array();
     foreach ($metas as $key => $value) {
         if ($key != 'stack_trace') {
             if (strpos(trim($value), "\n") === false) {
                 $table->row(array('id' => str_replace('_', ' ', $key), 'value' => trim($value) == '' ? '<em>empty</em>' : $value));
             } else {
                 $toTabs[] = $key;
             }
         }
     }
     $toTabsUnknown = array();
     $unknownMetas = $crash->getUnknownMetas();
     foreach ($unknownMetas as $key => $value) {
         if (strpos(trim($value), "\n") === false) {
             $table->row(array('id' => str_replace('_', ' ', $key), 'value' => (trim($value) == '' ? '<em>empty</em>' : $value) . ' ' . Bootstrap::label('unknown meta')->color('lightblue')));
         } else {
             $toTabsUnknown[] = $key;
         }
     }
     if ($crash->stack_trace_id !== null) {
         $table->row(array('id' => 'find reports with this stack trace', 'value' => Bootstrap::anchor(\Bootstrap::icon('search'), Url::href('reports', 'search', array('stack_trace_id' => $crash->stack_trace_id)))->asButton()->color('red')->size('xs')));
     }
     $panel->content($table);
     $content[] = Bootstrap::row()->add(12, $panel);
     $tabs = Bootstrap::nav();
     if (isset($metas['stack_trace'])) {
         $tabs->addLink('stack trace', "<pre class=\"text-danger\">{$metas['stack_trace']}</pre>");
     } else {
         if ($crash->stack_trace_id !== null) {
             $stackTrace = Stack\Trace::fetchOne($crash->stack_trace_id);
             $tabs->addLink('stack trace summary', "<pre class=\"text-danger\">{$stackTrace->summary}</pre>");
         }
     }
     if (sizeof($toTabs) > 0) {
         foreach ($toTabs as $key) {
             $tabs->addLink(str_replace('_', ' ', $key), "<pre>{$metas[$key]}</pre>");
         }
     }
     if (sizeof($toTabsUnknown) > 0) {
         foreach ($toTabsUnknown as $key) {
             $tabs->addLink(str_replace('_', ' ', $key) . ' ' . Bootstrap::label('?')->color('lightblue'), "<pre>{$unknownMetas[$key]}</pre>");
         }
     }
     if ($tabs->count() > 0) {
         $content[] = Bootstrap::row()->add(12, $tabs);
     }
     if ($crash->stack_trace_id !== null) {
         $content[] = Bootstrap::row()->add(12, Bootstrap::panel('This error count per day', new Chart\StackTracesPerDay($crash->stack_trace_id, 30))->color('red'));
     }
     return View::create('base')->with('title', $title)->with('content', $content);
 }
示例#14
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;
 }
 /**
  * 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;
 }
 public function searchAjax()
 {
     $validator = Validator::create(array('package_id' => 'required|integer', 'package_version_id' => 'required|integer', 'brand_id' => 'required|integer', 'os_version_id' => 'required|integer', 'product_id' => 'required|integer', 'model_id' => 'required|integer', 'country_id' => 'required|integer', 'provider_id' => 'required|integer', 'date_from' => null, 'date_to' => null, 'stack_trace_id' => 'required|integer'));
     if ($validator->failed()) {
         Application::throwError(400, 'Bad request');
     } else {
         $params = $validator->getParamsObj();
         $prms = array();
         $query = new ResultSet();
         $count = new Select();
         $count->from('crash_archive', 'a')->field('COUNT(*)', 'total');
         $query->from('crash_archive', 'a')->field('a.id')->field('a.created_at')->leftJoin('package p', 'p.id', '=', 'a.package_id')->field('p.name', 'package_name')->leftJoin('package_version pv', 'pv.id', '=', 'a.package_version_id')->field('pv.value', 'package_version')->leftJoin('brand b', 'b.id', '=', 'a.brand_id')->field('b.name', 'brand_name')->leftJoin('stack_trace st', 'st.id', '=', 'a.stack_trace_id')->field('st.summary', 'stack_trace')->leftJoin('version v', 'v.id', '=', 'a.os_version_id')->field('v.os', 'os_name')->field('v.name', 'os_version_name')->leftJoin('country c', 'c.id', '=', 'a.country_id')->field('c.country', 'country_name')->field('c.tld', 'tld');
         if ($params->date_from !== null) {
             $dateFrom = new DateTime($params->date_from);
             $query->where('a.created_at', '>=', Misc::utcFromUser('Y-m-d H:i:s', $dateFrom));
             $count->where('a.created_at', '>=', Misc::utcFromUser('Y-m-d H:i:s', $dateFrom));
             $prms['date_from'] = $params->date_from;
         }
         if ($params->date_to !== null) {
             $dateTo = new DateTime($params->date_to);
             $query->where('a.created_at', '<', Misc::utcFromUser('Y-m-d H:i:s', $dateTo));
             $count->where('a.created_at', '<', Misc::utcFromUser('Y-m-d H:i:s', $dateTo));
             $prms['date_to'] = $params->date_to;
         }
         if ($params->package_id > 0) {
             $query->where('a.package_id', $params->package_id);
             $count->where('a.package_id', $params->package_id);
             $prms['package_id'] = $params->package_id;
         }
         if ($params->package_version_id > 0) {
             $query->where('a.package_version_id', $params->package_version_id);
             $count->where('a.package_version_id', $params->package_version_id);
             $prms['package_version_id'] = $params->package_version_id;
         }
         if ($params->brand_id > 0) {
             $query->where('a.brand_id', $params->brand_id);
             $count->where('a.brand_id', $params->brand_id);
             $prms['brand_id'] = $params->brand_id;
         }
         if ($params->os_version_id > 0) {
             $query->where('a.os_version_id', $params->os_version_id);
             $count->where('a.os_version_id', $params->os_version_id);
             $prms['os_version_id'] = $params->os_version_id;
         }
         if ($params->product_id > 0) {
             $query->where('a.product_id', $params->product_id);
             $count->where('a.product_id', $params->product_id);
             $prms['product_id'] = $params->product_id;
         }
         if ($params->model_id > 0) {
             $query->where('a.model_id', $params->model_id);
             $count->where('a.model_id', $params->model_id);
             $prms['model_id'] = $params->model_id;
         }
         if ($params->country_id > 0) {
             $query->where('a.country_id', $params->country_id);
             $count->where('a.country_id', $params->country_id);
             $prms['country_id'] = $params->country_id;
         }
         if ($params->provider_id > 0) {
             $query->where('a.provider_id', $params->provider_id);
             $count->where('a.provider_id', $params->provider_id);
             $prms['provider_id'] = $params->provider_id;
         }
         if ($params->stack_trace_id > 0) {
             $query->where('a.stack_trace_id', $params->stack_trace_id);
             $count->where('a.stack_trace_id', $params->stack_trace_id);
             $prms['stack_trace_id'] = $params->stack_trace_id;
         }
         if (sizeof($prms) == 1) {
             // speed up count(*) ... because we have that precalculated
             if (isset($prms['stack_trace_id'])) {
                 $count = new Select();
                 $count->from('stack_trace')->field('total')->where('id', $prms['stack_trace_id']);
             } else {
                 if (isset($prms['brand_id'])) {
                     $count = new Select();
                     $count->from('brand')->field('total')->where('id', $prms['brand_id']);
                 } else {
                     if (isset($prms['package_id'])) {
                         $count = new Select();
                         $count->from('package')->field('total')->where('id', $prms['package_id']);
                     } else {
                         if (isset($prms['package_version_id'])) {
                             $count = new Select();
                             $count->from('package_version')->field('total')->where('id', $prms['package_version_id']);
                         } else {
                             if (isset($prms['os_version_id'])) {
                                 $count = new Select();
                                 $count->from('version')->field('total')->where('id', $prms['os_version_id']);
                             } else {
                                 if (isset($prms['country_id'])) {
                                     $count = new Select();
                                     $count->from('country')->field('total')->where('id', $prms['country_id']);
                                 } else {
                                     if (isset($prms['provider_id'])) {
                                         $count = new Select();
                                         $count->from('provider')->field('total')->where('id', $prms['provider_id']);
                                     } else {
                                         if (isset($prms['model_id'])) {
                                             $count = new Select();
                                             $count->from('phone_model')->field('total')->where('id', $prms['model_id']);
                                         }
                                     }
                                 }
                             }
                         }
                     }
                 }
             }
         }
         $query->setCountQuery($count);
         return BootstrapUI::tableRemoteResponse()->column('country_name', function ($value, $row) {
             if ($row['tld'] !== null) {
                 $country = \Koldy\Html::quotes($row['country_name']);
                 return '<img src="' . \Koldy\Url::link("img/flag/{$row['tld']}.png") . '" title="' . $country . '" />';
             } else {
                 return '';
             }
         })->column('created_at', function ($value, $row) {
             $user = \Koldy\Session::get('user');
             return \Koldy\Timezone::date($user['timezone'], 'd.m.Y', strtotime($value)) . '<br/>' . \Koldy\Timezone::date($user['timezone'], 'H:i:s', strtotime($value));
         })->column('package_name', function ($value, $row) {
             $html = $value;
             $html .= "<details><summary>View stack trace summary</summary><pre class=\"text-danger\">{$row['stack_trace']}</pre></details>";
             return $html;
         })->column('package_version')->column('brand_name')->column('os_version_name', function ($value, $row) {
             return "{$row['os_name']} {$row['os_version_name']}";
         })->column('country')->column('action', function ($value, $row) {
             return \Bootstrap::anchor(\Bootstrap::icon('eye-open'), \Koldy\Url::href('report', $row['id']))->title('View report')->size('xs');
         })->resultSet($query)->handle();
     }
 }
示例#17
0
 /**
  * I'm sure you sometimes want to show nice error to user! Well, if you call
  * Application::error(404), then it will end up here. This kind of errors are meant
  * only to show nice error to user. If you also want to log this or alert anyone that
  * this happened, then do that before calling Application::error() method.
  * 
  * @param int $code The HTTP error code
  * @param string $message Optional message that will be visible to user
  * @param \Exception $e Optional exception, if any. Be careful, you might not
  * want to show the exceptions to users, but you would like to show it to developers? Then
  * use Application::inDevelopment() and inProduction() methods.
  */
 public function error($code, $message = null, \Exception $e = null)
 {
     if (!headers_sent()) {
         switch ($code) {
             case 400:
                 header('HTTP/1.0 400 Bad Request', true, 400);
                 if ($message === null) {
                     $message = 'Bad request';
                 }
                 break;
             case 403:
                 header('HTTP/1.0 403 Forbidden', true, 403);
                 if ($message === null) {
                     $message = 'Forbidden';
                 }
                 break;
             case 404:
                 header('HTTP/1.0 404 Not Found', true, 404);
                 if ($message === null) {
                     $message = 'Page Not Found';
                 }
                 break;
             case 500:
                 header('HTTP/1.0 500 Internal Server Error', true, 500);
                 if ($message === null) {
                     $message = 'Internal Server Error';
                 }
                 break;
             case 503:
                 header('HTTP/1.1 503 Service Temporarily Unavailable', true, 503);
                 header('Status: 503 Service Temporarily Unavailable');
                 header('Retry-After: 300');
                 // 300 seconds / 5 minutes
                 if ($message === null) {
                     $message = 'Service Temporarily Unavailable';
                 }
                 break;
         }
     }
     if ($message === null) {
         $message = 'Page Not Found';
     }
     if ($this->isAjax()) {
         $data = array('success' => false, 'type' => 'http', 'code' => $code, 'message' => $message, 'exception' => $e !== null && Application::inDevelopment() ? $e->getMessage() : null);
         Json::create($data)->flush();
     } else {
         $path = Application::getPublicPath("{$code}.php");
         if (file_exists($path)) {
             $exception = $e;
             include $path;
         } else {
             // i don't know how to handle this message now!?
             throw new Exception($message === null ? 'Error ' . $code : $message);
         }
     }
     exit(0);
 }