Repository: horvey/Library-Manager Branch: master Commit: e3d3743f8c8f Files: 247 Total size: 1.3 MB Directory structure: gitextract__o9w64dy/ ├── Admin/ │ ├── Controller/ │ │ ├── BookController.class.php │ │ ├── BorrowController.class.php │ │ ├── IndexController.class.php │ │ └── UserController.class.php │ ├── Model/ │ │ ├── BookModel.class.php │ │ ├── BorrowModel.class.php │ │ └── UserModel.class.php │ └── View/ │ ├── Book/ │ │ ├── add.html │ │ ├── detail.html │ │ ├── edit.html │ │ └── index.html │ ├── Borrow/ │ │ └── index.html │ ├── Index/ │ │ └── index.html │ └── User/ │ ├── add.html │ ├── index.html │ └── manage.html ├── Base/ │ ├── Base.class.php │ ├── BaseController.class.php │ ├── BaseModel.class.php │ └── Conf.php ├── Common/ │ ├── Controller/ │ │ └── LoginController.class.php │ ├── Model/ │ │ └── UserModel.class.php │ └── View/ │ └── login.html ├── Home/ │ ├── Controller/ │ │ ├── BookController.class.php │ │ ├── BorrowController.class.php │ │ ├── IndexController.class.php │ │ └── UserController.class.php │ ├── Model/ │ │ ├── BookModel.class.php │ │ ├── BorrowModel.class.php │ │ └── UserModel.class.php │ └── View/ │ ├── Book/ │ │ ├── detail.html │ │ └── index.html │ ├── Index/ │ │ └── index.html │ └── User/ │ └── index.html ├── LICENSE ├── README.md ├── Tool/ │ ├── Db.class.php │ ├── MySmarty.class.php │ ├── Pager.class.php │ ├── Verify.class.php │ └── smarty-3.1.32/ │ └── libs/ │ ├── Autoloader.php │ ├── Smarty.class.php │ ├── SmartyBC.class.php │ ├── bootstrap.php │ ├── debug.tpl │ ├── plugins/ │ │ ├── block.textformat.php │ │ ├── function.counter.php │ │ ├── function.cycle.php │ │ ├── function.fetch.php │ │ ├── function.html_checkboxes.php │ │ ├── function.html_image.php │ │ ├── function.html_options.php │ │ ├── function.html_radios.php │ │ ├── function.html_select_date.php │ │ ├── function.html_select_time.php │ │ ├── function.html_table.php │ │ ├── function.mailto.php │ │ ├── function.math.php │ │ ├── modifier.capitalize.php │ │ ├── modifier.date_format.php │ │ ├── modifier.debug_print_var.php │ │ ├── modifier.escape.php │ │ ├── modifier.mb_wordwrap.php │ │ ├── modifier.regex_replace.php │ │ ├── modifier.replace.php │ │ ├── modifier.spacify.php │ │ ├── modifier.truncate.php │ │ ├── modifiercompiler.cat.php │ │ ├── modifiercompiler.count_characters.php │ │ ├── modifiercompiler.count_paragraphs.php │ │ ├── modifiercompiler.count_sentences.php │ │ ├── modifiercompiler.count_words.php │ │ ├── modifiercompiler.default.php │ │ ├── modifiercompiler.escape.php │ │ ├── modifiercompiler.from_charset.php │ │ ├── modifiercompiler.indent.php │ │ ├── modifiercompiler.lower.php │ │ ├── modifiercompiler.noprint.php │ │ ├── modifiercompiler.string_format.php │ │ ├── modifiercompiler.strip.php │ │ ├── modifiercompiler.strip_tags.php │ │ ├── modifiercompiler.to_charset.php │ │ ├── modifiercompiler.unescape.php │ │ ├── modifiercompiler.upper.php │ │ ├── modifiercompiler.wordwrap.php │ │ ├── outputfilter.trimwhitespace.php │ │ ├── shared.escape_special_chars.php │ │ ├── shared.literal_compiler_param.php │ │ ├── shared.make_timestamp.php │ │ ├── shared.mb_str_replace.php │ │ ├── shared.mb_unicode.php │ │ └── variablefilter.htmlspecialchars.php │ └── sysplugins/ │ ├── smarty_cacheresource.php │ ├── smarty_cacheresource_custom.php │ ├── smarty_cacheresource_keyvaluestore.php │ ├── smarty_data.php │ ├── smarty_internal_block.php │ ├── smarty_internal_cacheresource_file.php │ ├── smarty_internal_compile_append.php │ ├── smarty_internal_compile_assign.php │ ├── smarty_internal_compile_block.php │ ├── smarty_internal_compile_block_child.php │ ├── smarty_internal_compile_block_parent.php │ ├── smarty_internal_compile_break.php │ ├── smarty_internal_compile_call.php │ ├── smarty_internal_compile_capture.php │ ├── smarty_internal_compile_child.php │ ├── smarty_internal_compile_config_load.php │ ├── smarty_internal_compile_continue.php │ ├── smarty_internal_compile_debug.php │ ├── smarty_internal_compile_eval.php │ ├── smarty_internal_compile_extends.php │ ├── smarty_internal_compile_for.php │ ├── smarty_internal_compile_foreach.php │ ├── smarty_internal_compile_function.php │ ├── smarty_internal_compile_if.php │ ├── smarty_internal_compile_include.php │ ├── smarty_internal_compile_include_php.php │ ├── smarty_internal_compile_insert.php │ ├── smarty_internal_compile_ldelim.php │ ├── smarty_internal_compile_make_nocache.php │ ├── smarty_internal_compile_nocache.php │ ├── smarty_internal_compile_parent.php │ ├── smarty_internal_compile_private_block_plugin.php │ ├── smarty_internal_compile_private_foreachsection.php │ ├── smarty_internal_compile_private_function_plugin.php │ ├── smarty_internal_compile_private_modifier.php │ ├── smarty_internal_compile_private_object_block_function.php │ ├── smarty_internal_compile_private_object_function.php │ ├── smarty_internal_compile_private_php.php │ ├── smarty_internal_compile_private_print_expression.php │ ├── smarty_internal_compile_private_registered_block.php │ ├── smarty_internal_compile_private_registered_function.php │ ├── smarty_internal_compile_private_special_variable.php │ ├── smarty_internal_compile_rdelim.php │ ├── smarty_internal_compile_section.php │ ├── smarty_internal_compile_setfilter.php │ ├── smarty_internal_compile_shared_inheritance.php │ ├── smarty_internal_compile_while.php │ ├── smarty_internal_compilebase.php │ ├── smarty_internal_config_file_compiler.php │ ├── smarty_internal_configfilelexer.php │ ├── smarty_internal_configfileparser.php │ ├── smarty_internal_data.php │ ├── smarty_internal_debug.php │ ├── smarty_internal_errorhandler.php │ ├── smarty_internal_extension_handler.php │ ├── smarty_internal_method_addautoloadfilters.php │ ├── smarty_internal_method_adddefaultmodifiers.php │ ├── smarty_internal_method_append.php │ ├── smarty_internal_method_appendbyref.php │ ├── smarty_internal_method_assignbyref.php │ ├── smarty_internal_method_assignglobal.php │ ├── smarty_internal_method_clearallassign.php │ ├── smarty_internal_method_clearallcache.php │ ├── smarty_internal_method_clearassign.php │ ├── smarty_internal_method_clearcache.php │ ├── smarty_internal_method_clearcompiledtemplate.php │ ├── smarty_internal_method_clearconfig.php │ ├── smarty_internal_method_compileallconfig.php │ ├── smarty_internal_method_compilealltemplates.php │ ├── smarty_internal_method_configload.php │ ├── smarty_internal_method_createdata.php │ ├── smarty_internal_method_getautoloadfilters.php │ ├── smarty_internal_method_getconfigvariable.php │ ├── smarty_internal_method_getconfigvars.php │ ├── smarty_internal_method_getdebugtemplate.php │ ├── smarty_internal_method_getdefaultmodifiers.php │ ├── smarty_internal_method_getglobal.php │ ├── smarty_internal_method_getregisteredobject.php │ ├── smarty_internal_method_getstreamvariable.php │ ├── smarty_internal_method_gettags.php │ ├── smarty_internal_method_gettemplatevars.php │ ├── smarty_internal_method_literals.php │ ├── smarty_internal_method_loadfilter.php │ ├── smarty_internal_method_loadplugin.php │ ├── smarty_internal_method_mustcompile.php │ ├── smarty_internal_method_registercacheresource.php │ ├── smarty_internal_method_registerclass.php │ ├── smarty_internal_method_registerdefaultconfighandler.php │ ├── smarty_internal_method_registerdefaultpluginhandler.php │ ├── smarty_internal_method_registerdefaulttemplatehandler.php │ ├── smarty_internal_method_registerfilter.php │ ├── smarty_internal_method_registerobject.php │ ├── smarty_internal_method_registerplugin.php │ ├── smarty_internal_method_registerresource.php │ ├── smarty_internal_method_setautoloadfilters.php │ ├── smarty_internal_method_setdebugtemplate.php │ ├── smarty_internal_method_setdefaultmodifiers.php │ ├── smarty_internal_method_unloadfilter.php │ ├── smarty_internal_method_unregistercacheresource.php │ ├── smarty_internal_method_unregisterfilter.php │ ├── smarty_internal_method_unregisterobject.php │ ├── smarty_internal_method_unregisterplugin.php │ ├── smarty_internal_method_unregisterresource.php │ ├── smarty_internal_nocache_insert.php │ ├── smarty_internal_parsetree.php │ ├── smarty_internal_parsetree_code.php │ ├── smarty_internal_parsetree_dq.php │ ├── smarty_internal_parsetree_dqcontent.php │ ├── smarty_internal_parsetree_tag.php │ ├── smarty_internal_parsetree_template.php │ ├── smarty_internal_parsetree_text.php │ ├── smarty_internal_resource_eval.php │ ├── smarty_internal_resource_extends.php │ ├── smarty_internal_resource_file.php │ ├── smarty_internal_resource_php.php │ ├── smarty_internal_resource_registered.php │ ├── smarty_internal_resource_stream.php │ ├── smarty_internal_resource_string.php │ ├── smarty_internal_runtime_cachemodify.php │ ├── smarty_internal_runtime_cacheresourcefile.php │ ├── smarty_internal_runtime_capture.php │ ├── smarty_internal_runtime_codeframe.php │ ├── smarty_internal_runtime_filterhandler.php │ ├── smarty_internal_runtime_foreach.php │ ├── smarty_internal_runtime_getincludepath.php │ ├── smarty_internal_runtime_inheritance.php │ ├── smarty_internal_runtime_make_nocache.php │ ├── smarty_internal_runtime_tplfunction.php │ ├── smarty_internal_runtime_updatecache.php │ ├── smarty_internal_runtime_updatescope.php │ ├── smarty_internal_runtime_writefile.php │ ├── smarty_internal_smartytemplatecompiler.php │ ├── smarty_internal_template.php │ ├── smarty_internal_templatebase.php │ ├── smarty_internal_templatecompilerbase.php │ ├── smarty_internal_templatelexer.php │ ├── smarty_internal_templateparser.php │ ├── smarty_internal_testinstall.php │ ├── smarty_internal_undefined.php │ ├── smarty_resource.php │ ├── smarty_resource_custom.php │ ├── smarty_resource_recompiled.php │ ├── smarty_resource_uncompiled.php │ ├── smarty_security.php │ ├── smarty_template_cached.php │ ├── smarty_template_compiled.php │ ├── smarty_template_config.php │ ├── smarty_template_resource_base.php │ ├── smarty_template_source.php │ ├── smarty_undefined_variable.php │ ├── smarty_variable.php │ ├── smartycompilerexception.php │ └── smartyexception.php ├── book.sql └── index.php ================================================ FILE CONTENTS ================================================ ================================================ FILE: Admin/Controller/BookController.class.php ================================================ accessPage(); //页面参数 $currentPage = isset($_GET["page"]) ? $_GET["page"] : 1; //当前页数 $eachPerPage = 10; //每页显示条数 //获取搜索条件 if(isset($_GET['keyword']) && !empty($_GET['keyword'])){ $where = "name LIKE '%{$_GET['keyword']}%'"; $parms = array("keyword"=>$_GET['keyword']); $mode = "keyword"; }else if(isset($_GET['bookId']) && !empty($_GET['bookId'])){ $where = "id = '{$_GET['bookId']}'"; $parms = array("bookId"=>$_GET['bookId']); $mode = "bookId"; }else{ $where = "2>1"; $parms = array(); $mode = ""; } $bookModel = new BookModel; //获取图书总数用于计算总页数 $count = $bookModel->rowCount($where); //判断页数是否合法 if($count != 0){ if($currentPage < 1){ $currentPage = 1; }else if($currentPage > ceil($count/$eachPerPage)){ $currentPage = ceil($count/$eachPerPage); } }else{ //记录数为0时,直接从第一页开始,避免offset计算错误 $currentPage = 1; } //获取每页图书信息 $offset = ($currentPage - 1) * $eachPerPage; $books = $bookModel->fetchAllWithJoin($where,"LIMIT {$offset},{$eachPerPage}"); //分页 $pager = new Pager($currentPage,$count,$eachPerPage,"?p=Admin&c=Book&a=index",$parms); $this->smarty->assign("books",$books); $this->smarty->assign("mode",$mode); $this->smarty->assign("pageStr",$pager->page()); $this->smarty->display("Book/index.html"); } //显示图书详情页面 public function detail(){ $this->accessPage(); $id = $_GET['id']; $bookModel = new BookModel; $result = $bookModel->fetchOneWithJoin("book_info.id={$id}"); $this->smarty->assign("book",$result); $this->smarty->display("Book/detail.html"); } //显示添加图书页面 public function add(){ $this->accessPage(); $this->smarty->display("Book/add.html"); } //显示编辑图书页面 public function edit(){ $this->accessPage(); $id = $_GET['id']; $bookModel = new BookModel; $book = $bookModel->fetchOne("id={$id}"); $this->smarty->assign("book",$book); $this->smarty->display("Book/edit.html"); } //Json添加图书接口 public function insert(){ $this->accessJson(); $bookInfo['name'] = $_POST['name']; $bookInfo['author'] = $_POST['author']; $bookInfo['press'] = $_POST['press']; $bookInfo['press_time'] = $_POST['pressTime']; $bookInfo['price'] = $_POST['price']; $bookInfo['ISBN'] = $_POST['ISBN']; $bookInfo['desc'] = $_POST['desc']; //验证信息是否填写完整 if(in_array("",$bookInfo)){ $this->sendJsonMessage("请输入完整信息",1); } $bookModel = new BookModel; if($bookModel->insert($bookInfo)){ $this->sendJsonMessage("添加成功",0); }else{ $this->sendJsonMessage("添加失败",1); } } //Json接口修改图书 public function update(){ $this->accessJson(); $id = $_POST['id']; $bookInfo['name'] = $_POST['name']; $bookInfo['author'] = $_POST['author']; $bookInfo['press'] = $_POST['press']; $bookInfo['press_time'] = $_POST['press_time']; $bookInfo['price'] = $_POST['price']; $bookInfo['ISBN'] = $_POST['ISBN']; $bookInfo['desc'] = $_POST['desc']; //验证信息是否填写完整 if(in_array("",$bookInfo)){ $this->sendJsonMessage("请输入完整信息",1); } $bookModel = new BookModel; if($bookModel->update($bookInfo,"id={$id}")){ $this->sendJsonMessage("修改成功",0); }else{ $this->sendJsonMessage("修改失败",1); } } //Json删除图书接口 public function delete(){ $this->accessJson(); $id = $_POST['id']; $bookModel = new BookModel; $borrowModel = new BorrowModel; if($bookModel->delete("id={$id}") && $borrowModel->delete("book_id={$id}")){ $this->sendJsonMessage("删除成功",0); }else{ $this->sendJsonMessage("删除失败",1); } } } ================================================ FILE: Admin/Controller/BorrowController.class.php ================================================ accessPage(); $this->smarty->display("Borrow/index.html"); } //Json借书和还书接口 public function manage(){ $this->accessJson(); $bookId = $_POST['bookId']; $userId = $_POST['userId']; $action = $_POST['action']; if($userId == "" || $bookId == ""){ $this->sendJsonMessage("请填写完整信息",1); } $borrowModel = new BorrowModel; if($action == "borrow"){ //借书 if($borrowModel->canBorrow($bookId,$userId)){ $data = array( "book_id" => $bookId, "user_id" => $userId, "borrow_date" => date("Y-m-d"), "back_date" => date("Y-m-d",strtotime("+2 month")) ); if($borrowModel->insert($data)){ $this->sendJsonMessage("借书成功",0); }else{ $this->sendJsonMessage("借书失败",1); } }else{ $this->sendJsonMessage("信息错误或该书已借出",1); } }else if($action == "return"){ //还书 if($borrowModel->canReturn($bookId,$userId)){ if($borrowModel->delete("book_id={$bookId} AND user_id={$userId}")){ $this->sendJsonMessage("还书成功",0); }else{ $this->sendJsonMessage("还书失败",1); } }else{ $this->sendJsonMessage("信息错误或该用户未借此书",1); } }else{ $this->sendJsonMessage("参数错误",1); } } //Json续借接口 public function prolong(){ $this->accessJson(); //未传参中断 if(!isset($_POST['bookId']) || !isset($_POST['userId'])){ $this->sendJsonMessage("缺少参数",1); } $bookId = $_POST['bookId']; $userId = $_POST['userId']; $borrowModel = new BorrowModel; $result = $borrowModel->fetchOne("book_id={$bookId} AND user_id={$userId}"); //没有借书就不能续借 if(empty($result)){ $this->sendJsonMessage("该用户没有借阅此书",1); } //超期不能续借 if(strtotime($result['back_date']) < time()){ $this->sendJsonMessage("超期的书不能续借",1); } //计算应还时间 $backTime = date("Y-m-d",strtotime("+1 month",strtotime($result['back_date']))); $data = array("back_date"=>$backTime); if($borrowModel->update($data,"book_id={$bookId} AND user_id={$userId}")){ $this->sendJsonMessage("续借成功",0); }else{ $this->sendJsonMessage("续借失败",1); } } //Json还书接口 public function returnBook(){ $this->accessJson(); $bookId = $_POST['bookId']; $userId = $_POST['userId']; $borrowModel = new BorrowModel; if($borrowModel->canReturn($bookId,$userId)){ if($borrowModel->delete("book_id={$bookId} AND user_id={$userId}")){ $this->sendJsonMessage("还书成功",0); }else{ $this->sendJsonMessage("还书失败",1); } }else{ $this->sendJsonMessage("信息错误或该用户未借此书",1); } } } ================================================ FILE: Admin/Controller/IndexController.class.php ================================================ accessPage(); $userModel = new UserModel; //查询用户人数 $userNum = $userModel->rowCount("admin != 1"); $bookModel = new BookModel; //查询图书数量 $bookNum = $bookModel->rowCount(); $this->smarty->assign("userNum",$userNum); $this->smarty->assign("bookNum",$bookNum); $this->smarty->display("Index/index.html"); } } ================================================ FILE: Admin/Controller/UserController.class.php ================================================ accessPage(); //页面参数 $currentPage = isset($_GET["page"]) ? $_GET["page"] : 1; //当前页数 $eachPerPage = 10; //每页显示条数 //获取搜索条件 if(isset($_GET['name']) && !empty($_GET['name'])){ $where = "name LIKE '%{$_GET['name']}%'"; $parms = array("name"=>$_GET['name']); $mode = "name"; }else if(isset($_GET['userId']) && !empty($_GET['userId'])){ $where = "id = '{$_GET['userId']}'"; $parms = array("userId"=>$_GET['userId']); $mode = "userId"; }else{ $where = "2>1"; $parms = array(); $mode = ""; } $userModel = new UserModel; //获取记录条数,用于计算总页面数目 $count = $userModel->rowCount($where); //判断页数是否合法 if($count != 0){ if($currentPage < 1){ $currentPage = 1; }else if($currentPage > ceil($count/$eachPerPage)){ $currentPage = ceil($count/$eachPerPage); } }else{ //记录数为0时,直接从第一页开始,避免offset计算错误 $currentPage = 1; } //获取每页用户信息 $offset = ($currentPage - 1) * $eachPerPage; $users = $userModel->fetchAllUser($where,"LIMIT {$offset},{$eachPerPage}"); //分页 $pager = new Pager($currentPage,$count,$eachPerPage,"?p=Admin&c=User&a=index",$parms); $this->smarty->assign("users",$users); $this->smarty->assign("mode",$mode); $this->smarty->assign("pageStr",$pager->page()); $this->smarty->display("User/index.html"); } //显示添加用户界面 public function add(){ $this->accessPage(); $this->smarty->display("User/add.html"); } //显示管理用户界面 public function manage(){ $this->accessPage(); $id = $_GET['id']; $userModel = new UserModel; //获取用户信息 $userInfo = $userModel->fetchOne("id={$id}"); //阻止url非法传参 if(empty($userInfo)){ echo ""; die(); } $borrowModel = new BorrowModel; //获取用户借阅信息 $borrowInfo = $borrowModel->getBorrowInfo("borrow_list.user_id={$id}"); $this->smarty->assign("userInfo",$userInfo); $this->smarty->assign("borrowInfo",$borrowInfo); $this->smarty->display("User/manage.html"); } //Json添加用户接口 public function insert(){ $this->accessJson(); $user['id'] = $_POST['userId']; $user['pwd'] = md5($_POST['password']); $user['name'] = $_POST['name']; $user['class'] = $_POST['class']; $user['status'] = $_POST['status'] ? 1 : 0; $usermodel = new UserModel; if(in_array("",$user)){ $this->sendJsonMessage("请将信息填写完整",1); } if($usermodel->rowCount("id={$user['id']}")){ $this->sendJsonMessage("该用户ID已存在",1); } if($usermodel->insert($user)){ $this->sendJsonMessage("添加用户成功",0); }else{ $this->sendJsonMessage("添加用户失败",1); } } //Json修改用户接口 public function changeInfo(){ $this->accessJson(); $id = $_POST['userId']; $data['name'] = $_POST['name']; $data['class'] = $_POST['class']; if(in_array("",$data)){ $this->sendJsonMessage("请填写完整信息",1); } $userModel = new UserModel; if($userModel->update($data,"id={$id}")){ $this->sendJsonMessage("修改成功",0); }else{ $this->sendJsonMessage("修改失败",1); } } //Json挂失用户接口 public function lost(){ $this->accessJson(); $id = $_POST['userId']; $userModel = new UserModel; if($userModel->update(array("status"=>0),"id={$id}")){ $this->sendJsonMessage("挂失成功",0); }else{ $this->sendJsonMessage("挂失失败",1); } } //Json启用用户接口 public function open(){ $this->accessJson(); $id = $_POST['userId']; $userModel = new UserModel; if($userModel->update(array("status"=>1),"id={$id}")){ $this->sendJsonMessage("启用成功",0); }else{ $this->sendJsonMessage("启用失败",1); } } //Json修改用户密码接口 public function changePwd(){ $this->accessJson(); if(!$_POST['pwd']){ $this->sendJsonMessage("请输入密码",1); } $id = $_POST['userId']; $pwd = md5($_POST['pwd']); $userModel = new UserModel; if($userModel->update(array("pwd"=>$pwd),"id={$id}")){ $this->sendJsonMessage("修改成功",0); }else{ $this->sendJsonMessage("修改失败",1); } } //Json删除用户接口 public function delete(){ $this->accessJson(); $id = $_POST['userId']; $userModel = new UserModel; $borrowModel = new BorrowModel; if($userModel->delete("id={$id}") && $borrowModel->delete("user_id={$id}")){ $this->sendJsonMessage("删除成功",0); }else{ $this->sendJsonMessage("删除失败",1); } } } ================================================ FILE: Admin/Model/BookModel.class.php ================================================ 1",$limit = ""){ $sql = "SELECT id,name,author,user_id FROM {$this->table} "; $sql .= "LEFT JOIN borrow_list ON id=borrow_list.book_id "; $sql .= "WHERE {$where} "; $sql .= "{$limit}"; $result = $this->Db->query($sql); //条数为1时,把一维数组转换成二维数组,避免某些foreach循环出错 if(count($result) == count($result,1) && !empty($result)){ $result = array($result); } return $result; } public function fetchOneWithJoin($where = "2>1"){ $sql = "SELECT {$this->table}.*,borrow_list.back_date,user.name AS user_name FROM {$this->table} "; $sql .= "LEFT JOIN borrow_list ON {$this->table}.id=borrow_list.book_id "; $sql .= "LEFT JOIN user ON user.id=borrow_list.user_id "; $sql .= "WHERE {$where} "; $sql .= "LIMIT 1"; return $this->Db->query($sql); } } ================================================ FILE: Admin/Model/BorrowModel.class.php ================================================ table})"; if($this->Db->rowCount($sql)){ return true; }else{ return false; } } public function canReturn($bookId,$userId){ $sql = "SELECT * FROM {$this->table} "; $sql .= "WHERE user_id='{$userId}' AND book_id='{$bookId}'"; if($this->Db->rowCount($sql)){ return true; }else{ return false; } } public function getBorrowInfo($where){ $sql = "SELECT book_info.id,book_info.name,borrow_list.borrow_date,borrow_list.back_date FROM book_info "; $sql .= "LEFT JOIN {$this->table} ON book_info.id=borrow_list.book_id "; $sql .= "WHERE {$where}"; $result = $this->Db->query($sql); //条数为1时,把一维数组转换成二维数组,避免某些foreach循环出错 if(count($result) == count($result,1) && !empty($result)){ $result = array($result); } return $result; } } ================================================ FILE: Admin/Model/UserModel.class.php ================================================ 1",$limit = ""){ $sql = "SELECT id,name,class,status,last_login_time FROM {$this->table} "; $sql .= "WHERE {$where} AND admin!=1 "; $sql .= "{$limit}"; $result = $this->Db->query($sql); //条数为1时,把一维数组转换成二维数组,避免某些foreach循环出错 if(count($result) == count($result,1) && !empty($result)){ $result = array($result); } return $result; } //重写rowCount方法,将管理员排除在统计范围外 public function rowCount($where = "2>1") { $sql = "SELECT * FROM {$this->table} "; $sql .= "WHERE {$where} AND admin!=1"; return $this->Db->rowCount($sql); } } ================================================ FILE: Admin/View/Book/add.html ================================================ 图书馆管理系统
添加图书
图书名
作者
出版社
出版时间
价格
ISBN
================================================ FILE: Admin/View/Book/detail.html ================================================ 图书馆管理系统
图书详情
图书名:
作者:
出版社:
出版时间:
价格:
ISBN:
借出人
应还日期
================================================ FILE: Admin/View/Book/edit.html ================================================ 图书馆管理系统
编辑图书
图书名:
作者:
出版社:
出版时间:
价格:
ISBN:
================================================ FILE: Admin/View/Book/index.html ================================================ 图书馆管理系统
}value='{<$smarty.get.keyword>}'{}value='{<$smarty.get.bookId>}'{}>
添加图书 {} {} {} {} {} {} {}
图书号 图书名 作者 状态 操作
无记录!
{<$book.id>} {<$book.name>} {<$book.author>}在馆已借出 修改 
{<$pageStr>}
================================================ FILE: Admin/View/Borrow/index.html ================================================ 图书馆管理系统
借阅管理(模拟机器扫描操作)
读者ID
图书号
操作:     
    
