/** * Handler an error * * @param int $no The error number * @param string $str The error message * @param string $file The file that throwed the error * @param int $line The line in the file where the error was throwed * @param array $context All the variables in the error context */ public function error($no, $str, $file, $line, $context) { if (!(error_reporting() & $no)) { // This error code is not in error_reporting return; } switch ($no) { case E_NOTICE: case E_USER_NOTICE: $level = "info"; $icon = 'info-circle'; $title = "PHP Notice"; App::logger()->notice($str); break; case E_STRICT: $level = "info"; $icon = 'info-circle'; $title = "PHP Strict"; App::logger()->notice($str); break; case E_DEPRECATED: case E_USER_DEPRECATED: $level = "info"; $icon = 'info-circle'; $title = "PHP Deprecated"; App::logger()->notice($str); break; case E_USER_WARNING: case E_WARNING: $level = "warning"; $icon = "exclamation-triangle"; $title = "PHP Warning"; App::logger()->warning($str); break; default: $level = "danger"; $icon = "exclamation-circle"; $title = "PHP Error"; App::logger()->error($str); break; } $param = array('level' => $level, 'icon' => $icon, 'title' => $title, 'message' => $str, 'trace' => array(array('file' => $file, 'line' => $line))); if (!App::response()->getContentType() === "json") { App::response()->setBody($param); throw new AppStopException(); } else { echo View::make(Theme::getSelected()->getView('error.tpl'), $param); } }
public function run() { $uploader = new Uploader(); if (Yii::app()->request->isPostRequest) { //普通上传 $uploader->initSimple('album')->uploadSimple('simple_file'); $error = $uploader->getError(); if (!$error) { $data = array('file_name' => $uploader->file_name, 'file_path' => $uploader->file_path, 'file_path_full' => Helper::getFullUrl($uploader->file_path), 'thumb_path' => $uploader->thumb_path, 'thumb_path_full' => Helper::getFullUrl($uploader->thumb_path), 'file_ext' => $uploader->file_ext); App::response(200, 'success', $data); } else { App::response(101, $error); } } }
protected function redirectAction() { $shortURI = App::request()->getQueryVar('url'); $shortURIId = App::alphaid()->toId($shortURI); /** @var $urlRecord UrlModel */ $urlRecord = UrlModel::findOneByPk($shortURIId); if (false !== $urlRecord && !empty($urlRecord->longurl)) { // TODO cache // TODO statictics (hits/lastuse) App::response()->redirectAndExit($urlRecord->longurl, 301); // SEO friendly redirect } else { // redirect failed App::response()->sendNotFoundAndExit(); } }
public function run() { $uploader = new Uploader(); if (Yii::app()->request->isPostRequest) { //开始剪切 $image = $_POST['file']; $uploader->initSimple('avatar'); $cut_image = $uploader->imageCut($image, array('cut_w' => 100, 'cut_h' => 100, 'pos_x' => $_POST['x'], 'pos_y' => $_POST['y'])); $error = $uploader->getError(); if (!$error) { $data = array('cut_avatar' => $cut_image); App::response(200, '裁剪成功', $data); } else { App::response(101, $error); } } }
public function run() { $uploader = new Uploader(); if (Yii::app()->request->isPostRequest) { //断点上传 $uploader->initResumable('album')->uploadResumable('file'); $error = $uploader->getError(); if (!$error) { $data = array('file_name' => $uploader->file_name, 'file_path' => $uploader->file_path, 'file_path_full' => Helper::getFullUrl($uploader->file_path), 'file_ext' => $uploader->file_ext); App::response(200, 'success', $data); } else { App::response(101, $error); } } else { //校验已上传的片段 $uploader->checkExistChunks(); } }
public function parseRequestUrl($url) { // remove leading and trailing slashes $url = trim($url, '/'); $rule = $this->getMatchedRule($url); if (!is_array($rule) || is_array($rule) && count($rule) < 2) { App::response()->sendNotFoundAndExit(); } $rule[] = array(); // sizeof($rule) must be not less than 3 list($controller, $action, $parameters) = $rule; $controller = App::camelize($controller, true) . 'Controller'; $action = App::camelize($action, false) . 'Action'; // insert parsed parameters into query variables foreach ($parameters as $key => $value) { App::request()->addQueryVar($key, $value); } return array('controller' => $controller, 'action' => $action, 'parameters' => $parameters); }
public function run() { $this->init(); if (empty($this->_actionMethod)) { trigger_error('Action not defined in class ' . get_class($this) . '::run()', E_USER_ERROR); App::response()->sendNotFoundAndExit(); } if (!method_exists($this, $this->_actionMethod)) { trigger_error('Action method "' . $this->_actionMethod . '" not exit in class ' . get_class($this) . '::run()', E_USER_ERROR); App::response()->sendNotFoundAndExit(); } $this->{$this->_actionMethod}(); if ($this->_doRender) { // if action method called render() return $this->view->render(); // return rendered content } else { return $this->view->getData(); // return all variables } }
/** * Update Hawk */ public function updateHawk() { try { $api = new HawkApi(); $nextVersions = $api->getCoreAvailableUpdates(); if (empty($nextVersions)) { throw new \Exception("No newer version is available for Hawk"); } // Update incrementally all newer versions foreach ($nextVersions as $version) { // Download the update archive $archive = $api->getCoreUpdateArchive($version['version']); // Extract the downloaded file $zip = new \ZipArchive(); if ($zip->open($archive) !== true) { throw new \Exception('Impossible to open the zip archive'); } $zip->extractTo(TMP_DIR); // Put all modified or added files in the right folder $folder = TMP_DIR . 'update-v' . $version['version'] . '/'; App::fs()->copy($folder . 'to-update/*', ROOT_DIR); // Delete the files to delete $toDeleteFiles = explode(PHP_EOL, file_get_contents($folder . 'to-delete.txt')); foreach ($toDeleteFiles as $file) { if (is_file(ROOT_DIR . $file)) { unlink(ROOT_DIR . $file); } } // Remove temporary files and folders App::fs()->remove($folder); App::fs()->remove($archive); } // Execute the update method if exist $updater = new HawkUpdater(); $methods = get_class_methods($updater); foreach ($nextVersions as $version) { $method = 'v' . str_replace('.', '_', $version['version']); if (method_exists($updater, $method)) { $updater->{$method}(); } } App::cache()->clear('views'); App::cache()->clear('lang'); App::cache()->clear(Autoload::CACHE_FILE); App::cache()->clear(Lang::ORIGIN_CACHE_FILE); $response = array('status' => true); } catch (\Exception $e) { $response = array('status' => false, 'message' => DEBUG_MODE ? $e->getMessage() : Lang::get('admin.update-hawk-error')); } App::response()->setContentType('json'); return $response; }
/*** Execute action just after routing ***/ Event::on('after-routing', function ($event) { $route = $event->getData('route'); if (!App::conf()->has('db') && App::request()->getUri() == App::router()->getUri('index')) { // The application is not installed yet App::logger()->notice('Hawk is not installed yet, redirect to install process page'); App::response()->redirectToAction('install'); return; } }); /*** Compute the routage ***/ App::router()->route(); } catch (HTTPException $err) { App::response()->setStatus($err->getStatusCode()); $response = array('message' => $err->getMessage(), 'details' => $err->getDetails()); if (App::request()->getWantedType() === 'json') { App::response()->setContentType('json'); App::response()->setBody($response); } else { App::response()->setBody($response['message']); } } catch (AppStopException $e) { } // Finish the script App::logger()->debug('end of script'); $event = new Event('process-end', array('output' => App::response()->getBody(), 'execTime' => microtime(true) - SCRIPT_START_TIME)); $event->trigger(); App::response()->setBody($event->getData('output')); /*** Return the response to the client ***/ App::response()->end();
/** * Download a remote theme */ public function download() { App::response()->setContentType('json'); try { $api = new HawkApi(); $file = $api->downloadTheme($this->theme); $zip = new \ZipArchive(); if ($zip->open($file) !== true) { throw new \Exception('Impossible to open the zip archive'); } $zip->extractTo(THEMES_DIR); $theme = Theme::get($this->theme); if (!$theme) { throw new \Exception('An error occured while downloading the theme'); } unlink($file); return $theme; } catch (\Exception $e) { App::response()->setStatus(500); return array('message' => $e->getMessage()); } }
<?php App::response()->setStatusCode(404); ?> <div class="content box padding"> <h1><?php echo _s('Page does not exist'); ?> </h1> <p><?php echo _s('Sorry, but the page you were trying to view does not exist'); ?> </p> </div>
/** * Call a method of the controller * * @param string $method The method to call * @param array $arguments The arguments of the method call * * @return mixed The result of the method call */ public function __call($method, $arguments) { $this->controller->executingMethod = $method; /*** Load widgets before calling the controller method ***/ $class = $this->controller->getClassname(); $eventBasename = $this->controller->_plugin . '.' . $class . '.' . $method . '.'; $event = new Event($eventBasename . Controller::BEFORE_ACTION, array('controller' => $this->controller)); $event->trigger(); /*** Call the controller method ***/ $result = call_user_func_array(array($this->controller, $method), $arguments); if (App::response()->getContentType() == 'html' && is_string($result)) { // Create a phpQuery object to be modified by event listeners (widgets) $result = \phpQuery::newDocument($result); } /*** Load the widgets after calling the controller method ***/ $event = new Event($eventBasename . Controller::AFTER_ACTION, array('controller' => $this->controller, 'result' => $result)); $event->trigger(); // Return the result of the action $result = $event->getData('result'); if ($result instanceof \phpQuery || $result instanceof \phpQueryObject) { return $result->htmlOuter(); } else { return $result; } $this->controller->executingMethod = null; }
/** * 向浏览器返回json数据 * * @param array $notice */ public function returnJson($notice) { $this->app->response()->setJson($notice); exit; }
public static function onFatalError() { $error = error_get_last(); if (E_ERROR == $error['type']) { // PHP Fatal Error $msg = 'FATAL ERROR : ' . date("Y-m-d H:i:s (T)") . " \"{$error['message']}\" in file {$error['file']} at line {$error['line']}"; echo include_once static::basePath() . DIRECTORY_SEPARATOR . 'views' . DIRECTORY_SEPARATOR . 'error' . DIRECTORY_SEPARATOR . '500.phtml'; echo $msg; App::response()->sendContent(); } }
/** * setup the things that every app has * * it is up to the mainLoop() of the different types of app * to setup the rest (user, page, and theme) */ public static function init() { self::$browsers = new Browser_Manager(); self::$users = new User_Manager(); self::$routes = new Routing_Manager(); self::$pages = new Page_Manager(); self::$themes = new Theme_Manager(); self::$debug = new Debug_Manager(); // disable debugging if we are unit testing if (defined('UNIT_TEST') && UNIT_TEST) { self::$debug->setEnabled(false); } // with the general environment loaded, we can now load // the modules that are app-specific self::$request = new App_Request(); self::$response = new App_Response(); self::$conditions = new App_Conditions(); }
/** * @covers \Phix\App::response */ public function testResponseThrowsExceptionOnInvalidFormat() { $this->setExpectedException('\\Exception', 'Invalid format "bogus"'); $app = new App(); $app->response('123', 'bogus'); }
/** * Sign-out */ public function logout() { session_destroy(); App::response()->redirectToAction('index'); }
/** * Clear the cache and reload the whole page */ public function clearCache() { Event::unbind('process-end'); // Clear the directoty cache foreach (glob(CACHE_DIR . '*') as $elt) { App::fs()->remove($elt); } // Clear the directory of the theme foreach (glob(Theme::getSelected()->getStaticDir() . '*') as $element) { if (basename($element) != 'userfiles') { App::fs()->remove($element); } } App::response()->redirectToAction('index'); }
| for an application. | */ Route::conditions(array('_id' => '[0-9a-fA-F]{24}', 'start' => '(19|20)\\d\\d[\\-\\/.](0[1-9]|1[012])[\\-\\/.](0[1-9]|[12][0-9]|3[01])', 'end' => '(19|20)\\d\\d[\\-\\/.](0[1-9]|1[012])[\\-\\/.](0[1-9]|[12][0-9]|3[01])', 'token' => '[a-zA-Z0-9_-]{64,128}', 'version' => '[0-9]{1,6}')); /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Slim the URIs it should respond to | and give it the Closure to execute when that URI is requested. | */ Route::group('/v1', function () { App::response()->headers->set('X-OpenDRadio-Media-Type', 'opendradio.v1'); // Playlist Route::get('/playlist', 'App\\Http\\Controllers\\PlaylistController:getIndex')->name('playlist_url'); Route::group('/broadcasts', function () { // Get latest resources Route::get('/latest', 'App\\Http\\Controllers\\BroadcastController:getLatest')->name('broadcasts_latest_url'); // Get many resources by date range Route::get('/from/:start/to/:end', 'App\\Http\\Controllers\\BroadcastController:getFromTo')->name('broadcasts_from_to_url'); // Get one resource by id Route::get('/id/:_id', 'App\\Http\\Controllers\\BroadcastController:getOne')->name('broadcast_url'); }); Route::group('/news', function () { // Get latest resources Route::get('/latest', 'App\\Http\\Controllers\\NewsController:getLatest')->name('news_latest_url'); // Get many resources by date range Route::get('/from/:start/to/:end', 'App\\Http\\Controllers\\NewsController:getFromTo')->name('news_from_to_url');
} // Register Loader instance App::registerInstance($autoload, 'autoload'); // Register Request instance $request = new Request($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER); App::registerInstance($request, 'request'); // Starting the Firewall (new Mobicms\Firewall\Firewall())->run($request->getClientIp()); // Register Response instance $response = new Response('Content', Response::HTTP_OK, ['content-type' => 'text/html']); App::registerInstance($response, 'response'); // Database initialization $db = new \Mobicms\Database\PDOmysql(Config\Database::$dbHost, Config\Database::$dbName, Config\Database::$dbUser, Config\Database::$dbPass); App::registerInstance($db, 'db'); // Starting the Session and register instance $session = new Session(new NativeSessionStorage(new PdoSessionHandler($db, $request))); $session->start(); App::registerInstance($session, 'session'); // User initialization App::registerInstance(new \Mobicms\Checkpoint\Facade($db, $request, $response, $session), 'user'); // i18n functions require __DIR__ . DS . 'Mobicms/i18n/functions.php'; // Output buffering ob_start(); // Shutdown handlers register_shutdown_function(function () { App::response()->setContent(App::view()->render()); App::response()->prepare(App::request())->send(); session_register_shutdown(); // This important! });
/** * Reload all routes * * @return array The application routes */ public function getRoutes() { $routes = array(); foreach (App::router()->getRoutes() as $name => $route) { if ($route->isAccessible()) { $routes[$name] = array('url' => $route->url, 'where' => $route->where, 'default' => $route->default, 'pattern' => $route->pattern, 'duplicable' => !empty($route->duplicable)); } } App::response()->setContentType('json'); return $routes; }
/** * Return the response of the form (generally when submitted), * and set the Response HTTP code corresponding to the response, and the response type as JSON * * @param string $status The status to output. You can use the class constants STATUS_SUCCESS, STATUS_CHECK_ERROR or STATUS_ERROR * @param string $message The message to output. If not set, the default message corresponding to the status will be output * * @return array The response result, that will be displayed as json when the script ends */ public function response($status, $message = '') { $response = array(); switch ($status) { case self::STATUS_SUCCESS: // The form has been submitted correctly App::response()->setStatus(self::HTTP_CODE_SUCCESS); if (!$this->nomessage) { $response['message'] = $message ? $message : Lang::get('form.' . $status . '-' . $this->dbaction); } $response['data'] = $this->returns; break; case self::STATUS_CHECK_ERROR: // An error occured while checking field syntaxes throw new BadRequestException($message ? $message : Lang::get('form.error-fill'), $this->errors); case self::STATUS_ERROR: default: App::response()->setStatus(self::HTTP_CODE_ERROR); throw new InternalErrorException($message ? $message : Lang::get('form.' . $status . '-' . $this->dbaction), $this->errors); } App::response()->setContentType('json'); return $response; }
/** * Compute the routing, and execute the controller method associated to the URI */ public function route() { $path = str_replace(BASE_PATH, '', parse_url(App::request()->getUri(), PHP_URL_PATH)); // Scan each row foreach ($this->routes as $route) { if ($route->match($path)) { // The URI matches with the route $this->currentRoute =& $route; // Check if the route is accessible with the current method if (!$route->isCallableBy(App::request()->getMethod())) { throw new BadMethodException($route->url, App::request()->getMethod()); } // Emit an event, saying the routing action is finished $event = new Event('after-routing', array('route' => $route)); $event->trigger(); $route = $event->getData('route'); if (!$route->isAccessible()) { // The route is not accessible App::logger()->warning(sprintf('A user with the IP address %s tried to access %s without the necessary privileges', App::request()->clientIp(), App::request()->getUri())); if (!App::session()->isLogged()) { throw new UnauthorizedException(); } else { throw new ForbiddenException(); } } // The route authentications are validated list($classname, $method) = explode(".", $route->action); // call a controller method $this->currentController = $classname::getInstance($route->getData()); App::logger()->debug(sprintf('URI %s has been routed => %s::%s', App::request()->getUri(), $classname, $method)); // Set the controller result to the HTTP response App::response()->setBody($this->currentController->{$method}()); return; } } App::logger()->warning('The URI ' . App::request()->getUri() . ' has not been routed'); throw new PageNotFoundException(); }