diff --git a/Westdc/Authentication/AuthenticationService.php b/Westdc/Authentication/AuthenticationService.php index 227ea47..9bf780e 100644 --- a/Westdc/Authentication/AuthenticationService.php +++ b/Westdc/Authentication/AuthenticationService.php @@ -41,8 +41,14 @@ 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); +// view::Dump($e->getRouteMatch()->getMatchedRouteName() . ":" . $controller."-".$action,false); + $this->preCookieCheck(); try{ diff --git a/Westdc/Db/Db.php b/Westdc/Db/Db.php index d7f762d..f1097ec 100644 --- a/Westdc/Db/Db.php +++ b/Westdc/Db/Db.php @@ -8,7 +8,7 @@ class Db extends AbstractServiceManager { private $db; - function __construct(&$db,$param = array()) + function __construct(&$db = "",$param = array()) { $configService = $this->getServiceManager()->get('Config'); $config_local = $configService->get("local.php"); @@ -20,6 +20,7 @@ class Db extends AbstractServiceManager $this->db = new Adapter(array( 'driver' => $config_local->db->driver, 'hostname' => $config_local->db->hostname, + 'port' => $config_local->db->port, 'database' => $config_local->db->database, 'username' => $config_local->db->username, 'password' => $config_local->db->password diff --git a/Westdc/Db/Dbh.php b/Westdc/Db/Dbh.php new file mode 100644 index 0000000..9fe07b5 --- /dev/null +++ b/Westdc/Db/Dbh.php @@ -0,0 +1,141 @@ +db = new PDO(); + else + $this->db = $db; + } + + function insert($table,$data,$return=false) + { + $fields = array(); + $datas = array(); + + foreach($data as $k=>$v) + { + $fields[] = '"'.$k.'"'; + if(is_int($v) || is_float($v) || is_bool($v)) + { + $datas[] = $v; + }else{ + if(preg_match("/\'/",$v)) + { + $v = preg_replace("/\'/","''",$v); + } + $datas[] = "'".$v."'"; + } + } + + $fields = join(",",$fields); + $datas = join(",",$datas); + + if($return == false){ + + $sql = "INSERT INTO \"".$table."\" ($fields) VALUES ($datas)"; + try{ + return $this->db->exec($sql); + }catch (\Exception $e) { + if($this->product) + { + return false; + }else{ + echo 'Caught exception: '. $e->getMessage(). "\n"; + } + } + }else{ + $sql = "INSERT INTO \"".$table."\" ($fields) VALUES ($datas) RETURNING id"; + try{ + $sth = $this->db->prepare($sql); + if($sth->execute()) + { + $temp = $sth->fetch(\PDO::FETCH_ASSOC); + return $temp['id']; + }else{ + return false; + } + }catch (\Exception $e) { + if($this->product) + { + return false; + }else{ + echo view::Dump('Caught exception: '. $e->getMessage(). "\n"."SQL:".$sql,false); + } + } + } + }//insert + + function update($table,$data,$condition="",$return=false) + { + $ups = array(); + + foreach($data as $k=>$v) + { + if(is_int($v) || is_float($v) || is_bool($v)) + { + $ups[] = '"'.$k.'"='.$v; + }else{ + if(preg_match("/\'/",$v)) + { + $v = preg_replace("/\'/","''",$v); + } + $ups[] = '"'.$k.'"=\''.$v."'"; + } + } + + $fields = join(",",$ups); + + if(!empty($condition)) + { + $wheresql = " WHERE ".$condition; + }else{ + $wheresql = ""; + } + + if($return == false){ + + try{ + $sql = "UPDATE \"".$table."\" SET $fields $wheresql"; + if($this->db->exec($sql)) + { + return true; + }else{ + return false; + } + }catch (\Exception $e) { + if($this->product) + { + return false; + }else{ + echo 'Caught exception: '. $e->getMessage(). "\n"; + } + } + }else{ + try{ + $sql = "UPDATE \"".$table."\" SET $fields $wheresql"; + return $this->db->exec($sql); + }catch (\Exception $e) { + if($this->product) + { + return false; + }else{ + echo "
";
+					echo $sql."\r\n";
+					echo 'Caught exception: '.  $e->getMessage(). "\r\n";
+					echo "
"; + } + } + } + + }//update + +} \ No newline at end of file diff --git a/Westdc/Db/Pdo.php b/Westdc/Db/Pdo.php index 19b7644..ce6f3f5 100644 --- a/Westdc/Db/Pdo.php +++ b/Westdc/Db/Pdo.php @@ -17,7 +17,7 @@ class Pdo extends \PDO $config_local = new Zend_Config(include $this->config_local_path); $dsn = "pgsql:host={$config_local->db->hostname};" - . "port=5432;" + . "port={$config_local->db->port};" . "dbname={$config_local->db->database};" . "user={$config_local->db->username};" . "password={$config_local->db->password}"; 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/File/File.php b/Westdc/File/File.php new file mode 100644 index 0000000..4bed5d7 --- /dev/null +++ b/Westdc/File/File.php @@ -0,0 +1,95 @@ +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; + } + + //获取某个文件的信息 + 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/File/Listener/DefaultFileUploadListener.php b/Westdc/File/Listener/DefaultFileUploadListener.php new file mode 100644 index 0000000..4d172bc --- /dev/null +++ b/Westdc/File/Listener/DefaultFileUploadListener.php @@ -0,0 +1,76 @@ +serviceManager = new ServiceManager(); + $this->serviceManager = $this->serviceManager->getServiceManager(); + } + + public function attach(EventManagerInterface $events) + { + $this->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); + + $this->listeners[] = $events->attach('upload.after', function($e){ + + $file_data = $e->getParam('file_data'); + + $authService = $this->serviceManager->get('Auth'); + + $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); + + + } + + 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..81064f7 --- /dev/null +++ b/Westdc/File/Upload.php @@ -0,0 +1,250 @@ +serviceManager = $serviceManager; + + $this->init(); + + return $this; + } + + public function init() + { + $Listener = new DefaultFileUploadListener; + $this->getEventManager()->attachAggregate($Listener); + + $configService = $this->serviceManager->get('ConfigService'); + $this->config = $configService->get('file.php'); + } + + public function __invoke($files,$rootDir = "",$childDir = "",$fileName = "",$dateDirModel = self::DATETIME_MODEL_YMD) + { + return $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) { + return array("error"=>"请选择要上传的文件."); + } + + if (is_uploaded_file($files['tmp_name']) === false) { + return array("error"=>"文件上传失败,请重新上传"); + } + + $file = $files; + + $results = $this->getEventManager()->trigger('upload.pre', $this, compact('file')); + $cache_data = $results->last(); + + if($cache_data !== true) + { + return $cache_data; + } + + $fileService = $this->serviceManager->get('File'); + + $this->setRootDir($rootDir); + $this->setChildDir($childDir); + + if($dateDirModel !== false) + $this->makeDateDir($dateDirModel); + + $this->setFileName($fileName , $fileService->getFileTextExt($files['name'])); + + //移动文件 + $file_path = $this->getUploadPath() . $this->getFileName(); + + if (move_uploaded_file($file['tmp_name'], $file_path) === false) { + return array("error"=>"上传失败,请重试"); + } + + $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_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(); + + if(is_array($cache_data)) + $file_data = array_merge($file_data , $cache_data); + + return $file_data; + }//文件上传 + + /** + * 设置上传文件的根路径,这样操作会忽略config中的定义 + * 根路径需要自行创建 + * 路径结尾必须加 "/" + * @param string $path + * @return bool + */ + public function setRootDir($path = "") + { + if(empty($path)) + $this->uploadPath = $this->config->upload; + + $this->uploadPath = $path; + + if(!preg_match("/[\/|\\\]+$/",$this->uploadPath)) + $this->uploadPath .= "/"; + + return true; + } + + /** + * 设置子路径,自动加在根路径之后 + * 如果不存在程序将创建 + * @param string $dirname + * @return bool | string + */ + public function setChildDir($dirname) + { + if(empty($dirname)) { + return true; + } + + $this->uploadPath .= $dirname; + + if (!preg_match("/[\/|\\\]+$/", $this->uploadPath)) + $this->uploadPath .= "/"; + + + if(!file_exists($this->uploadPath)) { + if(!mkdir($this->uploadPath)) + return "failed to create folder :".$this->uploadPath; + } + + $this->relativePath = $dirname; + } + + /** + * 创建并返回年月日的子目录路径 + * @return string + */ + public function makeDateDir($model) + { + $y = date("Y"); + $m = date("m"); + $d = date("d"); + + 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); + } + + 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); + } + + 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; + $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; + + } + + + public function setParams($params) + { + $this->params = $params; + } + + /** + * @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/Assist.php b/Westdc/Helpers/Assist.php index 2884d9f..91bab44 100644 --- a/Westdc/Helpers/Assist.php +++ b/Westdc/Helpers/Assist.php @@ -14,20 +14,29 @@ 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'); - - $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); $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/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/Paginator.php b/Westdc/Helpers/Paginator.php new file mode 100644 index 0000000..2519f00 --- /dev/null +++ b/Westdc/Helpers/Paginator.php @@ -0,0 +1,132 @@ +serviceManager = $serviceManager; + + $this->setPageLimit(); + $this->setPageRange(); + $this->setRoute(); + + return $this; + } + + 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'); + + 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($this->pageLimit) + ->setPageRange($this->pageRange); + + $pagination = $ctl->getServiceLocator()->get('viewhelpermanager')->get('PaginationControl'); + + $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 diff --git a/Westdc/Helpers/Theme.php b/Westdc/Helpers/Theme.php new file mode 100644 index 0000000..5c06fa5 --- /dev/null +++ b/Westdc/Helpers/Theme.php @@ -0,0 +1,204 @@ +_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' + ), + ), + + '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( + '/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"); + + }// +} diff --git a/Westdc/Helpers/Tools.php b/Westdc/Helpers/Tools.php index fe9ec21..ee0658f 100644 --- a/Westdc/Helpers/Tools.php +++ b/Westdc/Helpers/Tools.php @@ -2,13 +2,84 @@ 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; + } + + /** + * @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; + } + + /** + * @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/Mail/Mail.php b/Westdc/Mail/Mail.php index 12613f3..6a7b120 100644 --- a/Westdc/Mail/Mail.php +++ b/Westdc/Mail/Mail.php @@ -8,36 +8,185 @@ namespace Westdc\Mail; -use Zend\EventManager\EventManagerInterface; -use Zend\EventManager\EventManager; -use Zend\EventManager\EventManagerAwareInterface; +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; + + public $mail; + public $config; + public $subject; + public $body; + public $type; + public $transport; + public $from; + + 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; + + $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 setDefaultFrom() + { + $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']; + + }//加载模板 + + /** + * @param $from + */ + public function setFrom($from) + { + $this->from = $from; + } + + + /** + * @param null $from + * @return bool + */ + public function preSend($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) && empty($this->from)) + { + $this->setDefaultFrom(); + }else{ + 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); + + return true; + } + + //使用loadTemplate 的结果发送邮件 + //在此之前需要使用 $this->mail->addTo()添加收件人 + /** + * @param null $from + */ + public function send($from = NULL){ + + if(!$status = $this->preSend($from)) + return $status; + + 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/Queue.php similarity index 51% rename from Westdc/Mail/MailService.php rename to Westdc/Mail/Queue.php index b8bd5c2..deeb13d 100644 --- a/Westdc/Mail/MailService.php +++ b/Westdc/Mail/Queue.php @@ -1,32 +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 new file mode 100644 index 0000000..b7c860c --- /dev/null +++ b/Westdc/Mail/Sender.php @@ -0,0 +1,90 @@ +serviceManager = $serviceManager; + + return $this; + } + + /** + * 发送即时邮件 + * @param $options + * @return bool + */ + 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'); + + if($this->debug == 0) + { + $tools->execBackend($cmd); + return true; + } + + var_dump($tools->execFront($cmd)); + 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 diff --git a/Westdc/Mail/Template.php b/Westdc/Mail/Template.php new file mode 100644 index 0000000..e369f19 --- /dev/null +++ b/Westdc/Mail/Template.php @@ -0,0 +1,139 @@ +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); + } + + //插入邮件模板 + 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(); + + if(empty($data['subject'])) + { + $data['subject']='未命名模板'; + } + + + $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($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(); + + + $rs = $dbh->update('emailtext',$data,"id=$id",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(); + } + + /** + * @param $key + * @param $data + * @return array + */ + public function load($key,$data){ + + $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(); + + 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/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/Dataset.php b/Westdc/Metadata/Dataset.php new file mode 100644 index 0000000..91c8728 --- /dev/null +++ b/Westdc/Metadata/Dataset.php @@ -0,0 +1,171 @@ +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(); + } + + /** + * + * @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 diff --git a/Westdc/Metadata/Metadata.php b/Westdc/Metadata/Metadata.php index 777a7a9..4844d80 100644 --- a/Westdc/Metadata/Metadata.php +++ b/Westdc/Metadata/Metadata.php @@ -8,10 +8,70 @@ 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 { + 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) + { + + $tools = $this->serviceManager->get('Tools'); + + 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 删除元数据 } \ No newline at end of file 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); + } + } +} diff --git a/Westdc/Reference/Handler/RisHandler.php b/Westdc/Reference/Handler/RisHandler.php new file mode 100644 index 0000000..413b9cc --- /dev/null +++ b/Westdc/Reference/Handler/RisHandler.php @@ -0,0 +1,84 @@ +dbService = $this->getServiceManager()->get('Db'); + $this->db = $this->dbService->getPdo(); + + $this->table = new \stdClass; + $this->table->reference = "reference"; + $this->table->reference_author = "ref_author"; + $this->table->reference_tag = "ref_tag"; + } + + //检查ris中的文献是否已经存在 + public function checkRisReference(EventInterface $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(EventInterface $e) + { + $id = $e->getParam('id'); + + $sql = "DELETE FROM {$this->table->reference_author} WHERE id=$id "; + return $this->db->exec($sql); + } + + public function deleteTag(EventInterface $e) + { + $id = $e->getParam('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/RisListener.php b/Westdc/Reference/Listener/RisListener.php new file mode 100644 index 0000000..761aee4 --- /dev/null +++ b/Westdc/Reference/Listener/RisListener.php @@ -0,0 +1,29 @@ +attach('checkLoad', array($Handler, 'checkRisReference'), 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]); + } + } + } + +} \ No newline at end of file diff --git a/Westdc/Reference/Reference.php b/Westdc/Reference/Reference.php new file mode 100644 index 0000000..e126cd0 --- /dev/null +++ b/Westdc/Reference/Reference.php @@ -0,0 +1,784 @@ +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"; + $this->table->metadata_reference = "mdref"; + $this->table->reference_tag = "ref_tag"; + $this->table->metadata = "metadata"; + $this->table->attachments = "attachments"; + } + + /** + * 添加或编辑文献 + * @param $data + * @param int $id + * @return bool|string + */ + public function reference($data,$id = 0) + { + $params = compact('data'); + $results = $this->getEventManager()->trigger('submit.before', $this, $params); + $cache_data = $results->bottom(); + + if($cache_data !== true) + { + return $cache_data; + } + + $results = $this->getEventManager()->trigger('submit.processData', $this, $params); + $data = $results->bottom(); + + $dbServices = $this->serviceManager->get('Db'); + $dbh = $dbServices->getDbh(); + + 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 "修改失败"; + } + } + + //上传文献PDF + public function uploadReferencePdf($file,$autoread = false) + { + $configService = $this->serviceManager->get('ConfigService'); + $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'])) + { + return array("error" => $file_info['error']); + } + + if($autoread) + { + $params = compact('file_data'); + $results = $this->events()->trigger('upload.insertToReferenceTable', $this, $params); + $cache_data = $results->bottom(); + $file_info = array_merge($file_info,$cache_data); + } + + return $file_info; + } + + //通过文件名自动提取文章标题 + 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 fetchAll() + { + $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']) + { + $fileService = $this->serviceManager->get('File'); + $attfile = $fileService->get($row['attid']); + + $row['file'] = $attfile; + } + return $row; + } + + //获得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 + $wheresql"; + $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 "参数错误"; + } + + $tools = $this->serviceManager->get('Tools'); + if(!$tools->isUuid($uuid)) + { + return "参数错误"; + } + + $data = array( + 'uuid'=>$uuid, + 'refid'=>$refid, + 'reftype'=>$reftype, + 'place'=>$place + ); + + $dbService = $this->serviceManager->get('Db'); + $dbh = $dbService->getDbh(); + + 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 makeMdref($data,$id = NULL) + { + $results = $this->getEventManager()->trigger('mdref.pre', $this, compact('data')); + $cache_data = $results->bottom(); + + if($cache_data !== true) + { + return $cache_data; + } + + $results = $this->getEventManager()->trigger('mdref.processData', $this, compact('data')); + $data = $results->last(); + + $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..e13c454 --- /dev/null +++ b/Westdc/Reference/Ris.php @@ -0,0 +1,333 @@ +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导入 + 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; + } + + $dbService = $this->serviceManager->get('Db'); + $dbh = $this->dbh = $dbService->getDbh(); + + 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->getEventManager()->trigger('checkLoad', $this, compact('ref')); + $id = $results->bottom(); + + if ($id > 0) + { + $this->unsetVar($ref); + $this->getEventManager()->trigger('delete.after', $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->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']); + + $dbService = $this->serviceManager->get('Db'); + $this->dbh = $dbh = $dbService->getDbh(); + + 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/RisExport.php b/Westdc/Reference/RisExport.php new file mode 100644 index 0000000..42081ec --- /dev/null +++ b/Westdc/Reference/RisExport.php @@ -0,0 +1,139 @@ +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(); + } + + //读取数据 + 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 = $this->serviceManager->get('Reference/Ris'); + $this->attr = $this->ris->attr; + $this->attr_flip = array_flip($this->ris->attr); + unset($this->ris); + + $this->reference = $this->serviceManager->get('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/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 diff --git a/Westdc/Service/ServiceAgent/Auth.php b/Westdc/Service/ServiceAgent/Auth.php index f75f0bf..998a96f 100644 --- a/Westdc/Service/ServiceAgent/Auth.php +++ b/Westdc/Service/ServiceAgent/Auth.php @@ -9,7 +9,13 @@ namespace Westdc\Service\ServiceAgent; use Westdc\Helpers\Auth as AuthHelper; +use Westdc\Member\Cookie; class Auth extends AuthHelper{ + public function getCookieCtl() + { + return new Cookie(); + } + } \ No newline at end of file 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 @@ +getAdapter(); + } + + public function getPdo() + { + return new WestdcDb\Pdo; + } + + public function getDbh() + { + return new WestdcDb\Dbh; + } + + +} \ No newline at end of file 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 @@ +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/ServiceManager.php b/Westdc/Service/ServiceManager.php index 1906b1a..e323740 100644 --- a/Westdc/Service/ServiceManager.php +++ b/Westdc/Service/ServiceManager.php @@ -16,8 +16,15 @@ class ServiceManager { function __construct() { - $this->serviceManager = new Zend_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 = "") 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 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){ + + } + } diff --git a/Westdc/User/Cookie.php b/Westdc/User/Cookie.php deleted file mode 100644 index 3a7667f..0000000 --- a/Westdc/User/Cookie.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/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 20456ea..9fe7d49 100644 --- a/Westdc/User/User.php +++ b/Westdc/User/User.php @@ -8,8 +8,39 @@ namespace Westdc\User; +use Zend\ServiceManager\ServiceManager; +use Zend\ServiceManager\ServiceManagerAwareInterface; +use Westdc\EventModel\AbstractEventManager; + +class User 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(); + } + + public function fetchAll(){ + $sql = "select * from users where usertype = 'member'"; + $rs = $this->db->query($sql); + return $rs->fetchAll(\PDO::FETCH_ASSOC); -class User { + } + + } \ 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