================================================ FILE: Admin/View/Index/index.html ================================================ 图书馆管理系统

{<$smarty.session.userId>}管理员,你好!

当前共有{<$bookNum>}本图书

当前共有{<$userNum>}位读者

上次登录时间:

{<$smarty.session.last_login_time>}

================================================ FILE: Admin/View/User/add.html ================================================ 图书馆管理系统
添加用户
用户ID
密码
姓名
班级
状态
================================================ FILE: Admin/View/User/index.html ================================================ 图书馆管理系统
}value='{<$smarty.get.name>}'{}value='{<$smarty.get.userId>}'{}>
添加用户 {} {} {} {} {} {} {}
用户ID 姓名 班级 最后登陆时间 状态 操作
无记录!
{<$user.id>} {<$user.name>} {<$user.class>} {<$user.last_login_time>}正常挂失 详情
{<$pageStr>} ================================================ FILE: Admin/View/User/manage.html ================================================ 图书馆管理系统
用户信息

用户ID:{<$userInfo.id>}

用户姓名:{<$userInfo.name>}

用户班级:{<$userInfo.class>}

用户状态:{}正常{}挂失{}

用户借阅信息
{} {} {} }class="danger"{}> {}
图书号 图书名称 借书时间 应还时间 操作
无记录!
{<$one.id>} {<$one.name>} {<$one.borrow_date>} {<$one.back_date>}  
================================================ FILE: Base/Base.class.php ================================================ $action(); }else{ echo "a参数错误"; die(); } } } ================================================ FILE: Base/BaseController.class.php ================================================ smarty = MySmarty::getInstance(); } //验证页面权限 protected function accessPage(){ if(isset($_SESSION['userId'])){ if($_SESSION['admin'] == 1 && P == "Admin"); else if($_SESSION['admin'] == 0 && P == "Home"); else{ $p = $_SESSION['admin'] ? "Admin" : "Home"; header("location:?p={$p}&c=Index&a=index"); die(); } }else{ header("location:?p=Common&c=Login&a=index"); die(); } } //验证接口权限 protected function accessJson(){ header("Content-Type:application/json"); if(isset($_SESSION['userId'])){ if($_SESSION['admin'] == 1 && P == "Admin"); else if($_SESSION['admin'] == 0 && P == "Home"); else{ $this->sendJsonMessage("操作权限不足",1); } }else{ $this->sendJsonMessage("未登陆",1); } } //返回Json信息 protected function sendJsonMessage($message,$code){ $message = array("message"=>$message,"code"=>$code); echo json_encode($message,JSON_UNESCAPED_UNICODE); die(); } } ================================================ FILE: Base/BaseModel.class.php ================================================ Db = Db::getInstance(); } //获取一条数据 public function fetchOne($where){ $sql = "SELECT * FROM {$this->table} WHERE {$where}"; return $this->Db->query($sql); } //获取全部数据 public function fetchAll($where = "2>1"){ $sql = "SELECT * FROM {$this->table} WHERE {$where}"; $result = $this->Db->query($sql); //条数为1时,把一维数组转换成二维数组,避免某些foreach循环出错 if(count($result) == count($result,1) && !empty($result)){ $result = array($result); } return $result; } //获取数据条数 public function rowCount($where = "2>1"){ $sql = "SELECT * FROM {$this->table} WHERE {$where}"; return $this->Db->rowCount($sql); } //插入数据 public function insert($data){ $keys = ""; $values = ""; foreach($data as $key=>$value){ $keys .= "`{$key}`,"; if($value == ""){ $values .= "null,"; }else{ $values .= "'{$value}',"; } } $keys = rtrim($keys,","); $values = rtrim($values,","); $sql = "INSERT INTO {$this->table}({$keys}) VALUE({$values})"; return $this->Db->exec($sql); } //更新数据 public function update($data,$where){ $update = ""; foreach($data as $key => $value){ $update .= "`{$key}`='{$value}',"; } $update = rtrim($update,","); $sql = "UPDATE {$this->table} SET {$update} WHERE {$where}"; return $this->Db->exec($sql); } //删除数据 public function delete($where){ $sql = "DELETE FROM {$this->table} WHERE {$where}"; return $this->Db->exec($sql); } } ================================================ FILE: Base/Conf.php ================================================ "127.0.0.1", 'db_user' => "root", 'db_pwd' => "root", 'db_name' => "mybook", 'db_port' => "3306", 'charset' => "utf8", //默认路由配置 'default_plantform' => "Common", 'default_controller' => "Login", 'default_action' => "index" ); ================================================ FILE: Common/Controller/LoginController.class.php ================================================ checkLogin(); $this->smarty->display("login.html"); } public function showVerify(){ new Verify; } //Json登陆接口 public function login(){ header("Content-Type:application/json"); $rightCode = strtolower($_SESSION['verifyCode']);//正确的验证码 $code = strtolower($_POST['verify']); //输入的验证码 $userId = htmlentities($_POST['userId']); //账号 $password = md5($_POST['password']); //密码 //先验证验证码,正确再验证账号密码,减小数据库压力 if($code != $rightCode){ $this->sendJsonMessage("验证码错误",1); } //验证账号密码 $userModel = new UserModel; $where = "id='{$userId}' and pwd='{$password}'"; $result = $userModel->fetchOne($where); if(!empty($result) && $result['status'] == 1){ $_SESSION['userId'] = $userId; $_SESSION['admin'] = $result['admin']; $_SESSION['last_login_time'] = $result['last_login_time']; $message = array("message"=>"OK","code"=>0,"admin"=>"{$result['admin']}"); //更新最后登陆时间 $time = date('Y-m-d H:i:s'); $userModel->update(array("last_login_time"=>$time),$where); }else if(!empty($result) && $result['status'] == 0){ $message = array("message"=>"该账户已挂失,请联系管理员解决","code"=>1); }else{ $message = array("message"=>"账号或密码错误","code"=>1); //销毁验证码session使其重新生成 $_SESSION = array(); session_destroy(); } echo json_encode($message,JSON_UNESCAPED_UNICODE); } //退出登陆 public function logout(){ $_SESSION = array(); session_destroy(); header("location:?p=Common&c=Login&a=index"); } } ================================================ FILE: Common/Model/UserModel.class.php ================================================ 图书馆管理系统
================================================ FILE: Home/Controller/BookController.class.php ================================================ accessPage(); //页面参数 $currentPage = isset($_GET["page"]) ? $_GET["page"] : 1; //当前页数 $eachPerPage = 10; //每页显示条数 //获取搜索条件 if(isset($_GET['keyword']) && !empty($_GET['keyword'])){ $where = "name LIKE '%{$_GET['keyword']}%'"; $parms = array("keyword"=>$_GET['keyword']); $mode = "keyword"; }else if(isset($_GET['bookId']) && !empty($_GET['bookId'])){ $where = "id = '{$_GET['bookId']}'"; $parms = array("bookId"=>$_GET['bookId']); $mode = "bookId"; }else{ $where = "2>1"; $parms = array(); $mode = ""; } $bookModel = new BookModel; //获取图书总数用于计算总页数 $count = $bookModel->rowCount($where); //判断页数是否合法 if($count != 0){ if($currentPage < 1){ $currentPage = 1; }else if($currentPage > ceil($count/$eachPerPage)){ $currentPage = ceil($count/$eachPerPage); } }else{ //记录数为0时,直接从第一页开始,避免offset计算错误 $currentPage = 1; } //获取每页图书信息 $offset = ($currentPage - 1) * $eachPerPage; $books = $bookModel->fetchAllWithJoin($where,"LIMIT {$offset},{$eachPerPage}"); //分页 $pager = new Pager($currentPage,$count,$eachPerPage,"?p=Home&c=Book&a=index",$parms); $this->smarty->assign("books",$books); $this->smarty->assign("mode",$mode); $this->smarty->assign("pageStr",$pager->page()); $this->smarty->display("Book/index.html"); } public function detail(){ $this->accessPage(); $id = $_GET['id']; $bookModel = new BookModel; $result = $bookModel->fetchOneWithJoin("book_info.id={$id}"); $this->smarty->assign("book",$result); $this->smarty->display("Book/detail.html"); } } ================================================ FILE: Home/Controller/BorrowController.class.php ================================================ accessJson(); //未传参中断 if(!isset($_POST['bookId'])){ $this->sendJsonMessage("缺少bookId参数",1); } $bookId = $_POST['bookId']; $borrowModel = new BorrowModel; $result = $borrowModel->fetchOne("book_id={$bookId} AND user_id={$_SESSION['userId']}"); //没有借书就不能续借 if(empty($result)){ $this->sendJsonMessage("该用户没有借阅此书",1); } //超期不能续借 if(strtotime($result['back_date']) < time()){ $this->sendJsonMessage("超期的书不能续借",1); } //计算应还时间 $backTime = date("Y-m-d",strtotime("+1 month",strtotime($result['back_date']))); $data = array("back_date"=>$backTime); if($borrowModel->update($data,"book_id={$bookId} AND user_id={$_SESSION['userId']}")){ $this->sendJsonMessage("续借成功",0); }else{ $this->sendJsonMessage("续借失败",1); } } } ================================================ FILE: Home/Controller/IndexController.class.php ================================================ accessPage(); //用户信息 $userModel = new UserModel; $userName = $userModel->fetchOne("id={$_SESSION['userId']}")['name']; //图书总数 $bookModel = new BookModel; $bookNum = $bookModel->rowCount(); //借阅信息 $borrowModel = new BorrowModel; $bookInfo = $borrowModel->fetchAll("user_id={$_SESSION['userId']}"); $borrowBookNum = count($bookInfo); $outDateBook = 0; foreach($bookInfo as $value){ if(strtotime($value['back_date']) < time()){ $outDateBook++; } } $this->smarty->assign("userName",$userName); $this->smarty->assign("bookNum",$bookNum); $this->smarty->assign("borrowBookNum",$borrowBookNum); $this->smarty->assign("outDateBook",$outDateBook); $this->smarty->display("Index/index.html"); } } ================================================ FILE: Home/Controller/UserController.class.php ================================================ accessPage(); //用户信息 $userModel = new UserModel; $userInfo = $userModel->fetchOne("id={$_SESSION['userId']}"); //借阅书籍详情 $borrowModel = new BorrowModel; $borrowInfo = $borrowModel->getBorrowInfo(); $this->smarty->assign("borrowInfo",$borrowInfo); $this->smarty->assign("userInfo",$userInfo); $this->smarty->display("User/index.html"); } //Json挂失接口 public function lost(){ $this->accessJson(); $id = $_SESSION['userId']; $userModel = new UserModel; if($userModel->update(array("status"=>0),"id={$id}")){ //挂失成功后销毁session,使登陆失效 $_SESSION = array(); session_destroy(); $this->sendJsonMessage("挂失成功",0); }else{ $this->sendJsonMessage("挂失失败",1); } } //Json修改密码接口 public function changePwd(){ $this->accessJson(); $originPwd = md5($_POST['originPwd']); $newPwd = md5($_POST['newPwd']); $confrimPwd = md5($_POST['confirmPwd']); //确认密码二次验证,防止非法提交 if($newPwd != $confrimPwd){ $this->sendJsonMessage("两次输入的密码不一致",1); } $userModel = new UserModel; if($userModel->rowCount("id={$_SESSION['userId']} and pwd='{$originPwd}'")){ if($userModel->update(array("pwd"=>$newPwd),"id={$_SESSION['userId']} and pwd='{$originPwd}'")){ //更改密码后销毁当前session $_SESSION = array(); session_destroy(); $this->sendJsonMessage("密码修改成功",0); }else{ $this->sendJsonMessage("密码修改失败",1); } }else{ $this->sendJsonMessage("原密码错误",1); } } } ================================================ FILE: Home/Model/BookModel.class.php ================================================ 1",$limit = ""){ $sql = "SELECT id,name,author,user_id FROM {$this->table} "; $sql .= "LEFT JOIN borrow_list ON id=borrow_list.book_id "; $sql .= "WHERE {$where} "; $sql .= "{$limit}"; $result = $this->Db->query($sql); //条数为1时,把一维数组转换成二维数组,避免某些foreach循环出错 if(count($result) == count($result,1) && !empty($result)){ $result = array($result); } return $result; } public function fetchOneWithJoin($where = "2>1"){ $sql = "SELECT {$this->table}.*,borrow_list.back_date,user.name AS user_name FROM {$this->table} "; $sql .= "LEFT JOIN borrow_list ON {$this->table}.id=borrow_list.book_id "; $sql .= "LEFT JOIN user ON user.id=borrow_list.user_id "; $sql .= "WHERE {$where} "; $sql .= "LIMIT 1"; return $this->Db->query($sql); } } ================================================ FILE: Home/Model/BorrowModel.class.php ================================================ table},book_info "; $sql .= "WHERE {$this->table}.book_id=book_info.id AND user_id={$_SESSION['userId']}"; $result = $this->Db->query($sql); //条数为1时,把一维数组转换成二维数组,避免某些foreach循环出错 if(count($result) == count($result,1) && !empty($result)){ $result = array($result); } return $result; } } ================================================ FILE: Home/Model/UserModel.class.php ================================================ 图书馆管理系统
图书详情
图书名:
作者:
出版社:
出版时间:
价格:
ISBN:
借出人
应还日期
================================================ FILE: Home/View/Book/index.html ================================================ 图书馆管理系统
}value='{<$smarty.get.keyword>}'{}value='{<$smarty.get.bookId>}'{}>
{} {} {} {} {} {} {}
图书号 图书名 作者 状态
无记录!
{<$book.id>} {<$book.name>} {<$book.author>}在馆已借出
{<$pageStr>}
================================================ FILE: Home/View/Index/index.html ================================================ 图书馆管理系统

