From 2a6b46f868435996e35c577d6de2a13f327457ac Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sat, 13 Dec 2014 22:53:47 +0800 Subject: [PATCH 01/32] add Theme helper --- .../Authentication/AuthenticationService.php | 1 + Westdc/Helpers/Theme.php | 202 ++++++++++++++++++ 2 files changed, 203 insertions(+) create mode 100644 Westdc/Helpers/Theme.php diff --git a/Westdc/Authentication/AuthenticationService.php b/Westdc/Authentication/AuthenticationService.php index 227ea47..2a14d8b 100644 --- a/Westdc/Authentication/AuthenticationService.php +++ b/Westdc/Authentication/AuthenticationService.php @@ -43,6 +43,7 @@ class AuthenticationService $action = $e->getRouteMatch()->getParam('action'); //view::Dump($e->getRouteMatch()->getMatchedRouteName() . ":" . $controller."-".$action,false); + $this->preCookieCheck(); try{ diff --git a/Westdc/Helpers/Theme.php b/Westdc/Helpers/Theme.php new file mode 100644 index 0000000..5993f38 --- /dev/null +++ b/Westdc/Helpers/Theme.php @@ -0,0 +1,202 @@ +_init_plus(); + } + + //初始化插件 + function _init_plus() + { + $this->plus = array( + + /**********Jquery公共库******/ + + //Jquery + 'jquery'=>array( + $this->ScriptKey => array( + '/js/lib/jquery.lasted.js' + ) + ), + + //Jquery UI + 'jquery_ui'=>array( + $this->ScriptKey => array( + '/js/lib/jquery.lasted.js', + '/js/lib/jquery.ui/jquery-ui.lasted.js' + ), + $this->CSSKey =>array( + '/js/lib/jquery.ui/jquery-ui.lasted.css' + ) + ), + + /********* Bootstrap ******/ + 'bootstrap'=>array( + $this->ScriptKey => array( + '/js/lib/bootstrap/js/bootstrap.min.js', + ), + $this->CSSKey =>array( + '/js/lib/bootstrap/css/bootstrap.min.css', + '/js/lib/bootstrap/css/bootstrap-responsive.min.css' + ) + ), + + + /********Jquery 插件********/ + + //colorbox + 'colorbox' => array( + $this->ScriptKey => array( + '/lib/jquery.colorbox/jquery.colorbox-min.js' + ), + $this->CSSKey => array( + '/lib/jquery.colorbox/style2/colorbox.css' + ) + ), + + //inputbg + 'inputbg' => array( + $this->ScriptKey => array( + '/js/lib/custom/jquery.inputbg.js' + ) + ), + + //loadinglayer + 'loadinglayer' => array( + $this->ScriptKey => array( + '/js/lib/custom/jquery.loadinglayer.js' + ) + ), + + //admin_plugin + 'admin_plugin' => array( + $this->ScriptKey => array( + '/js/lib/custom/admin_plugin.js' + ) + ), + + 'jplayer' => array( + $this->ScriptKey => array( + '/js/lib/jplayer/jquery.jplayer.min.js' + ) + ), + + //slides + 'slides' => array( + $this->ScriptKey => array( + '/js/lib/jquery.slides.min.js' + ) + ), + + 'datatable' => array( + $this->ScriptKey => array( + '/js/lib/jquery.datatable/jquery.dataTables.min.js' + ), + $this->CSSKey => array( + '/js/lib/jquery.datatable/datatable.css' + ) + ), + + 'masonry' => array( + $this->ScriptKey => array( + '/js/lib/jquery.masonry.min.js' + ), + ), + + 'uploadify' => array( + $this->ScriptKey => array( + '/js/lib/uploadify/jquery.uploadify.min.js' + ), + $this->CSSKey => array( + '/js/lib/uploadify/uploadify.css' + ), + ), + + 'datepicker' => array( + $this->ScriptKey => array( + '/js/lib/datepicker/jquery-ui-1.10.3.custom.min.js' + ), + $this->CSSKey => array( + '/js/lib/datepicker/jquery-ui-1.10.3.custom.min.css' + ) + ), + + /*********谷歌地图*********/ + + //Google Map API v3 + 'google_map_v3'=>array( + $this->ScriptKey => array( + 'http://maps.google.com/maps/api/js?sensor=false&language=zh-cn' + ) + ), + + //Google Map API v3 - KeyDragZone + 'google_map_keydragzone' => array( + $this->ScriptKey => array( + '/lib/google-map/keydragzoom.js' + ) + ), + + 'kindeditor' => array( + $this->ScriptKey => array( + '/lib/kindeditor/kindeditor-min.js', + '/lib/kindeditor/lang/zh_CN.js' + ) + ), + //Tianditu + 'tianditu'=>array( + $this->ScriptKey => array( + 'http://api.tianditu.com/js/maps.js' + ) + ), + );//插件列表 + + }// _init_plus() + + //前台添加插件 + function appendPlus($render,$plus_name){ + + $plus_name = strtolower($plus_name); + + $plusing = $this->plus; + + if(!empty($plusing[$plus_name][$this->ScriptKey])) + { + foreach($plusing[$plus_name][$this->ScriptKey] as $k=>$v) + { + $render->headScript()->appendFile($v); + } + } + + if(!empty($plusing[$plus_name][$this->CSSKey])) + { + foreach($plusing[$plus_name][$this->CSSKey] as $k=>$v) + { + $render->headLink()->appendStylesheet($v); + } + } + + }// AppendPlus + + //加载页面中的JS + function AppendModel($render,$model) + { + + $model = trim($model); + + $render->headScript()->appendFile("/js/lib/custom/models/".$model.".js"); + + }// +} From cc998bc5de5f8c7ef35d7404c1e290f4c8c34361 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sun, 14 Dec 2014 21:04:20 +0800 Subject: [PATCH 02/32] add ConfigService for fix conflicting service name of Config --- Westdc/Service/ServiceAgent/ConfigService.php | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Westdc/Service/ServiceAgent/ConfigService.php diff --git a/Westdc/Service/ServiceAgent/ConfigService.php b/Westdc/Service/ServiceAgent/ConfigService.php new file mode 100644 index 0000000..13c92b8 --- /dev/null +++ b/Westdc/Service/ServiceAgent/ConfigService.php @@ -0,0 +1,14 @@ + Date: Thu, 18 Dec 2014 21:14:30 +0800 Subject: [PATCH 03/32] add ServiceManagerAwareInterface --- Westdc/Member/Account.php | 21 +++++++++++++++++++-- Westdc/Member/Cookie.php | 7 ------- Westdc/Metadata/Metadata.php | 4 +++- 3 files changed, 22 insertions(+), 10 deletions(-) diff --git a/Westdc/Member/Account.php b/Westdc/Member/Account.php index ed87ee5..43da9fe 100644 --- a/Westdc/Member/Account.php +++ b/Westdc/Member/Account.php @@ -1,6 +1,8 @@ db = new Db(); $this->config = Config::get(); } + + public function init() + { + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + } + + public function setServiceManager(ServiceManager $serviceManager) + { + $this->serviceManager = $serviceManager; + + $this->init(); + + return $this; + } //获取账号信息,数组 public function getAccountInfo($id = 0) diff --git a/Westdc/Member/Cookie.php b/Westdc/Member/Cookie.php index ced375c..5d3f557 100644 --- a/Westdc/Member/Cookie.php +++ b/Westdc/Member/Cookie.php @@ -124,12 +124,5 @@ class Cookie setcookie('user','',time()-99999,'/'); setcookie('scr','',time()-99999,'/'); } - - public function getUser() - { - $sql = "SELECT * FROM ".$this->memberTable." m ORDER BY m.id DESC"; - $rs = $this->db->query($sql); - return $rs->fetchAll(); - } } \ No newline at end of file diff --git a/Westdc/Metadata/Metadata.php b/Westdc/Metadata/Metadata.php index 777a7a9..eb57df6 100644 --- a/Westdc/Metadata/Metadata.php +++ b/Westdc/Metadata/Metadata.php @@ -8,9 +8,11 @@ namespace Westdc\Metadata; +use Zend\ServiceManager\ServiceManager; +use Zend\ServiceManager\ServiceManagerAwareInterface; -class Metadata { +class Metadata implements ServiceManagerAwareInterface{ From 1ab6b8bbf31b2dd5dc19adfbdd756f60cadfa6fd Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Thu, 18 Dec 2014 23:25:15 +0800 Subject: [PATCH 04/32] add load lazy service function in Westdc/Service/ServiceFactory --- Westdc/Metadata/Metadata.php | 32 ++++++++++++++++- Westdc/Service/ServiceFactory.php | 49 +++++++++++++++++++++++--- Westdc/Service/service.lazy.config.php | 4 +++ 3 files changed, 80 insertions(+), 5 deletions(-) create mode 100644 Westdc/Service/service.lazy.config.php diff --git a/Westdc/Metadata/Metadata.php b/Westdc/Metadata/Metadata.php index eb57df6..8f3a9e5 100644 --- a/Westdc/Metadata/Metadata.php +++ b/Westdc/Metadata/Metadata.php @@ -10,10 +10,40 @@ namespace Westdc\Metadata; use Zend\ServiceManager\ServiceManager; use Zend\ServiceManager\ServiceManagerAwareInterface; +use Westdc\EventModel\AbstractEventManager; + +class Metadata extends AbstractEventManager implements ServiceManagerAwareInterface{ + + protected $serviceManager; + + private $db; + + public function setServiceManager(ServiceManager $serviceManager) + { + $this->serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init() + { + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + } -class Metadata implements ServiceManagerAwareInterface{ + public function delete($uuid) + { + $tools = $this->serviceManager->get('Tools'); + + if( false == $tools->isUUID($uuid) ) + return "参数错误"; + + return true; + }//delete 删除元数据 } \ No newline at end of file diff --git a/Westdc/Service/ServiceFactory.php b/Westdc/Service/ServiceFactory.php index ba8633a..3f5ed3b 100644 --- a/Westdc/Service/ServiceFactory.php +++ b/Westdc/Service/ServiceFactory.php @@ -12,8 +12,31 @@ use Zend\ServiceManager\AbstractFactoryInterface; class ServiceFactory implements AbstractFactoryInterface{ + private $invokedService; + private $invokedNames; + private $currentServiceType; + + function __construct() + { + $this->invokedService = $this->getInvokedServiceFromConfig(); + $this->invokedNames = array_keys($this->invokedService); + } + + private function getInvokedServiceFromConfig() + { + return include dirname(__FILE__) . "/service.lazy.config.php"; + } + public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { + if(!is_array($this->invokedService)) + throw new \RuntimeException('lazy services not found'); + + if(in_array($requestedName , $this->invokedNames)) + { + $this->currentServiceType = "lazy"; + return true; + } $serviceAgentDir = __DIR__ . "/ServiceAgent"; @@ -24,6 +47,7 @@ class ServiceFactory implements AbstractFactoryInterface{ while(false !== ($file = readdir($handle))) { if(substr($file,0,strlen($file)-4) == (string)$requestedName) { + $this->currentServiceType = "agent"; return true; } } @@ -36,13 +60,30 @@ class ServiceFactory implements AbstractFactoryInterface{ public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName) { - $serviceName = __NAMESPACE__ . "\\ServiceAgent\\" . $requestedName; + switch($this->currentServiceType) + { + case 'lazy': + $service = new $this->invokedService[$requestedName]; - $service = new $serviceName; + $service->WESTDC_SERVICE_TYPE = "lazy"; + $service->WESTDC_SERVICE_NAME = $requestedName; - $service->name = $requestedName; + return $service; + + case 'agent': + $serviceName = __NAMESPACE__ . "\\ServiceAgent\\" . $requestedName; + + $service = new $serviceName; + + $service->WESTDC_SERVICE_TYPE = "agent"; + $service->WESTDC_SERVICE_NAME = $requestedName; + + return $service; + + } - return $service; } + + } \ No newline at end of file diff --git a/Westdc/Service/service.lazy.config.php b/Westdc/Service/service.lazy.config.php new file mode 100644 index 0000000..7fce29b --- /dev/null +++ b/Westdc/Service/service.lazy.config.php @@ -0,0 +1,4 @@ + 'Westdc\Helpers\Tools' +); \ No newline at end of file From 16e8a7acae449199f312e12f6b10c3483169e977 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Thu, 18 Dec 2014 23:38:46 +0800 Subject: [PATCH 05/32] add invoked service loading logic in Westdc\Service\ServiceManager --- Westdc/Service/ServiceManager.php | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Westdc/Service/ServiceManager.php b/Westdc/Service/ServiceManager.php index 1906b1a..558c090 100644 --- a/Westdc/Service/ServiceManager.php +++ b/Westdc/Service/ServiceManager.php @@ -18,6 +18,13 @@ class ServiceManager { { $this->serviceManager = new Zend_ServiceManager(); $this->serviceManager->addAbstractFactory(new ServiceFactory); + + $configService = $this->serviceManager->get('ConfigService'); + $invoked_services = $configService->get('service.invoked.ini'); + + foreach($invoked_services as $k=>$v) { + $this->serviceManager->setInvokableClass($k, $v); + } } public function addKey($key,$value = "") From a09322d720278374d38309b115df7cd0b67276c9 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Fri, 19 Dec 2014 10:25:49 +0800 Subject: [PATCH 06/32] add User service --- Westdc/User/User.php | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/Westdc/User/User.php b/Westdc/User/User.php index 20456ea..b76aeb0 100644 --- a/Westdc/User/User.php +++ b/Westdc/User/User.php @@ -8,8 +8,31 @@ namespace Westdc\User; +use Zend\ServiceManager\ServiceManager; +use Zend\ServiceManager\ServiceManagerAwareInterface; +use Westdc\EventModel\AbstractEventManager; +class User extends AbstractEventManager implements ServiceManagerAwareInterface{ -class User { + protected $serviceManager; + + private $db; + + public function setServiceManager(ServiceManager $serviceManager) + { + $this->serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init() + { + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + } + + } \ No newline at end of file From 27beb8fbaf26b3d60c2460f9bc3975ba201df6ac Mon Sep 17 00:00:00 2001 From: cuixin Date: Fri, 19 Dec 2014 11:58:47 +0800 Subject: [PATCH 07/32] add user module --- .../Authentication/AuthenticationService.php | 2 +- Westdc/Helpers/Assist.php | 11 +- Westdc/Service/ServiceAgent/User.php | 17 +++ Westdc/User/Cookie.php | 135 ------------------ Westdc/User/Member.php | 135 ------------------ Westdc/User/Status.php | 54 +++++++ Westdc/User/User.php | 8 ++ Westdc/User/UserService.php | 32 ----- 8 files changed, 89 insertions(+), 305 deletions(-) create mode 100644 Westdc/Service/ServiceAgent/User.php delete mode 100644 Westdc/User/Cookie.php delete mode 100644 Westdc/User/Member.php create mode 100644 Westdc/User/Status.php delete mode 100644 Westdc/User/UserService.php diff --git a/Westdc/Authentication/AuthenticationService.php b/Westdc/Authentication/AuthenticationService.php index 2a14d8b..9818577 100644 --- a/Westdc/Authentication/AuthenticationService.php +++ b/Westdc/Authentication/AuthenticationService.php @@ -42,7 +42,7 @@ class AuthenticationService $controller = $e->getRouteMatch()->getParam('controller'); $action = $e->getRouteMatch()->getParam('action'); - //view::Dump($e->getRouteMatch()->getMatchedRouteName() . ":" . $controller."-".$action,false); +// view::Dump($e->getRouteMatch()->getMatchedRouteName() . ":" . $controller."-".$action,false); $this->preCookieCheck(); diff --git a/Westdc/Helpers/Assist.php b/Westdc/Helpers/Assist.php index 2884d9f..cab69e7 100644 --- a/Westdc/Helpers/Assist.php +++ b/Westdc/Helpers/Assist.php @@ -18,8 +18,15 @@ class Assist { $request = $ctl->getRequest(); $page = $ctl->params()->fromRoute('page'); - - $paginator = new \Zend\Paginator\Paginator(new \Zend\Paginator\Adapter\ArrayAdapter($data)); + + if(is_array($data)){ + $data = new \Zend\Paginator\Adapter\ArrayAdapter($data); + } +// elseif($data instanceof ){ +// +// } + + $paginator = new \Zend\Paginator\Paginator($data); $paginator->setCurrentPageNumber($page) ->setItemCountPerPage($limit) ->setPageRange(6); diff --git a/Westdc/Service/ServiceAgent/User.php b/Westdc/Service/ServiceAgent/User.php new file mode 100644 index 0000000..78b4f0f --- /dev/null +++ b/Westdc/Service/ServiceAgent/User.php @@ -0,0 +1,17 @@ +db = new Db(); - $this->config = Config::get(); - - if(!empty($_COOKIE['scr'])) - { - $this->scr = $_COOKIE['scr']; - } - if(!empty($_COOKIE['user'])) - { - $this->user= $_COOKIE['user']; - } - } - - - /** - * 检测cookie - */ - public function checkcookie() - { - $uname = $this->user; - $hash = $this->scr; - - if(!empty($uname) && !empty($hash)) - { - if (preg_match("/[<|>|#|$|%|^|*|(|)|{|}|'|\"|;|:]/i",$uname) || preg_match("/[<|>|#|$|%|^|*|(|)|{|}|'|\"|;|:]/i",$hash)) - { - $this->mid=0; - return false; - } - else{ - $sql = "select {$this->FieldUsername} as userid,{$this->FieldPasword} as pwd from {$this->memberTable} where {$this->FieldUsername}='$uname'"; - $rs = $this->db->query($sql); - $row = $rs->fetch(); - $scr = $this->makescr($row['userid'],$row['pwd']); - - if($hash == $scr) - { - $this->srpwd=$row['pwd']; - return true; - } - else { - return false; - } - }//cookie安全 - }else { - return false; - }//exit - }//function checkcookie - - /** - * putcookie - * - * 登陆成功后放置cookie,包含安全码 - * - * @param String $uname - * @param String $pwd - * @param Int $time - */ - public function putcookie($uname,$pwd,$time = 604800) - { - try { - $scrString = $this->makescr($uname,$pwd);//加密验证串:防止用户密码被盗;防止伪造cookie。 - - if(!is_numeric($time)) - { - $time = 604800; - } - - setcookie('user',$uname,time()+$time,'/'); - setcookie('scr',$scrString,time()+$time,'/'); - - return true; - } catch (Exception $e) { - return false; - } - - }//function putcookie - - /** - * 生成安全码 - * - * @param String $u - * @param String $p - */ - public function makescr($u,$p) - { - return substr(md5($u.$p.$this->ck),3,20); - } - - /** - * 清除cookie - */ - static function flushcookie() - { - setcookie('user','',time()-99999,'/'); - setcookie('scr','',time()-99999,'/'); - } - - public function getUser() - { - $sql = "SELECT * FROM ".$this->memberTable." m ORDER BY m.id DESC"; - $rs = $this->db->query($sql); - return $rs->fetchAll(); - } - -} \ No newline at end of file diff --git a/Westdc/User/Member.php b/Westdc/User/Member.php deleted file mode 100644 index 9666e98..0000000 --- a/Westdc/User/Member.php +++ /dev/null @@ -1,135 +0,0 @@ -db = new Db(); - $this->config = Config::get(); - - if(!empty($_COOKIE['scr'])) - { - $this->scr = $_COOKIE['scr']; - } - if(!empty($_COOKIE['user'])) - { - $this->user= $_COOKIE['user']; - } - } - - - /** - * 检测cookie - */ - public function checkcookie() - { - $uname = $this->user; - $hash = $this->scr; - - if(!empty($uname) && !empty($hash)) - { - if (preg_match("/[<|>|#|$|%|^|*|(|)|{|}|'|\"|;|:]/i",$uname) || preg_match("/[<|>|#|$|%|^|*|(|)|{|}|'|\"|;|:]/i",$hash)) - { - $this->mid=0; - return false; - } - else{ - $sql = "select {$this->FieldUsername} as userid,{$this->FieldPasword} as pwd from {$this->memberTable} where {$this->FieldUsername}='$uname'"; - $rs = $this->db->query($sql); - $row = $rs->fetch(); - $scr = $this->makescr($row['userid'],$row['pwd']); - - if($hash == $scr) - { - $this->srpwd=$row['pwd']; - return true; - } - else { - return false; - } - }//cookie安全 - }else { - return false; - }//exit - }//function checkcookie - - /** - * putcookie - * - * 登陆成功后放置cookie,包含安全码 - * - * @param String $uname - * @param String $pwd - * @param Int $time - */ - public function putcookie($uname,$pwd,$time = 604800) - { - try { - $scrString = $this->makescr($uname,$pwd);//加密验证串:防止用户密码被盗;防止伪造cookie。 - - if(!is_numeric($time)) - { - $time = 604800; - } - - setcookie('user',$uname,time()+$time,'/'); - setcookie('scr',$scrString,time()+$time,'/'); - - return true; - } catch (Exception $e) { - return false; - } - - }//function putcookie - - /** - * 生成安全码 - * - * @param String $u - * @param String $p - */ - public function makescr($u,$p) - { - return substr(md5($u.$p.$this->ck),3,20); - } - - /** - * 清除cookie - */ - static function flushcookie() - { - setcookie('user','',time()-99999,'/'); - setcookie('scr','',time()-99999,'/'); - } - - public function getUser() - { - $sql = "SELECT * FROM ".$this->memberTable." m ORDER BY m.id DESC"; - $rs = $this->db->query($sql); - return $rs->fetchAll(); - } - -} \ No newline at end of file diff --git a/Westdc/User/Status.php b/Westdc/User/Status.php new file mode 100644 index 0000000..d19105a --- /dev/null +++ b/Westdc/User/Status.php @@ -0,0 +1,54 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init() + { + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + } + + + public function getUserCount(){ + + $sql="select count(id) as total from users"; + $uq=$this->db->query($sql); + + return $uq->fetchColumn(0); + + } + + public function getAdminCount(){ + + $sql="select count(id) as total from users where usertype='administrator'"; + $uq=$this->db->query($sql); + + return $uq->fetchColumn(0); + + } + +} \ No newline at end of file diff --git a/Westdc/User/User.php b/Westdc/User/User.php index b76aeb0..9fe7d49 100644 --- a/Westdc/User/User.php +++ b/Westdc/User/User.php @@ -33,6 +33,14 @@ class User extends AbstractEventManager implements ServiceManagerAwareInterface{ $this->db = $dbService->getPdo(); } + public function fetchAll(){ + $sql = "select * from users where usertype = 'member'"; + $rs = $this->db->query($sql); + return $rs->fetchAll(\PDO::FETCH_ASSOC); + + + } + } \ No newline at end of file diff --git a/Westdc/User/UserService.php b/Westdc/User/UserService.php deleted file mode 100644 index ef7a597..0000000 --- a/Westdc/User/UserService.php +++ /dev/null @@ -1,32 +0,0 @@ -serviceManager = $serviceManager; - - return $this; - } - -} \ No newline at end of file From aeb8f034b7f15050b994eaf0faedffa01dfb01fa Mon Sep 17 00:00:00 2001 From: "shayupi@qq.com" Date: Fri, 19 Dec 2014 14:48:02 +0800 Subject: [PATCH 08/32] add class Westdc\Mail\Template --- Westdc/Mail/Template.php | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 Westdc/Mail/Template.php diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php new file mode 100644 index 0000000..05e4a68 --- /dev/null +++ b/Westdc/Mail/Template.php @@ -0,0 +1,34 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init() + { + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + } + + public function fetchAll() + { + $sql='SELECT * FROM emailtext'; + $rs=$this->db->query($sql); + return $rs->fetchAll(\PDO::FETCH_ASSOC); + } +} \ No newline at end of file From d5e6c1e1bece06b877929588182fdecdbad1efdc Mon Sep 17 00:00:00 2001 From: "shayupi@qq.com" Date: Fri, 19 Dec 2014 18:23:38 +0800 Subject: [PATCH 09/32] West\Mail Template --- Westdc/Mail/Template.php | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index 05e4a68..18ed104 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -23,6 +23,7 @@ class Template implements ServiceManagerAwareInterface { $dbService = $this->serviceManager->get('Db'); $this->db = $dbService->getPdo(); + } public function fetchAll() @@ -31,4 +32,40 @@ class Template implements ServiceManagerAwareInterface $rs=$this->db->query($sql); return $rs->fetchAll(\PDO::FETCH_ASSOC); } + + public function insert($data,$id=0) + { + if($this->fetch($data['template'])) + { + return"该邮件模板已经存在!"; + } + + $dbhService = $this->serviceManager->get('Db'); + $dbh = $dbhService->getDbh(); + + if(empty($data['subject'])) + { + $data['subject']='未命名模板'; + } + + // 替换邮件内容中的'为'' + $data['body']=str_replace("'","''",$data['body']); + + $rs = $dbh->insert('emailtext',$data,1); + return $rs; + } + + public function fetch($key) + { + if(is_numeric($key)) + { + $sql="SELECT * FROM emailtext WHERE id=$key"; + }else + { + $sql="SELECT * FROM emailtext WHERE template='$key'"; + } + + $rs=$this->db->query($sql); + return $rs->fetch(); + } } \ No newline at end of file From 80a91fd4d5e0415e5d54244b3789079ffe52c8f5 Mon Sep 17 00:00:00 2001 From: "shayupi@qq.com" Date: Fri, 19 Dec 2014 21:17:03 +0800 Subject: [PATCH 10/32] Westdc\Mail\Template tools CURD --- Westdc/Mail/Template.php | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index 18ed104..312a95d 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -35,10 +35,6 @@ class Template implements ServiceManagerAwareInterface public function insert($data,$id=0) { - if($this->fetch($data['template'])) - { - return"该邮件模板已经存在!"; - } $dbhService = $this->serviceManager->get('Db'); $dbh = $dbhService->getDbh(); @@ -48,13 +44,33 @@ class Template implements ServiceManagerAwareInterface $data['subject']='未命名模板'; } - // 替换邮件内容中的'为'' + // 替换邮件内容中的 ' 为 '' $data['body']=str_replace("'","''",$data['body']); $rs = $dbh->insert('emailtext',$data,1); return $rs; } + //删除邮件模板 + public function del($id) + { + $sql = "DELETE FROM emailtext WHERE id=$id"; + $rs = $this->db->exec($sql); + return $rs; + } + + //更新邮件模板 + public function update($table,$data,$id) + { + $dbhService = $this->serviceManager->get('Db'); + $dbh = $dbhService->getDbh(); + + // 替换邮件内容中的 ' 为 '' + $data['body']=str_replace("'","''",$data['body']); + $rs = $dbh->update('emailtext',$data,"id=$id",1); + return $rs; + } + public function fetch($key) { if(is_numeric($key)) From 2ef3279992a992c1dfc6764d6b603968f06d47aa Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sun, 21 Dec 2014 11:21:38 +0800 Subject: [PATCH 11/32] add Westdc\Metadata\Search class , profection metadata delete function --- Westdc/Metadata/Metadata.php | 16 ++ Westdc/Metadata/Search.php | 292 +++++++++++++++++++++++++++++++++++ 2 files changed, 308 insertions(+) create mode 100644 Westdc/Metadata/Search.php diff --git a/Westdc/Metadata/Metadata.php b/Westdc/Metadata/Metadata.php index 8f3a9e5..4cd419a 100644 --- a/Westdc/Metadata/Metadata.php +++ b/Westdc/Metadata/Metadata.php @@ -43,6 +43,22 @@ class Metadata extends AbstractEventManager implements ServiceManagerAwareInterf if( false == $tools->isUUID($uuid) ) return "参数错误"; + + $sql = "delete from mdstatus where uuid='$uuid'"; + $sql1 = "delete from mdauthor where uuid='$uuid'"; + $sql2="delete from metadata where uuid='$uuid'"; + + try{ + $this->db->exec($sql); + $this->db->exec($sql1); + $this->db->exec($sql2); + + $search=new Search(); + $search->del($uuid,'uuid'); + }catch(\Exception $e){ + return $e->getMessage(); + } + return true; }//delete 删除元数据 diff --git a/Westdc/Metadata/Search.php b/Westdc/Metadata/Search.php new file mode 100644 index 0000000..8c9901d --- /dev/null +++ b/Westdc/Metadata/Search.php @@ -0,0 +1,292 @@ +text; + $temp = array(); + preg_match_all('/"([^"]+)"|([^\\s]+)/', (( $safe ) ? $this->safe_query($search) : $search), $temp); + + for ($i = 1; $i < count($temp); $i++) + { + foreach ( $temp[$i] as $value ) + { + if ( strlen($value) >= 3 ) + { + $this->terms[] = $value; + } + } + } + + } + + function sql_expr($field) + { + $sql=" 1=1 "; + if (!is_array($field)) + { + $field=array($field); + } + if (!count($this->terms)) + $this->parse_search(); + foreach($this->terms as $t) + { + $sql.=" and (1<>1 "; + foreach($field as $f) + { + $sql.=" or ".$f." ilike '%".$t."%' "; + } + $sql.=") "; + } + return $sql; + } + function __construct($text='') + { + require_once '/home/wlx/xunsearch/sdk/php/lib/XS.php'; + $this->xs=new XS('heihe'); + $this->search=$this->xs->search; + $this->terms = array(); + $this->text=$text; + + // other variable maybe used + $this->count = $this->total = $this->search_cost = 0; + $this->docs = $this->related = $this->corrected =$this->expanded = $this->hot = array(); + $this->error = $this->pager = $this->base_url=''; + } + + function dosearch() + { +// +// 支持的 GET 参数列表 +// q: 查询语句 +// m: 开启模糊搜索,其值为 yes/no +// f: 只搜索某个字段,其值为字段名称,要求该字段的索引方式为 self/both +// s: 排序字段名称及方式,其值形式为:xxx_ASC 或 xxx_DESC +// p: 显示第几页,每页数量为 XSSearch::PAGE_SIZE 即 10 条 +// ie: 查询语句编码,默认为 UTF-8 +// oe: 输出编码,默认为 UTF-8 +// xml: 是否将搜索结果以 XML 格式输出,其值为 yes/no +// +// variables + $eu = ''; + $__ = array('q', 'm', 'f', 's', 'p', 'ie', 'oe', 'syn', 'xml','east','west','south','north','begin','end'); + foreach ($__ as $_) + $$_ = isset($_GET[$_]) ? $_GET[$_] : ''; + +// recheck request parameters + $q = get_magic_quotes_gpc() ? stripslashes($q) : $q; + $f = empty($f) ? '_all' : $f; + ${'m_check'} = ($m == 'yes' ? ' checked' : ''); + ${'syn_check'} = ($syn == 'yes' ? ' checked' : ''); + ${'f_' . $f} = ' checked'; + ${'s_' . $s} = ' selected'; + if (!isset($q)) $q=''; +// base url + $this->base_url = '/search?q=' . urlencode($q) . '&m=' . $m . '&f=' . $f . '&s=' . $s .'&begin='.$begin.'&end='.$end.'&east='.$east.'&north='.$north.'&west='.$west.'&south='.$south. $eu; + + $total_begin = microtime(true); +// perform the search + try + { + $this->search->setCharset('UTF-8'); + + if (empty($q)) + { + // just show hot query + $this->hot = $this->search->getHotQuery(); + } + + { + // fuzzy search + $this->search->setFuzzy($m === 'yes'); + + // synonym search + $this->search->setAutoSynonyms($syn === 'yes'); + + // set query + if (!empty($f) && $f != '_all') + { + $this->search->setQuery($f . ':(' . $q . ')'); + } + else + { + $this->search->setQuery($q); + } + + //spatial search + if (!empty($east) && !empty($west) && !empty($south) && !empty($north)) + { + $this->search->addRange('east',null,$east); + $this->search->addRange('west',$west,null); + $this->search->addRange('south',$south,null); + $this->search->addRange('north',null,$north); + } + + //date search + if (!empty($begin)) + { + $from=strtotime($begin); + $this->search->addRange('timebegin',$from,null); + } + if (!empty($end)) + { + $to=strtotime($end); + $this->search->addRange('timeend',null,$to); + } + + // set sort + if (($pos = strrpos($s, '_')) !== false) + { + $sf = substr($s, 0, $pos); + $st = substr($s, $pos + 1); + $this->search->setSort($sf, $st === 'ASC'); + } + + // set offset, limit + $p = max(1, intval($p)); + $n = XSSearch::PAGE_SIZE; + $this->search->setLimit($n, ($p - 1) * $n); + + // get the result + $search_begin = microtime(true); + $this->docs = $this->search->search(); + $this->search_cost = microtime(true) - $search_begin; + + // get other result + $this->count = $this->search->getLastCount(); + $this->total = $this->search->getDbTotal(); + + if ($xml !== 'yes') + { + if ($this->count<1) + $this->expanded=$this->search->getExpandedQuery($q); + // try to corrected, if resul too few + if ($this->count < 1 || $this->count < ceil(0.001 * $this->total)) + $this->corrected = $this->search->getCorrectedQuery(); + // get related query + $this->related = $this->search->getRelatedQuery(); + } + + // gen pager + if ($this->count > $n) + { + $pb = max($p - 5, 1); + $pe = min($pb + 10, ceil($this->count / $n) + 1); + $this->pager = ''; + do + { + $this->pager .= ($pb == $p) ? '' . $p . '' : '[' . $pb . ']'; + } + while (++$pb < $pe); + } + } + } + catch (XSException $e) + { + $this->error = strval($e); + } +// calculate total time cost + $this->total_cost = microtime(true) - $total_begin; + +// XML OUPUT + if ($xml === 'yes' && !empty($q)) + { + header("Content-Type: text/xml; charset=$oe"); + echo "\n"; + echo "count\" total=\"$this->total\" cost=\"$this->total_cost\" xmlns:xs=\"http://www.xunsearch.com\">\n"; + if ($this->error !== '') + echo " error . "]]>\n"; + + foreach ($this->docs as $doc) + { + echo " rank() . "\" percent=\"" . $doc->percent() . "%\">\n"; + foreach ($doc as $k => $v) + { + echo " <$k>"; + if (is_numeric($v)) + echo $v; + else + echo "\n \n "; + echo "\n"; + } + echo " \n"; + } + echo "\n"; + exit(0); + } + } + //搜索建议 + function suggest($q) + { + $terms = array(); + if (!empty($q) && strpos($q, ':') === false) + { + try { + $terms = $this->search->setCharset('UTF-8')->getExpandedQuery($q); + } catch (XSException $e) { } + } + return json_encode($terms); + } + + //添加新文档 + //$data: 包含field和value的数组 + function add($data) + { + $doc=new XSDocument; + $index=$this->xs->index; + $doc->setFields($data); + $index->add($doc); + } + + //更新已有文档 + //$data: 包含field和value的数组 + function update($data) + { + $doc=new XSDocument; + $index=$this->xs->index; + $doc->setFields($data); + $index->update($doc); + } + //根据主键删除对应的索引 + function del($data,$field='') + { + $index=$this->xs->index; + if (empty($field)) + $index->del($data); + else { + $index->del($data,$field); + } + } +} From c705293d85a6ad451f84a31dbc713d033c50750d Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sun, 21 Dec 2014 20:19:17 +0800 Subject: [PATCH 12/32] add class Westdc\Metadata\Dataset --- Westdc/Metadata/Dataset.php | 51 +++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Westdc/Metadata/Dataset.php diff --git a/Westdc/Metadata/Dataset.php b/Westdc/Metadata/Dataset.php new file mode 100644 index 0000000..d0271bb --- /dev/null +++ b/Westdc/Metadata/Dataset.php @@ -0,0 +1,51 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init() + { + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + } + + /** + * @param $uuid + * @return mixed + */ + public function fetch($uuid) + { + $sql = "SELECT * FROM dataset WHERE uuid=?"; + $sth = $this->db->prepare($sql); + $sth ->execute(array($uuid)); + return $sth->fetch(); + } + + + + +} \ No newline at end of file From 658e1d96702dd45e35d1fb60779c23151db2ad93 Mon Sep 17 00:00:00 2001 From: "shayupi@qq.com" Date: Mon, 22 Dec 2014 13:57:24 +0800 Subject: [PATCH 13/32] edit emailTemplate duplicate --- Westdc/Mail/Template.php | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index 312a95d..374717b 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -33,8 +33,14 @@ class Template implements ServiceManagerAwareInterface return $rs->fetchAll(\PDO::FETCH_ASSOC); } - public function insert($data,$id=0) + //插入邮件模板 + public function insert($data) { + $temp=$this->fetch($data['template']); + if(isset($temp['id']) && is_numeric($temp['id']) && $temp['id']>0) + { + return '该邮件模板标识已经存在,请更换标识!'; + } $dbhService = $this->serviceManager->get('Db'); $dbh = $dbhService->getDbh(); @@ -44,8 +50,6 @@ class Template implements ServiceManagerAwareInterface $data['subject']='未命名模板'; } - // 替换邮件内容中的 ' 为 '' - $data['body']=str_replace("'","''",$data['body']); $rs = $dbh->insert('emailtext',$data,1); return $rs; @@ -60,13 +64,19 @@ class Template implements ServiceManagerAwareInterface } //更新邮件模板 - public function update($table,$data,$id) + public function update($data,$id) { + $temp=$this->fetch($data['template']); + if(isset($temp['id']) && is_numeric($temp['id']) && $temp['id']>0) + { + if($id!=$temp['id']) + return '该邮件模板标识已经存在,请更换标识!'; + } + $dbhService = $this->serviceManager->get('Db'); $dbh = $dbhService->getDbh(); - // 替换邮件内容中的 ' 为 '' - $data['body']=str_replace("'","''",$data['body']); + $rs = $dbh->update('emailtext',$data,"id=$id",1); return $rs; } From 66aeb02dc7f4d3fbc3abccddd51230de265c3651 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Mon, 22 Dec 2014 14:42:19 +0800 Subject: [PATCH 14/32] fixed a variable missing in AbstractEventManager,profection the Westdc\Metadata\Dataset --- Westdc/EventModel/AbstractEventManager.php | 2 + Westdc/Metadata/Dataset.php | 120 +++++++++++++++++++++ 2 files changed, 122 insertions(+) diff --git a/Westdc/EventModel/AbstractEventManager.php b/Westdc/EventModel/AbstractEventManager.php index 74357e5..7e1b051 100644 --- a/Westdc/EventModel/AbstractEventManager.php +++ b/Westdc/EventModel/AbstractEventManager.php @@ -14,6 +14,8 @@ use Zend\EventManager\EventManagerAwareInterface; abstract class AbstractEventManager { + protected $events; + public function setEventManager (EventManagerInterface $events) { $events->setIdentifiers(array( __CLASS__, diff --git a/Westdc/Metadata/Dataset.php b/Westdc/Metadata/Dataset.php index d0271bb..91c8728 100644 --- a/Westdc/Metadata/Dataset.php +++ b/Westdc/Metadata/Dataset.php @@ -34,6 +34,7 @@ class Dataset extends AbstractEventManager implements ServiceManagerAwareInterfa } /** + * 查询某个元数据的数据集信息(数据存储位置) * @param $uuid * @return mixed */ @@ -45,7 +46,126 @@ class Dataset extends AbstractEventManager implements ServiceManagerAwareInterfa return $sth->fetch(); } + /** + * + * @param $uuid + * @param $host + * @param $path + * @return bool|string + */ + public function record($uuid,$host,$path) + { + $tools = $this->serviceManager->get('Tools'); + + if( false == $tools->isUUID($uuid) ) + return "Invalid UUID"; + + $data = $this->fetch($uuid); + + if(isset($data['id']) && $data['id'] > 0) + return $this->update($uuid,$host,$path); + else + return $this->insert($uuid,$host,$path); + + } + + /** + * @param $uuid + * @param $host + * @param $path + * @return bool + */ + public function update($uuid,$host,$path) + { + $sql = "UPDATE dataset SET host='$host',path='$path' WHERE uuid='$uuid'"; + if($this->db->exec($sql) > 0) + { + $this->proftpUpload($uuid,$host); + $this->getEventManager()->trigger('dataset.update.success', $this, compact('uuid','host','path')); + return true; + }else{ + return false; + } + } + + /** + * @param $uuid + * @param $host + * @param $path + * @return bool + */ + public function insert($uuid,$host,$path) + { + $dbService = $this->serviceManager->get('Db'); + $dbh = $dbService->getDbh(); + + $id = $dbh->insert('dataset',[ + 'uuid' => $uuid, + 'host' => $host, + 'path' => $path, + ],true); + + if(is_numeric($id) && $id>0) + { + $this->proftpUpload($uuid,$host); + $this->getEventManager()->trigger('dataset.insert.success', $this, compact('id','uuid','host','path')); + return true; + }else{ + return false; + } + + } + + /** + * @param $uuid + * @return bool + */ + public function delete($uuid) + { + $sql = "DELETE FROM dataset WHERE uuid='$uuid'"; + if($this->db->exec($sql) > 0) + { + $this->getEventManager()->trigger('dataset.delete.success', $this, compact('uuid')); + return true; + }else{ + return false; + } + } + public function reload($uuid) + { + $data = $this->fetch($uuid); + + if(!isset($data['id']) || empty($data['id'])) + { + return "未找到对应的记录,无法完成更新"; + } + + try { + $this->proftpUpload($uuid, $data['host']); + }catch(\Exception $e){ + return $e->getMessage(); + } + return true; + + } + + + /** + * @param $uuid + * @param $host + */ + public function proftpUpload($uuid,$host) + { + if ($host=='ftp1.westgis.ac.cn') + { + //var_dump("http://ftp1.westgis.ac.cn/proftp_upload.php?uuid=".$uuid."&filelist=1"); + file_get_contents("http://ftp1.westgis.ac.cn/proftp_upload.php?uuid=".$uuid."&filelist=1"); + } else if ($host=='ftp2.westgis.ac.cn') { + //var_dump("http://ftp1.westgis.ac.cn/proftp_upload.php?uuid=".$uuid."&filelist=1"); + file_get_contents("http://ftp2.westgis.ac.cn/proftp_upload.php?uuid=".$uuid."&filelist=1"); + } + } } \ No newline at end of file From 80c90895c9e9e65f00750c5f4aa21d1885229d9f Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Tue, 23 Dec 2014 22:32:23 +0800 Subject: [PATCH 15/32] add new service Mail,add Reference module --- Westdc/Helpers/Auth.php | 5 +- Westdc/Helpers/Tools.php | 18 +- Westdc/Mail/Mail.php | 161 +++- Westdc/Mail/MailService.php | 32 - Westdc/Mail/Template.php | 35 + Westdc/Reference/Event/ReferenceEvent.php | 15 + Westdc/Reference/Event/RisEvent.php | 9 + Westdc/Reference/Handler/ReferenceHandler.php | 138 +++ Westdc/Reference/Handler/RisHandler.php | 91 ++ .../Reference/Listener/ReferenceListener.php | 31 + Westdc/Reference/Listener/RisListener.php | 27 + Westdc/Reference/Reference.php | 812 ++++++++++++++++++ Westdc/Reference/Ris.php | 342 ++++++++ Westdc/Reference/RisOutput.php | 153 ++++ Westdc/User/Account.php | 17 +- 15 files changed, 1826 insertions(+), 60 deletions(-) delete mode 100644 Westdc/Mail/MailService.php create mode 100644 Westdc/Reference/Event/ReferenceEvent.php create mode 100644 Westdc/Reference/Event/RisEvent.php create mode 100644 Westdc/Reference/Handler/ReferenceHandler.php create mode 100644 Westdc/Reference/Handler/RisHandler.php create mode 100644 Westdc/Reference/Listener/ReferenceListener.php create mode 100644 Westdc/Reference/Listener/RisListener.php create mode 100644 Westdc/Reference/Reference.php create mode 100644 Westdc/Reference/Ris.php create mode 100644 Westdc/Reference/RisOutput.php diff --git a/Westdc/Helpers/Auth.php b/Westdc/Helpers/Auth.php index ff76729..5334bc1 100644 --- a/Westdc/Helpers/Auth.php +++ b/Westdc/Helpers/Auth.php @@ -28,6 +28,9 @@ class Auth public function getIdentity($field) { - return $this->auth->getIdentity()->$field; + if(isset($this->auth->getIdentity()->$field)) + return $this->auth->getIdentity()->$field; + else + return null; } } \ No newline at end of file diff --git a/Westdc/Helpers/Tools.php b/Westdc/Helpers/Tools.php index fe9ec21..949a88e 100644 --- a/Westdc/Helpers/Tools.php +++ b/Westdc/Helpers/Tools.php @@ -2,13 +2,23 @@ namespace Westdc\Helpers; class Tools { - /** - * 判断是否为UUID字符串 - * 返回结果为0或1 - */ + + /** + * 判断是否为UUID字符串 + * @param $uuid + * @return int + */ public static function isUUID($uuid) { return preg_match("/^[0-9A-Za-z]{8}-[0-9A-Za-z]{4}-[0-9A-Za-z]{4}-[0-9A-Za-z]{4}-[0-9A-Za-z]{12}$/",$uuid); } + + /** + * @param $str + * @return bool + */ + public function isEmail($str){ + return true; + } } \ No newline at end of file diff --git a/Westdc/Mail/Mail.php b/Westdc/Mail/Mail.php index 12613f3..32fadd4 100644 --- a/Westdc/Mail/Mail.php +++ b/Westdc/Mail/Mail.php @@ -8,36 +8,163 @@ namespace Westdc\Mail; -use Zend\EventManager\EventManagerInterface; -use Zend\EventManager\EventManager; -use Zend\EventManager\EventManagerAwareInterface; +use Zend\Mime\Mime; +use Zend\ServiceManager\ServiceManager; +use Zend\ServiceManager\ServiceManagerAwareInterface; +use Westdc\EventModel\AbstractEventManager; +use Westdc\Service\ServiceManager as WestdcServiceManager; use Zend\Mail\Message; use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; +use Zend\Mime\Message as MimeMessage; +use Zend\Mime\Part as MimePart; -class Mail { +class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ - function __construct() + protected $serviceManager; + + private $db; + + public $mail; + public $config; + public $subject; + public $body; + public $type; + public $transport; + + public function setServiceManager(ServiceManager $serviceManager) { + $this->serviceManager = $serviceManager; - } + $this->init(); - public function setEventManager(EventManagerInterface $events) - { - $events->setIdentifiers(array( - __CLASS__, - get_called_class(), - )); - $this->events = $events; return $this; } - public function getEventManager() + private function init() { - if (NULL === $this->events) { - $this->setEventManager(new EventManager()); + if(!$this->serviceManager instanceof ServiceManager) + { + $serviceManager = new WestdcServiceManager(); + $this->serviceManager = $serviceManager->getServiceManager(); } - return $this->events; + + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + + $this->loadConfigure(); + $this->smtp(); + $this->buildMailMessage(); } + //单独调用Mail类的时候需要先执行委托函数 + public function __invoke() + { + $this->init(); + } + + public function loadConfigure() + { + $configService = $this->serviceManager->get('ConfigService'); + $this->config = $configService->get('email.ini'); + } + + public function smtp() + { + $this->transport = new SmtpTransport(); + + $options = new SmtpOptions(array( + 'name' => $this->config['smtp']['hostname'], + 'host' => $this->config['smtp']['host'], + 'port' => $this->config['smtp']['port'], // Notice port change for TLS is 587 + 'connection_class' => $this->config['smtp']['auth'], + 'connection_config' => array( + 'username' => $this->config['smtp']['username'], + 'password' => $this->config['smtp']['password'], + 'ssl' => $this->config['smtp']['ssl'], + ), + )); + + $this->transport->setOptions($options); + } + + public function buildMailMessage($mail = NULL) + { + if(empty($mail)) + { + $this->mail = new Message(); + }else{ + $this->mail = $mail; + } + + $this->mail->setEncoding("UTF-8"); + } + + //设置默认发件人 + public function setDefaultForm() + { + $this->mail->setFrom($this->config['smtp']['username'],$this->config['smtp']['name']); + } + + //添加收件人 + public function addTo($email,$name) + { + $this->mail->addTo($email,$name); + } + + //加载模板 + public function loadTemplate($id,$data){ + + $mailTemplate = $this->serviceManager->get('Mail/Template'); + + $content = $mailTemplate->load($id,$data); + + $this->subject = $content['subject']; + $this->body = $content['body']; + $this->type = $content['type']; + + }//加载模板 + + //使用loadTemplate 的结果发送邮件 + //在此之前需要使用 $this->mail->addTo()添加收件人 + public function send($from = NULL){ + + if(empty($this->subject) || empty($this->body)) + { + return "邮件信息不完整"; + } + + if($this->type == 'html') + { + $bodyPart = new MimeMessage(); + + $bodyMessage = new MimePart($this->body); + $bodyMessage->type = 'text/html'; + + $bodyPart->setParts(array($bodyMessage)); + + $this->mail->setBody($bodyPart); + }else{ + $this->mail->setBody($this->body); + } + + if(empty($from)) + { + $this->setDefaultForm(); + }else{ + $this->mail->setFrom($from['email'],$from['name']); + } + + $this->mail->setSubject($this->subject); + + try { + $this->transport->send($this->mail); + return true; + }catch(\Exception $e) + { + throw new \RuntimeException($e->getMessage()); + } + } + + } \ No newline at end of file diff --git a/Westdc/Mail/MailService.php b/Westdc/Mail/MailService.php deleted file mode 100644 index b8bd5c2..0000000 --- a/Westdc/Mail/MailService.php +++ /dev/null @@ -1,32 +0,0 @@ -serviceManager = $serviceManager; - - return $this; - } - -} \ No newline at end of file diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index 374717b..a590101 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -10,6 +10,8 @@ class Template implements ServiceManagerAwareInterface private $db; + const DEFAULT_TEMPLATE_TYPE = 'text'; + public function setServiceManager(ServiceManager $serviceManager) { $this->serviceManager = $serviceManager; @@ -94,4 +96,37 @@ class Template implements ServiceManagerAwareInterface $rs=$this->db->query($sql); return $rs->fetch(); } + + /** + * @param $key + * @param $data + * @return array + */ + public function load($key,$data){ + + $template_data = $this->fetch($key); + + $patterns = array(); + $replacements = array(); + + foreach($data as $k=>$v) + { + $patterns[]='/{'.$k.'}/i'; + $replacements[]=$v; + } + + ksort($patterns); + ksort($replacements); + + $replaced_body = preg_replace($patterns, $replacements, $template_data['body']); + $replaced_subject = preg_replace($patterns, $replacements, $template_data['subject']); + + return [ + 'subject' => $replaced_subject, + 'body' => $replaced_body, + 'type' => isset($template_data['type']) ? $template_data['type'] : self::DEFAULT_TEMPLATE_TYPE + ]; + + }//function load + } \ No newline at end of file diff --git a/Westdc/Reference/Event/ReferenceEvent.php b/Westdc/Reference/Event/ReferenceEvent.php new file mode 100644 index 0000000..8afc79f --- /dev/null +++ b/Westdc/Reference/Event/ReferenceEvent.php @@ -0,0 +1,15 @@ +db = \Zend_Registry::get('db'); + }else{ + $this->db = $db; + } + + $this->config = \Zend_Registry::get('config'); + $this->table = new Table(); + } + + public function checkReferenceParam(\Zend_EventManager_Event $e) + { + $data = $e->getParam('data'); + + if(!is_array($data)) + { + return "参数错误"; + } + + if(empty($data["title"])) + { + return "请输入标题"; + } + + if(empty($data['reference'])) + { + return "请输入前台引用方式,并且唯一"; + } + + return true; + } + + public function processReferenceData(\Zend_EventManager_Event $e) + { + $data = $e->getParam('data'); + + if(empty($data['attid'])) + { + $data['attid'] = 0; + } + + return $data; + } + + public function insertToReferenceTable(\Zend_EventManager_Event $e) + { + $att = $e->getParam('file_data'); + + $reference = new Reference(); + $title = $reference->getReferenceTitleFromFilenName($att['realname']); + + $data = array( + 'title'=>$title, + 'attid'=>$att['id'], + 'reference'=>$title.'---'.date("Y-m-d H:i:s").".".microtime().rand() + ); + + $dbh = new dbh(); + + $cache_data = array(); + + $cache_data['ref_id'] = $dbh->insert($this->table->reference,$data,true); + $cache_data['ref_title'] = $title; + + return $cache_data; + } + + public function checkMdrefParam(\Zend_EventManager_Event $e) + { + $data = $e->getParam('data'); + + if(!is_array($data)) + { + return "参数错误"; + } + + if(empty($data["refid"])) + { + return "请填写文献ID"; + } + + if(empty($data['uuid'])) + { + return "请填写UUID"; + } + + if(!view::isUuid($data['uuid'])) + { + return "UUID格式不正确"; + } + + if(($data['reftype']==='')) + { + return "请选择文献类型"; + } + + return true; + } + + public function processMdrefData(\Zend_EventManager_Event $e) + { + $data = $e->getParam('data'); + + if(empty($data['place'])) + { + $data['place'] = 0; + } + + if(!is_numeric($data['place'])) + { + $data['place'] = 0; + } + + return $data; + } + +} diff --git a/Westdc/Reference/Handler/RisHandler.php b/Westdc/Reference/Handler/RisHandler.php new file mode 100644 index 0000000..8a82079 --- /dev/null +++ b/Westdc/Reference/Handler/RisHandler.php @@ -0,0 +1,91 @@ +db = \Zend_Registry::get('db'); + }else{ + $this->db = $db; + } + + $this->config = \Zend_Registry::get('config'); + $this->table = new Table(); + } + + //检查ris中的文献是否已经存在 + public function checkRisReference(\Zend_EventManager_Event $e) + { + $ref = $e->getParam('ref'); + + $wheresql = array(); + + if(preg_match("/\'/",$ref['title'])) + { + $ref['title'] = preg_replace("/\'/","''",$ref['title']); + } + + $wheresql[] = " lower(title)=lower('{$ref['title']}') "; + $wheresql[] = " year='{$ref['year']}' "; + + //暂时不使用期刊限制 + /*if(isset($ref['publisher'])) + { + $wheresql[] = " publisher='{$ref['publisher']}' "; + }*/ + + if(count($wheresql) > 0) + { + $wheresql = " WHERE ".join(" and ",$wheresql); + }else{ + $wheresql = ""; + } + + $sql="select * from {$this->table->reference} $wheresql"; + $sth=$this->db->query($sql); + $row=$sth->fetch(); + $id=$row['id']; + + if(!empty($row['id'])) + { + return $id; + }else{ + return 0; + } + } + + //删除作者 + public function deleteAuthor(\Zend_EventManager_Event $e) + { + $id = $e->getParam('id'); + + $ref = new Reference(); + + return $ref->deleteReferenceAuthor($id); + } + + public function deleteTag(\Zend_EventManager_Event $e) + { + $id = $e->getParam('id'); + + $ref = new Reference(); + + return $ref->deleteReferenceTag($id); + } +} \ No newline at end of file diff --git a/Westdc/Reference/Listener/ReferenceListener.php b/Westdc/Reference/Listener/ReferenceListener.php new file mode 100644 index 0000000..a2aed5c --- /dev/null +++ b/Westdc/Reference/Listener/ReferenceListener.php @@ -0,0 +1,31 @@ +event = new \Zend_EventManager_EventManager(); + } + + public function attach(\Zend_EventManager_EventCollection $events) + { + $Handler = new ReferenceHandler(); + $events->attach('submit.checkParam', array($Handler, 'checkReferenceParam'), 100); + $events->attach('submit.processData', array($Handler, 'processReferenceData'), 100); + + $events->attach('upload.insertToReferenceTable', array($Handler, 'insertToReferenceTable'), 100); + + $events->attach('mdref.checkParam', array($Handler, 'checkMdrefParam'), 100); + $events->attach('mdref.processData', array($Handler, 'processMdrefData'), 100); + } + + public function detach(\Zend_EventManager_EventCollection $events) + { + + } + +} \ No newline at end of file diff --git a/Westdc/Reference/Listener/RisListener.php b/Westdc/Reference/Listener/RisListener.php new file mode 100644 index 0000000..e51e17b --- /dev/null +++ b/Westdc/Reference/Listener/RisListener.php @@ -0,0 +1,27 @@ +event = new \Zend_EventManager_EventManager(); + } + + public function attach(\Zend_EventManager_EventCollection $events) + { + $Handler = new RisHandler(); + $events->attach('checkLoad', array($Handler, 'checkRisReference'), 100); + $events->attach('deleteAuthor', array($Handler, 'deleteAuthor'), 100); + $events->attach('deleteTag', array($Handler, 'deleteTag'), 100); + } + + public function detach(\Zend_EventManager_EventCollection $events) + { + + } + +} \ No newline at end of file diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php new file mode 100644 index 0000000..47c9655 --- /dev/null +++ b/Westdc/Reference/Reference.php @@ -0,0 +1,812 @@ +db = \Zend_Registry::get('db'); + }else{ + $this->db = $db; + } + + $this->config = \Zend_Registry::get('config'); + + $Listener = new ReferenceListener(); + @$this->events()->attachAggregate($Listener); + + $this->table = new \Helpers\Table(); + } + + public function events(\Zend_EventManager_EventCollection $events = NULL) + { + if ($events !== NULL) { + $this->events = $events; + } elseif ($this->events === NULL) { + $this->events = new \Zend_EventManager_EventManager(__CLASS__); + } + return $this->events; + } + + public function reference($id = 0) + { + $data = $this->getReferenceParam(); + + $params = compact('data'); + $results = $this->events()->trigger('submit.checkParam', $this, $params); + $cache_data = $results->bottom(); + + if($cache_data !== true) + { + return $cache_data; + } + + $results = $this->events()->trigger('submit.processData', $this, $params); + $data = $results->bottom(); + + unset($data['submit']); + + $dbh = new dbh(); + + if(empty($id)) + { + $id = $dbh->insert($this->table->reference,$data,true); + }else{ + if(!$dbh->update($this->table->reference,$data," id=$id ",true)) + { + return "修改失败!请重试"; + } + } + + if(!empty($id) && is_numeric($id)) + { + return true; + }else{ + return "修改失败"; + } + } + + //获得参数 + public function getReferenceParam(\Zend_Controller_Request_Abstract $request = NULL) + { + $request = new \Zend_Controller_Request_Http(); + $data = array( + 'reference' => trim($request->getParam('reference')), + 'link' => trim($request->getParam('link')), + 'publisher' => trim($request->getParam('publisher')), + 'year' => (int)$request->getParam('year'), + 'title' => trim($request->getParam('title')), + 'ris' => trim($request->getParam('ris')), + 'note' => trim($request->getParam('note')), + 'attid' => (int)$request->getParam('attid'), + 'abstract' => $request->getParam('abstract'), + 'type' => $request->getParam('type'), + 'language' => $request->getParam('language'), + 'doi' => $request->getParam('doi'), + ); + return $data; + } + + //上传文献PDF + public function uploadReferencePdf($file,$autoread = false) + { + $files = new Files(); + $file_info = $files->upload($file,'literature/',true); + + if(isset($file_info['error']) && !empty($file_info['error'])) + { + return array("error" => $file_info['error']); + } + + $file_data = array( + 'filename' => $file_info['file_url'], + 'filetype' => 'literature', + 'filedesc' => $file_info['file_mime'], + 'userid' => view::User('id'), + 'filesize' => $file_info['file_size'], + 'realname' => $file_info['realname'] + ); + + $dbh = new dbh(); + + $file_id = $dbh->insert($this->table->attachments,$file_data,true); + $file_data['id'] = $file_id; + + if($autoread) + { + $params = compact('file_data'); + $results = $this->events()->trigger('upload.insertToReferenceTable', $this, $params); + $cache_data = $results->bottom(); + $file_data = array_merge($file_data,$cache_data); + } + + return $file_data; + } + + //通过文件名自动提取文章标题 + public function getReferenceTitleFromFilenName($filename) + { + $file = new Files(); + $title = str_replace( ".".$file->getFileTextExt($filename),"",$filename); + return $title; + } + + //删除文献文件 + public function deleteReferenceAttchment($attid) + { + if(empty($attid) || !is_numeric($attid)) + { + return array("error"=>"参数错误"); + } + + $files = new Files(); + $status = $files->delete($attid); + + if($status !== true) + { + return array("error"=>$status); + }else{ + return array("success"=>1); + } + } + + //所有文献 + public function fetchReferences() + { + $wheresql = array(); + if(!empty($this->keyword)) + { + $wheresql[] = " ({$this->table->reference}.title LIKE '%{$this->keyword}%' OR {$this->table->reference}.reference LIKE '%{$this->keyword}%') "; + } + + if(!empty($this->field)) + { + foreach($this->field as $k=>$v) + { + if(!empty($v)) + { + if(!is_numeric($v)) $v="'{$v}'"; + $wheresql[] = " ({$this->table->reference}.{$k}={$v} ) "; + }else{ + if(is_numeric($v)) + $wheresql[] = " ({$this->table->reference}.{$k} IS NULL OR {$this->table->reference}.{$k}=0 ) "; + else + $wheresql[] = " ({$this->table->reference}.{$k} IS NULL ) "; + }//if(empty($v) + }//foreach + } + + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "{$this->table->reference}.title"; + }else{ + $order = "{$this->table->reference}.{$this->order}"; + } + + $sql = "SELECT {$this->table->reference}.* FROM + {$this->table->reference} + $wheresql + ORDER BY $order {$this->sort}"; + $rs = $this->db->query($sql); + return $rs->fetchAll(); + } + + //获取专题数据的文献 + public function fetchThemeReferences($code) + { + $wheresql = array(); + //$wheresql[] = " s.code='$code' "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title iLIKE '%{$this->keyword}%' OR ref.reference iLIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " and ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "ref.year,ref.title"; + }else{ + $order = "ref.{$this->order} {$this->sort}"; + } + + $sql="select distinct ref.* from {$this->table->reference} ref where ref.id in (select r.refid from mdref r + left join datasource ds on r.uuid=ds.uuid left join {$this->table->source} s on s.id=ds.sourceid + where s.code='$code') + $wheresql + ORDER BY $order"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //Get WestDC references + public function fetchWestdcReferences() + { + $wheresql = array(); + $wheresql[]=" r.uuid='e31f5ea7-a4af-4ae3-9ac1-1a84132c4338' "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "ref.year,ref.title"; + }else{ + $order = "ref.{$this->order} {$this->sort}"; + } + + $sql="select distinct ref.* from mdref r left join {$this->table->reference} ref on r.refid=ref.id + $wheresql + ORDER BY $order"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //Get references which need to deal with + public function fetchTodoReferences() + { + $wheresql = array(); + $wheresql[]=" ref.id not in (select distinct refid from mdref) "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "ref.year,ref.title"; + }else{ + $order = "ref.{$this->order} {$this->sort}"; + } + + $sql="select distinct ref.* from {$this->table->reference} ref + $wheresql + ORDER BY $order"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //Get data author references which need to deal with + public function fetchAuthorReferences() + { + $wheresql = array(); + $wheresql[] = " ref.ris is NULL "; + $wheresql[]=" ref.id in (select distinct refid from mdref where reftype=0) "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "ref.year,ref.title"; + }else{ + $order = "ref.{$this->order} {$this->sort}"; + } + + $sql="select distinct ref.* from {$this->table->reference} ref + $wheresql + ORDER BY $order"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //Get references by data UUID + public function fetchReferencesByUUID($uuid) + { + $wheresql = array(); + $wheresql[]=" r.uuid='$uuid' "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "ref.year,ref.title"; + }else{ + $order = "ref.{$this->order} {$this->sort}"; + } + + $sql="select distinct ref.*,r.reftype,r.place,r.id as mrid from {$this->table->reference} ref left join {$this->table->metadata_reference} r on ref.id=r.refid + $wheresql + ORDER BY $order"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //Get references with data UUID + public function fetchReferencesWithUUID($uuid) + { + $wheresql = array(); + //$wheresql[]=" r.uuid='$uuid' "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if(empty($this->order)) + { + $order = "ref.year,ref.title"; + }else{ + $order = "ref.{$this->order} {$this->sort}"; + } + + $sql="select distinct ref.*,r.reftype,r.place,r.id as mrid from {$this->table->reference} ref left join + (select * from {$this->table->metadata_reference} r where uuid='$uuid') r on ref.id=r.refid + $wheresql + ORDER BY $order"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //单条文献的信息 + public function getOneReferenceData($id) + { + if(empty($id) || !is_numeric($id)) + { + return false; + } + + $sql = "SELECT * FROM {$this->table->reference} WHERE id=$id LIMIT 1"; + $rs = $this->db->query($sql); + $row = $rs->fetch(); + if ($row['attid']) + { + $files = new Files(); + $attfile = $files->getOne($row['attid']); + + $row['file'] = $attfile; + } + return $row; + } + + //获得reference类型的附件 + public function getReferenceFiles() + { + $sql = "SELECT att.*,ref.attid,ref.id as refid FROM {$this->table->attachments} att + LEFT JOIN {$this->table->reference} ref ON att.id=ref.attid + WHERE att.filetype='literature'"; + $rs = $this->db->query($sql); + $rows = $rs->fetchAll(); + return $rows; + } + + //删除文献 + public function deleteReference($id,$delete_att = false) + { + if(empty($id) || !is_numeric($id)) + { + return false; + } + + if($delete_att == false) + { + $sql = "DELETE FROM {$this->table->reference} WHERE id=$id"; + @$this->db->exec($sql); + + $sql = "DELETE FROM {$this->table->metadata_reference} WHERE refid=$id"; + @$this->db->exec($sql); + + $this->deleteReferenceAuthor($id); + $this->deleteReferenceTag($id); + + return true; + }else{ + + } + } + + //删除作者信息 + public function deleteReferenceAuthor($id) + { + if(empty($id) || !is_numeric($id)) + { + return false; + } + + $sql = "DELETE FROM {$this->table->reference_author} WHERE id=$id "; + return $this->db->exec($sql); + } + + //删除标签信息 + public function deleteReferenceTag($id) + { + if(empty($id) || !is_numeric($id)) + { + return false; + } + + $sql = "DELETE FROM {$this->table->reference_tag} WHERE id=$id "; + return $this->db->exec($sql); + } + + //建立文献与数据的关系 + public function createRelationFromReferenceToData($refid,$uuid,$reftype,$place,$id = NULL) + { + if(empty($refid) || !is_numeric($refid)) + { + return "参数错误"; + } + + if(!view::isUuid($uuid)) + { + return "参数错误"; + } + + $data = array( + 'uuid'=>$uuid, + 'refid'=>$refid, + 'reftype'=>$reftype, + 'place'=>$place + ); + + $dbh = new dbh(); + + if(empty($id)) + { + $id = $dbh->insert($this->table->metadata_reference,$data,true); + + if(is_numeric($id)) + { + return $id; + }else{ + return "关系写入失败,请检查是否已经存在"; + } + }else{ + $status = $dbh->update($this->table->metadata_reference,$data," id=$id "); + + if($status === true) + { + return $id; + }else{ + return "修改失败"; + } + } + } + + //获得某个文献关联的数据 (根据文献获得数据) + public function getDataByReference($id) + { + if(empty($id) || !is_numeric($id)) + { + return "参数错误"; + } + + $sql = "SELECT mr.id,mr.refid,mr.reftype,mr.place,md.title,md.uuid FROM {$this->table->metadata_reference} mr + LEFT JOIN {$this->table->metadata} md ON mr.uuid=md.uuid + WHERE mr.refid=$id + ORDER BY mr.place ASC"; + + $rs = $this->db->query($sql); + $rows = $rs->fetchAll(); + return $rows; + } + + //获得某个数据关联的文献 (根据数据获得文献) + public function getReferenceByData($uuid) + { + if(!view::isUuid($uuid)) + { + return "参数错误"; + } + + $sql = "SELECT mr.reftype,mr.place,md.title,md.uuid FROM {$this->table->metadata_reference} mr + LEFT JOIN {$this->table->metadata} md + WHERE mr.uuid = $uuid"; + + $rs = $this->db->query($sql); + $rows = $rs->fetchAll(); + return $rows; + } + + //文献类型 + public function referenceType() + { + return array( + 0 => '相关文献',//作者建议的文献或数据中心建议的文献 + 1 => '施引文献', + 2 => '参考文献', + 3 => '多篇文献', + 4 => '专题文献' + ); + } + + //数据文献参数 + public function getMdrefParam(\Zend_Controller_Request_Abstract $request = NULL) + { + $request = new \Zend_Controller_Request_Http(); + $data = array( + 'uuid' => trim($request->getParam('uuid')), + 'refid' => (int)$request->getParam('refid'), + 'place' => (int)$request->getParam('place'), + 'reftype' => (int)$request->getParam('reftype'), + ); + return $data; + } + + //写入数据文献 + public function makeMdref($id = NULL) + { + $data = $this->getMdrefParam(); + + $results = $this->events()->trigger('mdref.checkParam', $this, compact('data')); + $cache_data = $results->bottom(); + + if($cache_data !== true) + { + return $cache_data; + } + + $results = $this->events()->trigger('mdref.processData', $this, compact('data')); + $data = $results->bottom(); + + $id = $this->createRelationFromReferenceToData($data['refid'],$data['uuid'],$data['reftype'],$data['place'],$id); + + if(is_numeric($id)) + { + return true; + }else{ + return $id; + } + } + + //删除数据文献 + public function delMdref($id) + { + if(empty($id) || !is_numeric($id)) + { + return "参数错误"; + } + + $sql = "DELETE FROM {$this->table->metadata_reference} WHERE id=$id"; + if($this->db->exec($sql)) + { + return true; + }else{ + return "删除失败"; + } + } + + //按年份获得文献数量 + public function countByYear() + { + $sql = "SELECT count(id) as num,year FROM {$this->table->reference} GROUP BY year ORDER BY year DESC"; + $rs = $this->db->query($sql); + $rows = $rs->fetchAll(); + + return $rows; + } + + //获得作者 + public function getAuthorByReference($id,$join = false) + { + if(is_numeric($id)) + { + $sql = "SELECT * FROM {$this->table->reference_author} WHERE id=$id ORDER BY place ASC"; + $rs = $this->db->query($sql); + if(!$join) + { + return $rs->fetchAll(); + }else{ + foreach($rows = $rs->fetchAll() as $k=>$v) + { + $rows[$k] = (string)$v['firstname'].$v['lastname']; + } + return $rows; + } + } + + if(is_array($id)) + { + $sql = "SELECT * FROM {$this->table->reference_author} WHERE id IN (".join(",",$id).")"; + $rs = $this->db->query($sql); + return $rs->fetchAll(); + } + + return; + } + + //获得标签 + public function getTagsByReference($id,$single = false) + { + if(is_numeric($id)) + { + $sql = "SELECT * FROM {$this->table->reference_tag} WHERE id=$id"; + $rs = $this->db->query($sql); + if(!$single) + { + return $rs->fetchAll(); + }else{ + foreach($rows = $rs->fetchAll() as $k=>$v) + { + $rows[$k] = (string)$v['tag']; + } + return $rows; + } + } + + return; + } + + //Get data author references + //$ordertype 0: by data, 1: by literature + public function getReferencesByAuthor($uid,$ordertype=0,$reftype=0) + { + $wheresql = array(); + $wheresql[] = " a.userid=$uid "; + $wheresql[] = " a.status=1 "; + if(!empty($this->keyword)) + { + if($ordertype==0) + { + $wheresql[] = " (md.title LIKE '%{$this->keyword}%' OR md.description LIKE '%{$this->keyword}%') "; + }else{ + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + if($ordertype==0) + { + $order = "md.title"; + $sql="SELECT md.title,md.uuid,count(mr.id) as c FROM metadata md + LEFT JOIN (select * from mdref where reftype=$reftype) mr ON md.uuid=mr.uuid + LEFT JOIN mdauthor a ON md.uuid=a.uuid + left join reference ref on mr.refid=ref.id + $wheresql + group by md.title,md.uuid + ORDER BY c desc,$order"; + }else{ + $order = "ref.title"; + $sql="SELECT ref.*,count(mr.uuid) as c FROM metadata md + LEFT JOIN mdref mr ON md.uuid=mr.uuid + LEFT JOIN mdauthor a ON md.uuid=a.uuid + left join reference ref on mr.refid=ref.id + $wheresql and mr.reftype=$reftype + group by ref.id + ORDER BY c desc,$order"; + } + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //Get author references by data uuid + public function getReferencesByAuthorUUID($uid,$uuid) + { + $wheresql = array(); + $wheresql[] = " a.userid=$uid "; + $wheresql[] = " a.status=1 "; + $wheresql[] = " mr.uuid='$uuid' "; + if(!empty($this->keyword)) + { + $wheresql[] = " (ref.title LIKE '%{$this->keyword}%' OR ref.reference LIKE '%{$this->keyword}%') "; + } + if(count($wheresql)>0) + { + $wheresql = " WHERE ".join(" AND ",$wheresql); + }else{ + $wheresql = ""; + } + + $order = "ref.title"; + $sql="SELECT md.title as mdtitle,md.uuid,ref.id,ref.reference,ref.link,mr.place,mr.id as mrid,mr.reftype FROM mdref mr + LEFT JOIN metadata md ON md.uuid=mr.uuid + LEFT JOIN mdauthor a ON md.uuid=a.uuid + left join reference ref on mr.refid=ref.id + $wheresql + order by mr.reftype,mr.place ASC,ref.id DESC,md.ts_created desc"; + $rs=$this->db->query($sql); + return $rs->fetchAll(); + } + + //数据作者修改推荐文献的排序 + public function changeOrderByAuthor($uid,$id,$order) + { + $sql="update mdref set place=$order where id=$id and uuid in + (select uuid from mdauthor where status=1 and userid=$uid)"; + if($this->db->exec($sql)) + { + return true; + }else{ + return false; + } + } + + //数据作者移除推荐文献 + public function removeReferenceByAuthor($uid,$id) + { + $sql = "DELETE FROM mdref WHERE id=$id and uuid in (select uuid from mdauthor where userid=$uid AND status=1)"; + if($this->db->exec($sql)) + { + return true; + }else{ + return false; + } + } + + //数据作者添加推荐文献 + public function insertMdrefByAuthor($uid,$refid,$uuid,$place,$reftype=0) + { + $sql="select * from mdauthor where status=1 and uuid='$uuid' and userid=$uid"; + $rs=$this->db->fetchRow($sql); + if ($rs) + { + $id = $this->createRelationFromReferenceToData($refid,$uuid,$reftype,$place); + if(is_numeric($id)) + { + return true; + }else{ + return $id; + } + } else { + return false; + } + } +} diff --git a/Westdc/Reference/Ris.php b/Westdc/Reference/Ris.php new file mode 100644 index 0000000..72da0dc --- /dev/null +++ b/Westdc/Reference/Ris.php @@ -0,0 +1,342 @@ +db = \Zend_Registry::get('db'); + }else{ + $this->db = $db; + } + + $this->config = \Zend_Registry::get('config'); + + $Listener = new RisListener(); + @$this->events()->attachAggregate($Listener); + + $this->table = new \Helpers\Table(); + } + + public function events(\Zend_EventManager_EventCollection $events = NULL) + { + if ($events !== NULL) { + $this->events = $events; + } elseif ($this->events === NULL) { + $this->events = new \Zend_EventManager_EventManager(__CLASS__); + } + return $this->events; + } + + //ris导入 + public function loadout() + { + $file = $this->uploadRisFile(); + $text = $this->loadRisText(); + + if(empty($text) && $file === false) + { + return "导入失败,请选择要导入的文件或直接使用ris文本"; + } + + $records = array(); + + if($file !== false) + { + $records = array_merge($records,$this->processRis($file,NULL)); + } + + if(!empty($text)) + { + $records = array_merge($records,$this->processRis(NULL,$text)); + } + + $this->ris_records = $records; + + $data = $this->reBuildRisArray($records); + return $data; + } + + //上传RIS文件 + public function uploadRisFile() + { + if(!isset($_FILES['Filedata'])) + { + return; + } + + $file = $_FILES['Filedata']; + + if (@is_uploaded_file($file['tmp_name']) === false) { + return; + } + + return $file; + } + + //文本直接导入 + public function loadRisText() + { + if(!isset($_REQUEST['ristext'])) + { + return; + } + + $text = $_REQUEST['ristext']; + return $text; + } + + //处理ris文件 + public function processRis($file = NULL,$text = NULL) + { + $ris = new RISReader(); + if(!empty($file) && empty($text)) + { + $ris->parseFile($file['tmp_name']); + }else{ + $ris->parseString($text); + } + + $records = $ris->getRecords(); + + return $records; + } + + //对解析过的数据进行编排 + public function reBuildRisArray($records) + { + $data = array(); + foreach($records as $k=>$ref) + { + $data[$k] = array(); + foreach($ref as $index=>$value) + { + if(isset($this->attr[$index])) + { + $index_name = $this->attr[$index]; + if(count($value) > 1) + { + $data[$k][$index_name] = array(); + foreach($value as $item) + { + $data[$k][$index_name][] = $item; + } + }else{ + $data[$k][$index_name] = $value[0]; + } + } + } + } + unset($records); + return $data; + } + + //将解析好的ris数据写入数据库 + public function pushToDataTable($data){ + + if(!is_array($data) || count($data) < 1) + { + return false; + } + + $dbh = $this->dbh = new dbh(); + + foreach($data as $k=>$ref) + { + if (is_null($ref['title'])) + { + return; + } + + @$tags = $ref['tags']; + @$author = $ref['author']; + + $ref['ris'] = $this->makeRisData(array(0=>$this->ris_records[$k])); + + $results = $this->events()->trigger('checkLoad', $this, compact('ref')); + $id = $results->bottom(); + + if ($id > 0) + { + $this->unsetVar($ref); + $this->events()->trigger('deleteAuthor', $this, compact('id')); + $this->events()->trigger('deleteTag', $this, compact('id')); + + unset($ref['reference']); + + $dbh->update($this->table->reference,$ref," id=$id "); + } else { + $ref['reference'] = $this->makeReferenceFlag($ref); + $this->unsetVar($ref); + $id = $dbh->insert($this->table->reference,$ref,true); + } + + $this->insertTags($id,$tags); + $this->insertAuthor($id,$author); + } + } + + //更新单个reference的RIS + public function updateWithRis($id,$ref) + { + if(empty($id) || !is_numeric($id)) + { + return false; + } + + if (is_null($ref['title'])) + { + return; + } + + @$tags = $ref['tags']; + @$author = $ref['author']; + + $ref['ris'] = $this->makeRisData(array(0=>$this->ris_records[0])); + + $this->events()->trigger('deleteAuthor', $this, compact('id')); + $this->events()->trigger('deleteTag', $this, compact('id')); + + $this->unsetVar($ref); + if(isset($ref['reference'])) unset($ref['reference']); + + $this->dbh = $dbh = new dbh(); + + if($dbh->update($this->table->reference,$ref," id=$id ")) + { + $this->insertTags($id,$tags); + $this->insertAuthor($id,$author); + return true; + }else{ + return false; + } + + } + + //写入标签 + public function insertTags($id,$tags){ + if(is_array($tags) && count($tags) > 0) + { + foreach($tags as $v) + { + $this->dbh->insert($this->table->reference_tag,array('id'=>$id,'tag'=>$v)); + } + return true; + }else{ + return false; + } + } + + //写入作者 + public function insertAuthor($id,$author) + { + $index = 0; + if(is_array($author) && count($author) > 0) + { + foreach($author as $v) + { + $index ++ ; + $author_splited = $this->splitAuthor($v); + $this->dbh->insert($this->table->reference_author,array('id'=>$id , 'lastname'=>$author_splited['lastname'] , 'firstname'=>$author_splited['firstname'] , 'place'=>$index )); + } + return true; + }else{ + if(is_string($author)) + { + $author_splited = $this->splitAuthor($author); + $this->dbh->insert($this->table->reference_author,array('id'=>$id , 'lastname'=>$author_splited['lastname'] , 'firstname'=>$author_splited['firstname'] , 'place'=>0 )); + } + return false; + } + } + + //创建ris格式的数据 + public function makeRisData($ref) + { + $ris_writer = new RISWriter(); + return $ris_writer->writeRecords($ref); + } + + //创建reference 字段 + public function makeReferenceFlag($ref){ + $str=''; + if(is_array($ref['author']) && count($ref['author']) > 0) + { + $str .= join(', ',$ref['author']).'. '; + } else if (is_string($ref['author'])) { + $str .= $ref['author'].'. '; + } + $str .= $ref['title'].'. '; + $str .= $ref['publisher'].', '; + isset($ref['year']) ? $str .= $ref['year'].', ':""; + isset($ref['volume']) ? $str .= $ref['volume']:""; + isset($ref['issue']) ? $str .= '('.$ref['issue'].')':""; + isset($ref['pages']) ? $str .= ':'.$ref['pages']:""; + isset($ref['endpage'])? $str .= '-'.$ref['endpage']:""; + isset($ref['doi']) ? $str .= '. doi:'.$ref['doi'] : ""; + + return $str; + } + + //卸载不需要的变量 + public function unsetVar(&$ref) + { + unset($ref['pages']); + unset($ref['endpage']); + unset($ref['issue']); + unset($ref['volume']); + unset($ref['tags']); + unset($ref['author']); + } + + //将作者名字分割为数组 + public function splitAuthor($author){ + if(preg_match("/\,/",$author)) + { + $arr = explode(",",$author); + return array( + 'lastname' => trim($arr[0]), + 'firstname' => trim($arr[1]) + ); + }else{ + return array( + 'firstname' => '', + 'lastname' => trim($author) + ); + } + } + + public $attr = array( + 'TY' => 'type', + 'TI' => 'title', + 'AU' => 'author', + 'PY' => 'year', + 'LA' => 'language', + 'KW' => 'tags', + 'AB' => 'abstract', + 'DO' => 'doi', + 'T2' => 'publisher', + 'VL' => 'volume', + 'IS' => 'issue', + 'SP' => 'pages', + 'EP' => 'endpage' + ); +} diff --git a/Westdc/Reference/RisOutput.php b/Westdc/Reference/RisOutput.php new file mode 100644 index 0000000..44b7151 --- /dev/null +++ b/Westdc/Reference/RisOutput.php @@ -0,0 +1,153 @@ +db = \Zend_Registry::get('db'); + }else{ + $this->db = $db; + } + + $this->config = \Zend_Registry::get('config'); + + //$Listener = new Listener(); + //@$this->events()->attachAggregate($Listener); + + $this->table = new \Helpers\Table(); + } + + public function events(\Zend_EventManager_EventCollection $events = NULL) + { + if ($events !== NULL) { + $this->events = $events; + } elseif ($this->events === NULL) { + $this->events = new \Zend_EventManager_EventManager(__CLASS__); + } + return $this->events; + } + + //读取数据 + public function preRead($mode = "all") + { + if($mode == "all") + { + $sql = "SELECT * FROM {$this->table->reference} where length(ris)<10 or ris is null ORDER BY year DESC,title ASC,id ASC"; + $rs = $this->db->query($sql); + return $rs->fetchAll(); + } + + + }//preRead + + //将数据组成RIS数组格式 + public function processArrayDataToRisData($arrayData,$risPrior = true,$mixAuthor = true,$mixTags = true) + { + if(!is_array($arrayData)) + { + return false; + } + + $risData = array(); + + if($risPrior === true) + { + $risReader = new RISReader(); + } + + $this->ris = new Ris(); + $this->attr = $this->ris->attr; + $this->attr_flip = array_flip($this->ris->attr); + unset($this->ris); + + $this->reference = new Reference(); + + foreach($arrayData as $k=>$v) + { + $risData[$k] = $this->transformToRis($v); + if($mixAuthor === true || $mixTags === true) + { + if($mixAuthor === true) + { + $author = $this->reference->getAuthorByReference($v['id'],true); + if(is_array($author) && count($author)>0) + { + $risData[$k] = array_merge($risData[$k],array("AU"=>$author)); + } + unset($author); + }//mixAuthor + + if($mixTags === true) + { + $tags = $this->reference->getTagsByReference($v['id'],true); + if(is_array($tags) && count($tags) > 0) + { + $risData[$k] = array_merge($risData[$k],array("KW"=>$tags)); + } + unset($tags); + } + } + + if(!is_array($risData[$k]) || count($risData[$k]) < 1) + { + unset($risData[$k]); + } + + unset($arrayData[$k]); + } + + return $risData; + }//processArrayDataToRisData + + //单条记录的整编 + public function transformToRis($record) + { + $arr = array(); + + foreach($record as $k=>$v) + { + if(!empty($v)) + { + if(isset($this->attr_flip[$k])) + { + //echo $k ."-". $this->attr_flip[$k] . '-' .$v; + //echo "
"; + $arr[$this->attr_flip[$k]] = array(0=>$v); + } + } + } + //echo "
"; + return $arr; + }//transformToRis + + //输出成文件 + public function output($risData) + { + $risWirte = new RISWriter(); + return @$risWirte->writeRecords($risData); + }//output +} diff --git a/Westdc/User/Account.php b/Westdc/User/Account.php index 655e786..9c526ff 100644 --- a/Westdc/User/Account.php +++ b/Westdc/User/Account.php @@ -375,12 +375,17 @@ class Account implements EventManagerAwareInterface $mail_data = array( 'name'=>$row['realname'], ); - $mail = new Mail(); - $mail->loadTemplate($mail_template,$mail_data); - $mail->addTo($row['email'],$row['realname']); - $mail->send(); - - return true; + + try { + $mail = new Mail(); + $mail->loadTemplate($mail_template, $mail_data); + $mail->addTo($row['email'], $row['realname']); + $mail->send(); + return true; + }catch(\Exception $e){ + + } + } From 91044298c8430244e78f4e502aa5d9d0ce84a3f8 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Wed, 24 Dec 2014 15:59:42 +0800 Subject: [PATCH 16/32] profection the Mail module ,add console route match rule in AuthenticationService --- .../Authentication/AuthenticationService.php | 5 +++++ Westdc/Mail/Mail.php | 20 +++++++++++++++---- Westdc/Mail/Template.php | 7 +++++++ 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/Westdc/Authentication/AuthenticationService.php b/Westdc/Authentication/AuthenticationService.php index 9818577..9bf780e 100644 --- a/Westdc/Authentication/AuthenticationService.php +++ b/Westdc/Authentication/AuthenticationService.php @@ -41,6 +41,11 @@ class AuthenticationService $namespace = $e->getRouteMatch()->getParam('__NAMESPACE__'); $controller = $e->getRouteMatch()->getParam('controller'); $action = $e->getRouteMatch()->getParam('action'); + + if($module == 'Engine' && $namespace == 'ConsoleApp') + { + return true; + } // view::Dump($e->getRouteMatch()->getMatchedRouteName() . ":" . $controller."-".$action,false); diff --git a/Westdc/Mail/Mail.php b/Westdc/Mail/Mail.php index 32fadd4..eeb7cf4 100644 --- a/Westdc/Mail/Mail.php +++ b/Westdc/Mail/Mail.php @@ -31,6 +31,7 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ public $body; public $type; public $transport; + public $from; public function setServiceManager(ServiceManager $serviceManager) { @@ -101,7 +102,7 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ } //设置默认发件人 - public function setDefaultForm() + public function setDefaultFrom() { $this->mail->setFrom($this->config['smtp']['username'],$this->config['smtp']['name']); } @@ -125,6 +126,14 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ }//加载模板 + /** + * @param $from + */ + public function setFrom($from) + { + $this->from = $from; + } + //使用loadTemplate 的结果发送邮件 //在此之前需要使用 $this->mail->addTo()添加收件人 public function send($from = NULL){ @@ -148,11 +157,14 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ $this->mail->setBody($this->body); } - if(empty($from)) + if(empty($from) && empty($this->from)) { - $this->setDefaultForm(); + $this->setDefaultFrom(); }else{ - $this->mail->setFrom($from['email'],$from['name']); + if(!empty($this->from)) + $this->mail->setFrom($this->from['email'],$this->from['name']); + if(!empty($from)) + $this->mail->setFrom($from['email'],$from['name']); } $this->mail->setSubject($this->subject); diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index a590101..32984e0 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -106,6 +106,13 @@ class Template implements ServiceManagerAwareInterface $template_data = $this->fetch($key); + if(empty($data) || !is_array($data) || count($data) < 1) + return [ + 'subject' => $template_data['subject'], + 'body' => $template_data['body'], + 'type' => isset($template_data['type']) ? $template_data['type'] : self::DEFAULT_TEMPLATE_TYPE + ]; + $patterns = array(); $replacements = array(); From b3f581ebb3ad11b453b08778bbae9b0a458cb71f Mon Sep 17 00:00:00 2001 From: "shayupi@qq.com" Date: Wed, 24 Dec 2014 17:41:07 +0800 Subject: [PATCH 17/32] rewrite --- Westdc/Mail/Template.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index 374717b..ee542f3 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -94,4 +94,6 @@ class Template implements ServiceManagerAwareInterface $rs=$this->db->query($sql); return $rs->fetch(); } + + } \ No newline at end of file From 0c31626c841c9bef197c95be29db66ffbf91da30 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Thu, 25 Dec 2014 00:38:23 +0800 Subject: [PATCH 18/32] add function of send email in backend --- Westdc/Helpers/Tools.php | 35 ++++++++++++++++++++++++++++++ Westdc/Mail/Mail.php | 22 +++++++++++-------- Westdc/Mail/Sender.php | 47 ++++++++++++++++++++++++++++++++++++++++ Westdc/Mail/Template.php | 5 +---- 4 files changed, 96 insertions(+), 13 deletions(-) create mode 100644 Westdc/Mail/Sender.php diff --git a/Westdc/Helpers/Tools.php b/Westdc/Helpers/Tools.php index 949a88e..071479a 100644 --- a/Westdc/Helpers/Tools.php +++ b/Westdc/Helpers/Tools.php @@ -19,6 +19,41 @@ class Tools { public function isEmail($str){ return true; } + + /** + * @param $cmd + */ + public function execBackend($cmd) + { + if (substr(php_uname(), 0, 7) == "Windows"){ + pclose(popen("start cmd /c ". $cmd, "r")); + } + else { + exec($cmd . " > /dev/null &"); + } + + return; + } + + /** + * 返回的汉语文字信息在windows中是GB2312编码,需要手动改成UTF8 + * iconv("GB2312","UTF-8",$read); + * @param $cmd + * @return array + */ + public function execFront($cmd) + { + $response = array(); + $handle = popen("$cmd 2>&1", 'r'); + $read = ''; + while ($read = fread($handle, 20096)) { + $response[] = trim($read); + } + pclose($handle); + flush(); + + return $response; + } } \ No newline at end of file diff --git a/Westdc/Mail/Mail.php b/Westdc/Mail/Mail.php index eeb7cf4..b0a5590 100644 --- a/Westdc/Mail/Mail.php +++ b/Westdc/Mail/Mail.php @@ -8,7 +8,6 @@ namespace Westdc\Mail; -use Zend\Mime\Mime; use Zend\ServiceManager\ServiceManager; use Zend\ServiceManager\ServiceManagerAwareInterface; use Westdc\EventModel\AbstractEventManager; @@ -16,6 +15,7 @@ use Westdc\Service\ServiceManager as WestdcServiceManager; use Zend\Mail\Message; use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; +use Zend\Mime\Mime; use Zend\Mime\Message as MimeMessage; use Zend\Mime\Part as MimePart; @@ -23,8 +23,6 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ protected $serviceManager; - private $db; - public $mail; public $config; public $subject; @@ -50,9 +48,6 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ $this->serviceManager = $serviceManager->getServiceManager(); } - $dbService = $this->serviceManager->get('Db'); - $this->db = $dbService->getPdo(); - $this->loadConfigure(); $this->smtp(); $this->buildMailMessage(); @@ -134,10 +129,9 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ $this->from = $from; } - //使用loadTemplate 的结果发送邮件 - //在此之前需要使用 $this->mail->addTo()添加收件人 - public function send($from = NULL){ + public function preSend($from = NULL) + { if(empty($this->subject) || empty($this->body)) { return "邮件信息不完整"; @@ -169,6 +163,16 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ $this->mail->setSubject($this->subject); + return true; + } + + //使用loadTemplate 的结果发送邮件 + //在此之前需要使用 $this->mail->addTo()添加收件人 + public function send($from = NULL){ + + if(!$status = $this->preSend($from)) + return $status; + try { $this->transport->send($this->mail); return true; diff --git a/Westdc/Mail/Sender.php b/Westdc/Mail/Sender.php new file mode 100644 index 0000000..2099440 --- /dev/null +++ b/Westdc/Mail/Sender.php @@ -0,0 +1,47 @@ +serviceManager = $serviceManager; + + return $this; + } + + public function backend($options) + { + $cmd = "php ".CURRENT_BOOTSTRAP_SCRIPT; + $cmd .= ' mail send'; + $cmd .= ' --email="'.$options['email'].'"'; + $cmd .= ' --name="'.$options['name'].'"'; + $cmd .= ' --template="'.$options['template'].'"'; + + if(isset($options['data'])) + { + $data = json_encode($options['data']); + $cmd .= ' --data=\''.$data.'\''; + } + + $tools = $this->serviceManager->get('Tools'); + //$tools->execBackend($cmd); + //echo $cmd; + //var_dump($tools->execFront($cmd)); + //exit(); + return true; + } + +} \ No newline at end of file diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php index f2280d0..e369f19 100644 --- a/Westdc/Mail/Template.php +++ b/Westdc/Mail/Template.php @@ -25,7 +25,6 @@ class Template implements ServiceManagerAwareInterface { $dbService = $this->serviceManager->get('Db'); $this->db = $dbService->getPdo(); - } public function fetchAll() @@ -94,11 +93,10 @@ class Template implements ServiceManagerAwareInterface } $rs=$this->db->query($sql); + return $rs->fetch(); } -<<<<<<< HEAD -======= /** * @param $key * @param $data @@ -137,6 +135,5 @@ class Template implements ServiceManagerAwareInterface ]; }//function load ->>>>>>> 91044298c8430244e78f4e502aa5d9d0ce84a3f8 } \ No newline at end of file From f6d4934410db7b722e20c4c83fd510c7b5f3b8bd Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Thu, 25 Dec 2014 11:49:51 +0800 Subject: [PATCH 19/32] remove useless codes --- Westdc/Mail/Sender.php | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Westdc/Mail/Sender.php b/Westdc/Mail/Sender.php index 2099440..eda573d 100644 --- a/Westdc/Mail/Sender.php +++ b/Westdc/Mail/Sender.php @@ -37,10 +37,8 @@ class Sender implements ServiceManagerAwareInterface{ } $tools = $this->serviceManager->get('Tools'); - //$tools->execBackend($cmd); - //echo $cmd; - //var_dump($tools->execFront($cmd)); - //exit(); + $tools->execBackend($cmd); + return true; } From a87b4b8d2a6996ec0008f06da2a32d76977dab48 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Fri, 26 Dec 2014 00:53:46 +0800 Subject: [PATCH 20/32] add Paginator Service,fixed a issue about zf1 update to zf2 in Westdc/Reference/Reference.php --- Westdc/Helpers/Assist.php | 8 +++-- Westdc/Helpers/Paginator.php | 62 ++++++++++++++++++++++++++++++++++ Westdc/Mail/Mail.php | 8 ++++- Westdc/Reference/Reference.php | 59 ++++++++++++++++---------------- 4 files changed, 103 insertions(+), 34 deletions(-) create mode 100644 Westdc/Helpers/Paginator.php diff --git a/Westdc/Helpers/Assist.php b/Westdc/Helpers/Assist.php index cab69e7..91bab44 100644 --- a/Westdc/Helpers/Assist.php +++ b/Westdc/Helpers/Assist.php @@ -14,7 +14,7 @@ class Assist } - static function addPaginator($data,$ctl,$limit = 10,$viewPartial = "layout/manager/pagination") + static function addPaginator($data,$ctl,$limit = 10,$viewPartial = "layout/manager/pagination" ) { $request = $ctl->getRequest(); $page = $ctl->params()->fromRoute('page'); @@ -33,8 +33,10 @@ class Assist $paginator->setDefaultScrollingStyle('Sliding'); $pagination = $ctl->getServiceLocator()->get('viewhelpermanager')->get('PaginationControl'); - $renderer = $ctl->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer'); - $paginator->setView($renderer); + $renderer = $ctl->getServiceLocator()->get('Zend\View\Renderer\PhpRenderer'); + + $paginator->setView($renderer); + $pagination->setDefaultViewPartial($viewPartial); $ctl->ViewModel->setVariable('paginator',$paginator); diff --git a/Westdc/Helpers/Paginator.php b/Westdc/Helpers/Paginator.php new file mode 100644 index 0000000..5b37e77 --- /dev/null +++ b/Westdc/Helpers/Paginator.php @@ -0,0 +1,62 @@ +serviceManager = $serviceManager; + + return $this; + } + + public function add($data,$ctl,$limit = 10,$route = "",$viewPartial = "layout/manager/pagination") + { + $page = $ctl->params()->fromRoute('page'); + + if(is_array($data)) + $data = new ArrayAdapter($data); + + if($data instanceof Select) + { + $dbService = $this->serviceManager->get('Db'); + $zendDb = $dbService->getZendDb(); + $data = new DbSelect($data,$zendDb); + } + + if($data instanceof TableGateway) + $data = new DbTableGateway($data,$this->sqlQuery,$this->sqlOrder,$this->sqlGroup,$this->sqlHaving); + + $paginator = new Zend_Paginator($data); + $paginator->setCurrentPageNumber($page) + ->setItemCountPerPage($limit) + ->setPageRange(6); + + $pagination = $ctl->getServiceLocator()->get('viewhelpermanager')->get('PaginationControl'); + $pageSliding = $pagination($paginator,'Sliding',$viewPartial,array('route'=>$route)); + + $ctl->ViewModel->setVariable('pagination',$pageSliding); + $ctl->ViewModel->setVariable('paginator',$paginator); + } + +} \ No newline at end of file diff --git a/Westdc/Mail/Mail.php b/Westdc/Mail/Mail.php index b0a5590..6a7b120 100644 --- a/Westdc/Mail/Mail.php +++ b/Westdc/Mail/Mail.php @@ -15,7 +15,6 @@ use Westdc\Service\ServiceManager as WestdcServiceManager; use Zend\Mail\Message; use Zend\Mail\Transport\Smtp as SmtpTransport; use Zend\Mail\Transport\SmtpOptions; -use Zend\Mime\Mime; use Zend\Mime\Message as MimeMessage; use Zend\Mime\Part as MimePart; @@ -130,6 +129,10 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ } + /** + * @param null $from + * @return bool + */ public function preSend($from = NULL) { if(empty($this->subject) || empty($this->body)) @@ -168,6 +171,9 @@ class Mail extends AbstractEventManager implements ServiceManagerAwareInterface{ //使用loadTemplate 的结果发送邮件 //在此之前需要使用 $this->mail->addTo()添加收件人 + /** + * @param null $from + */ public function send($from = NULL){ if(!$status = $this->preSend($from)) diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index 47c9655..c19b6ae 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -1,15 +1,15 @@ db = \Zend_Registry::get('db'); - }else{ - $this->db = $db; - } - - $this->config = \Zend_Registry::get('config'); - - $Listener = new ReferenceListener(); - @$this->events()->attachAggregate($Listener); - - $this->table = new \Helpers\Table(); + } - - public function events(\Zend_EventManager_EventCollection $events = NULL) + + public function setServiceManager(ServiceManager $serviceManager) { - if ($events !== NULL) { - $this->events = $events; - } elseif ($this->events === NULL) { - $this->events = new \Zend_EventManager_EventManager(__CLASS__); - } - return $this->events; + $this->serviceManager = $serviceManager; + + $this->init(); + + return $this; } + + private function init(){ + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + unset($dbService); + + $this->table = new \stdClass(); + $this->table->reference = "reference"; + $this->table->reference_author = "ref_author"; + $this->table->source = "source"; + } + public function reference($id = 0) { @@ -170,7 +169,7 @@ class Reference } //所有文献 - public function fetchReferences() + public function fetchAll() { $wheresql = array(); if(!empty($this->keyword)) @@ -209,7 +208,7 @@ class Reference $order = "{$this->table->reference}.{$this->order}"; } - $sql = "SELECT {$this->table->reference}.* FROM + $sql = "SELECT {$this->table->reference}.* FROM {$this->table->reference} $wheresql ORDER BY $order {$this->sort}"; @@ -240,7 +239,7 @@ class Reference $order = "ref.{$this->order} {$this->sort}"; } - $sql="select distinct ref.* from {$this->table->reference} ref where ref.id in (select r.refid from mdref r + $sql="select distinct ref.* from {$this->table->reference} ref where ref.id in (select r.refid from mdref r left join datasource ds on r.uuid=ds.uuid left join {$this->table->source} s on s.id=ds.sourceid where s.code='$code') $wheresql From a68a573cb9a75d57af8697235c0d5143fa12fb97 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Fri, 26 Dec 2014 13:28:50 +0800 Subject: [PATCH 21/32] optimization the Paginator service --- Westdc/Helpers/Paginator.php | 78 ++++++++++++++++++++++++++++++++++-- 1 file changed, 74 insertions(+), 4 deletions(-) diff --git a/Westdc/Helpers/Paginator.php b/Westdc/Helpers/Paginator.php index 5b37e77..2519f00 100644 --- a/Westdc/Helpers/Paginator.php +++ b/Westdc/Helpers/Paginator.php @@ -10,6 +10,7 @@ namespace Westdc\Helpers; use Zend\ServiceManager\ServiceManager; use Zend\ServiceManager\ServiceManagerAwareInterface; +use Zend\Mvc\Controller\AbstractActionController; use Zend\Paginator\Adapter\ArrayAdapter; use Zend\Paginator\Adapter\DbSelect; use Zend\Paginator\Adapter\DbTableGateway; @@ -23,14 +24,76 @@ class Paginator implements ServiceManagerAwareInterface{ public $sqlQuery,$sqlOrder,$sqlGroup,$sqlHaving; + private $pageLimit,$pageRange,$route,$params; + public function setServiceManager(ServiceManager $serviceManager) { $this->serviceManager = $serviceManager; + $this->setPageLimit(); + $this->setPageRange(); + $this->setRoute(); + return $this; } - public function add($data,$ctl,$limit = 10,$route = "",$viewPartial = "layout/manager/pagination") + public function setPageLimit($limit = 0) + { + $this->pageLimit = (int)$limit; + if(empty($this->pageLimit)) + $this->pageLimit = 10; + } + + public function setPageRange($range = 0) + { + $this->pageRange = (int)$range; + if(empty($this->pageRange)) + $this->pageRange = 6; + } + + public function setRoute($route = "",$params = "") + { + + if(empty($route)) { + $routeMatch = $this->serviceManager->get('Application')->getMvcEvent()->getRouteMatch(); + $this->route = str_replace("/wildcard", "", $routeMatch->getMatchedRouteName()); + $this->params = []; + }else{ + $this->route = $route; + } + + if(empty($params)) { + if(!isset($routeMatch)) + $routeMatch = $this->serviceManager->get('Application')->getMvcEvent()->getRouteMatch(); + + if (!empty($routeMatch->getParam('__CONTROLLER__'))) + $this->params['controller'] = $routeMatch->getParam('__CONTROLLER__'); + + if (!empty($routeMatch->getParam('action'))) + $this->params['action'] = $routeMatch->getParam('action'); + + if (!empty($routeMatch->getParam('ac'))) + $this->params['ac'] = $routeMatch->getParam('ac'); + + if (!empty($routeMatch->getParam['id'])) + $this->params['id'] = $routeMatch->getParam('id'); + + if (!empty($routeMatch->getParam['uuid'])) + $this->params['uuid'] = $routeMatch->getParam('uuid'); + }else{ + $this->params = $params; + } + + unset($routeMatch); + } + + /** + * @param AbstractActionController $ctl + * @param mixed $data + * @param string $viewPartial + * @return bool + */ + public function add(AbstractActionController $ctl,$data,$viewPartial = "pagination") { $page = $ctl->params()->fromRoute('page'); @@ -49,14 +112,21 @@ class Paginator implements ServiceManagerAwareInterface{ $paginator = new Zend_Paginator($data); $paginator->setCurrentPageNumber($page) - ->setItemCountPerPage($limit) - ->setPageRange(6); + ->setItemCountPerPage($this->pageLimit) + ->setPageRange($this->pageRange); $pagination = $ctl->getServiceLocator()->get('viewhelpermanager')->get('PaginationControl'); - $pageSliding = $pagination($paginator,'Sliding',$viewPartial,array('route'=>$route)); + + $pageSliding = $pagination( + $paginator, + 'Sliding', + $viewPartial, + ['route'=>$this->route,'params'=>$this->params] + ); $ctl->ViewModel->setVariable('pagination',$pageSliding); $ctl->ViewModel->setVariable('paginator',$paginator); + return true; } } \ No newline at end of file From 08d0192a60092e455dbea1118a77b18b0d442f47 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Fri, 26 Dec 2014 21:45:05 +0800 Subject: [PATCH 22/32] add Westdc\File namespace,add uuid maker in Tools Service --- Westdc/File/File.php | 44 ++++ Westdc/File/Listener/DefaultFileListener.php | 40 ++++ Westdc/File/Upload.php | 233 +++++++++++++++++++ Westdc/Helpers/Theme.php | 20 +- Westdc/Helpers/Tools.php | 26 +++ Westdc/Reference/Reference.php | 7 +- 6 files changed, 359 insertions(+), 11 deletions(-) create mode 100644 Westdc/File/File.php create mode 100644 Westdc/File/Listener/DefaultFileListener.php create mode 100644 Westdc/File/Upload.php diff --git a/Westdc/File/File.php b/Westdc/File/File.php new file mode 100644 index 0000000..268cf7a --- /dev/null +++ b/Westdc/File/File.php @@ -0,0 +1,44 @@ +serviceManager = $serviceManager; + + return $this; + } + + //获取文件扩展名 + public function getFileTextExt($file_name) + { + $temp_arr = explode(".", $file_name); + $file_ext = array_pop($temp_arr); + $file_ext = trim($file_ext); + $file_ext = strtolower($file_ext); + return $file_ext; + } + + //获取文件Mime,通过finfo扩展 + public function getFileMime($file_name) + { + $finfo = finfo_open(FILEINFO_MIME_TYPE); + $filetype = finfo_file($finfo, $file_name) ; //文件mime类型 + finfo_close($finfo); + return $filetype; + } + +} \ No newline at end of file diff --git a/Westdc/File/Listener/DefaultFileListener.php b/Westdc/File/Listener/DefaultFileListener.php new file mode 100644 index 0000000..a93ba09 --- /dev/null +++ b/Westdc/File/Listener/DefaultFileListener.php @@ -0,0 +1,40 @@ +listeners[] = $events->attach('upload.pre', function($e){ + return true; + return ['error' => '文件格式不在可上传的范围内']; + }, 100); + + $this->listeners[] = $events->attach('upload.pre', function($e){ + return true; + return ['error' => '文件大小超出了限制']; + }, 80); + + } + + public function detach(EventManagerInterface $events) + { + foreach ($this->listeners as $index => $listener) { + if ($events->detach($listener)) { + unset($this->listeners[$index]); + } + } + } + +} diff --git a/Westdc/File/Upload.php b/Westdc/File/Upload.php new file mode 100644 index 0000000..4e7878a --- /dev/null +++ b/Westdc/File/Upload.php @@ -0,0 +1,233 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + public function init() + { + $Listener = new DefaultFileListener; + $this->getEventManager()->attachAggregate($Listener); + + $configService = $this->serviceManager->get('ConfigService'); + $this->config = $configService->get('file.php'); + } + + /** + * upload + * + * 文件上传 + * + * @param Array $files e.g. $_FILES['Filedata'] + * + * @return Array $msg e.g. if($msg['error']) + */ + public function upload($files) + { + if (empty($files) !== false) { + return array("error"=>"请选择要上传的文件."); + } + + if (is_uploaded_file($files['tmp_name']) === false) { + return array("error"=>"文件上传失败,请重新上传"); + } + + $source = $this->source; + $file = $files; + + $results = $this->getEventManager()->trigger('upload.pre', $this, compact('file')); + $cache_data = $results->last(); + + if($cache_data !== true) + { + return $cache_data; + } + + $msg = array(); + + $file_name = $files['name']; //原文件名 + $file_size = $files['size']; //文件大小 + + $results = $this->makeUploadTarget(); + + if(isset($results['error'])) + { + return $results; + }//文件夹问题 + + $new_file_basename = $this->gen_uuid(); + $file_ext = $this->getFileTextExt($file_name); + $new_file_name = $new_file_basename . '.' . $file_ext;//新文件名 + + //移动文件 + $file_path = $results['save_path'] . $new_file_name ; + + if (move_uploaded_file($file['tmp_name'], $file_path) === false) { + return array("error"=>"上传失败,请重试"); + } + + $dbsave = $db_path = $results['dbsave']; + $dbsave .= $new_file_name;//数据库最终存储的文件 + $file_url = $dbsave;//文件链接 + + $results = $this->getEventManager()->trigger('upload.makeThumb', $this, compact('conf','file_path','db_path','file_ext','new_file_basename')); + $thumbnail = $results->last(); + + $msg['file_url'] = $file_url; + $msg['file_size'] = $file_size; + $msg['db_path'] = $dbsave; + $msg['realname'] = $file_name; + $msg['file_ext'] = $file_ext; + $msg['file_type'] = $this->getFileMime($file_path); + $msg['thumb'] = $thumbnail; + + return $msg; + }//文件上传 + + /** + * 设置上传文件的根路径,这样操作会忽略config中的定义 + * 根路径需要自行创建 + * 路径结尾必须加 "/" + * @param string $path + */ + public function setRootDir($path = "") + { + if(empty($path)) + $this->uploadPath = $this->config->upload; + + $this->uploadPath = $path; + + if(!preg_match("/[\/|\\\]+$/",$this->uploadPath)) + $this->uploadPath .= "/"; + } + + /** + * 设置子路径,自动加在根路径之后 + * 如果不存在程序将创建 + * @param $dirname + */ + public function setChildDir($dirname) + { + if(empty($dirname)) { + return false; + } + + $this->uploadPath .= $dirname; + + if (!preg_match("/[\/|\\\]+$/", $this->uploadPath)) + $this->uploadPath .= "/"; + + + if(!file_exists($this->uploadPath)) + mkdir($this->uploadPath); + + $this->relativePath = $dirname; + } + + /** + * 创建并返回年月日的子目录路径 + * @return string + */ + public function makeDateDir() + { + $y = date("Y"); + $m = date("m"); + $d = date("d"); + + $current_path = $y . "/"; + + $save_path = $this->uploadPath . $current_path; + + if (!file_exists($save_path)) { + mkdir($save_path); + } + + $current_path .= $m . "/"; + $save_path .= $current_path; + + if (!file_exists($save_path)) { + mkdir($save_path); + } + + $current_path .= $d ."/"; + $save_path .= $current_path; + + if (!file_exists($save_path)) { + mkdir($save_path); + } + + $this->uploadPath .= $current_path; + $this->relativePath .= $current_path; + return $current_path; + } + + /** + * @param $fileName + * @param $fileExt + */ + public function setFileName($fileName,$fileExt) + { + if(!empty($fileName)){ + $this->fileName = $fileName . "." .$fileExt; + return; + } + + $tools = $this->serviceManager->get('Tools'); + $uuid = $tools->uuid(); + + $this->fileName = $uuid . "." . $fileExt; + + } + + /** + * @return string + */ + public function getFileName() + { + return $this->fileName; + } + + /** + * @return string + */ + public function getUploadPath() + { + return $this->uploadPath; + } + + /** + * @return string + */ + public function getRelativePath() + { + return $this->relativePath; + } + +} \ No newline at end of file diff --git a/Westdc/Helpers/Theme.php b/Westdc/Helpers/Theme.php index 5993f38..5c06fa5 100644 --- a/Westdc/Helpers/Theme.php +++ b/Westdc/Helpers/Theme.php @@ -114,15 +114,17 @@ class Theme '/js/lib/jquery.masonry.min.js' ), ), - - 'uploadify' => array( - $this->ScriptKey => array( - '/js/lib/uploadify/jquery.uploadify.min.js' - ), - $this->CSSKey => array( - '/js/lib/uploadify/uploadify.css' - ), - ), + + 'jquery-fileupload' => array( + $this->ScriptKey => array( + '/static/lib/jquery-fileupload/vendor/jquery.ui.widget.js', + '/static/lib/jquery-fileupload/jquery.iframe-transport.js', + '/static/lib/jquery-fileupload/jquery.fileupload.js', + ), + $this->CSSKey => array( + '/static/lib/jquery-fileupload/css/jquery.fileupload.css', + ) + ), 'datepicker' => array( $this->ScriptKey => array( diff --git a/Westdc/Helpers/Tools.php b/Westdc/Helpers/Tools.php index 071479a..ee0658f 100644 --- a/Westdc/Helpers/Tools.php +++ b/Westdc/Helpers/Tools.php @@ -54,6 +54,32 @@ class Tools { return $response; } + + /** + * @return string + */ + public function uuid() + { + return sprintf( '%04x%04x-%04x-%04x-%04x-%04x%04x%04x', + // 32 bits for "time_low" + mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), + + // 16 bits for "time_mid" + mt_rand( 0, 0xffff ), + + // 16 bits for "time_hi_and_version", + // four most significant bits holds version number 4 + mt_rand( 0, 0x0fff ) | 0x4000, + + // 16 bits, 8 bits for "clk_seq_hi_res", + // 8 bits for "clk_seq_low", + // two most significant bits holds zero and one for variant DCE1.1 + mt_rand( 0, 0x3fff ) | 0x8000, + + // 48 bits for "node" + mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ) + ); + } } \ No newline at end of file diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index c19b6ae..24184db 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -108,13 +108,16 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter //上传文献PDF public function uploadReferencePdf($file,$autoread = false) { - $files = new Files(); - $file_info = $files->upload($file,'literature/',true); + $fileService = $this->serviceManager->get('File/Upload'); + $file_info = $fileService->upload($file,'literature/',true); if(isset($file_info['error']) && !empty($file_info['error'])) { return array("error" => $file_info['error']); } + + var_dump($file_info); + exit(); $file_data = array( 'filename' => $file_info['file_url'], From d21de7cc1171c3fb8d61213a5393bfae882ab4c0 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sun, 28 Dec 2014 00:03:41 +0800 Subject: [PATCH 23/32] add new service File/Upload,add reference upload test function,rename file upload listener --- ...ener.php => DefaultFileUploadListener.php} | 18 ++- Westdc/File/Upload.php | 110 ++++++++---------- Westdc/Reference/Reference.php | 5 +- Westdc/Service/ServiceManager.php | 2 +- 4 files changed, 71 insertions(+), 64 deletions(-) rename Westdc/File/Listener/{DefaultFileListener.php => DefaultFileUploadListener.php} (64%) diff --git a/Westdc/File/Listener/DefaultFileListener.php b/Westdc/File/Listener/DefaultFileUploadListener.php similarity index 64% rename from Westdc/File/Listener/DefaultFileListener.php rename to Westdc/File/Listener/DefaultFileUploadListener.php index a93ba09..c6cc3b6 100644 --- a/Westdc/File/Listener/DefaultFileListener.php +++ b/Westdc/File/Listener/DefaultFileUploadListener.php @@ -4,14 +4,18 @@ namespace Westdc\File\Listener; use Zend\EventManager\EventCollection; use Zend\EventManager\ListenerAggregateInterface; use Zend\EventManager\EventManagerInterface; +use Westdc\Service\ServiceManager; -class DefaultFileListener implements ListenerAggregateInterface +class DefaultFileUploadListener implements ListenerAggregateInterface { protected $listeners = array(); + protected $serviceManager; + function __construct() { - + $this->serviceManager = new ServiceManager(); + $this->serviceManager = $this->serviceManager->getServiceManager(); } public function attach(EventManagerInterface $events) @@ -26,6 +30,16 @@ class DefaultFileListener implements ListenerAggregateInterface return ['error' => '文件大小超出了限制']; }, 80); + $this->listeners[] = $events->attach('upload.after', function($e){ + + $file_data = $e->getParam('file_data'); + + return true; + + return ['error' => '文件大小超出了限制']; + }, 80); + + } public function detach(EventManagerInterface $events) diff --git a/Westdc/File/Upload.php b/Westdc/File/Upload.php index 4e7878a..bd5ee6a 100644 --- a/Westdc/File/Upload.php +++ b/Westdc/File/Upload.php @@ -11,7 +11,7 @@ namespace Westdc\File; use Zend\ServiceManager\ServiceManager; use Zend\ServiceManager\ServiceManagerAwareInterface; use Westdc\EventModel\AbstractEventManager; -use Westdc\File\Listener\DefaultFileListener; +use Westdc\File\Listener\DefaultFileUploadListener; class Upload extends AbstractEventManager implements ServiceManagerAwareInterface{ @@ -22,6 +22,10 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac private $fileName = ""; private $config; + const DATETIME_MODEL_YMD = "Y/M/D/"; + const DATETIME_MODEL_YM = "Y/M/"; + const DATETIME_MODEL_Y = "Y/"; + public function setServiceManager(ServiceManager $serviceManager) { $this->serviceManager = $serviceManager; @@ -33,23 +37,15 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac public function init() { - $Listener = new DefaultFileListener; + $Listener = new DefaultFileUploadListener; $this->getEventManager()->attachAggregate($Listener); $configService = $this->serviceManager->get('ConfigService'); $this->config = $configService->get('file.php'); } - /** - * upload - * - * 文件上传 - * - * @param Array $files e.g. $_FILES['Filedata'] - * - * @return Array $msg e.g. if($msg['error']) - */ - public function upload($files) + + public function upload($files,$rootDir = "",$childDir = "",$fileName = "",$dateDirModel = self::DATETIME_MODEL_YMD) { if (empty($files) !== false) { return array("error"=>"请选择要上传的文件."); @@ -59,7 +55,6 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac return array("error"=>"文件上传失败,请重新上传"); } - $source = $this->source; $file = $files; $results = $this->getEventManager()->trigger('upload.pre', $this, compact('file')); @@ -70,45 +65,38 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac return $cache_data; } - $msg = array(); + $fileService = $this->serviceManager->get('File'); - $file_name = $files['name']; //原文件名 - $file_size = $files['size']; //文件大小 + $this->setRootDir($rootDir); + $this->setChildDir($childDir); - $results = $this->makeUploadTarget(); + if($dateDirModel !== false) + $this->makeDateDir($dateDirModel); - if(isset($results['error'])) - { - return $results; - }//文件夹问题 - - $new_file_basename = $this->gen_uuid(); - $file_ext = $this->getFileTextExt($file_name); - $new_file_name = $new_file_basename . '.' . $file_ext;//新文件名 + $this->setFileName($fileName , $fileService->getFileTextExt($files['name'])); //移动文件 - $file_path = $results['save_path'] . $new_file_name ; + $file_path = $this->getUploadPath() . $this->getFileName(); if (move_uploaded_file($file['tmp_name'], $file_path) === false) { return array("error"=>"上传失败,请重试"); } - $dbsave = $db_path = $results['dbsave']; - $dbsave .= $new_file_name;//数据库最终存储的文件 - $file_url = $dbsave;//文件链接 + $file_data = array(); + $file_data['file_url'] = $this->getRelativePath() . $this->getFileName(); + $file_data['file_size'] = $files['size']; + $file_data['db_path'] = $this->getRelativePath() . $this->getFileName(); + $file_data['realname'] = $files['name']; + $file_data['file_ext'] = $fileService->getFileTextExt($files['name']); + $file_data['file_type'] = $fileService->getFileMime($file_path); - $results = $this->getEventManager()->trigger('upload.makeThumb', $this, compact('conf','file_path','db_path','file_ext','new_file_basename')); - $thumbnail = $results->last(); + $results = $this->getEventManager()->trigger('upload.after', $this, compact('file_data')); + $cache_data = $results->last(); - $msg['file_url'] = $file_url; - $msg['file_size'] = $file_size; - $msg['db_path'] = $dbsave; - $msg['realname'] = $file_name; - $msg['file_ext'] = $file_ext; - $msg['file_type'] = $this->getFileMime($file_path); - $msg['thumb'] = $thumbnail; + if(is_array($cache_data)) + $file_data = array_merge($file_data , $cache_data); - return $msg; + return $file_data; }//文件上传 /** @@ -116,6 +104,7 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac * 根路径需要自行创建 * 路径结尾必须加 "/" * @param string $path + * @return bool */ public function setRootDir($path = "") { @@ -126,17 +115,20 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac if(!preg_match("/[\/|\\\]+$/",$this->uploadPath)) $this->uploadPath .= "/"; + + return true; } /** * 设置子路径,自动加在根路径之后 * 如果不存在程序将创建 - * @param $dirname + * @param string $dirname + * @return bool | string */ public function setChildDir($dirname) { if(empty($dirname)) { - return false; + return true; } $this->uploadPath .= $dirname; @@ -145,8 +137,10 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac $this->uploadPath .= "/"; - if(!file_exists($this->uploadPath)) - mkdir($this->uploadPath); + if(!file_exists($this->uploadPath)) { + if(!mkdir($this->uploadPath)) + return "failed to create folder :".$this->uploadPath; + } $this->relativePath = $dirname; } @@ -155,32 +149,28 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac * 创建并返回年月日的子目录路径 * @return string */ - public function makeDateDir() + public function makeDateDir($model) { $y = date("Y"); $m = date("m"); $d = date("d"); - $current_path = $y . "/"; - - $save_path = $this->uploadPath . $current_path; - - if (!file_exists($save_path)) { - mkdir($save_path); + if($model == self::DATETIME_MODEL_YMD || $model == self::DATETIME_MODEL_YM || $model == self::DATETIME_MODEL_Y) { + $current_path = $y . "/"; + if (!file_exists($this->uploadPath . $current_path)) + mkdir($this->uploadPath . $current_path); } - $current_path .= $m . "/"; - $save_path .= $current_path; - - if (!file_exists($save_path)) { - mkdir($save_path); + if($model == self::DATETIME_MODEL_YMD || $model == self::DATETIME_MODEL_YM){ + $current_path .= $m . "/"; + if (!file_exists($this->uploadPath . $current_path)) + mkdir($this->uploadPath . $current_path); } - $current_path .= $d ."/"; - $save_path .= $current_path; - - if (!file_exists($save_path)) { - mkdir($save_path); + if($model == self::DATETIME_MODEL_YMD) { + $current_path .= $d ."/"; + if (!file_exists($this->uploadPath . $current_path)) + mkdir($this->uploadPath . $current_path); } $this->uploadPath .= $current_path; diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index 24184db..a576692 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -108,8 +108,11 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter //上传文献PDF public function uploadReferencePdf($file,$autoread = false) { + $configService = $this->serviceManager->get('ConfigService'); + $appConfig = $configService->get('application.ini'); + $fileService = $this->serviceManager->get('File/Upload'); - $file_info = $fileService->upload($file,'literature/',true); + $file_info = $fileService->upload($file,$appConfig['reference_save_path'],"","",$fileService::DATETIME_MODEL_Y); if(isset($file_info['error']) && !empty($file_info['error'])) { diff --git a/Westdc/Service/ServiceManager.php b/Westdc/Service/ServiceManager.php index 558c090..e323740 100644 --- a/Westdc/Service/ServiceManager.php +++ b/Westdc/Service/ServiceManager.php @@ -16,7 +16,7 @@ class ServiceManager { function __construct() { - $this->serviceManager = new Zend_ServiceManager(); + $this->serviceManager = new Zend_ServiceManager; $this->serviceManager->addAbstractFactory(new ServiceFactory); $configService = $this->serviceManager->get('ConfigService'); From 862187d0a5159b6fc734626a4c3bb1fa9bcb650d Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sun, 28 Dec 2014 00:33:12 +0800 Subject: [PATCH 24/32] add function __invoke() in File/Upload service --- Westdc/File/Upload.php | 14 ++++++++++++++ Westdc/Reference/Reference.php | 4 ++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/Westdc/File/Upload.php b/Westdc/File/Upload.php index bd5ee6a..052179c 100644 --- a/Westdc/File/Upload.php +++ b/Westdc/File/Upload.php @@ -22,6 +22,7 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac private $fileName = ""; private $config; + //日期路径模式 const DATETIME_MODEL_YMD = "Y/M/D/"; const DATETIME_MODEL_YM = "Y/M/"; const DATETIME_MODEL_Y = "Y/"; @@ -44,7 +45,20 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac $this->config = $configService->get('file.php'); } + public function __invoke($files,$rootDir = "",$childDir = "",$fileName = "",$dateDirModel = self::DATETIME_MODEL_YMD) + { + $this->upload($files,$rootDir,$childDir,$fileName,$dateDirModel); + } + /** + * 上传文件 + * @param $files 上传文件的信息 e.g.$_FILE['fileData'] + * @param string $rootDir 文件存储的根路径(磁盘物理路径),如果没有设置则从 config/autoload/file.php 中读取 upload 配置 + * @param string $childDir 根路径中的下一级路径,默认为空 + * @param string $fileName 新文件的文件名,如果不指定则设置为新的UUID + * @param string $dateDirModel 年月日目录模式,如果设为 false 则存储时不添加年月日路径,年月日路径在子文件夹中创建,unix和linux中需要开启上传目录的权限,否则无法创建文件夹 + * @return array + */ public function upload($files,$rootDir = "",$childDir = "",$fileName = "",$dateDirModel = self::DATETIME_MODEL_YMD) { if (empty($files) !== false) { diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index a576692..e0098de 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -111,8 +111,8 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter $configService = $this->serviceManager->get('ConfigService'); $appConfig = $configService->get('application.ini'); - $fileService = $this->serviceManager->get('File/Upload'); - $file_info = $fileService->upload($file,$appConfig['reference_save_path'],"","",$fileService::DATETIME_MODEL_Y); + $fileUploadService = $this->serviceManager->get('File/Upload'); + $file_info = $fileUploadService($file,$appConfig['reference_save_path'],"","",$fileUploadService::DATETIME_MODEL_Y); if(isset($file_info['error']) && !empty($file_info['error'])) { From 6e2cfad2cb02c397099eb15e575beccc363c1e77 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sun, 28 Dec 2014 23:37:16 +0800 Subject: [PATCH 25/32] add new function in service File/Upload --- .../Listener/DefaultFileUploadListener.php | 28 +++++++++++++++++-- Westdc/File/Upload.php | 17 +++++++++-- Westdc/Reference/Reference.php | 1 + 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/Westdc/File/Listener/DefaultFileUploadListener.php b/Westdc/File/Listener/DefaultFileUploadListener.php index c6cc3b6..4d172bc 100644 --- a/Westdc/File/Listener/DefaultFileUploadListener.php +++ b/Westdc/File/Listener/DefaultFileUploadListener.php @@ -34,10 +34,32 @@ class DefaultFileUploadListener implements ListenerAggregateInterface $file_data = $e->getParam('file_data'); - return true; + $authService = $this->serviceManager->get('Auth'); - return ['error' => '文件大小超出了限制']; - }, 80); + $data = [ + 'filename' => $file_data['db_path'], + 'filetype' => $file_data['file_type'], + 'filedesc' => $file_data['file_mime'], + 'userid' => $authService->getIdentity('id'), + 'filesize' => $file_data['file_size'], + 'realname' => $file_data['realname'], + ]; + + if(isset($file_data['language'])) + { + $data['language'] = $file_data['language']; + } + + $dbServices = $this->serviceManager->get('Db'); + $dbh = $dbServices->getDbh(); + + $attid = $dbh->insert("attachments" , $data , true); + + if(is_numeric($attid)) + return ['attid' => $attid]; + + return false; + }, 100); } diff --git a/Westdc/File/Upload.php b/Westdc/File/Upload.php index 052179c..81064f7 100644 --- a/Westdc/File/Upload.php +++ b/Westdc/File/Upload.php @@ -21,6 +21,7 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac private $relativePath = ""; private $fileName = ""; private $config; + private $params; //日期路径模式 const DATETIME_MODEL_YMD = "Y/M/D/"; @@ -47,7 +48,7 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac public function __invoke($files,$rootDir = "",$childDir = "",$fileName = "",$dateDirModel = self::DATETIME_MODEL_YMD) { - $this->upload($files,$rootDir,$childDir,$fileName,$dateDirModel); + return $this->upload($files,$rootDir,$childDir,$fileName,$dateDirModel); } /** @@ -97,12 +98,18 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac } $file_data = array(); + $file_data['file_url'] = $this->getRelativePath() . $this->getFileName(); $file_data['file_size'] = $files['size']; $file_data['db_path'] = $this->getRelativePath() . $this->getFileName(); $file_data['realname'] = $files['name']; $file_data['file_ext'] = $fileService->getFileTextExt($files['name']); - $file_data['file_type'] = $fileService->getFileMime($file_path); + $file_data['file_mime'] = $fileService->getFileMime($file_path); + + if(!empty($file_data) && is_array($file_data)) + { + $file_data = array_merge($file_data,$this->params); + } $results = $this->getEventManager()->trigger('upload.after', $this, compact('file_data')); $cache_data = $results->last(); @@ -210,6 +217,12 @@ class Upload extends AbstractEventManager implements ServiceManagerAwareInterfac } + + public function setParams($params) + { + $this->params = $params; + } + /** * @return string */ diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index e0098de..87dcf23 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -112,6 +112,7 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter $appConfig = $configService->get('application.ini'); $fileUploadService = $this->serviceManager->get('File/Upload'); + $fileUploadService->setParams(['file_type' => 'literature']); $file_info = $fileUploadService($file,$appConfig['reference_save_path'],"","",$fileUploadService::DATETIME_MODEL_Y); if(isset($file_info['error']) && !empty($file_info['error'])) From c66f62089b5c12f9da24d1053835593e86ac2c7a Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Mon, 29 Dec 2014 17:55:22 +0800 Subject: [PATCH 26/32] fixed errors in Reference module,add new functions in File service --- Westdc/File/File.php | 51 ++++++++++++++ .../Reference/Listener/ReferenceListener.php | 33 ++++++--- Westdc/Reference/Reference.php | 70 +++++-------------- 3 files changed, 94 insertions(+), 60 deletions(-) diff --git a/Westdc/File/File.php b/Westdc/File/File.php index 268cf7a..4bed5d7 100644 --- a/Westdc/File/File.php +++ b/Westdc/File/File.php @@ -41,4 +41,55 @@ class File implements ServiceManagerAwareInterface{ return $filetype; } + //获取某个文件的信息 + public function get($id) + { + if(!is_numeric($id) || $id<1) + return false; + + $dbService = $this->serviceManager->get('Db'); + $db = $dbService->getPdo(); + $sql = "SELECT * FROM attachments WHERE id=$id"; + $rs = $db->query($sql); + + return $rs->fetch(); + } + + //删除文件 + public function delete($id) + { + if(!is_numeric($id) || $id<1) + return false; + + $file_info = $this->get($id); + + $basePath = $this->getFileSaveDirByType($file_info['filetype']); + + @unlink($basePath . $file_info['filename']); + + $dbService = $this->serviceManager->get('Db'); + $db = $dbService->getPdo(); + + return $db->exec("DELETE FROM attachments WHERE id=$id"); + } + + public function getFileSaveDirByType($fileType) + { + $configService = $this->serviceManager->get('ConfigService'); + + $basePath = ""; + + switch ($fileType){ + case "literature": + $appConfig = $configService->get('application.ini'); + $basePath = $appConfig['reference_save_path']; + break; + } + + if (!preg_match("/[\/|\\\]+$/", $basePath)) + $basePath .= "/"; + + return $basePath; + } + } \ No newline at end of file diff --git a/Westdc/Reference/Listener/ReferenceListener.php b/Westdc/Reference/Listener/ReferenceListener.php index a2aed5c..4f77d00 100644 --- a/Westdc/Reference/Listener/ReferenceListener.php +++ b/Westdc/Reference/Listener/ReferenceListener.php @@ -13,14 +13,31 @@ class ReferenceListener implements \Zend_EventManager_ListenerAggregate public function attach(\Zend_EventManager_EventCollection $events) { - $Handler = new ReferenceHandler(); - $events->attach('submit.checkParam', array($Handler, 'checkReferenceParam'), 100); - $events->attach('submit.processData', array($Handler, 'processReferenceData'), 100); - - $events->attach('upload.insertToReferenceTable', array($Handler, 'insertToReferenceTable'), 100); - - $events->attach('mdref.checkParam', array($Handler, 'checkMdrefParam'), 100); - $events->attach('mdref.processData', array($Handler, 'processMdrefData'), 100); + $this->listeners[] = $events->attach('submit.before', function($e){ + $data = $e->getParam('data'); + + if(!is_array($data)) + return "参数错误"; + + if(empty($data["title"])) + return "请输入标题"; + + if(empty($data['reference'])) + return "请输入前台引用方式,并且唯一"; + + return true; + }, 100); //参数检查 + + $this->listeners[] = $events->attach('submit.processData', function($e){ + $data = $e->getParam('data'); + + if(empty($data['attid'])) + { + $data['attid'] = 0; + } + + return $data; + }, 50); } public function detach(\Zend_EventManager_EventCollection $events) diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index 87dcf23..8ab3d66 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -43,15 +43,20 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter $this->table->reference = "reference"; $this->table->reference_author = "ref_author"; $this->table->source = "source"; + $this->table->metadata_reference = "mdref"; + $this->table->reference_tag = "ref_tag"; } - - public function reference($id = 0) + /** + * 添加或编辑文献 + * @param $data + * @param int $id + * @return bool|string + */ + public function reference($data,$id = 0) { - $data = $this->getReferenceParam(); - $params = compact('data'); - $results = $this->events()->trigger('submit.checkParam', $this, $params); + $results = $this->getEventManager()->trigger('submit.before', $this, $params); $cache_data = $results->bottom(); if($cache_data !== true) @@ -59,12 +64,11 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter return $cache_data; } - $results = $this->events()->trigger('submit.processData', $this, $params); + $results = $this->getEventManager()->trigger('submit.processData', $this, $params); $data = $results->bottom(); - - unset($data['submit']); - - $dbh = new dbh(); + + $dbServices = $this->serviceManager->get('Db'); + $dbh = $dbServices->getDbh(); if(empty($id)) { @@ -84,27 +88,6 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter } } - //获得参数 - public function getReferenceParam(\Zend_Controller_Request_Abstract $request = NULL) - { - $request = new \Zend_Controller_Request_Http(); - $data = array( - 'reference' => trim($request->getParam('reference')), - 'link' => trim($request->getParam('link')), - 'publisher' => trim($request->getParam('publisher')), - 'year' => (int)$request->getParam('year'), - 'title' => trim($request->getParam('title')), - 'ris' => trim($request->getParam('ris')), - 'note' => trim($request->getParam('note')), - 'attid' => (int)$request->getParam('attid'), - 'abstract' => $request->getParam('abstract'), - 'type' => $request->getParam('type'), - 'language' => $request->getParam('language'), - 'doi' => $request->getParam('doi'), - ); - return $data; - } - //上传文献PDF public function uploadReferencePdf($file,$autoread = false) { @@ -119,33 +102,16 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter { return array("error" => $file_info['error']); } - - var_dump($file_info); - exit(); - - $file_data = array( - 'filename' => $file_info['file_url'], - 'filetype' => 'literature', - 'filedesc' => $file_info['file_mime'], - 'userid' => view::User('id'), - 'filesize' => $file_info['file_size'], - 'realname' => $file_info['realname'] - ); - - $dbh = new dbh(); - - $file_id = $dbh->insert($this->table->attachments,$file_data,true); - $file_data['id'] = $file_id; if($autoread) { $params = compact('file_data'); $results = $this->events()->trigger('upload.insertToReferenceTable', $this, $params); $cache_data = $results->bottom(); - $file_data = array_merge($file_data,$cache_data); + $file_info = array_merge($file_info,$cache_data); } - return $file_data; + return $file_info; } //通过文件名自动提取文章标题 @@ -420,8 +386,8 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter $row = $rs->fetch(); if ($row['attid']) { - $files = new Files(); - $attfile = $files->getOne($row['attid']); + $fileService = $this->serviceManager->get('File'); + $attfile = $fileService->get($row['attid']); $row['file'] = $attfile; } From 39fb5b515b09136b0c8dc277c0ee15331b768072 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Tue, 30 Dec 2014 14:44:39 +0800 Subject: [PATCH 27/32] add class Ris in Reference module,remove useless files --- Westdc/Reference/Event/ReferenceEvent.php | 15 -- Westdc/Reference/Event/RisEvent.php | 9 -- Westdc/Reference/Handler/ReferenceHandler.php | 138 ------------------ Westdc/Reference/Handler/RisHandler.php | 47 +++--- .../Reference/Listener/ReferenceListener.php | 48 ------ Westdc/Reference/Listener/RisListener.php | 36 ++--- Westdc/Reference/Ris.php | 87 +++++------ 7 files changed, 78 insertions(+), 302 deletions(-) delete mode 100644 Westdc/Reference/Event/ReferenceEvent.php delete mode 100644 Westdc/Reference/Event/RisEvent.php delete mode 100644 Westdc/Reference/Handler/ReferenceHandler.php delete mode 100644 Westdc/Reference/Listener/ReferenceListener.php diff --git a/Westdc/Reference/Event/ReferenceEvent.php b/Westdc/Reference/Event/ReferenceEvent.php deleted file mode 100644 index 8afc79f..0000000 --- a/Westdc/Reference/Event/ReferenceEvent.php +++ /dev/null @@ -1,15 +0,0 @@ -db = \Zend_Registry::get('db'); - }else{ - $this->db = $db; - } - - $this->config = \Zend_Registry::get('config'); - $this->table = new Table(); - } - - public function checkReferenceParam(\Zend_EventManager_Event $e) - { - $data = $e->getParam('data'); - - if(!is_array($data)) - { - return "参数错误"; - } - - if(empty($data["title"])) - { - return "请输入标题"; - } - - if(empty($data['reference'])) - { - return "请输入前台引用方式,并且唯一"; - } - - return true; - } - - public function processReferenceData(\Zend_EventManager_Event $e) - { - $data = $e->getParam('data'); - - if(empty($data['attid'])) - { - $data['attid'] = 0; - } - - return $data; - } - - public function insertToReferenceTable(\Zend_EventManager_Event $e) - { - $att = $e->getParam('file_data'); - - $reference = new Reference(); - $title = $reference->getReferenceTitleFromFilenName($att['realname']); - - $data = array( - 'title'=>$title, - 'attid'=>$att['id'], - 'reference'=>$title.'---'.date("Y-m-d H:i:s").".".microtime().rand() - ); - - $dbh = new dbh(); - - $cache_data = array(); - - $cache_data['ref_id'] = $dbh->insert($this->table->reference,$data,true); - $cache_data['ref_title'] = $title; - - return $cache_data; - } - - public function checkMdrefParam(\Zend_EventManager_Event $e) - { - $data = $e->getParam('data'); - - if(!is_array($data)) - { - return "参数错误"; - } - - if(empty($data["refid"])) - { - return "请填写文献ID"; - } - - if(empty($data['uuid'])) - { - return "请填写UUID"; - } - - if(!view::isUuid($data['uuid'])) - { - return "UUID格式不正确"; - } - - if(($data['reftype']==='')) - { - return "请选择文献类型"; - } - - return true; - } - - public function processMdrefData(\Zend_EventManager_Event $e) - { - $data = $e->getParam('data'); - - if(empty($data['place'])) - { - $data['place'] = 0; - } - - if(!is_numeric($data['place'])) - { - $data['place'] = 0; - } - - return $data; - } - -} diff --git a/Westdc/Reference/Handler/RisHandler.php b/Westdc/Reference/Handler/RisHandler.php index 8a82079..413b9cc 100644 --- a/Westdc/Reference/Handler/RisHandler.php +++ b/Westdc/Reference/Handler/RisHandler.php @@ -1,36 +1,31 @@ db = \Zend_Registry::get('db'); - }else{ - $this->db = $db; - } + $this->dbService = $this->getServiceManager()->get('Db'); + $this->db = $this->dbService->getPdo(); - $this->config = \Zend_Registry::get('config'); - $this->table = new Table(); + $this->table = new \stdClass; + $this->table->reference = "reference"; + $this->table->reference_author = "ref_author"; + $this->table->reference_tag = "ref_tag"; } //检查ris中的文献是否已经存在 - public function checkRisReference(\Zend_EventManager_Event $e) + public function checkRisReference(EventInterface $e) { $ref = $e->getParam('ref'); @@ -71,21 +66,19 @@ class RisHandler implements \Reference\Event\RisEvent } //删除作者 - public function deleteAuthor(\Zend_EventManager_Event $e) + public function deleteAuthor(EventInterface $e) { $id = $e->getParam('id'); - - $ref = new Reference(); - - return $ref->deleteReferenceAuthor($id); + + $sql = "DELETE FROM {$this->table->reference_author} WHERE id=$id "; + return $this->db->exec($sql); } - public function deleteTag(\Zend_EventManager_Event $e) + public function deleteTag(EventInterface $e) { $id = $e->getParam('id'); - - $ref = new Reference(); - - return $ref->deleteReferenceTag($id); + + $sql = "DELETE FROM {$this->table->reference_tag} WHERE id=$id "; + return $this->db->exec($sql); } } \ No newline at end of file diff --git a/Westdc/Reference/Listener/ReferenceListener.php b/Westdc/Reference/Listener/ReferenceListener.php deleted file mode 100644 index 4f77d00..0000000 --- a/Westdc/Reference/Listener/ReferenceListener.php +++ /dev/null @@ -1,48 +0,0 @@ -event = new \Zend_EventManager_EventManager(); - } - - public function attach(\Zend_EventManager_EventCollection $events) - { - $this->listeners[] = $events->attach('submit.before', function($e){ - $data = $e->getParam('data'); - - if(!is_array($data)) - return "参数错误"; - - if(empty($data["title"])) - return "请输入标题"; - - if(empty($data['reference'])) - return "请输入前台引用方式,并且唯一"; - - return true; - }, 100); //参数检查 - - $this->listeners[] = $events->attach('submit.processData', function($e){ - $data = $e->getParam('data'); - - if(empty($data['attid'])) - { - $data['attid'] = 0; - } - - return $data; - }, 50); - } - - public function detach(\Zend_EventManager_EventCollection $events) - { - - } - -} \ No newline at end of file diff --git a/Westdc/Reference/Listener/RisListener.php b/Westdc/Reference/Listener/RisListener.php index e51e17b..761aee4 100644 --- a/Westdc/Reference/Listener/RisListener.php +++ b/Westdc/Reference/Listener/RisListener.php @@ -1,27 +1,29 @@ event = new \Zend_EventManager_EventManager(); - } - - public function attach(\Zend_EventManager_EventCollection $events) + protected $listeners = array(); + + public function attach(EventManagerInterface $events) { $Handler = new RisHandler(); $events->attach('checkLoad', array($Handler, 'checkRisReference'), 100); - $events->attach('deleteAuthor', array($Handler, 'deleteAuthor'), 100); - $events->attach('deleteTag', array($Handler, 'deleteTag'), 100); + $events->attach('delete.after', array($Handler, 'deleteAuthor'), 100); + $events->attach('delete.after', array($Handler, 'deleteTag'), 80); + } + + public function detach(EventManagerInterface $events) + { + foreach ($this->listeners as $index => $listener) { + if ($events->detach($listener)) { + unset($this->listeners[$index]); + } + } } - public function detach(\Zend_EventManager_EventCollection $events) - { - - } - } \ No newline at end of file diff --git a/Westdc/Reference/Ris.php b/Westdc/Reference/Ris.php index 72da0dc..e13c454 100644 --- a/Westdc/Reference/Ris.php +++ b/Westdc/Reference/Ris.php @@ -1,49 +1,39 @@ db = \Zend_Registry::get('db'); - }else{ - $this->db = $db; - } - - $this->config = \Zend_Registry::get('config'); - - $Listener = new RisListener(); - @$this->events()->attachAggregate($Listener); - - $this->table = new \Helpers\Table(); - } - - public function events(\Zend_EventManager_EventCollection $events = NULL) + private $dbh; + + public function setServiceManager(ServiceManager $serviceManager) { - if ($events !== NULL) { - $this->events = $events; - } elseif ($this->events === NULL) { - $this->events = new \Zend_EventManager_EventManager(__CLASS__); - } - return $this->events; + $this->serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + public function init() + { + $Listener = new RisListener; + $this->getEventManager()->attachAggregate($Listener); + + $this->table = new \stdClass; + $this->table->reference = "reference"; + $this->table->reference_author = "ref_author"; + $this->table->reference_tag = "ref_tag"; } //ris导入 @@ -156,8 +146,9 @@ class Ris { return false; } - - $dbh = $this->dbh = new dbh(); + + $dbService = $this->serviceManager->get('Db'); + $dbh = $this->dbh = $dbService->getDbh(); foreach($data as $k=>$ref) { @@ -171,14 +162,13 @@ class Ris $ref['ris'] = $this->makeRisData(array(0=>$this->ris_records[$k])); - $results = $this->events()->trigger('checkLoad', $this, compact('ref')); + $results = $this->getEventManager()->trigger('checkLoad', $this, compact('ref')); $id = $results->bottom(); if ($id > 0) { $this->unsetVar($ref); - $this->events()->trigger('deleteAuthor', $this, compact('id')); - $this->events()->trigger('deleteTag', $this, compact('id')); + $this->getEventManager()->trigger('delete.after', $this, compact('id')); unset($ref['reference']); @@ -212,13 +202,14 @@ class Ris $ref['ris'] = $this->makeRisData(array(0=>$this->ris_records[0])); - $this->events()->trigger('deleteAuthor', $this, compact('id')); - $this->events()->trigger('deleteTag', $this, compact('id')); + $this->getEventManager()->trigger('delete.after', $this, compact('id')); + $this->getEventManager()->trigger('delete.after', $this, compact('id')); $this->unsetVar($ref); if(isset($ref['reference'])) unset($ref['reference']); - - $this->dbh = $dbh = new dbh(); + + $dbService = $this->serviceManager->get('Db'); + $this->dbh = $dbh = $dbService->getDbh(); if($dbh->update($this->table->reference,$ref," id=$id ")) { From 6f6b0ecb9a543a0b336e1d6a05113f47096d6e30 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Tue, 30 Dec 2014 17:34:30 +0800 Subject: [PATCH 28/32] fixed bugs in Reference module --- Westdc/Reference/Reference.php | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index 8ab3d66..68c3417 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -45,6 +45,7 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter $this->table->source = "source"; $this->table->metadata_reference = "mdref"; $this->table->reference_tag = "ref_tag"; + $this->table->metadata = "metadata"; } /** @@ -461,8 +462,9 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter { return "参数错误"; } - - if(!view::isUuid($uuid)) + + $tools = $this->serviceManager->get('Tools'); + if(!$tools->isUuid($uuid)) { return "参数错误"; } @@ -473,8 +475,9 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter 'reftype'=>$reftype, 'place'=>$place ); - - $dbh = new dbh(); + + $dbService = $this->serviceManager->get('Db'); + $dbh = $dbService->getDbh(); if(empty($id)) { @@ -545,25 +548,10 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter ); } - //数据文献参数 - public function getMdrefParam(\Zend_Controller_Request_Abstract $request = NULL) - { - $request = new \Zend_Controller_Request_Http(); - $data = array( - 'uuid' => trim($request->getParam('uuid')), - 'refid' => (int)$request->getParam('refid'), - 'place' => (int)$request->getParam('place'), - 'reftype' => (int)$request->getParam('reftype'), - ); - return $data; - } - //写入数据文献 - public function makeMdref($id = NULL) + public function makeMdref($data,$id = NULL) { - $data = $this->getMdrefParam(); - - $results = $this->events()->trigger('mdref.checkParam', $this, compact('data')); + $results = $this->getEventManager()->trigger('mdref.pre', $this, compact('data')); $cache_data = $results->bottom(); if($cache_data !== true) @@ -571,8 +559,8 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter return $cache_data; } - $results = $this->events()->trigger('mdref.processData', $this, compact('data')); - $data = $results->bottom(); + $results = $this->getEventManager()->trigger('mdref.processData', $this, compact('data')); + $data = $results->last(); $id = $this->createRelationFromReferenceToData($data['refid'],$data['uuid'],$data['reftype'],$data['place'],$id); From 649edb70b5dd600dae3e8f0ae10bf4dc797e461a Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Tue, 30 Dec 2014 19:49:04 +0800 Subject: [PATCH 29/32] add attachment table name define in Reference module --- Westdc/Reference/Reference.php | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php index 68c3417..e126cd0 100644 --- a/Westdc/Reference/Reference.php +++ b/Westdc/Reference/Reference.php @@ -46,6 +46,7 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter $this->table->metadata_reference = "mdref"; $this->table->reference_tag = "ref_tag"; $this->table->metadata = "metadata"; + $this->table->attachments = "attachments"; } /** @@ -398,9 +399,20 @@ class Reference extends AbstractEventManager implements ServiceManagerAwareInter //获得reference类型的附件 public function getReferenceFiles() { + $wheresql = [ + "att.filetype='literature'", + ]; + + if(!empty($this->keyword)) + { + $wheresql[] = " (att.realname LIKE '%{$this->keyword}%' OR att.filename LIKE '%{$this->keyword}%') "; + } + + $wheresql = " WHERE ".join(" AND ",$wheresql); + $sql = "SELECT att.*,ref.attid,ref.id as refid FROM {$this->table->attachments} att LEFT JOIN {$this->table->reference} ref ON att.id=ref.attid - WHERE att.filetype='literature'"; + $wheresql"; $rs = $this->db->query($sql); $rows = $rs->fetchAll(); return $rows; From 1dd78e14f60089b7506ac9b8e4d0b539c68dcd12 Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Wed, 31 Dec 2014 00:31:57 +0800 Subject: [PATCH 30/32] rename RisOutput as RisExport ,and update to a service,add simpleFetch() in Metadata service --- Westdc/Metadata/Metadata.php | 12 +++ .../{RisOutput.php => RisExport.php} | 74 ++++++++----------- 2 files changed, 42 insertions(+), 44 deletions(-) rename Westdc/Reference/{RisOutput.php => RisExport.php} (63%) diff --git a/Westdc/Metadata/Metadata.php b/Westdc/Metadata/Metadata.php index 4cd419a..4844d80 100644 --- a/Westdc/Metadata/Metadata.php +++ b/Westdc/Metadata/Metadata.php @@ -34,7 +34,19 @@ class Metadata extends AbstractEventManager implements ServiceManagerAwareInterf } + public function simpleFetch($uuid) + { + $sql="select * from metadata where uuid='$uuid'"; + $rs = $this->db->query($sql); + return $rs->fetch(); + }//simpleFetch + + /** + * 通过UUID删除元数据 + * @param $uuid + * @return bool|string + */ public function delete($uuid) { diff --git a/Westdc/Reference/RisOutput.php b/Westdc/Reference/RisExport.php similarity index 63% rename from Westdc/Reference/RisOutput.php rename to Westdc/Reference/RisExport.php index 44b7151..42081ec 100644 --- a/Westdc/Reference/RisOutput.php +++ b/Westdc/Reference/RisExport.php @@ -1,54 +1,40 @@ db = \Zend_Registry::get('db'); - }else{ - $this->db = $db; - } - - $this->config = \Zend_Registry::get('config'); - - //$Listener = new Listener(); - //@$this->events()->attachAggregate($Listener); - - $this->table = new \Helpers\Table(); - } - - public function events(\Zend_EventManager_EventCollection $events = NULL) + + + public function setServiceManager(ServiceManager $serviceManager) { - if ($events !== NULL) { - $this->events = $events; - } elseif ($this->events === NULL) { - $this->events = new \Zend_EventManager_EventManager(__CLASS__); - } - return $this->events; + $this->serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + public function init() + { + $this->table = new \stdClass; + $this->table->reference = "reference"; + + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); } //读取数据 @@ -79,12 +65,12 @@ class RisOutput $risReader = new RISReader(); } - $this->ris = new Ris(); + $this->ris = $this->serviceManager->get('Reference/Ris'); $this->attr = $this->ris->attr; $this->attr_flip = array_flip($this->ris->attr); unset($this->ris); - $this->reference = new Reference(); + $this->reference = $this->serviceManager->get('Reference'); foreach($arrayData as $k=>$v) { From 414b8f1f73be940d382f7431bd87b27f8d6037bf Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Fri, 2 Jan 2015 23:11:09 +0800 Subject: [PATCH 31/32] add debug option in MailSender,add Review library --- Westdc/Mail/Sender.php | 12 +- Westdc/Review/Review.php | 260 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 270 insertions(+), 2 deletions(-) create mode 100644 Westdc/Review/Review.php diff --git a/Westdc/Mail/Sender.php b/Westdc/Mail/Sender.php index eda573d..e85f54f 100644 --- a/Westdc/Mail/Sender.php +++ b/Westdc/Mail/Sender.php @@ -15,6 +15,8 @@ class Sender implements ServiceManagerAwareInterface{ protected $serviceManager; + public $debug = 0; + public function setServiceManager(ServiceManager $serviceManager) { $this->serviceManager = $serviceManager; @@ -37,8 +39,14 @@ class Sender implements ServiceManagerAwareInterface{ } $tools = $this->serviceManager->get('Tools'); - $tools->execBackend($cmd); - + + if($this->debug == 0) + { + $tools->execBackend($cmd); + return true; + } + + var_dump($tools->execFront($cmd)); return true; } diff --git a/Westdc/Review/Review.php b/Westdc/Review/Review.php new file mode 100644 index 0000000..010988e --- /dev/null +++ b/Westdc/Review/Review.php @@ -0,0 +1,260 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init(){ + $dbService = $this->serviceManager->get('Db'); + $this->db = $dbService->getPdo(); + unset($dbService); + + $this->opt = new \stdClass; + } + + /** + * 处理sql中用到的排序,limit等语句 + */ + private function processOptions() + { + if(isset($this->opt->limit) && $this->opt->limit > 0) + $this->limitSql = "LIMIT {$this->opt->limit}"; + + if(isset($this->opt->order) && !empty($this->opt->order)) { + $this->orderSql = "ORDER BY {$this->opt->order}"; + + if (isset($this->opt->sortSql) && !empty($this->opt->sortSql)) + $this->sortSql = "{$this->opt->sort}"; + else + $this->sortSql = "DESC"; + } + } + + /** + * 获得最新的数据 + * @return mixed + */ + public function getLatest() + { + $this->processOptions(); + + $sql = "select m.id,md.title,u.username,u.realname,m.status from mdstatus m + right join metadata md on md.uuid=m.uuid + left join users u on u.id=m.userid + order by m.id desc + {$this->limitSql}"; + $rs = $this->db->query($sql); + return $rs->fetchAll(); + }//getLatest() + + /** + * 获得管理员负责的评审 + * @param $userId + * @return mixed + */ + public function getAdminReview($userId) + { + $this->processOptions(); + + $sql = "select m.id,md.title,u.username,u.realname,m.status from mdstatus m + right join metadata md on md.uuid=m.uuid + left join users u on u.id=m.userid + where u.id='$userId' + {$this->limitSql}"; + + $rs = $this->db->query($sql); + return $rs->fetchAll(); + } //getAdminReview + + /** + * 投稿元数据 + * @return mixed + */ + public function getDraft(){ + + $this->processOptions(); + + $searchJoin = ""; + if(isset($this->opt->keyword) && !empty($this->opt->keyword)) + { + $searchJoin = " AND md.title LIKE '%{$this->opt->keyword}%'"; + } + + if(empty($this->orderSql)) + { + $this->orderSql = "ORDER BY m.ts_created DESC"; + } + + $sql = "SELECT m.id,md.title,md.uuid,u.username,u.realname,m.status,m.ts_created,gn.id as gnid FROM mdstatus m + RIGHT JOIN metadata md ON md.uuid=m.uuid + LEFT JOIN users u ON u.id=m.userid + LEFT JOIN geonetworkmetadata gn ON m.uuid=gn.uuid + WHERE m.status=0 $searchJoin + {$this->orderSql} {$this->sortSql} + {$this->limitSql}"; + + $rs = $this->db->query($sql); + return $rs->fetchAll(); + }//getDraft() + + /** + * 取消评审 + * @param $id + * @return bool + */ + public function cancel($id){ + if(!is_numeric($id) || $id<1) + return false; + return $this->changeStatus($id,self::REVIEW_STATUS_CANCELED); + } + + /** + * 接收投稿的元数据 + * @param $id + * @return bool + */ + public function accept($id){ + + if($this->getStatus($id) != self::REVIEW_STATUS_DEFAULT) + return [ + '评审状态错误,有可能的错误是:', + '此评审已被取消,请到已取消评审的元数据中将其重置', + '此评审已经被接收', + '此评审已经处于待分配责任编辑、邀请专家、等待专家评审、已通过评审的状态中' + ]; + + $status = $this->changeStatus($id,self::REVIEW_STATUS_ACCEPT); + + if(false === $status){ + return false; + } + + $authorEmail = $this->getAuthor($id); + + foreach($authorEmail as $v) + { + $mailSender = $this->serviceManager->get('Mail/Sender'); + $mailSender->backend([ + 'email' => $v['email'], + 'name' => !empty($v['realname']) ? $v['realname']:$v['username'], + 'template' => 'review-new-accept', + 'data' => [ + 'uuid' => $v['uuid'], + 'title' => $v['title'], + ] + ]); + } + + return true; + + }//accept($id) + + /** + * 获得某条评审涉及的元数据相关作者信息(email,元数据标题,uuid) + * @param $id + * @return mixed + */ + public function getAuthor($id){ + $sql = "SELECT DISTINCT u.email,u.realname,u.username,m.title,m.uuid FROM mdstatus s + LEFT JOIN metadata m ON s.uuid=m.uuid + RIGHT JOIN mdauthor a ON s.uuid=a.uuid + LEFT JOIN users u ON a.userid=u.id + WHERE s.id=$id + ORDER BY u.email"; + + $rs = $this->db->query($sql); + return $rs->fetchAll(\PDO::FETCH_ASSOC); + } + + public function reset($id){ + + } + + /** + * 更改mdstatus中的status字段 + * @param $id + * @param $status + * @return bool + */ + function changeStatus($id,$status){ + $statusValues = array( + self::REVIEW_STATUS_CANCELED, //取消评审 + self::REVIEW_STATUS_DEFAULT, //初始状态 + self::REVIEW_STATUS_ACCEPT, //接受元数据评审,进入评审阶段 + self::REVIEW_STATUS_EXPERT_INVITED, //开始邀请专家,送审阶段 + self::REVIEW_STATUS_EXPERT_ACCEPT, //专家接受邀请,在审阶段 + self::REVIEW_STATUS_EXPERT_FEEDBACK,//专家反馈,在审 + self::REVIEW_STATUS_PUBLISH, //评审结束,发布 + 6,7 + ); + if(empty($id) || !isset($status) || !in_array($status,$statusValues)) + { + return false; + } + else + { + if($status==1) + {$sql = "update mdstatus set status='$status',ts_accepted='now()' where id in ($id)"; } + else if($status==5) + {$sql = "update mdstatus set status='$status',ts_finished='now()' where id in ($id)";} + else + {$sql = "update mdstatus set status='$status' where id in ($id)";} + try{ + if($this->db->exec($sql)>0) + { + return true; + } + } + catch(\Exception $e) + { + return false; + } + } + }//changestatus 更改状态 + + + /** + * 获取mdstatus表中的status字段 + * @param $id + * @return mixed + */ + public function getStatus($id) + { + $sql = "SELECT status FROM mdstatus WHERE id=$id"; + $rs = $this->db->query($sql); + + return $rs->fetchColumn(0); + } + + +} \ No newline at end of file From 40b58bda04cb76bd456aea318f7b80207cebf17d Mon Sep 17 00:00:00 2001 From: Jianxuan Li Date: Sat, 3 Jan 2015 22:29:35 +0800 Subject: [PATCH 32/32] add class Westdc\Mail\Queue --- Westdc/Mail/Queue.php | 41 +++++++++++++++++++++++++++++++++++++++++ Westdc/Mail/Sender.php | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 Westdc/Mail/Queue.php diff --git a/Westdc/Mail/Queue.php b/Westdc/Mail/Queue.php new file mode 100644 index 0000000..deeb13d --- /dev/null +++ b/Westdc/Mail/Queue.php @@ -0,0 +1,41 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + private function init() + { + + } + + public function add(){ + + } + + public function show(){ + + } + +} \ No newline at end of file diff --git a/Westdc/Mail/Sender.php b/Westdc/Mail/Sender.php index e85f54f..b7c860c 100644 --- a/Westdc/Mail/Sender.php +++ b/Westdc/Mail/Sender.php @@ -24,6 +24,11 @@ class Sender implements ServiceManagerAwareInterface{ return $this; } + /** + * 发送即时邮件 + * @param $options + * @return bool + */ public function backend($options) { $cmd = "php ".CURRENT_BOOTSTRAP_SCRIPT; @@ -50,4 +55,36 @@ class Sender implements ServiceManagerAwareInterface{ return true; } + /** + * 将邮件添加到发送列队,降低内存和cpu消耗,但是用户无法即时收到,适用于通知类型的邮件和大批量发送的邮件 + * @param $options + * @return bool + */ + public function queue($options) + { + $cmd = "php ".CURRENT_BOOTSTRAP_SCRIPT; + $cmd .= ' mail queue'; + $cmd .= ' --email="'.$options['email'].'"'; + $cmd .= ' --name="'.$options['name'].'"'; + $cmd .= ' --template="'.$options['template'].'"'; + + if(isset($options['data'])) + { + $data = json_encode($options['data']); + $cmd .= ' --data=\''.$data.'\''; + } + + $tools = $this->serviceManager->get('Tools'); + + if($this->debug == 0) + { + $tools->execBackend($cmd); + return true; + } + + var_dump($tools->execFront($cmd)); + return true; + return true; + } + } \ No newline at end of file