<?php
class BookAction extends Action{
const BOOK_SAVE_DIR = "/data/book/" ;
private $uri ;
private $baseUrl ;
private $book ;
private $bookname ;
public function show(){
$book = $_GET [ 'book' ];
$this ->book = $book ;
$this ->uri = str_replace ( "/book-{$book}/" , "" , $_SERVER [ 'REQUEST_URI' ]);
if (!method_exists( $this , $book )){
$this ->error404();
}
try {
$this -> $book ();
} catch (Exception $e ){
$this ->error404();
}
}
/**
* http://akaedu.github.io/book/
*/
private function c(){
$this ->baseUrl = "http://akaedu.github.io/book/" ;
$url = $this ->baseUrl. $this ->uri;
$this ->output( $url );
}
private function output( $url ){
$ext = pathinfo ( $url ,PATHINFO_EXTENSION);
if (! $ext ) {
$url = $url . "/index.html" ;
$ext = "html" ;
}
switch ( $ext ){
case "css" :
header( "Content-Type: text/css; charset=UTF-8" );
break ;
default :
header( "Content-Type: text/html; charset=UTF-8" );
break ;
}
// 如果已经缓存
$filename = self::BOOK_SAVE_DIR. $this ->book. "/" . str_replace ( $this ->baseUrl, "" , $url );
if ( file_exists ( $filename )){
$data = file_get_contents ( $filename );
} else {
$data = file_get_contents ( $url );
$dir = dirname( $filename );
if (! file_exists ( $dir )){
mkdir ( $dir ,755,true);
}
file_put_contents ( $filename , $data );
}
// 增加原始版权说明
echo $data ;
}
}
|