function handle($uri = '') { try { if (($matched = dispatch($uri)) != null) { if (!before()) { $handler = $matched['handler']; if (!empty($matched['options']['router'])) { $handler = call_user_func($handler, $matched); } if (!empty($matched['options']['create'])) { $controllerClass = $handler[0]; $handler[0] = new $controllerClass(); } if (isset($matched['params'])) { call_user_func_array($handler, $matched['params']); } else { call_user_func_array($handler, $matched['segments']); } after(); } } else { notFound(); } finish(); } catch (Exception $e) { error_log($e->getMessage()); error_log($e->getTraceAsString()); } exit; }
/** * 入口 */ public static function run() { spl_autoload_register('bt::autoload'); set_error_handler('bt::errorHandler'); register_shutdown_function('bt::shutdown'); self::init(); //开启session session_start(); //路由处理. if (isset($_GET[Conf::ACTION_NAME]) && isset($_GET[Conf::METHOD_NAME])) { $actionName = trim($_GET[Conf::ACTION_NAME]); $action = $actionName . 'Action'; $method = trim($_GET[Conf::METHOD_NAME]); define('CONST_ACTION', $actionName); define('CONST_METHOD', $method); if (class_exists($action)) { $cls = new $action(); if (method_exists($cls, $method)) { call_user_func(array($cls, $method)); return false; } } } //错误处理. if (!function_exists('notFound')) { function notFound() { echo '404'; } } notFound(); }
function downloadFile($url, $path) { if (isValidUrl($url)) { touch($path); $remoteFile = fopen($url, "rb"); if ($remoteFile) { $newFile = fopen($path, "wb"); if ($newFile) { while (!feof($remoteFile)) { fwrite($newFile, fread($remoteFile, 1024 * 8), 1024 * 8); } } } else { return false; } if ($remoteFile) { fclose($remoteFile); } if ($newFile) { fclose($newFile); } return true; } else { notFound(); return false; } }
/** * Download file with given name to given path * @param $url url to download * @param $path output filepath * @return true if success, else you know what */ function downloadFile($url, $path) { $fp = fopen($path, 'wb'); $ch = curl_init($url); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_FAILONERROR, 1); curl_exec($ch); fclose($fp); if (curl_errno($ch) > 0) { notFound(); return false; } curl_close($ch); fclose($fp); return true; }
function deleteBook() { if (!isLogged()) { header('Location: ./'); exit; } $books = new Books(isLogged()); $id = (int) $_GET['delete'] + 0; if (!isset($books[$id])) { notFound(); } global $_CONFIG; // process to delete book in database if (!empty($_GET['token']) && acceptToken($_GET['token'])) { // check if a miniature exists and delete it $img = $_CONFIG['images'] . '/' . $id . '.jpg'; if (is_file($img)) { unlink($img); } // delete book in database unset($books[$id]); $books->save(); header('Location: ./'); exit; } else { errorPage('The received token was empty or invalid.', 'Invalid security token'); } }
$book = Book::getBookByDataId($idData); } else { $book = Book::getBookById($bookId); } if (!$book) { notFound(); return; } if ($book && ($type == "jpg" || empty($config['calibre_internal_directory']))) { if ($type == "jpg") { $file = $book->getFilePath($type); } else { $file = $book->getFilePath($type, $idData); } if (!$file || !file_exists($file)) { notFound(); return; } } switch ($type) { case "jpg": header("Content-Type: image/jpeg"); if ($book->getThumbnail(getURLParam("width"), getURLParam("height"))) { // The cover had to be resized return; } break; default: $data = $book->getDataById($idData); header("Content-Type: " . $data->getMimeType()); break;
/** * Remoção de dispositivo */ function deleteDevice() { global $log; $input = null; $app = Slim::getInstance(); try { // obtém os dados informados $input = json_decode($app->request()->getBody()); $log->Debug(sprintf("api - deleteDevice - %s", print_r($input, true))); if (!$input || !isset($input->token)) { throw new \InvalidArgumentException("O identificador do dispositivo não foi informado."); } } catch (Exception $e) { badRequest($e, $log); return; } try { if (DeviceManager::deleteDevice($input->token)) { noContent("Dispositivo removido com sucesso."); } else { notFound("O dispositivo informado não foi encontrado."); } } catch (Exception $e) { internalServerError($e, $log); } }
protected function actionRemove() { if (count($this->routes) > 0) { $id = array_shift($this->routes); $file = $this->dir . $id . self::jsonExtension; if (is_file($file)) { unlink($file); return '{"result":"deleted"}'; } } return notFound(); }
/** * Stream audio. Now just redirects to file. * * @param String $filePath path of file * @param String $fileName name of audio for log * @return content */ function stream($filePath, $fileName) { logStream("{$filePath} {$fileName}"); checkIsBadMp3($filePath); @error_reporting(0); // Make sure the files exists, otherwise we are wasting our time if (!file_exists($filePath)) { notFound(); } //just redirect to file header("Location: /{$filePath}"); }
exit; } } $function = $route->getFunctionName(); $params = $route->getParameterValues(); // Execute controller try { $controller = new $class($serviceFactory, $env->input(), $env->getConfig(), $env->auth(), $env); if ($params) { $output = call_user_func_array(array($controller, $function), $params); } else { $output = $controller->{$function}(); } echo $output; } catch (NotFoundException $e) { notFound($format, $route->getUri()); } catch (UnauthorizedException $e) { unauthorized($format, $e, $route->getUri()); // User safe error message (usually invalid input, etc) } catch (UserSafeException $e) { userError($format, $e); // Unexpected Exception } catch (Exception $e) { serverError($format, $e, $env->isProduction()); } function notFound($format, $uri) { http_response_code(404); if ($format == 'plain') { echo "Resource Not Found\nThere is no resource located at {$uri}\n"; } else {
/** * resizeimage * 缩放图片,节省资源 */ function resizeimage($filename, $w, $h = 0, $format = "jpg") { if ($w <= 0 && $h <= 0) { notFound(); } // session_start();//读取session // $etag = substr( md5($filename),0,8); // if($_SERVER['HTTP_IF_NONE_MATCH'] == $etag){ // header('HTTP/1.1 304 Not Modified'); //返回304,告诉浏览器调用缓存 // exit(); // }else{ // header('Etag:'.$etag); // }; $etag = 'W/' . substr(md5($filename), 0, 8); header('Etag:' . $etag); $modified_time = $_SERVER['HTTP_IF_MODIFIED_SINCE']; $time = 315360000; //10年缓存时间 if (strtotime($modified_time) + $time > time()) { header('HTTP/1.1 304 Not Modified'); //返回304,告诉浏览器调用缓存 setHeader(strtotime($modified_time)); //设置缓存 exit; } $path = "/data/www/pic1{$filename}"; if (!file_exists($path)) { notFound(); } list($o_w, $o_h, $type) = getimagesize($path); if ($h <= 0) { $w = $o_w > $w ? $w : $o_w; $h = ceil($o_h * $w / $o_w); } if ($w <= 0) { $h = $o_h > $h ? $h : $o_h; $w = ceil($o_w * $h / $o_h); } switch ($type) { case 1: $src = imagecreatefromgif($path); break; case 2: $src = imagecreatefromjpeg($path); break; case 3: $src = imagecreatefrompng($path); break; } if (!$src) { notFound(); } setHeader(time()); //设置缓存 $image = imagecreatetruecolor($w, $h); imagecopyresampled($image, $src, 0, 0, 0, 0, $w, $h, $o_w, $o_h); switch ($type) { case 1: header('Content-type: image/gif'); imagegif($image); break; case 2: header('Content-type: image/jpg'); imagejpeg($image, null, 100); break; case 3: header('Content-type: image/png'); imagepng($image, null, 9); break; } imagedestroy($image); exit; }
if (!array_key_exists('cnt_session_id', $request->getCookieParams())) { logger($this)->addWarning('No contractor session id', getPath($request)); return forbidden($response); } $contractorSessionId = $request->getCookieParams()['cnt_session_id']; $contractorId = getContractorId($contractorSessionId); if (!isset($contractorId)) { logger($this)->addWarning('No contractor found by session id', array('cnt_session_id' => $contractorSessionId, 'uri' => $request->getUri()->getPath())); return forbidden($response); } // Trying to take the order before anyone! list($bidsPdo, $bid) = getBidAndDeleteItWithoutCommit($id); if (!isset($bidsPdo)) { logger($this)->addWarning('Bid has already been taken', array('id' => $id, 'uri' => $request->getUri()->getPath())); // Someone has already taken the order, what a bummer. return notFound($response); } // We won the bid! Let's charge money from the customer $customerId = $bid['customer_id']; $sum = $bid['price']; $royalty = getRoyalty($sum); if (!isset($royalty)) { logger($this)->addError('Wrong royalty in the configuration'); // Bad royalty percent format in the config return internalError($response); } $sumWithRoyalty = bcadd($sum, $royalty, 2); if (!chargeCustomer($customerId, $sumWithRoyalty)) { logger($this)->addError("Unable to charge a customer", array('customerId' => $customerId, 'sum' => $sum)); $bidsPdo->rollback(); // The lousy miser customer doesn't have enough money to pay.
if (!$matches) { preg_match('/<body(?:.*?)>(.*)/s', file_get_contents('/mnt/media/Unsorted/ASA/files/' . $complaint['year'] . '/html/' . $complaint['id'] . '.html'), $matches); } if ($matches) { $html = make_clickable(iconv('UTF-8', 'ASCII//TRANSLIT', $matches[1])); print '<div class="panel panel-info"><div class="panel-heading"><h3 class="panel-title">Document</h3></div><div class="panel-body">' . $html . '</div></div>'; } else { print "<pre>"; print_r($complaint['doc']); print "</pre>"; } } else { api($complaint, 'complaint'); } } else { notFound('Complaint'); } } } } else { $top = 20; $data["complainants"] = complainantsData($top); $data["companies"] = companiesData($top); $data["products"] = productsData(); $data["years"] = yearsData(); $data["media"] = mediaData(); $data["codes"] = codesData(); $data["complaints"] = getComplaintsDetails("(SELECT id FROM complaints WHERE meetingdate > (NOW() - INTERVAL 2 MONTH) AND meetingdate < (NOW() + INTERVAL 1 DAY) ORDER BY meetingdate DESC)"); if ($GLOBALS['filetype'] == 'html') { printheader('ASA Complaints'); print '<div class="row"><div class="col-md-6">';
break; case 'gs': imagefilter($im, IMG_FILTER_GRAYSCALE); break; case 'h': $im = scale_height($im, $params[0]); break; case 'w': $im = scale_width($im, $params[0]); break; case 'f': $force = $params[0]; // should be 1 or 0 break; default: notFound(4); } } if ($type == 'png') { $quality = $quality / 11.11; // translate 0-100 quality scale to 0-9, which is what imagepng() expects. } // quality parameter will be ignored for imagegif(). $outputfunc($im, $dir . '/' . $filename, $quality); header("Content-type: {$mime}"); echo file_get_contents($dir . '/' . $filename); function scale_longside($im, $longside) { global $force; $width = imagesx($im); $height = imagesy($im);
/** * Stream audio. Now just redirects to file. * * @param String $filePath path of file * @param String $fileName name of audio for log * @return content */ function stream($file, $fileName) { writeStream("{$file} {$fileName}"); //log @error_reporting(0); // Make sure the files exists, otherwise we are wasting our time if (!file_exists($file)) { notFound(); } //just redirect to file header("Location: /{$file}"); }
$actorID = findActorID($db, $firstname, $lastname); $rows = $db->prepare("SELECT m.* FROM movies m JOIN roles r1 ON r1.movie_id = m.id JOIN roles r2 ON r2.movie_id = m.id JOIN actors a1 ON r1.actor_id = a1.id JOIN actors a2 ON r2.actor_id = a2.id WHERE a1.id = '{$kevinID}' AND a2.id = '{$actorID}' ORDER BY m.year DESC"); $rows->execute(); $movies = $rows->fetchAll(PDO::FETCH_ASSOC); return $movies; } ?> <!DOCTYPE html> <html> <?php $movies = findAllKevins($db, $firstname, $lastname); // $actorfname = $movies[0]["first_name"]; // $actorlname = $movies[0]["last_name"]; if (count($movies) == 0) { notFound($firstname, $lastname); return; } head(); ?> <body> <div id = "frame"> <?php banner(); ?> <div id = "main"> <h1>All Films with <?php echo $firstname; ?> <?php
function execute($args) { //frontpage and controller breadcrumbs $this->breadcrumb(HOMEPAGE, HOMEPAGE_URL); if ($this->controller != 'DEFAULT_CONTROLLER') { $this->breadcrumb($this->getName(), $this->controller); } //figure out what action to use if (array_key_exists(0, $args) && method_exists($this, $args[0] . 'Action')) { $action = $args[0]; } else { if (method_exists($this, $this->defaultAction . 'Action')) { $action = $this->defaultAction; } else { notFound(); } } //save arguments for controller use $this->args = $args; $this->currId = array_key_exists(1, $args) ? $args[1] : NULL; $this->action = $action; //save information about the view we want to display //by default we use the view with the name of the action //(may be modified by action) $this->renderView($action); //find the action's human name if ($action != $this->defaultAction) { if (array_key_exists($action, $this->actionNames)) { $actionName = $this->actionNames[$action]; } else { $actionName = $action; } } //figure out which template should be used by default $this->template = $this->getTemplate($action); //take care of any requirements $this->doRequirements($action); //run the action global $render_times; $render_times[] = array('Init', microtime(true)); call_user_func(array($this, $action . 'Action')); //set breadcrumbs if (count($this->breadcrumbs) <= 2) { if ($this->subjectName) { $this->breadcrumb($this->subjectName, $this->controller . '/show/' . (array_key_exists(1, $this->args) ? $this->args[1] : '')); } if ($action != $this->defaultAction && $action != 'show') { $this->breadcrumb($actionName, $this->controller . '/' . $action); } //I don't forsee a case where that breadcrumb URL is shown, btw. } //include the template, which will call back for view $render_times[] = array('Action', microtime(true)); if ($this->template !== false) { include $this->template; } else { //if this occurs, a 404 will be delivered but the //action may still have been completed. notFound(); } }