{<$userName>}同学,你好!

当前共有{<$bookNum>}本图书

你已借{<$borrowBookNum>}本书

已超期{<$outDateBook>}本书

上次登录时间:

{<$smarty.session.last_login_time>}

================================================ FILE: Home/View/User/index.html ================================================ 图书馆管理系统
用户信息

用户账号:{<$smarty.session.userId>}

用户姓名:{<$userInfo.name>}

用户班级:{<$userInfo.class>}

用户状态:{}正常{}挂失{}

我的借阅信息
{} {} {} }class="danger"{}> {}
图书号 图书名称 借书时间 应还时间 操作
无记录!
{<$one.book_id>} {<$one.name>} {<$one.borrow_date>} {<$one.back_date>}
================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # 图书管理系统 >这个图书管理系统是我学完PHP时写的一个练手项目,功能参考了自己学校的图书管理系统。为了锻炼自己的动手能力以及加深对代码的理解,前端和后端均由自己完成,前端使用了一些基本的框架(毕竟我主攻后端开发方向),后端大部分要用到的功能都是自己从底层实现并封装,基本没有用到第三方框架。总体来说还是比较简陋的,在某些地方可能存在缺陷或者漏洞。 ### 基本功能 + 用户 + 查询图书状态(能够进行搜索) + 管理自己的账户,如:修改密码、挂失等 + 对已借的图书进行续借操作 + 管理员 + 管理图书,增删改查 + 管理用户,如修改密码、挂失、删除等 + 借阅管理 ### 特点 + 数据库中的数据来自豆瓣图书Top250 + 前端页面使用`jQuery`+`BootStrap`实现,勉强能看(前端能力实在有限) + 后端采用MVC的思想,参考`ThinkPHP`框架的结构和思路,自己实现并封装了一个简单的MVC框架(View层使用了Smarty模板引擎) + 后端使用的数据库工具类、验证码类、分页类均由自己实现并封装 + 可通过配置文件(`Base/Conf.php`)对项目进行配置(数据库设置和默认路由设置) + 前端大部分数据通过Ajax与后端进行交互,页面跳转较少 ### 部署注意事项 1. `index.php`为整个项目的入口文件 2. 确保你的PHP开启了`gd2`、`mysqli`扩展 3. 将项目中的book.sql中的数据导入到数据库,**并在`Base/Conf.php`修改数据库连接信息(点击登录没反应可能就是没有设置正确的连接信息)** 4. 默认管理员账号为`10086`,密码为`admin` 5. 默认一般用户的密码为`123456`,初始的账号有`10000`、`10001`、`10002`、`10010`,其中`10010`默认被挂失 ### 部分截图 #### 登陆界面 ![](https://img2018.cnblogs.com/blog/1556823/201901/1556823-20190127193126712-133882588.png) #### 图书管理 ![](https://img2018.cnblogs.com/blog/1556823/201901/1556823-20190127193136627-359174758.png) ![](https://img2018.cnblogs.com/blog/1556823/201901/1556823-20190127193145620-32043274.png) #### 用户管理 ![](https://img2018.cnblogs.com/blog/1556823/201901/1556823-20190127193149631-864366552.png) ![](https://img2018.cnblogs.com/blog/1556823/201901/1556823-20190127193153638-1859828350.png) #### 借阅管理 ![](https://img2018.cnblogs.com/blog/1556823/201901/1556823-20190127193156695-1693862812.png) ================================================ FILE: Tool/Db.class.php ================================================ db_host = $GLOBALS['conf']['db_host']; $this->db_user = $GLOBALS['conf']['db_user']; $this->db_pwd = $GLOBALS['conf']['db_pwd']; $this->db_name = $GLOBALS['conf']['db_name']; $this->db_port = $GLOBALS['conf']['db_port']; $this->charset = $GLOBALS['conf']['charset']; $this->connect(); $this->setCharSet(); } private function connect(){ @$this->mysqli = new \mysqli($this->db_host,$this->db_user,$this->db_pwd,$this->db_name,$this->db_port); if($this->mysqli->connect_errno != 0){ echo "

MySql连接错误!

"; echo "错误信息:".$this->mysqli->connect_error; die(); } } private function setCharSet(){ $this->mysqli->set_charset($this->charset); } //判断sql语句是否出错 private function isErr(){ if($this->mysqli->errno != 0){ echo "

Sql语句错误

"; echo "错误信息:".$this->mysqli->error; die(); } } //初始化Db类只需执行该静态方法 public static function getInstance(){ if(!(self::$Db instanceof self)){ self::$Db = new self; } return self::$Db; } public function query($sql,$mode = 1){ //$mode解释: 1:关联数组 2:索引数组 3:混合数组 if(strtoupper(substr($sql,0,6)) != "SELECT"){ die("query函数只能接受SELECT语句!"); } @$result = $this->mysqli->query($sql); $this->isErr(); //判断语句是否出错 $data = array(); //返回的结果数组 if($this->mysqli->affected_rows == 1){ //只有一行数据时直接返回一维数组 $data = $result->fetch_array($mode); }else{ //有多行数据是返回二维数组 while($row = $result->fetch_array($mode)){ $data[] = $row; } } return $data; } public function exec($sql){ if(strtoupper(substr($sql,0,6)) == "SELECT"){ die("exec函数只能接受非SELECT语句!"); } if(@!$this->mysqli->query($sql)){ $this->isErr(); //判断语句是否出错 }else{ return true; } } public function rowCount($sql){ @$this->mysqli->query($sql); $this->isErr(); //判断语句是否出错 return $this->mysqli->affected_rows; } }; ================================================ FILE: Tool/MySmarty.class.php ================================================ clearCompiledTemplate(); self::$smarty->left_delimiter = "{<"; self::$smarty->right_delimiter = ">}"; self::$smarty->setCompileDir(sys_get_temp_dir()); self::$smarty->setTemplateDir(VIEWPATH); } //获取smarty实例 public static function getInstance(){ if(!(self::$smarty instanceof \smarty)){ self::$smarty = new \smarty; self::smartyInit(); } return self::$smarty; } } ================================================ FILE: Tool/Pager.class.php ================================================ currentPage = $currentPage; $this->total = $total; $this->each = $each; $this->url = $url; $this->parms = $parms; $this->pageNum = ceil($total/$each); $this->parmsParse(); $this->firstInit(); $this->middleInit(); $this->lastInit(); } public function page(){ //页数为1时不输出分页 if($this->pageNum <= 1){ $this->pageStr = ""; } return $this->pageStr; } //解析参数数组 private function parmsParse(){ $parmsStr = ""; $url = $this->url; $pre = $this->currentPage-1; $next = $this->currentPage+1; foreach($this->parms as $key=>$value){ $parmsStr .= "{$key}={$value}&"; } if(strstr($url,"?")){ //url带问号说明有参数,后面加&方便参数连接 $url .= "&"; }else{ //url不带问号说明无参数,后面加?准备连接参数或页数 $url .= "?"; } $this->urlStr = $url.$parmsStr."page="; $this->pre = $url.$parmsStr."page={$pre}"; $this->next = $url.$parmsStr."page={$next}"; } //上一页 private function firstInit(){ if($this->currentPage == 1){ //在第一页时上一页失效 $disable = "class='disabled'"; $tag = "span"; $link = ""; }else{ //不在第一页时 $disable = ""; $tag = "a"; $link = "href='{$this->pre}'"; } $this->pageStr =""; } } ================================================ FILE: Tool/Verify.class.php ================================================ width = $width; $this->height = $height; $this->picInit(); $this->createPic(); $this->writeCode(); $this->writeNoise(); $this->outPutPic(); } private function picInit(){ header("Content-Type:image/png"); } private function createPic(){ //创建画布 $this->picRes = imagecreatetruecolor($this->width, $this->height); //给画布分配颜色 $color = imagecolorallocate($this->picRes, rand(150, 255), rand(150, 255), rand(150, 255)); //给画布上色 imagefill($this->picRes, 0, 0, $color); } private function writeCode(){ $fontDir = ROOT . "Resources" . DS . "Verify.ttf"; $codeLib = "abcdefghjknmpqrstuvwxyzABCDEFGHIJKLNMPQRSTUVWXYZ123456789"; $code = ""; for ($i = 0; $i < 4; $i++) { //验证码分配颜色 $color = imagecolorallocate($this->picRes, rand(50, 150), rand(50, 150), rand(50, 150)); //生成随机单个验证码 $oneCode = $codeLib[rand(0,strlen($codeLib)-1)]; //绘制单个验证码 imagettftext($this->picRes,18,rand(-10,10),2+($i*14),25,$color,$fontDir,$oneCode); //保存整个验证码并写入session $code .= $oneCode; } $_SESSION["verifyCode"] = $code; } private function writeNoise(){ for($i = 0; $i < 4; $i++){ $color = imagecolorallocate($this->picRes,rand(50, 150), rand(50, 150), rand(50, 150)); imageline($this->picRes,rand(0,60),rand(0,34),rand(0,60),rand(0,34),$color); } } private function outPutPic(){ imagepng($this->picRes); } } ================================================ FILE: Tool/smarty-3.1.32/libs/Autoloader.php ================================================ 'Smarty.class.php', 'smartybc' => 'SmartyBC.class.php',); /** * Registers Smarty_Autoloader backward compatible to older installations. * * @param bool $prepend Whether to prepend the autoloader or not. */ public static function registerBC($prepend = false) { /** * register the class autoloader */ if (!defined('SMARTY_SPL_AUTOLOAD')) { define('SMARTY_SPL_AUTOLOAD', 0); } if (SMARTY_SPL_AUTOLOAD && set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false ) { $registeredAutoLoadFunctions = spl_autoload_functions(); if (!isset($registeredAutoLoadFunctions[ 'spl_autoload' ])) { spl_autoload_register(); } } else { self::register($prepend); } } /** * Registers Smarty_Autoloader as an SPL autoloader. * * @param bool $prepend Whether to prepend the autoloader or not. */ public static function register($prepend = false) { self::$SMARTY_DIR = defined('SMARTY_DIR') ? SMARTY_DIR : dirname(__FILE__) . DIRECTORY_SEPARATOR; self::$SMARTY_SYSPLUGINS_DIR = defined('SMARTY_SYSPLUGINS_DIR') ? SMARTY_SYSPLUGINS_DIR : self::$SMARTY_DIR . 'sysplugins' . DIRECTORY_SEPARATOR; if (version_compare(PHP_VERSION, '5.3.0', '>=')) { spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend); } else { spl_autoload_register(array(__CLASS__, 'autoload')); } } /** * Handles auto loading of classes. * * @param string $class A class name. */ public static function autoload($class) { if ($class[ 0 ] !== 'S' && strpos($class, 'Smarty') !== 0) { return; } $_class = strtolower($class); if (isset(self::$rootClasses[ $_class ])) { $file = self::$SMARTY_DIR . self::$rootClasses[ $_class ]; if (is_file($file)) { include $file; } } else { $file = self::$SMARTY_SYSPLUGINS_DIR . $_class . '.php'; if (is_file($file)) { include $file; } } return; } } ================================================ FILE: Tool/smarty-3.1.32/libs/Smarty.class.php ================================================ * @author Uwe Tews * @author Rodney Rehm * @package Smarty * @version 3.1.32 */ /** * set SMARTY_DIR to absolute path to Smarty library files. * Sets SMARTY_DIR only if user application has not already defined it. */ if (!defined('SMARTY_DIR')) { /** * */ define('SMARTY_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR); } /** * set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins. * Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it. */ if (!defined('SMARTY_SYSPLUGINS_DIR')) { /** * */ define('SMARTY_SYSPLUGINS_DIR', SMARTY_DIR . 'sysplugins' . DIRECTORY_SEPARATOR); } if (!defined('SMARTY_PLUGINS_DIR')) { /** * */ define('SMARTY_PLUGINS_DIR', SMARTY_DIR . 'plugins' . DIRECTORY_SEPARATOR); } if (!defined('SMARTY_MBSTRING')) { /** * */ define('SMARTY_MBSTRING', function_exists('mb_get_info')); } if (!defined('SMARTY_RESOURCE_CHAR_SET')) { // UTF-8 can only be done properly when mbstring is available! /** * @deprecated in favor of Smarty::$_CHARSET */ define('SMARTY_RESOURCE_CHAR_SET', SMARTY_MBSTRING ? 'UTF-8' : 'ISO-8859-1'); } if (!defined('SMARTY_RESOURCE_DATE_FORMAT')) { /** * @deprecated in favor of Smarty::$_DATE_FORMAT */ define('SMARTY_RESOURCE_DATE_FORMAT', '%b %e, %Y'); } /** * Load Smarty_Autoloader */ if (!class_exists('Smarty_Autoloader')) { include dirname(__FILE__) . '/bootstrap.php'; } /** * Load always needed external class files */ require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_data.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_extension_handler.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_templatebase.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_template.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_resource.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_variable.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_template_source.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_template_resource_base.php'; require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_resource_file.php'; /** * This is the main Smarty class * * @package Smarty * * The following methods will be dynamically loaded by the extension handler when they are called. * They are located in a corresponding Smarty_Internal_Method_xxxx class * * @method int clearAllCache(int $exp_time = null, string $type = null) * @method int clearCache(string $template_name, string $cache_id = null, string $compile_id = null, int $exp_time = null, string $type = null) * @method int compileAllTemplates(string $extension = '.tpl', bool $force_compile = false, int $time_limit = 0, $max_errors = null) * @method int compileAllConfig(string $extension = '.conf', bool $force_compile = false, int $time_limit = 0, $max_errors = null) * @method int clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null) */ class Smarty extends Smarty_Internal_TemplateBase { /** * smarty version */ const SMARTY_VERSION = '3.1.32'; /** * define variable scopes */ const SCOPE_LOCAL = 1; const SCOPE_PARENT = 2; const SCOPE_TPL_ROOT = 4; const SCOPE_ROOT = 8; const SCOPE_SMARTY = 16; const SCOPE_GLOBAL = 32; /** * define caching modes */ const CACHING_OFF = 0; const CACHING_LIFETIME_CURRENT = 1; const CACHING_LIFETIME_SAVED = 2; /** * define constant for clearing cache files be saved expiration dates */ const CLEAR_EXPIRED = -1; /** * define compile check modes */ const COMPILECHECK_OFF = 0; const COMPILECHECK_ON = 1; const COMPILECHECK_CACHEMISS = 2; /** * define debug modes */ const DEBUG_OFF = 0; const DEBUG_ON = 1; const DEBUG_INDIVIDUAL = 2; /** * modes for handling of "" tags in templates. */ const PHP_PASSTHRU = 0; //-> print tags as plain text const PHP_QUOTE = 1; //-> escape tags as entities const PHP_REMOVE = 2; //-> escape tags as entities const PHP_ALLOW = 3; //-> escape tags as entities /** * filter types */ const FILTER_POST = 'post'; const FILTER_PRE = 'pre'; const FILTER_OUTPUT = 'output'; const FILTER_VARIABLE = 'variable'; /** * plugin types */ const PLUGIN_FUNCTION = 'function'; const PLUGIN_BLOCK = 'block'; const PLUGIN_COMPILER = 'compiler'; const PLUGIN_MODIFIER = 'modifier'; const PLUGIN_MODIFIERCOMPILER = 'modifiercompiler'; /** * assigned global tpl vars */ public static $global_tpl_vars = array(); /** * Flag denoting if Multibyte String functions are available */ public static $_MBSTRING = SMARTY_MBSTRING; /** * The character set to adhere to (e.g. "UTF-8") */ public static $_CHARSET = SMARTY_RESOURCE_CHAR_SET; /** * The date format to be used internally * (accepts date() and strftime()) */ public static $_DATE_FORMAT = SMARTY_RESOURCE_DATE_FORMAT; /** * Flag denoting if PCRE should run in UTF-8 mode */ public static $_UTF8_MODIFIER = 'u'; /** * Flag denoting if operating system is windows */ public static $_IS_WINDOWS = false; /** * auto literal on delimiters with whitespace * * @var boolean */ public $auto_literal = true; /** * display error on not assigned variables * * @var boolean */ public $error_unassigned = false; /** * look up relative file path in include_path * * @var boolean */ public $use_include_path = false; /** * flag if template_dir is normalized * * @var bool */ public $_templateDirNormalized = false; /** * joined template directory string used in cache keys * * @var string */ public $_joined_template_dir = null; /** * flag if config_dir is normalized * * @var bool */ public $_configDirNormalized = false; /** * joined config directory string used in cache keys * * @var string */ public $_joined_config_dir = null; /** * default template handler * * @var callable */ public $default_template_handler_func = null; /** * default config handler * * @var callable */ public $default_config_handler_func = null; /** * default plugin handler * * @var callable */ public $default_plugin_handler_func = null; /** * flag if template_dir is normalized * * @var bool */ public $_compileDirNormalized = false; /** * flag if plugins_dir is normalized * * @var bool */ public $_pluginsDirNormalized = false; /** * flag if template_dir is normalized * * @var bool */ public $_cacheDirNormalized = false; /** * force template compiling? * * @var boolean */ public $force_compile = false; /** * use sub dirs for compiled/cached files? * * @var boolean */ public $use_sub_dirs = false; /** * allow ambiguous resources (that are made unique by the resource handler) * * @var boolean */ public $allow_ambiguous_resources = false; /** * merge compiled includes * * @var boolean */ public $merge_compiled_includes = false; /* * flag for behaviour when extends: resource and {extends} tag are used simultaneous * if false disable execution of {extends} in templates called by extends resource. * (behaviour as versions < 3.1.28) * * @var boolean */ public $extends_recursion = true; /** * force cache file creation * * @var boolean */ public $force_cache = false; /** * template left-delimiter * * @var string */ public $left_delimiter = "{"; /** * template right-delimiter * * @var string */ public $right_delimiter = "}"; /** * array of strings which shall be treated as literal by compiler * * @var array string */ public $literals = array(); /** * class name * This should be instance of Smarty_Security. * * @var string * @see Smarty_Security */ public $security_class = 'Smarty_Security'; /** * implementation of security class * * @var Smarty_Security */ public $security_policy = null; /** * controls handling of PHP-blocks * * @var integer */ public $php_handling = self::PHP_PASSTHRU; /** * controls if the php template file resource is allowed * * @var bool */ public $allow_php_templates = false; /** * debug mode * Setting this to true enables the debug-console. * * @var boolean */ public $debugging = false; /** * This determines if debugging is enable-able from the browser. *
    *
  • NONE => no debugging control allowed
  • *
  • URL => enable debugging when SMARTY_DEBUG is found in the URL.
  • *
* * @var string */ public $debugging_ctrl = 'NONE'; /** * Name of debugging URL-param. * Only used when $debugging_ctrl is set to 'URL'. * The name of the URL-parameter that activates debugging. * * @var string */ public $smarty_debug_id = 'SMARTY_DEBUG'; /** * Path of debug template. * * @var string */ public $debug_tpl = null; /** * When set, smarty uses this value as error_reporting-level. * * @var int */ public $error_reporting = null; /** * Controls whether variables with the same name overwrite each other. * * @var boolean */ public $config_overwrite = true; /** * Controls whether config values of on/true/yes and off/false/no get converted to boolean. * * @var boolean */ public $config_booleanize = true; /** * Controls whether hidden config sections/vars are read from the file. * * @var boolean */ public $config_read_hidden = false; /** * locking concurrent compiles * * @var boolean */ public $compile_locking = true; /** * Controls whether cache resources should use locking mechanism * * @var boolean */ public $cache_locking = false; /** * seconds to wait for acquiring a lock before ignoring the write lock * * @var float */ public $locking_timeout = 10; /** * resource type used if none given * Must be an valid key of $registered_resources. * * @var string */ public $default_resource_type = 'file'; /** * caching type * Must be an element of $cache_resource_types. * * @var string */ public $caching_type = 'file'; /** * config type * * @var string */ public $default_config_type = 'file'; /** * check If-Modified-Since headers * * @var boolean */ public $cache_modified_check = false; /** * registered plugins * * @var array */ public $registered_plugins = array(); /** * registered objects * * @var array */ public $registered_objects = array(); /** * registered classes * * @var array */ public $registered_classes = array(); /** * registered filters * * @var array */ public $registered_filters = array(); /** * registered resources * * @var array */ public $registered_resources = array(); /** * registered cache resources * * @var array */ public $registered_cache_resources = array(); /** * autoload filter * * @var array */ public $autoload_filters = array(); /** * default modifier * * @var array */ public $default_modifiers = array(); /** * autoescape variable output * * @var boolean */ public $escape_html = false; /** * start time for execution time calculation * * @var int */ public $start_time = 0; /** * required by the compiler for BC * * @var string */ public $_current_file = null; /** * internal flag to enable parser debugging * * @var bool */ public $_parserdebug = false; /** * This object type (Smarty = 1, template = 2, data = 4) * * @var int */ public $_objType = 1; /** * Debug object * * @var Smarty_Internal_Debug */ public $_debug = null; /** * template directory * * @var array */ protected $template_dir = array('./templates/'); /** * flags for normalized template directory entries * * @var array */ protected $_processedTemplateDir = array(); /** * config directory * * @var array */ protected $config_dir = array('./configs/'); /** * flags for normalized template directory entries * * @var array */ protected $_processedConfigDir = array(); /** * compile directory * * @var string */ protected $compile_dir = './templates_c/'; /** * plugins directory * * @var array */ protected $plugins_dir = array(); /** * cache directory * * @var string */ protected $cache_dir = './cache/'; /** * removed properties * * @var string[] */ protected $obsoleteProperties = array('resource_caching', 'template_resource_caching', 'direct_access_security', '_dir_perms', '_file_perms', 'plugin_search_order', 'inheritance_merge_compiled_includes', 'resource_cache_mode',); /** * List of private properties which will call getter/setter on a direct access * * @var string[] */ protected $accessMap = array('template_dir' => 'TemplateDir', 'config_dir' => 'ConfigDir', 'plugins_dir' => 'PluginsDir', 'compile_dir' => 'CompileDir', 'cache_dir' => 'CacheDir',); /** * Initialize new Smarty object */ public function __construct() { $this->_clearTemplateCache(); parent::__construct(); if (is_callable('mb_internal_encoding')) { mb_internal_encoding(Smarty::$_CHARSET); } $this->start_time = microtime(true); if (isset($_SERVER[ 'SCRIPT_NAME' ])) { Smarty::$global_tpl_vars[ 'SCRIPT_NAME' ] = new Smarty_Variable($_SERVER[ 'SCRIPT_NAME' ]); } // Check if we're running on windows Smarty::$_IS_WINDOWS = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; // let PCRE (preg_*) treat strings as ISO-8859-1 if we're not dealing with UTF-8 if (Smarty::$_CHARSET !== 'UTF-8') { Smarty::$_UTF8_MODIFIER = ''; } } /** * Enable error handler to mute expected messages * * @return boolean * @deprecated */ public static function muteExpectedErrors() { return Smarty_Internal_ErrorHandler::muteExpectedErrors(); } /** * Disable error handler muting expected messages * * @deprecated */ public static function unmuteExpectedErrors() { restore_error_handler(); } /** * Check if a template resource exists * * @param string $resource_name template name * * @return bool status * @throws \SmartyException */ public function templateExists($resource_name) { // create source object $source = Smarty_Template_Source::load(null, $this, $resource_name); return $source->exists; } /** * Loads security class and enables security * * @param string|Smarty_Security $security_class if a string is used, it must be class-name * * @return Smarty current Smarty instance for chaining * @throws SmartyException when an invalid class name is provided */ public function enableSecurity($security_class = null) { Smarty_Security::enableSecurity($this, $security_class); return $this; } /** * Disable security * * @return Smarty current Smarty instance for chaining */ public function disableSecurity() { $this->security_policy = null; return $this; } /** * Add template directory(s) * * @param string|array $template_dir directory(s) of template sources * @param string $key of the array element to assign the template dir to * @param bool $isConfig true for config_dir * * @return Smarty current Smarty instance for chaining */ public function addTemplateDir($template_dir, $key = null, $isConfig = false) { if ($isConfig) { $processed = &$this->_processedConfigDir; $dir = &$this->config_dir; $this->_configDirNormalized = false; } else { $processed = &$this->_processedTemplateDir; $dir = &$this->template_dir; $this->_templateDirNormalized = false; } if (is_array($template_dir)) { foreach ($template_dir as $k => $v) { if (is_int($k)) { // indexes are not merged but appended $dir[] = $v; } else { // string indexes are overridden $dir[ $k ] = $v; unset($processed[ $key ]); } } } else { if ($key !== null) { // override directory at specified index $dir[ $key ] = $template_dir; unset($processed[ $key ]); } else { // append new directory $dir[] = $template_dir; } } return $this; } /** * Get template directories * * @param mixed $index index of directory to get, null to get all * @param bool $isConfig true for config_dir * * @return array list of template directories, or directory of $index */ public function getTemplateDir($index = null, $isConfig = false) { if ($isConfig) { $dir = &$this->config_dir; } else { $dir = &$this->template_dir; } if ($isConfig ? !$this->_configDirNormalized : !$this->_templateDirNormalized) { $this->_normalizeTemplateConfig($isConfig); } if ($index !== null) { return isset($dir[ $index ]) ? $dir[ $index ] : null; } return $dir; } /** * Set template directory * * @param string|array $template_dir directory(s) of template sources * @param bool $isConfig true for config_dir * * @return \Smarty current Smarty instance for chaining */ public function setTemplateDir($template_dir, $isConfig = false) { if ($isConfig) { $this->config_dir = array(); $this->_processedConfigDir = array(); } else { $this->template_dir = array(); $this->_processedTemplateDir = array(); } $this->addTemplateDir($template_dir, null, $isConfig); return $this; } /** * Add config directory(s) * * @param string|array $config_dir directory(s) of config sources * @param mixed $key key of the array element to assign the config dir to * * @return Smarty current Smarty instance for chaining */ public function addConfigDir($config_dir, $key = null) { return $this->addTemplateDir($config_dir, $key, true); } /** * Get config directory * * @param mixed $index index of directory to get, null to get all * * @return array configuration directory */ public function getConfigDir($index = null) { return $this->getTemplateDir($index, true); } /** * Set config directory * * @param $config_dir * * @return Smarty current Smarty instance for chaining */ public function setConfigDir($config_dir) { return $this->setTemplateDir($config_dir, true); } /** * Adds directory of plugin files * * @param null|array|string $plugins_dir * * @return Smarty current Smarty instance for chaining */ public function addPluginsDir($plugins_dir) { if (empty($this->plugins_dir)) { $this->plugins_dir[] = SMARTY_PLUGINS_DIR; } $this->plugins_dir = array_merge($this->plugins_dir, (array)$plugins_dir); $this->_pluginsDirNormalized = false; return $this; } /** * Get plugin directories * * @return array list of plugin directories */ public function getPluginsDir() { if (empty($this->plugins_dir)) { $this->plugins_dir[] = SMARTY_PLUGINS_DIR; $this->_pluginsDirNormalized = false; } if (!$this->_pluginsDirNormalized) { if (!is_array($this->plugins_dir)) { $this->plugins_dir = (array)$this->plugins_dir; } foreach ($this->plugins_dir as $k => $v) { $this->plugins_dir[ $k ] = $this->_realpath(rtrim($v, "/\\") . DIRECTORY_SEPARATOR, true); } $this->_cache[ 'plugin_files' ] = array(); $this->_pluginsDirNormalized = true; } return $this->plugins_dir; } /** * Set plugins directory * * @param string|array $plugins_dir directory(s) of plugins * * @return Smarty current Smarty instance for chaining */ public function setPluginsDir($plugins_dir) { $this->plugins_dir = (array)$plugins_dir; $this->_pluginsDirNormalized = false; return $this; } /** * Get compiled directory * * @return string path to compiled templates */ public function getCompileDir() { if (!$this->_compileDirNormalized) { $this->_normalizeDir('compile_dir', $this->compile_dir); $this->_compileDirNormalized = true; } return $this->compile_dir; } /** * * @param string $compile_dir directory to store compiled templates in * * @return Smarty current Smarty instance for chaining */ public function setCompileDir($compile_dir) { $this->_normalizeDir('compile_dir', $compile_dir); $this->_compileDirNormalized = true; return $this; } /** * Get cache directory * * @return string path of cache directory */ public function getCacheDir() { if (!$this->_cacheDirNormalized) { $this->_normalizeDir('cache_dir', $this->cache_dir); $this->_cacheDirNormalized = true; } return $this->cache_dir; } /** * Set cache directory * * @param string $cache_dir directory to store cached templates in * * @return Smarty current Smarty instance for chaining */ public function setCacheDir($cache_dir) { $this->_normalizeDir('cache_dir', $cache_dir); $this->_cacheDirNormalized = true; return $this; } /** * creates a template object * * @param string $template the resource handle of the template file * @param mixed $cache_id cache id to be used with this template * @param mixed $compile_id compile id to be used with this template * @param object $parent next higher level of Smarty variables * @param boolean $do_clone flag is Smarty object shall be cloned * * @return \Smarty_Internal_Template template object * @throws \SmartyException */ public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true) { if ($cache_id !== null && (is_object($cache_id) || is_array($cache_id))) { $parent = $cache_id; $cache_id = null; } if ($parent !== null && is_array($parent)) { $data = $parent; $parent = null; } else { $data = null; } if (!$this->_templateDirNormalized) { $this->_normalizeTemplateConfig(false); } $_templateId = $this->_getTemplateId($template, $cache_id, $compile_id); $tpl = null; if ($this->caching && isset(Smarty_Internal_Template::$isCacheTplObj[ $_templateId ])) { $tpl = $do_clone ? clone Smarty_Internal_Template::$isCacheTplObj[ $_templateId ] : Smarty_Internal_Template::$isCacheTplObj[ $_templateId ]; $tpl->inheritance = null; $tpl->tpl_vars = $tpl->config_vars = array(); } else if (!$do_clone && isset(Smarty_Internal_Template::$tplObjCache[ $_templateId ])) { $tpl = clone Smarty_Internal_Template::$tplObjCache[ $_templateId ]; $tpl->inheritance = null; $tpl->tpl_vars = $tpl->config_vars = array(); } else { /* @var Smarty_Internal_Template $tpl */ $tpl = new $this->template_class($template, $this, null, $cache_id, $compile_id, null, null); $tpl->templateId = $_templateId; } if ($do_clone) { $tpl->smarty = clone $tpl->smarty; } $tpl->parent = $parent ? $parent : $this; // fill data if present if (!empty($data) && is_array($data)) { // set up variable values foreach ($data as $_key => $_val) { $tpl->tpl_vars[ $_key ] = new Smarty_Variable($_val); } } if ($this->debugging || $this->debugging_ctrl === 'URL') { $tpl->smarty->_debug = new Smarty_Internal_Debug(); // check URL debugging control if (!$this->debugging && $this->debugging_ctrl === 'URL') { $tpl->smarty->_debug->debugUrl($tpl->smarty); } } return $tpl; } /** * Takes unknown classes and loads plugin files for them * class name format: Smarty_PluginType_PluginName * plugin filename format: plugintype.pluginname.php * * @param string $plugin_name class plugin name to load * @param bool $check check if already loaded * * @throws SmartyException * @return string |boolean filepath of loaded file or false */ public function loadPlugin($plugin_name, $check = true) { return $this->ext->loadPlugin->loadPlugin($this, $plugin_name, $check); } /** * Get unique template id * * @param string $template_name * @param null|mixed $cache_id * @param null|mixed $compile_id * @param null $caching * @param \Smarty_Internal_Template $template * * @return string * @throws \SmartyException */ public function _getTemplateId($template_name, $cache_id = null, $compile_id = null, $caching = null, Smarty_Internal_Template $template = null) { $template_name = (strpos($template_name, ':') === false) ? "{$this->default_resource_type}:{$template_name}" : $template_name; $cache_id = $cache_id === null ? $this->cache_id : $cache_id; $compile_id = $compile_id === null ? $this->compile_id : $compile_id; $caching = (int)($caching === null ? $this->caching : $caching); if ((isset($template) && strpos($template_name, ':.') !== false) || $this->allow_ambiguous_resources) { $_templateId = Smarty_Resource::getUniqueTemplateName((isset($template) ? $template : $this), $template_name) . "#{$cache_id}#{$compile_id}#{$caching}"; } else { $_templateId = $this->_joined_template_dir . "#{$template_name}#{$cache_id}#{$compile_id}#{$caching}"; } if (isset($_templateId[ 150 ])) { $_templateId = sha1($_templateId); } return $_templateId; } /** * Normalize path * - remove /./ and /../ * - make it absolute if required * * @param string $path file path * @param bool $realpath if true - convert to absolute * false - convert to relative * null - keep as it is but remove /./ /../ * * @return string */ public function _realpath($path, $realpath = null) { static $nds = null; static $sepDotsep = null; static $sepDot = null; static $sepSep =null; if (!isset($nds)) { $nds = array('/' => '\\', '\\' => '/'); $sepDotsep = DIRECTORY_SEPARATOR . '.' . DIRECTORY_SEPARATOR; $sepDot = DIRECTORY_SEPARATOR . '.'; $sepSep = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR; } // normalize DIRECTORY_SEPARATOR $path = str_replace(array($nds[DIRECTORY_SEPARATOR], $sepDotsep), DIRECTORY_SEPARATOR, $path); if (strpos($path,$sepDot) === false && (($realpath === false && $path[0] === '.') || $realpath === null) && $path[0] !== '\\') { return $path; } preg_match('%^(?(?:[[:alpha:]]:[\\\\]|/|[\\\\]{2}[[:alpha:]]+|[[:print:]]{2,}:[/]{2}|[\\\\])?)(?(.*))$%u', $path, $parts); $path = $parts[ 'path' ]; if ($parts[ 'root' ] === '\\') { $parts[ 'root' ] = substr(getcwd(), 0, 2) . $parts[ 'root' ]; } else { if ($realpath !== null && !$parts[ 'root' ]) { $path = getcwd() . DIRECTORY_SEPARATOR . $path; } } // remove noop 'DIRECTORY_SEPARATOR DIRECTORY_SEPARATOR' and 'DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR' patterns $path = str_replace(array($sepDotsep,$sepSep), DIRECTORY_SEPARATOR, $path); // resolve '..DIRECTORY_SEPARATOR' pattern, smallest first if (strpos($path, '..' . DIRECTORY_SEPARATOR) !== false && preg_match_all('#[\\\\/]([.][.][\\\\/])+#u', $path, $match) ) { $counts = array(); foreach ($match[ 0 ] as $m) { $counts[] = (int)((strlen($m) - 1) / 3); } sort($counts); foreach ($counts as $count) { $path = preg_replace('#([\\\\/]+[^\\\\/]+){' . $count . '}[\\\\/]+([.][.][\\\\/]+){' . $count . '}#u', DIRECTORY_SEPARATOR, $path); } } return $realpath !== false ? $parts[ 'root' ] . $path : str_ireplace(getcwd(), '.', $parts[ 'root' ] . $path); } /** * Empty template objects cache */ public function _clearTemplateCache() { Smarty_Internal_Template::$isCacheTplObj = array(); Smarty_Internal_Template::$tplObjCache = array(); } /** * @param boolean $use_sub_dirs */ public function setUseSubDirs($use_sub_dirs) { $this->use_sub_dirs = $use_sub_dirs; } /** * @param int $error_reporting */ public function setErrorReporting($error_reporting) { $this->error_reporting = $error_reporting; } /** * @param boolean $escape_html */ public function setEscapeHtml($escape_html) { $this->escape_html = $escape_html; } /** * Return auto_literal flag * * @return boolean */ public function getAutoLiteral() { return $this->auto_literal; } /** * Set auto_literal flag * * @param boolean $auto_literal */ public function setAutoLiteral($auto_literal = true) { $this->auto_literal = $auto_literal; } /** * @param boolean $force_compile */ public function setForceCompile($force_compile) { $this->force_compile = $force_compile; } /** * @param boolean $merge_compiled_includes */ public function setMergeCompiledIncludes($merge_compiled_includes) { $this->merge_compiled_includes = $merge_compiled_includes; } /** * Get left delimiter * * @return string */ public function getLeftDelimiter() { return $this->left_delimiter; } /** * Set left delimiter * * @param string $left_delimiter */ public function setLeftDelimiter($left_delimiter) { $this->left_delimiter = $left_delimiter; } /** * Get right delimiter * * @return string $right_delimiter */ public function getRightDelimiter() { return $this->right_delimiter; } /** * Set right delimiter * * @param string */ public function setRightDelimiter($right_delimiter) { $this->right_delimiter = $right_delimiter; } /** * @param boolean $debugging */ public function setDebugging($debugging) { $this->debugging = $debugging; } /** * @param boolean $config_overwrite */ public function setConfigOverwrite($config_overwrite) { $this->config_overwrite = $config_overwrite; } /** * @param boolean $config_booleanize */ public function setConfigBooleanize($config_booleanize) { $this->config_booleanize = $config_booleanize; } /** * @param boolean $config_read_hidden */ public function setConfigReadHidden($config_read_hidden) { $this->config_read_hidden = $config_read_hidden; } /** * @param boolean $compile_locking */ public function setCompileLocking($compile_locking) { $this->compile_locking = $compile_locking; } /** * @param string $default_resource_type */ public function setDefaultResourceType($default_resource_type) { $this->default_resource_type = $default_resource_type; } /** * @param string $caching_type */ public function setCachingType($caching_type) { $this->caching_type = $caching_type; } /** * Test install * * @param null $errors */ public function testInstall(&$errors = null) { Smarty_Internal_TestInstall::testInstall($this, $errors); } /** * Get Smarty object * * @return Smarty */ public function _getSmartyObj() { return $this; } /** * <> Generic getter. * Calls the appropriate getter function. * Issues an E_USER_NOTICE if no valid getter is found. * * @param string $name property name * * @return mixed * @throws \SmartyException */ public function __get($name) { if (isset($this->accessMap[ $name ])) { $method = 'get' . $this->accessMap[ $name ]; return $this->{$method}(); } else if (isset($this->_cache[ $name ])) { return $this->_cache[ $name ]; } else if (in_array($name, $this->obsoleteProperties)) { return null; } else { trigger_error('Undefined property: ' . get_class($this) . '::$' . $name, E_USER_NOTICE); } return null; } /** * <> Generic setter. * Calls the appropriate setter function. * Issues an E_USER_NOTICE if no valid setter is found. * * @param string $name property name * @param mixed $value parameter passed to setter * * @throws \SmartyException */ public function __set($name, $value) { if (isset($this->accessMap[ $name ])) { $method = 'set' . $this->accessMap[ $name ]; $this->{$method}($value); } else if (in_array($name, $this->obsoleteProperties)) { return; } else { if (is_object($value) && method_exists($value, $name)) { $this->$name = $value; } else { trigger_error('Undefined property: ' . get_class($this) . '::$' . $name, E_USER_NOTICE); } } } /** * Normalize and set directory string * * @param string $dirName cache_dir or compile_dir * @param string $dir filepath of folder */ private function _normalizeDir($dirName, $dir) { $this->{$dirName} = $this->_realpath(rtrim($dir, "/\\") . DIRECTORY_SEPARATOR, true); if (class_exists('Smarty_Internal_ErrorHandler', false)) { if (!isset(Smarty_Internal_ErrorHandler::$mutedDirectories[ $this->{$dirName} ])) { Smarty_Internal_ErrorHandler::$mutedDirectories[ $this->{$dirName} ] = null; } } } /** * Normalize template_dir or config_dir * * @param bool $isConfig true for config_dir * */ private function _normalizeTemplateConfig($isConfig) { if ($isConfig) { $processed = &$this->_processedConfigDir; $dir = &$this->config_dir; } else { $processed = &$this->_processedTemplateDir; $dir = &$this->template_dir; } if (!is_array($dir)) { $dir = (array)$dir; } foreach ($dir as $k => $v) { if (!isset($processed[ $k ])) { $dir[ $k ] = $v = $this->_realpath(rtrim($v, "/\\") . DIRECTORY_SEPARATOR, true); $processed[ $k ] = true; } } $isConfig ? $this->_configDirNormalized = true : $this->_templateDirNormalized = true; $isConfig ? $this->_joined_config_dir = join('#', $this->config_dir) : $this->_joined_template_dir = join('#', $this->template_dir); } } ================================================ FILE: Tool/smarty-3.1.32/libs/SmartyBC.class.php ================================================ * @author Uwe Tews * @author Rodney Rehm * @package Smarty */ /** * @ignore */ require_once(dirname(__FILE__) . '/Smarty.class.php'); /** * Smarty Backward Compatibility Wrapper Class * * @package Smarty */ class SmartyBC extends Smarty { /** * Smarty 2 BC * * @var string */ public $_version = self::SMARTY_VERSION; /** * This is an array of directories where trusted php scripts reside. * * @var array */ public $trusted_dir = array(); /** * Initialize new SmartyBC object * */ public function __construct() { parent::__construct(); } /** * wrapper for assign_by_ref * * @param string $tpl_var the template variable name * @param mixed &$value the referenced value to assign */ public function assign_by_ref($tpl_var, &$value) { $this->assignByRef($tpl_var, $value); } /** * wrapper for append_by_ref * * @param string $tpl_var the template variable name * @param mixed &$value the referenced value to append * @param boolean $merge flag if array elements shall be merged */ public function append_by_ref($tpl_var, &$value, $merge = false) { $this->appendByRef($tpl_var, $value, $merge); } /** * clear the given assigned template variable. * * @param string $tpl_var the template variable to clear */ public function clear_assign($tpl_var) { $this->clearAssign($tpl_var); } /** * Registers custom function to be used in templates * * @param string $function the name of the template function * @param string $function_impl the name of the PHP function to register * @param bool $cacheable * @param mixed $cache_attrs * * @throws \SmartyException */ public function register_function($function, $function_impl, $cacheable = true, $cache_attrs = null) { $this->registerPlugin('function', $function, $function_impl, $cacheable, $cache_attrs); } /** * Unregister custom function * * @param string $function name of template function */ public function unregister_function($function) { $this->unregisterPlugin('function', $function); } /** * Registers object to be used in templates * * @param string $object name of template object * @param object $object_impl the referenced PHP object to register * @param array $allowed list of allowed methods (empty = all) * @param boolean $smarty_args smarty argument format, else traditional * @param array $block_methods list of methods that are block format * * @throws SmartyException * @internal param array $block_functs list of methods that are block format */ public function register_object($object, $object_impl, $allowed = array(), $smarty_args = true, $block_methods = array()) { settype($allowed, 'array'); settype($smarty_args, 'boolean'); $this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods); } /** * Unregister object * * @param string $object name of template object */ public function unregister_object($object) { $this->unregisterObject($object); } /** * Registers block function to be used in templates * * @param string $block name of template block * @param string $block_impl PHP function to register * @param bool $cacheable * @param mixed $cache_attrs * * @throws \SmartyException */ public function register_block($block, $block_impl, $cacheable = true, $cache_attrs = null) { $this->registerPlugin('block', $block, $block_impl, $cacheable, $cache_attrs); } /** * Unregister block function * * @param string $block name of template function */ public function unregister_block($block) { $this->unregisterPlugin('block', $block); } /** * Registers compiler function * * @param string $function name of template function * @param string $function_impl name of PHP function to register * @param bool $cacheable * * @throws \SmartyException */ public function register_compiler_function($function, $function_impl, $cacheable = true) { $this->registerPlugin('compiler', $function, $function_impl, $cacheable); } /** * Unregister compiler function * * @param string $function name of template function */ public function unregister_compiler_function($function) { $this->unregisterPlugin('compiler', $function); } /** * Registers modifier to be used in templates * * @param string $modifier name of template modifier * @param string $modifier_impl name of PHP function to register * * @throws \SmartyException */ public function register_modifier($modifier, $modifier_impl) { $this->registerPlugin('modifier', $modifier, $modifier_impl); } /** * Unregister modifier * * @param string $modifier name of template modifier */ public function unregister_modifier($modifier) { $this->unregisterPlugin('modifier', $modifier); } /** * Registers a resource to fetch a template * * @param string $type name of resource * @param array $functions array of functions to handle resource */ public function register_resource($type, $functions) { $this->registerResource($type, $functions); } /** * Unregister a resource * * @param string $type name of resource */ public function unregister_resource($type) { $this->unregisterResource($type); } /** * Registers a prefilter function to apply * to a template before compiling * * @param callable $function * * @throws \SmartyException */ public function register_prefilter($function) { $this->registerFilter('pre', $function); } /** * Unregister a prefilter function * * @param callable $function */ public function unregister_prefilter($function) { $this->unregisterFilter('pre', $function); } /** * Registers a postfilter function to apply * to a compiled template after compilation * * @param callable $function * * @throws \SmartyException */ public function register_postfilter($function) { $this->registerFilter('post', $function); } /** * Unregister a postfilter function * * @param callable $function */ public function unregister_postfilter($function) { $this->unregisterFilter('post', $function); } /** * Registers an output filter function to apply * to a template output * * @param callable $function * * @throws \SmartyException */ public function register_outputfilter($function) { $this->registerFilter('output', $function); } /** * Unregister an outputfilter function * * @param callable $function */ public function unregister_outputfilter($function) { $this->unregisterFilter('output', $function); } /** * load a filter of specified type and name * * @param string $type filter type * @param string $name filter name * * @throws \SmartyException */ public function load_filter($type, $name) { $this->loadFilter($type, $name); } /** * clear cached content for the given template and cache id * * @param string $tpl_file name of template file * @param string $cache_id name of cache_id * @param string $compile_id name of compile_id * @param string $exp_time expiration time * * @return boolean */ public function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null) { return $this->clearCache($tpl_file, $cache_id, $compile_id, $exp_time); } /** * clear the entire contents of cache (all templates) * * @param string $exp_time expire time * * @return boolean */ public function clear_all_cache($exp_time = null) { return $this->clearCache(null, null, null, $exp_time); } /** * test to see if valid cache exists for this template * * @param string $tpl_file name of template file * @param string $cache_id * @param string $compile_id * * @return bool * @throws \Exception * @throws \SmartyException */ public function is_cached($tpl_file, $cache_id = null, $compile_id = null) { return $this->isCached($tpl_file, $cache_id, $compile_id); } /** * clear all the assigned template variables. */ public function clear_all_assign() { $this->clearAllAssign(); } /** * clears compiled version of specified template resource, * or all compiled template files if one is not specified. * This function is for advanced use only, not normally needed. * * @param string $tpl_file * @param string $compile_id * @param string $exp_time * * @return boolean results of {@link smarty_core_rm_auto()} */ public function clear_compiled_tpl($tpl_file = null, $compile_id = null, $exp_time = null) { return $this->clearCompiledTemplate($tpl_file, $compile_id, $exp_time); } /** * Checks whether requested template exists. * * @param string $tpl_file * * @return bool * @throws \SmartyException */ public function template_exists($tpl_file) { return $this->templateExists($tpl_file); } /** * Returns an array containing template variables * * @param string $name * * @return array */ public function get_template_vars($name = null) { return $this->getTemplateVars($name); } /** * Returns an array containing config variables * * @param string $name * * @return array */ public function get_config_vars($name = null) { return $this->getConfigVars($name); } /** * load configuration values * * @param string $file * @param string $section * @param string $scope */ public function config_load($file, $section = null, $scope = 'global') { $this->ConfigLoad($file, $section, $scope); } /** * return a reference to a registered object * * @param string $name * * @return object */ public function get_registered_object($name) { return $this->getRegisteredObject($name); } /** * clear configuration values * * @param string $var */ public function clear_config($var = null) { $this->clearConfig($var); } /** * trigger Smarty error * * @param string $error_msg * @param integer $error_type */ public function trigger_error($error_msg, $error_type = E_USER_WARNING) { trigger_error("Smarty error: $error_msg", $error_type); } } ================================================ FILE: Tool/smarty-3.1.32/libs/bootstrap.php ================================================ * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * Load and register Smarty Autoloader */ if (!class_exists('Smarty_Autoloader')) { require dirname(__FILE__) . '/Autoloader.php'; } Smarty_Autoloader::register(true); ================================================ FILE: Tool/smarty-3.1.32/libs/debug.tpl ================================================ {capture name='_smarty_debug' assign=debug_output} Smarty Debug Console

Smarty {Smarty::SMARTY_VERSION} Debug Console - {if isset($template_name)}{$template_name|debug_print_var nofilter} {/if}{if !empty($template_data)}Total Time {$execution_time|string_format:"%.5f"}{/if}

{if !empty($template_data)}

included templates & config files (load time in seconds)

{foreach $template_data as $template} {$template.name}
   (compile {$template['compile_time']|string_format:"%.5f"}) (render {$template['render_time']|string_format:"%.5f"}) (cache {$template['cache_time']|string_format:"%.5f"})
{/foreach}
{/if}

assigned template variables

{foreach $assigned_vars as $vars} {/foreach}

${$vars@key}

{if isset($vars['nocache'])}Nocache
{/if} {if isset($vars['scope'])}Origin: {$vars['scope']|debug_print_var nofilter}{/if}

Value

{$vars['value']|debug_print_var:10:80 nofilter}
{if isset($vars['attributes'])}

Attributes

{$vars['attributes']|debug_print_var nofilter} {/if}

assigned config file variables

{foreach $config_vars as $vars} {/foreach}

#{$vars@key}#

{if isset($vars['scope'])}Origin: {$vars['scope']|debug_print_var nofilter}{/if}
{$vars['value']|debug_print_var:10:80 nofilter}
{/capture} ================================================ FILE: Tool/smarty-3.1.32/libs/plugins/block.textformat.php ================================================ * @throws \SmartyException */ function smarty_block_textformat($params, $content, Smarty_Internal_Template $template, &$repeat) { if (is_null($content)) { return; } if (Smarty::$_MBSTRING) { $template->_checkPlugins(array(array('function' => 'smarty_modifier_mb_wordwrap', 'file' => SMARTY_PLUGINS_DIR . 'modifier.mb_wordwrap.php'))); } $style = null; $indent = 0; $indent_first = 0; $indent_char = ' '; $wrap = 80; $wrap_char = "\n"; $wrap_cut = false; $assign = null; foreach ($params as $_key => $_val) { switch ($_key) { case 'style': case 'indent_char': case 'wrap_char': case 'assign': $$_key = (string) $_val; break; case 'indent': case 'indent_first': case 'wrap': $$_key = (int) $_val; break; case 'wrap_cut': $$_key = (bool) $_val; break; default: trigger_error("textformat: unknown attribute '{$_key}'"); } } if ($style === 'email') { $wrap = 72; } // split into paragraphs $_paragraphs = preg_split('![\r\n]{2}!', $content); foreach ($_paragraphs as &$_paragraph) { if (!$_paragraph) { continue; } // convert mult. spaces & special chars to single space $_paragraph = preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER, '!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER), array(' ', ''), $_paragraph); // indent first line if ($indent_first > 0) { $_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph; } // wordwrap sentences if (Smarty::$_MBSTRING) { $_paragraph = smarty_modifier_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } else { $_paragraph = wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut); } // indent lines if ($indent > 0) { $_paragraph = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraph); } } $_output = implode($wrap_char . $wrap_char, $_paragraphs); if ($assign) { $template->assign($assign, $_output); } else { return $_output; } } ================================================ FILE: Tool/smarty-3.1.32/libs/plugins/function.counter.php ================================================ * @link http://www.smarty.net/manual/en/language.function.counter.php {counter} * (Smarty online manual) * * @param array $params parameters * @param Smarty_Internal_Template $template template object * * @return string|null */ function smarty_function_counter($params, $template) { static $counters = array(); $name = (isset($params[ 'name' ])) ? $params[ 'name' ] : 'default'; if (!isset($counters[ $name ])) { $counters[ $name ] = array('start' => 1, 'skip' => 1, 'direction' => 'up', 'count' => 1); } $counter =& $counters[ $name ]; if (isset($params[ 'start' ])) { $counter[ 'start' ] = $counter[ 'count' ] = (int) $params[ 'start' ]; } if (!empty($params[ 'assign' ])) { $counter[ 'assign' ] = $params[ 'assign' ]; } if (isset($counter[ 'assign' ])) { $template->assign($counter[ 'assign' ], $counter[ 'count' ]); } if (isset($params[ 'print' ])) { $print = (bool) $params[ 'print' ]; } else { $print = empty($counter[ 'assign' ]); } if ($print) { $retval = $counter[ 'count' ]; } else { $retval = null; } if (isset($params[ 'skip' ])) { $counter[ 'skip' ] = $params[ 'skip' ]; } if (isset($params[ 'direction' ])) { $counter[ 'direction' ] = $params[ 'direction' ]; } if ($counter[ 'direction' ] === 'down') { $counter[ 'count' ] -= $counter[ 'skip' ]; } else { $counter[ 'count' ] += $counter[ 'skip' ]; } return $retval; } ================================================ FILE: Tool/smarty-3.1.32/libs/plugins/function.cycle.php ================================================ * @author credit to Mark Priatel * @author credit to Gerard * @author credit to Jason Sweat * @version 1.3 * * @param array $params parameters * @param Smarty_Internal_Template $template template object * * @return string|null */ function smarty_function_cycle($params, $template) { static $cycle_vars; $name = (empty($params[ 'name' ])) ? 'default' : $params[ 'name' ]; $print = (isset($params[ 'print' ])) ? (bool) $params[ 'print' ] : true; $advance = (isset($params[ 'advance' ])) ? (bool) $params[ 'advance' ] : true; $reset = (isset($params[ 'reset' ])) ? (bool) $params[ 'reset' ] : false; if (!isset($params[ 'values' ])) { if (!isset($cycle_vars[ $name ][ 'values' ])) { trigger_error('cycle: missing \'values\' parameter'); return; } } else { if (isset($cycle_vars[ $name ][ 'values' ]) && $cycle_vars[ $name ][ 'values' ] !== $params[ 'values' ]) { $cycle_vars[ $name ][ 'index' ] = 0; } $cycle_vars[ $name ][ 'values' ] = $params[ 'values' ]; } if (isset($params[ 'delimiter' ])) { $cycle_vars[ $name ][ 'delimiter' ] = $params[ 'delimiter' ]; } elseif (!isset($cycle_vars[ $name ][ 'delimiter' ])) { $cycle_vars[ $name ][ 'delimiter' ] = ','; } if (is_array($cycle_vars[ $name ][ 'values' ])) { $cycle_array = $cycle_vars[ $name ][ 'values' ]; } else { $cycle_array = explode($cycle_vars[ $name ][ 'delimiter' ], $cycle_vars[ $name ][ 'values' ]); } if (!isset($cycle_vars[ $name ][ 'index' ]) || $reset) { $cycle_vars[ $name ][ 'index' ] = 0; } if (isset($params[ 'assign' ])) { $print = false; $template->assign($params[ 'assign' ], $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]); } if ($print) { $retval = $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]; } else { $retval = null; } if ($advance) { if ($cycle_vars[ $name ][ 'index' ] >= count($cycle_array) - 1) { $cycle_vars[ $name ][ 'index' ] = 0; } else { $cycle_vars[ $name ][ 'index' ] ++; } } return $retval; } ================================================ FILE: Tool/smarty-3.1.32/libs/plugins/function.fetch.php ================================================ * * @param array $params parameters * @param Smarty_Internal_Template $template template object * * @throws SmartyException * @return string|null if the assign parameter is passed, Smarty assigns the result to a template variable */ function smarty_function_fetch($params, $template) { if (empty($params[ 'file' ])) { trigger_error('[plugin] fetch parameter \'file\' cannot be empty', E_USER_NOTICE); return; } // strip file protocol if (stripos($params[ 'file' ], 'file://') === 0) { $params[ 'file' ] = substr($params[ 'file' ], 7); } $protocol = strpos($params[ 'file' ], '://'); if ($protocol !== false) { $protocol = strtolower(substr($params[ 'file' ], 0, $protocol)); } if (isset($template->smarty->security_policy)) { if ($protocol) { // remote resource (or php stream, …) if (!$template->smarty->security_policy->isTrustedUri($params[ 'file' ])) { return; } } else { // local file if (!$template->smarty->security_policy->isTrustedResourceDir($params[ 'file' ])) { return; } } } $content = ''; if ($protocol === 'http') { // http fetch if ($uri_parts = parse_url($params[ 'file' ])) { // set defaults $host = $server_name = $uri_parts[ 'host' ]; $timeout = 30; $accept = 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*'; $agent = 'Smarty Template Engine ' . Smarty::SMARTY_VERSION; $referer = ''; $uri = !empty($uri_parts[ 'path' ]) ? $uri_parts[ 'path' ] : '/'; $uri .= !empty($uri_parts[ 'query' ]) ? '?' . $uri_parts[ 'query' ] : ''; $_is_proxy = false; if (empty($uri_parts[ 'port' ])) { $port = 80; } else { $port = $uri_parts[ 'port' ]; } if (!empty($uri_parts[ 'user' ])) { $user = $uri_parts[ 'user' ]; } if (!empty($uri_parts[ 'pass' ])) { $pass = $uri_parts[ 'pass' ]; } // loop through parameters, setup headers foreach ($params as $param_key => $param_value) { switch ($param_key) { case 'file': case 'assign': case 'assign_headers': break; case 'user': if (!empty($param_value)) { $user = $param_value; } break; case 'pass': if (!empty($param_value)) { $pass = $param_value; } break; case 'accept': if (!empty($param_value)) { $accept = $param_value; } break; case 'header': if (!empty($param_value)) { if (!preg_match('![\w\d-]+: .+!', $param_value)) { trigger_error("[plugin] invalid header format '{$param_value}'", E_USER_NOTICE); return; } else { $extra_headers[] = $param_value; } } break; case 'proxy_host': if (!empty($param_value)) { $proxy_host = $param_value; } break; case 'proxy_port': if (!preg_match('!\D!', $param_value)) { $proxy_port = (int) $param_value; } else { trigger_error("[plugin] invalid value for attribute '{$param_key }'", E_USER_NOTICE); return; } break; case 'agent': if (!empty($param_value)) { $agent = $param_value; } break; case 'referer': if (!empty($param_value)) { $referer = $param_value; } break; case 'timeout': if (!preg_match('!\D!', $param_value)) { $timeout = (int) $param_value; } else { trigger_error("[plugin] invalid value for attribute '{$param_key}'", E_USER_NOTICE); return; } break; default: trigger_error("[plugin] unrecognized attribute '{$param_key}'", E_USER_NOTICE); return; } } if (!empty($proxy_host) && !empty($proxy_port)) { $_is_proxy = true; $fp = fsockopen($proxy_host, $proxy_port, $errno, $errstr, $timeout); } else { $fp = fsockopen($server_name, $port, $errno, $errstr, $timeout); } if (!$fp) { trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE); return; } else { if ($_is_proxy) { fputs($fp, 'GET ' . $params[ 'file' ] . " HTTP/1.0\r\n"); } else { fputs($fp, "GET $uri HTTP/1.0\r\n"); } if (!empty($host)) { fputs($fp, "Host: $host\r\n"); } if (!empty($accept)) { fputs($fp, "Accept: $accept\r\n"); } if (!empty($agent)) { fputs($fp, "User-Agent: $agent\r\n"); } if (!empty($referer)) { fputs($fp, "Referer: $referer\r\n"); } if (isset($extra_headers) && is_array($extra_headers)) { foreach ($extra_headers as $curr_header) { fputs($fp, $curr_header . "\r\n"); } } if (!empty($user) && !empty($pass)) { fputs($fp, 'Authorization: BASIC ' . base64_encode("$user:$pass") . "\r\n"); } fputs($fp, "\r\n"); while (!feof($fp)) { $content .= fgets($fp, 4096); } fclose($fp); $csplit = preg_split("!\r\n\r\n!", $content, 2); $content = $csplit[ 1 ]; if (!empty($params[ 'assign_headers' ])) { $template->assign($params[ 'assign_headers' ], preg_split("!\r\n!", $csplit[ 0 ])); } } } else { trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE); return; } } else { $content = @file_get_contents($params[ 'file' ]); if ($content === false) { throw new SmartyException("{fetch} cannot read resource '" . $params[ 'file' ] . "'"); } } if (!empty($params[ 'assign' ])) { $template->assign($params[ 'assign' ], $content); } else { return $content; } } ================================================ FILE: Tool/smarty-3.1.32/libs/plugins/function.html_checkboxes.php ================================================ ' output=$names} * {html_checkboxes values=$ids checked=$checked separator='
' output=$names} * * Params: * * - name (optional) - string default "checkbox" * - values (required) - array * - options (optional) - associative array * - checked (optional) - array default not set * - separator (optional) - ie
or   * - output (optional) - the output next to each checkbox * - assign (optional) - assign the output as an array to this variable * - escape (optional) - escape the content (not value), defaults to true * * * @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} * (Smarty online manual) * @author Christopher Kvarme * @author credits to Monte Ohrt * @version 1.0 * * @param array $params parameters * @param Smarty_Internal_Template $template template object * * @return string * @uses smarty_function_escape_special_chars() * @throws \SmartyException */ function smarty_function_html_checkboxes($params, Smarty_Internal_Template $template) { $template->_checkPlugins(array(array('function' => 'smarty_function_escape_special_chars', 'file' => SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php'))); $name = 'checkbox'; $values = null; $options = null; $selected = array(); $separator = ''; $escape = true; $labels = true; $label_ids = false; $output = null; $extra = ''; foreach ($params as $_key => $_val) { switch ($_key) { case 'name': case 'separator': $$_key = (string) $_val; break; case 'escape': case 'labels': case 'label_ids': $$_key = (bool) $_val; break; case 'options': $$_key = (array) $_val; break; case 'values': case 'output': $$_key = array_values((array) $_val); break; case 'checked': case 'selected': if (is_array($_val)) { $selected = array(); foreach ($_val as $_sel) { if (is_object($_sel)) { if (method_exists($_sel, '__toString')) { $_sel = smarty_function_escape_special_chars((string) $_sel->__toString()); } else { trigger_error('html_checkboxes: selected attribute contains an object of class \'' . get_class($_sel) . '\' without __toString() method', E_USER_NOTICE); continue; } } else { $_sel = smarty_function_escape_special_chars((string) $_sel); } $selected[ $_sel ] = true; } } elseif (is_object($_val)) { if (method_exists($_val, '__toString')) { $selected = smarty_function_escape_special_chars((string) $_val->__toString()); } else { trigger_error('html_checkboxes: selected attribute is an object of class \'' . get_class($_val) . '\' without __toString() method', E_USER_NOTICE); } } else { $selected = smarty_function_escape_special_chars((string) $_val); } break; case 'checkboxes': trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', E_USER_WARNING); $options = (array) $_val; break; case 'assign': break; case 'strict': break; case 'disabled': case 'readonly': if (!empty($params[ 'strict' ])) { if (!is_scalar($_val)) { trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute", E_USER_NOTICE); } if ($_val === true || $_val === $_key) { $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"'; } break; } // omit break; to fall through! default: if (!is_array($_val)) { $extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"'; } else { trigger_error("html_checkboxes: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) { return ''; } /* raise error here? */ $_html_result = array(); if (isset($options)) { foreach ($options as $_key => $_val) { $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); } } else { foreach ($values as $_i => $_key) { $_val = isset($output[ $_i ]) ? $output[ $_i ] : ''; $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids, $escape); } } if (!empty($params[ 'assign' ])) { $template->assign($params[ 'assign' ], $_html_result); } else { return implode("\n", $_html_result); } } /** * @param $name * @param $value * @param $output * @param $selected * @param $extra * @param $separator * @param $labels * @param $label_ids * @param bool $escape * * @return string */ function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids, $escape = true) { $_output = ''; if (is_object($value)) { if (method_exists($value, '__toString')) { $value = (string) $value->__toString(); } else { trigger_error('html_options: value is an object of class \'' . get_class($value) . '\' without __toString() method', E_USER_NOTICE); return ''; } } else { $value = (string) $value; } if (is_object($output)) { if (method_exists($output, '__toString')) { $output = (string) $output->__toString(); } else { trigger_error('html_options: output is an object of class \'' . get_class($output) . '\' without __toString() method', E_USER_NOTICE); return ''; } } else { $output = (string) $output; } if ($labels) { if ($label_ids) { $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_', $name . '_' . $value)); $_output .= '