commit new libraries,add Westdc ServiceFactory

This commit is contained in:
Jianxuan Li 2014-11-04 17:05:21 +08:00
parent b525655bd2
commit 69ea4689a6
32 changed files with 3985 additions and 0 deletions

View File

@ -0,0 +1,67 @@
<?php
namespace Westdc\Authentication;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
class AclAuthorize
{
public $acl;
public $role;
function __construct(Acl &$acl,$config = "")
{
$this->acl = $acl;
$this->loadAuthorize($config);
$acl = $this->acl;
}
public function loadAuthorize($config = "")
{
$this->config = include(CONFIG_PATH.'/auth/acl_authorize.php');
foreach($this->config as $k=>$auth)
{
if(!isset($auth['inherit']) || empty($auth['inherit']))
$this->acl->addRole(new Role($auth['alias']));
else
$this->acl->addRole(new Role($auth['alias']),$this->config[$auth['inherit']]['alias']);
if( isset($auth['allow']) && is_array($auth['allow']))
{
foreach($auth['allow'] as $index => $allow)
{
if(is_numeric($index))
$this->acl->allow($auth['alias'], $allow);
else
$this->acl->allow($auth['alias'], $index , $allow);
}
}
if( isset($auth['allow']) && is_string($auth['allow']) && $auth['allow'] == 'all')
{
$this->acl->allow($auth['alias']);
}
if( isset($auth['deny']) && is_array($auth['deny']) )
{
foreach($auth['deny'] as $index => $deny)
{
if(is_numeric($index))
$this->acl->deny($auth['alias'], $deny);
else
$this->acl->deny($auth['alias'], $index , $deny);
}
}
}//foreach
}
}

View File

@ -0,0 +1,74 @@
<?php
namespace Westdc\Authentication;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Westdc\Helpers\View as view;
class AclResource
{
public $acl;
public $config;
function __construct(Acl &$acl)
{
$this->acl = $acl;
$this->config = include(CONFIG_PATH.'/auth/acl_resource.php');
$this->loadResource();
$acl = $this->acl;
}
/*public function loadResource()
{
foreach($this->config as $index => $resource)
{
if(!is_array($resource))
{
$this->acl->addResource(new Resource($resource));
continue;
}
$this->acl->addResource(new Resource($index));
foreach($resource as $controller=>$action)
{
$this->acl->addResource(new Resource($controller.'\\'.$action));
}
}
}*/
public function loadResource()
{
foreach($this->config as $index => $resource)
{
if(!is_array($resource))
{
$this->acl->addResource(new Resource($resource));
continue;
}
$this->acl->addResource(new Resource($index));
foreach($resource as $action)
{
if($this->acl->hasResource($action))
{
//exit($index."-".$action);
//$this->acl->addResource($this->acl->getResource($action),$index);
continue;
}
//echo $index."-".$action."<br />";
$this->acl->addResource(new Resource($action),$index);
}
}
}
}

View File

@ -0,0 +1,185 @@
<?php
namespace Westdc\Authentication;
use Zend\Permissions\Acl\Acl;
use Zend\Permissions\Acl\Role\GenericRole as Role;
use Zend\Permissions\Acl\Resource\GenericResource as Resource;
use Westdc\Helpers\Assist as view;
use Westdc\Member\Cookie;
use Zend\Mvc\MvcEvent;
class AuthenticationService
{
private $db;
public $acl;
protected $role;
public $loginRouterName = "login";
function __construct()
{
//初始化配置
$this->configure();
$this->role = new \stdClass();
$this->role->guest = 'guest';
$user = view::User();
if(!$user)
{
$this->role->current = 'guest';
}else{
$this->role->current = $user->usertype;
}
}
public function run($e)
{
$module = $e->getRouteMatch()->getParam('module');
$namespace = $e->getRouteMatch()->getParam('__NAMESPACE__');
$controller = $e->getRouteMatch()->getParam('controller');
$action = $e->getRouteMatch()->getParam('action');
//view::Dump($e->getRouteMatch()->getMatchedRouteName() . ":" . $controller."-".$action,false);
$this->preCookieCheck();
try{
if(!$this->acl->hasResource($controller))
{
$this->badRequest($e);
return;
}
if($this->acl->isAllowed($this->role->current,$controller) === true)
{
return true;
}else{
if($this->acl->isAllowed($this->role->current,$controller,$action) === true)
{
return true;
}else{
$this->response($e);
}
}
}catch (Exception $e) {
//echo 'Caught exception: ', $e->getMessage(), "\n";
$this->badRequest($e);
return;
}
}
public function preCookieCheck()
{
if(!view::User())
{
$mb = new Cookie;
//view::Dump($mb->checkcookie());
if($mb->checkcookie())
{
$account = new Account();
$account->cookieLogin(array($mb->FieldUsername=>$mb->user,$mb->FieldPasword=>$mb->srpwd));
}
}
}
public function response($e)
{
//用户已经登录的情况
if(view::User() !== false)
{
$this->badRequest($e,403);
return;
}
//没有登录的情况
if(view::isXmlHttpRequest())
{
}else{
$response = $e->getResponse();
$response->setStatusCode(404);
$response->sendHeaders();
$layout = $e->getViewModel();
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
$partial = $viewHelperManager->get('partial');
$page_content = $partial(
'layout/layout/message',
array(
'message' => '请先登陆',
'url'=> $e->getRouter()->assemble(array(), array('name' => $this->loginRouterName))."?href=".$_SERVER['REQUEST_URI'],
)
);
$layout->setVariable('content',$page_content);
$layout->setTemplate('layout/layout');
$e->stopPropagation();
return $response;
}
}
public function badRequest($e,$type = 404)
{
$response = $e->getResponse();
$response->setStatusCode(404);
$response->sendHeaders();
$layout = $e->getViewModel();
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
$partial = $viewHelperManager->get('partial');
if($type == 404)
{
$page_content = $partial(
'error/404',
array(
'message' => 'This page has been eaten by dinosaurs',
'controller'=>$controller = $e->getRouteMatch()->getParam('controller'),
'display_exceptions' => true,
'reason' => 'error-controller-invalid',
)
);
}else{
$page_content = $partial(
'error/404',
array(
'message' => '您没有权限访问此页面',
'controller'=>$controller = $e->getRouteMatch()->getParam('controller'),
'reason' => 'error-controller-invalid',
'display_exceptions' => true
)
);
}
$layout->setVariable('content',$page_content);
$layout->setTemplate('layout/layout');
$e->stopPropagation();
return $response;
}
//加载配置
public function configure()
{
//初始化ACL
$this->acl = new Acl();
$this->acl->deny();
//加载资源
new AclResource($this->acl);
//加载权限
new AclAuthorize($this->acl);
}
}

View File

@ -0,0 +1,18 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2014/10/22
* Time: 11:29
*/
namespace Westdc\Config;
interface ConfigInterface {
public function get();
}

28
Westdc/Db/Pdo.php Normal file
View File

@ -0,0 +1,28 @@
<?php
namespace Westdc\Db;
use Zend\Config\Config as Zend_Config;
class Pdo extends \PDO
{
private $debug = 0; //调试模式
private $config_local_path = "config/autoload/local.php";
function __construct($DSN = NULL)
{
if (!empty($DSN)) {
parent::__construct($DSN);
} else {
$config_local = new Zend_Config(include $this->config_local_path);
$dsn = "pgsql:host={$config_local->db->hostname};"
. "port=5432;"
. "dbname={$config_local->db->database};"
. "user={$config_local->db->username};"
. "password={$config_local->db->password}";
parent::__construct($dsn);
}
}
}

285
Westdc/Helpers/Assist.php Normal file
View File

@ -0,0 +1,285 @@
<?php
namespace Westdc\Helpers;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver;
use Westdc\Helpers\Auth;
class Assist
{
function __construct($db = NULL)
{
}
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));
$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);
$pagination->setDefaultViewPartial($viewPartial);
$ctl->ViewModel->setVariable('paginator',$paginator);
}
static function Msg($type,$content,$url=''){
$html = '<div class="alert '.$type.'">'."\r\n";
$html.= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'."\r\n";
$html.= $content."\r\n";
$html.= '</div>'."\r\n";
if(!empty($url))
{
if($url == -1){
$html.= '<script language="javascript">setTimeout("window.history.back(-1);",3000);</script>'."\r\n";
}else{
$html.= '<script language="javascript">setTimeout("self.location=\''.$url.'\'",3000);</script>'."\r\n";
}
}
return $html;
}
static function Error($content,$type='',$url=''){
if(empty($type))
{
$AlertType = "alert-danger";
}else{
$AlertType = $type;
}
$html = '<div class="alert '.$AlertType.'" id="Alert-error-box">'."\r\n";
$html.= '<button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>'."\r\n";
if(!is_array($content)) {
$html.= $content."\r\n";
}else{
$html.= '<ul>'."\r\n";
foreach($content as $v) {
$html.='<li>'.$v.'</li>'."\r\n";
}
$html.= '</ul>'."\r\n";
}
$html.= '</div>'."\r\n";
return $html;
}
static function User($param = NULL){
$auth = new Auth;
$result = $auth->getInstance();
if($result->hasIdentity() == true)
{
if(!empty($param))
{
$user = $result->getIdentity();
return $user->$param;
}else{
$user = $result->getIdentity();
return $user;
}
}else{
return false;
}
}
static function Dump($data,$exit = true){
echo "<pre>";
var_dump($data);
echo "</pre>";
if($exit)
{
exit();
}
}
static function Post($ctl,$message,$url=""){
$ctl->ViewModel->setTemplate("layout/layout/message");
$ctl->ViewModel->setVariable('message',$message);
$ctl->ViewModel->setVariable('url',$url);
return $ctl->ViewModel;
}
static function HttpError($viewModel = NULL,$code = 404){
if(empty($viewModel))
{
$viewModel = new ViewModel();
}
$response = new \Zend\Http\PhpEnvironment\Response;
$response->setStatusCode(404);
$response->send();
$viewModel->setVariable('message','This page has been eaten by dinosaurs');
return $viewModel;
}
static function getHostLink()
{
$protocol = "http";
if(strpos(strtolower($_SERVER['SERVER_PROTOCOL']),"https"))
{
$protocol = "https";
}
return $protocol."://".$_SERVER['SERVER_NAME'];
}
static function isXmlHttpRequest($viewModel = NULL,$request = NULL){
if(empty($request))
{
$request = new \Zend\Http\Request();
}
if($request->isXmlHttpRequest())
{
if(!empty($viewModel))
{
$viewModel->setTerminal(true);
return $viewModel;
}
return true;
}else{
return false;
}
}
static function checkOs()
{
$uname = strtolower(php_uname());
if (strpos($uname, "darwin") !== false) {
return 'osx';
} else if (strpos($uname, "win") !== false) {
return 'windows';
} else if (strpos($uname, "linux") !== false) {
return 'linux';
} else {
return 'other';
}
}
static function get_class_name($object = null)
{
if (!is_object($object) && !is_string($object)) {
return false;
}
$class = explode('\\', (is_string($object) ? $object : get_class($object)));
return $class[count($class) - 1];
}
static function thumbnailDecode($thumbjson,$multi = true,$size = 400,$cut = false,$sizeforce = false)
{
$thumb = json_decode($thumbjson,true);
unset($thumbjson);
if(count($thumb) < 1)
{
return NULL;
}
if($multi)
{
$url = array();
foreach($thumb as $k=>$v)
{
if($size == -1)
{
$url['source'] = $v['fileurl'];
if(count($v['thumb']))
{
foreach($v['thumb'] as $k=>$v)
{
if(file_exists("./public/uploads/".$v['url']))
{
$url[$k] = $v['url'];
}
}
}
}else{
$url['source'] = $v['fileurl'];
if(count($v['thumb']))
{
foreach($v['thumb'] as $k=>$v)
{
if(is_numeric($k) && $size < $k && file_exists("./public/uploads/".$v['url']))
{
$url[$k] = $v['url'];
}
}
}
}
}
return $url;
}
if(count($thumb)<1)
{
return NULL;
}
$thumb = $thumb[0];
foreach($thumb['thumb'] as $k=>$v)
{
if($cut)
{
if(isset($thumb['thumb']['cut']))
{
if($sizeforce)
{
return file_exists("./public/uploads/".$thumb['thumb']['cut'][$size]['url']) ? $thumb['thumb']['cut'][$size]['url']:$thumb['fileurl'];
}else{
if($size > (int)$k)
{
return file_exists("./public/uploads/".$v['url']) ? $v['url']:$thumb['fileurl'];
}
}
}else{
return $thumb['fileurl'];
}
}else{
if(is_numeric($k))
{
if($size > $k)
{
return file_exists("./public/uploads/".$v['url']) ? $v['url']:$thumb['fileurl'];
}
}
}
}
return $thumb['fileurl'];
}
static function sksort($array,$key = NULL,$type=SORT_DESC) {
$sortArray = array();
foreach($array as $v){
foreach($v as $key=>$value){
if(!isset($sortArray[$key])){
$sortArray[$key] = array();
}
$sortArray[$key][] = $value;
}
}
if(array_multisort($sortArray[$key],$type,$array))
{
return $array;
}else{
return $array;
}
}
static function QRcode($data)
{
include_once('./vendor/Qrcode/qrlib.php');
\QRcode::png($data);
}
}

33
Westdc/Helpers/Auth.php Normal file
View File

@ -0,0 +1,33 @@
<?php
namespace Westdc\Helpers;
use \Zend\Authentication\AuthenticationService;
use \Zend\Authentication\Storage\Session as SessionStorage;
use \Westdc\Helpers\Config;
class Auth
{
public $auth;
function __construct($getAuthService = false)
{
$config = Config::get();
$this->auth = new AuthenticationService();
$this->auth->setStorage(new SessionStorage($config->session_namespace));
}
public function getInstance()
{
return $this->auth;
}
public function clearIndentity()
{
return $this->auth->clearIdentity();
}
public function getIdentity($field)
{
return $this->auth->getIdentity()->$field;
}
}

30
Westdc/Helpers/Config.php Normal file
View File

@ -0,0 +1,30 @@
<?php
namespace Westdc\Helpers;
class Config
{
private $config_path = array(
'local' => "config/autoload/local.php",
'global' => "config/autoload/global.php"
);
function __construct()
{
//$reader = new \Zend\Config\Reader\Ini();
//$data = $reader->fromFile('config/config.ini');
}
static function get($type = 'global')
{
$config_path = array(
'local' => "config/autoload/local.php",
'global' => "config/autoload/global.php",
'file' => "config/autoload/file.php"
);
$config = new \Zend\Config\Config(include $config_path[$type]);
return $config;
}
}

120
Westdc/Helpers/Layout.php Normal file
View File

@ -0,0 +1,120 @@
<?php
namespace Westdc\Helpers;
use \Zend\Authentication\AuthenticationService;
use \Zend\Authentication\Storage\Session as SessionStorage;
use \Westdc\Helpers\Config;
use Westdc\Helpers\MobileDetect;
use View as view;
class Layout
{
public $config;
function __construct()
{
$this->config = Config::get();
}
//设置网页标题
public function setLayoutTitle($e)
{
$matches = $e->getRouteMatch();
if(empty($matches))
{
return;
}
$action = $matches->getParam('action');
$controller = $matches->getParam('controller');
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
$headTitleHelper = $viewHelperManager->get('headTitle');
// Setting a separator string for segments
$headTitleHelper->setSeparator(' - ');
if(isset($this->config->title_map->$controller->action->$action))
{
$headTitleHelper->append($this->config->title_map->$controller->action->$action->title);
}
if(isset($this->config->title_map->$controller))
{
$headTitleHelper->append($this->config->title_map->$controller->title);
}
}
//导航条按钮激活
public function setPageNav($e)
{
$matches = $e->getRouteMatch();
$action = $matches->getParam('action');
$controller = $matches->getParam('controller');
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
$inlineScriptHelper = $viewHelperManager->get('inlineScript');
$inlineScriptHelper ->captureStart();
echo "$('#page-nav-".$this->getControllerNavName($controller)."-".$action."').addClass('active');";
$inlineScriptHelper ->captureEnd();
}
public function getControllerNavName($invokename)
{
$ctl = array(
'Application\Controller\Index' => 'index',
'Application\Controller\Account' => 'account'
);
return isset($ctl[$invokename]) ? $ctl[$invokename]:"";
}
//添加用户Ajax脚本
public function setMemberScript($e)
{
$viewHelperManager = $e->getApplication()->getServiceManager()->get('viewHelperManager');
$inlineScriptHelper = $viewHelperManager->get('inlineScript');
$inlineScriptHelper->prependFile('/js/member.js');
}
//移动设备识别
public function mobileDetect($e)
{
if(!isset($_COOKIE['deviceType']) || empty($_COOKIE['deviceType']))
{
$detect = new MobileDetect;
$deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
setcookie("deviceType", $deviceType, time()+86400,"/");
if(!isset($_SESSION['deviceType']) || empty($_SESSION['deviceType']))
{
$_SESSION['deviceType'] = $deviceType;
}
}else{
if(!isset($_SESSION['deviceType']) || empty($_SESSION['deviceType']))
{
$_SESSION['deviceType'] = $_COOKIE['deviceType'];
}
}
}
//重置session支持flash上传
public function resetSession($e)
{
$session_name = session_name();
//echo session_id();
if (isset($_POST[$session_name])) {
if(view::checkOs() !== 'windows')
{
session_destroy();
session_id($_POST[$session_name]);
session_start();
}else{
session_id($_POST[$session_name]);
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,9 @@
<?php
namespace Westdc\Helpers;
trait Settings
{
public $debug=false;
public $lang='zh';
public $md='normalmetadadta';
}

387
Westdc/Member/Account.php Normal file
View File

@ -0,0 +1,387 @@
<?php
namespace Westdc\Member;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
use Westdc\Helpers\View as view;
use Westdc\Helpers\Config;
use Westdc\Helpers\Dbh as dbh;
use Westdc\Helpers\PDO as Db;
use Westdc\Helpers\Db as Zend_Db;
use Westdc\Mail\Mail;
use Westdc\User\Listener\AccountListener as Listener;
use Westdc\User\Listener\PwdListener;
use Westdc\User\Member;
class Account implements EventManagerAwareInterface
{
public $memberTable = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $GravatarEmailField = "gravatar_email";
public $RoleMember = "member";
private $db;
protected $events = NULL; //事件
private $config;
function __construct()
{
$this->db = new Db();
$this->config = Config::get();
$Listener = new Listener();
$this->getEventManager()->attachAggregate($Listener);
}
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_called_class(),
));
$this->events = $events;
return $this;
}
public function getEventManager()
{
if (NULL === $this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
//获取账号信息,数组
public function getAccountInfo($id = 0)
{
if($id == 0)
{
$id = view::User('id');
}
$sql = "SELECT * FROM {$this->memberTable} WHERE id=$id";
$rs = $this->db->query($sql);
return $rs->fetch();
}
//注册
public function register($data)
{
$params = compact('data');
$results = $this->getEventManager()->trigger('register.checkParam', $this, $params);
$cache_data = $results->last();
if($cache_data !== true)
{
if(!is_array($cache_data))
{
return array('error'=>$cache_data);
}else{
return $cache_data;
}
}
$results = $this->getEventManager()->trigger('register.checkUser', $this, $params);
$cache_data = $results->last();
if($cache_data !== true)
{
if(!is_array($cache_data))
{
return array('error'=>$cache_data);
}else{
return $cache_data;
}
}
$loginData = array(
'username'=>$data['username'],
'password'=>$data['password']
);
$data['password'] = md5($data['password']);
$data['usertype'] = "guest";
unset($data['confirm_password']);
$dbh = new dbh();
$id = $dbh->insert($this->memberTable,$data,true);
if(!empty($id) && is_numeric($id))
{
$this->storeLogin($loginData);
if(isset($state['success']))
{
//$mb = new Member();
//$mb->putcookie($data[$this->FieldUsername],$data[$this->FieldPasword]);
}
$params = compact('data','id');
$results = $this->getEventManager()->trigger('register.success', $this, $params);
return array("success" => 1);
}else{
if($id === false)
{
return array('error'=>'服务器开小差了,请稍后再试');
}else{
return array('error'=>'服务器处理中遇到错误,请联系管理员');
}
}
}//register
//登陆
public function login($data)
{
$results = $this->getEventManager()->trigger('login.checkParam', $this, compact('data'));
$cache_data = $results->last();
if($cache_data !== true)
{
if(!is_array($cache_data))
{
return array('error'=>$cache_data);
}else{
return $cache_data;
}
}
$state = $this->storeLogin($data);
if(isset($state['success']))
{
//$mb = new Member();
//$mb->putcookie($data[$this->FieldUsername],md5($data[$this->FieldPasword]));
}
return $state;
}//login
//storeLogin
private function storeLogin($data,$md5 = true)
{
$auth = new AuthenticationService();
$auth->setStorage(new SessionStorage($this->config->session_namespace));
new Zend_Db($dbAdapter);
$authAdapter = new \Zend\Authentication\Adapter\DbTable(
$dbAdapter,
$this->memberTable,
$this->FieldUsername,
$this->FieldPasword
);
if($md5 === true)
{
$password = md5($data[$this->FieldPasword]);
}else{
$password = $data[$this->FieldPasword];
}
$authAdapter
->setIdentity($data[$this->FieldUsername])
->setCredential($password)
;
$result = $authAdapter->authenticate();
$user = $authAdapter->getResultRowObject(null,array($this->FieldPasword));
if(!$result->isValid())
{
return array("error"=>"用户信息验证失败");
}
$email = $user->email;
$results = $this->getEventManager()->trigger('login.success.createAvatar', $this, compact('email'));
$user->avatar = $results->last();
$auth->getStorage()->write($user);
$id = $user->id;
$results = $this->getEventManager()->trigger('login.success.updateStatus', $this, compact('id'));
return array('success'=>1);
}
public function cookieLogin($data)
{
return $this->storeLogin($data,false);
}
//注册信息参数
public function getParam(\Zend_Controller_Request_Abstract $request)
{
$data = array(
'username'=>$request->getParam('username'),
'password'=>$request->getParam('password'),
'confirm_password'=>$request->getParam('confirm_password'),
'email'=>$request->getParam('email'),
'realname'=>$request->getParam('realname')
);
return $data;
}
//获取用户账户修改参数
public function getEditParam($request)
{
$request = new \Zend\Http\PhpEnvironment\Request;
$type = $request->getPost('type');
if($type == "general")
{
$data = array(
'realname'=>$request->getPost('realname'),
'signature'=>$request->getPost('signature'),
'description'=>$request->getPost('description')
);
}
if($type == "password")
{
$data = array(
'password' => $request->getPost('password'),
'password_new'=>$request->getPost('password_new'),
'password_confirm'=>$request->getPost('password_confirm')
);
}
return $data;
}
//编辑
public function edit($data,$type)
{
$results = $this->getEventManager()->trigger('edit.checkParam', $this, compact('data','type'));
$cache_data = $results->last();
if($cache_data !== true)
{
return $cache_data;
}
if($type == "general")
{
$data['signature'] = htmlspecialchars($data['signature']);
$data['description'] = htmlspecialchars($data['description']);
}else if($type == "password")
{
$data['password'] = md5($data['password_new']);
unset($data['password_new']);
unset($data['password_confirm']);
}else{
return "参数错误";
}
$dbh = new dbh();
$uid = view::User('id');
if($dbh->update($this->memberTable,$data," id=$uid") === true)
{
return true;
}else{
return false;
}
}
//找回密码
public function getMyPassword($email)
{
$pwdListener = new PwdListener;
$this->getEventManager()->attachAggregate($pwdListener);
$results = $this->getEventManager()->trigger('pwd.forgot.checkParam', $this, compact('email'));
$cache_data = $results->last();
if($cache_data !== true)
{
return $cache_data;
}
$sql = "SELECT * FROM {$this->memberTable} WHERE email='$email'";
$rs = $this->db->query($sql);
$row = $rs->fetch();
if(!isset($row['username']) || empty($row['username']))
{
return array('error'=>"此邮箱并未注册",'place'=>'email');
}
$salt = md5($email.'---'.$row['username']);
$sql = "UPDATE {$this->memberTable} SET salt='$salt' WHERE id={$row['id']}";
$state = $this->db->exec($sql);
if($state<1)
{
return array('error'=>"处理中出现错误,请重试",'place'=>'email');
}
$mail_template = "forgotpassword";
$mail_data = array(
'name'=>$row['realname'],
'link'=> view::getHostLink().'/account/getpassword/?salt='.$salt
);
try{
$mail = new Mail();
$mail->loadTemplate($mail_template,$mail_data);
$mail->addTo($email,$row['realname']);
$mail->send();
}catch(Exception $e)
{
echo "".$e->getMessage();
}
return array("success"=>1);
}
//重置密码
public function resetPassword($data)
{
$results = $this->getEventManager()->trigger('pwd.reset.checkParam', $this, compact('data'));
$cache_data = $results->last();
if($cache_data !== true)
{
return $cache_data;
}
$sql = "SELECT * FROM {$this->memberTable} WHERE salt=?";
$sth = $this->db->prepare($sql);
$sth->execute(array($data['salt']));
$row = $sth->fetch();
if(!isset($row['username']) || empty($row['username']))
{
return array('error'=>"您提供的校验码不正确,请重新申请重置密码",'place'=>'confirm_password');
}
if($row['username'] !== $data['username'])
{
return array('error'=>"您提供的校验码不正确,请重新申请重置密码",'place'=>'confirm_password');
}
$sql = "UPDATE {$this->memberTable} SET password='".md5($data['password'])."',salt='' WHERE id={$row['id']}";
$this->db->exec($sql);
$mail_template = "getpassworded";
$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;
}
}

135
Westdc/Member/Cookie.php Normal file
View File

@ -0,0 +1,135 @@
<?php
namespace Westdc\Member;
use Westdc\Helpers\Config;
use Westdc\Db\PDO as Db;
class Cookie
{
var $ck='Dxe8SqIcmyUf';
var $db; //传入PDO对象
var $mid; //会员ID
public $scr; //cookie 安全码 $_COOKIE['scr']
public $user;//cookie User $_COOKIE['user']
public $srpwd;//执行checkcookie后方可调用
public $memberTable = "users";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $GravatarEmailField = "gravatar_email";
public $RoleMember = "member";
function __construct()
{
$this->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();
}
}

View File

@ -0,0 +1,17 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 14-9-25
* Time: 下午2:41
*/
namespace Westdc\Metadata;
class Metadata {
}

View File

@ -0,0 +1,15 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2014/11/4
* Time: 12:15
*/
namespace Westdc\Service\ServiceAgent;
use Westdc\Helpers\Auth as AuthHelper;
class Auth extends AuthHelper{
}

View File

@ -0,0 +1,20 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2014/11/4
* Time: 11:23
*/
namespace Westdc\Service\ServiceAgent;
use Westdc\Member\Account;
class User extends Account implements WestdcConfigureInterface{
private function init()
{
}
}

View File

@ -0,0 +1,48 @@
<?php
/**
* Created by PhpStorm.
* User: Administrator
* Date: 2014/11/4
* Time: 10:39
*/
namespace Westdc\Service;
use Zend\ServiceManager\ServiceLocatorInterface;
use Zend\ServiceManager\AbstractFactoryInterface;
class ServiceFactory implements AbstractFactoryInterface{
public function canCreateServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$serviceAgentDir = __DIR__ . "/ServiceAgent";
if(is_dir($serviceAgentDir))
{
if(false != ($handle = opendir($serviceAgentDir)))
{
while(false !== ($file = readdir($handle)))
{
if(substr($file,0,strlen($file)-4) == (string)$requestedName) {
return true;
}
}
}
}
return false;
}
public function createServiceWithName(ServiceLocatorInterface $serviceLocator, $name, $requestedName)
{
$serviceName = __NAMESPACE__ . "\\ServiceAgent\\" . $requestedName;
$service = new $serviceName;
$service->name = $requestedName;
return $service;
}
}

387
Westdc/User/Account.php Normal file
View File

@ -0,0 +1,387 @@
<?php
namespace Westdc\User;
use Zend\EventManager\EventManagerInterface;
use Zend\EventManager\EventManager;
use Zend\EventManager\EventManagerAwareInterface;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Storage\Session as SessionStorage;
use Westdc\Helpers\View as view;
use Westdc\Helpers\Config;
use Westdc\Helpers\Dbh as dbh;
use Westdc\Helpers\PDO as Db;
use Westdc\Helpers\Db as Zend_Db;
use Westdc\Mail\Mail;
use Westdc\User\Listener\AccountListener as Listener;
use Westdc\User\Listener\PwdListener;
use Westdc\User\Member;
class Account implements EventManagerAwareInterface
{
public $memberTable = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $GravatarEmailField = "gravatar_email";
public $RoleMember = "member";
private $db;
protected $events = NULL; //事件
private $config;
function __construct()
{
$this->db = new Db();
$this->config = Config::get();
$Listener = new Listener();
$this->getEventManager()->attachAggregate($Listener);
}
public function setEventManager(EventManagerInterface $events)
{
$events->setIdentifiers(array(
__CLASS__,
get_called_class(),
));
$this->events = $events;
return $this;
}
public function getEventManager()
{
if (NULL === $this->events) {
$this->setEventManager(new EventManager());
}
return $this->events;
}
//获取账号信息,数组
public function getAccountInfo($id = 0)
{
if($id == 0)
{
$id = view::User('id');
}
$sql = "SELECT * FROM {$this->memberTable} WHERE id=$id";
$rs = $this->db->query($sql);
return $rs->fetch();
}
//注册
public function register($data)
{
$params = compact('data');
$results = $this->getEventManager()->trigger('register.checkParam', $this, $params);
$cache_data = $results->last();
if($cache_data !== true)
{
if(!is_array($cache_data))
{
return array('error'=>$cache_data);
}else{
return $cache_data;
}
}
$results = $this->getEventManager()->trigger('register.checkUser', $this, $params);
$cache_data = $results->last();
if($cache_data !== true)
{
if(!is_array($cache_data))
{
return array('error'=>$cache_data);
}else{
return $cache_data;
}
}
$loginData = array(
'username'=>$data['username'],
'password'=>$data['password']
);
$data['password'] = md5($data['password']);
$data['usertype'] = "guest";
unset($data['confirm_password']);
$dbh = new dbh();
$id = $dbh->insert($this->memberTable,$data,true);
if(!empty($id) && is_numeric($id))
{
$this->storeLogin($loginData);
if(isset($state['success']))
{
//$mb = new Member();
//$mb->putcookie($data[$this->FieldUsername],$data[$this->FieldPasword]);
}
$params = compact('data','id');
$results = $this->getEventManager()->trigger('register.success', $this, $params);
return array("success" => 1);
}else{
if($id === false)
{
return array('error'=>'服务器开小差了,请稍后再试');
}else{
return array('error'=>'服务器处理中遇到错误,请联系管理员');
}
}
}//register
//登陆
public function login($data)
{
$results = $this->getEventManager()->trigger('login.checkParam', $this, compact('data'));
$cache_data = $results->last();
if($cache_data !== true)
{
if(!is_array($cache_data))
{
return array('error'=>$cache_data);
}else{
return $cache_data;
}
}
$state = $this->storeLogin($data);
if(isset($state['success']))
{
//$mb = new Member();
//$mb->putcookie($data[$this->FieldUsername],md5($data[$this->FieldPasword]));
}
return $state;
}//login
//storeLogin
private function storeLogin($data,$md5 = true)
{
$auth = new AuthenticationService();
$auth->setStorage(new SessionStorage($this->config->session_namespace));
new Zend_Db($dbAdapter);
$authAdapter = new \Zend\Authentication\Adapter\DbTable(
$dbAdapter,
$this->memberTable,
$this->FieldUsername,
$this->FieldPasword
);
if($md5 === true)
{
$password = md5($data[$this->FieldPasword]);
}else{
$password = $data[$this->FieldPasword];
}
$authAdapter
->setIdentity($data[$this->FieldUsername])
->setCredential($password)
;
$result = $authAdapter->authenticate();
$user = $authAdapter->getResultRowObject(null,array($this->FieldPasword));
if(!$result->isValid())
{
return array("error"=>"用户信息验证失败");
}
$email = $user->email;
$results = $this->getEventManager()->trigger('login.success.createAvatar', $this, compact('email'));
$user->avatar = $results->last();
$auth->getStorage()->write($user);
$id = $user->id;
$results = $this->getEventManager()->trigger('login.success.updateStatus', $this, compact('id'));
return array('success'=>1);
}
public function cookieLogin($data)
{
return $this->storeLogin($data,false);
}
//注册信息参数
public function getParam(\Zend_Controller_Request_Abstract $request)
{
$data = array(
'username'=>$request->getParam('username'),
'password'=>$request->getParam('password'),
'confirm_password'=>$request->getParam('confirm_password'),
'email'=>$request->getParam('email'),
'realname'=>$request->getParam('realname')
);
return $data;
}
//获取用户账户修改参数
public function getEditParam($request)
{
$request = new \Zend\Http\PhpEnvironment\Request;
$type = $request->getPost('type');
if($type == "general")
{
$data = array(
'realname'=>$request->getPost('realname'),
'signature'=>$request->getPost('signature'),
'description'=>$request->getPost('description')
);
}
if($type == "password")
{
$data = array(
'password' => $request->getPost('password'),
'password_new'=>$request->getPost('password_new'),
'password_confirm'=>$request->getPost('password_confirm')
);
}
return $data;
}
//编辑
public function edit($data,$type)
{
$results = $this->getEventManager()->trigger('edit.checkParam', $this, compact('data','type'));
$cache_data = $results->last();
if($cache_data !== true)
{
return $cache_data;
}
if($type == "general")
{
$data['signature'] = htmlspecialchars($data['signature']);
$data['description'] = htmlspecialchars($data['description']);
}else if($type == "password")
{
$data['password'] = md5($data['password_new']);
unset($data['password_new']);
unset($data['password_confirm']);
}else{
return "参数错误";
}
$dbh = new dbh();
$uid = view::User('id');
if($dbh->update($this->memberTable,$data," id=$uid") === true)
{
return true;
}else{
return false;
}
}
//找回密码
public function getMyPassword($email)
{
$pwdListener = new PwdListener;
$this->getEventManager()->attachAggregate($pwdListener);
$results = $this->getEventManager()->trigger('pwd.forgot.checkParam', $this, compact('email'));
$cache_data = $results->last();
if($cache_data !== true)
{
return $cache_data;
}
$sql = "SELECT * FROM {$this->memberTable} WHERE email='$email'";
$rs = $this->db->query($sql);
$row = $rs->fetch();
if(!isset($row['username']) || empty($row['username']))
{
return array('error'=>"此邮箱并未注册",'place'=>'email');
}
$salt = md5($email.'---'.$row['username']);
$sql = "UPDATE {$this->memberTable} SET salt='$salt' WHERE id={$row['id']}";
$state = $this->db->exec($sql);
if($state<1)
{
return array('error'=>"处理中出现错误,请重试",'place'=>'email');
}
$mail_template = "forgotpassword";
$mail_data = array(
'name'=>$row['realname'],
'link'=> view::getHostLink().'/account/getpassword/?salt='.$salt
);
try{
$mail = new Mail();
$mail->loadTemplate($mail_template,$mail_data);
$mail->addTo($email,$row['realname']);
$mail->send();
}catch(Exception $e)
{
echo "".$e->getMessage();
}
return array("success"=>1);
}
//重置密码
public function resetPassword($data)
{
$results = $this->getEventManager()->trigger('pwd.reset.checkParam', $this, compact('data'));
$cache_data = $results->last();
if($cache_data !== true)
{
return $cache_data;
}
$sql = "SELECT * FROM {$this->memberTable} WHERE salt=?";
$sth = $this->db->prepare($sql);
$sth->execute(array($data['salt']));
$row = $sth->fetch();
if(!isset($row['username']) || empty($row['username']))
{
return array('error'=>"您提供的校验码不正确,请重新申请重置密码",'place'=>'confirm_password');
}
if($row['username'] !== $data['username'])
{
return array('error'=>"您提供的校验码不正确,请重新申请重置密码",'place'=>'confirm_password');
}
$sql = "UPDATE {$this->memberTable} SET password='".md5($data['password'])."',salt='' WHERE id={$row['id']}";
$this->db->exec($sql);
$mail_template = "getpassworded";
$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;
}
}

135
Westdc/User/Cookie.php Normal file
View File

@ -0,0 +1,135 @@
<?php
namespace Westdc\User;
use Westdc\Helpers\Config;
use Westdc\Db\PDO as Db;
class Cookie
{
var $ck='Dxe8SqIcmyUf';
var $db; //传入PDO对象
var $mid; //会员ID
public $scr; //cookie 安全码 $_COOKIE['scr']
public $user;//cookie User $_COOKIE['user']
public $srpwd;//执行checkcookie后方可调用
public $memberTable = "users";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $GravatarEmailField = "gravatar_email";
public $RoleMember = "member";
function __construct()
{
$this->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();
}
}

View File

@ -0,0 +1,13 @@
<?php
namespace Sookon\User\Event;
use Zend\EventManager\EventInterface;
interface EditEvent
{
public function checkParam(EventInterface $e);
public function editSuccess(EventInterface $e);
}

View File

@ -0,0 +1,14 @@
<?php
namespace Sookon\User\Event;
use Zend\EventManager\EventInterface;
interface LoginEvent
{
public function checkParam(EventInterface $e);
public function updateStatus(EventInterface $e);
public function createAvatar(EventInterface $e);
}

View File

@ -0,0 +1,15 @@
<?php
namespace Sookon\User\Event;
use Zend\EventManager\EventInterface;
interface PwdEvent
{
public function forgotPwdCheckParam(EventInterface $e);
public function sendGetPasswordMail(EventInterface $e);
public function resetPwdCheckParam(EventInterface $e);
}

View File

@ -0,0 +1,15 @@
<?php
namespace Sookon\User\Event;
use Zend\EventManager\EventInterface;
interface RegisterEvent
{
public function checkParam(EventInterface $e);
public function checkUser(EventInterface $e);
public function registerSuccess(EventInterface $e);
}

20
Westdc/User/Gravatar.php Normal file
View File

@ -0,0 +1,20 @@
<?php
namespace Sookon\User;
class Gravatar{
function Get( $email, $size='' ) {
$default = "http://www.msgfm.com/static/img/gCons/agent.png";
if(empty($size))
{
$size = 40;
}
$url = "http://www.gravatar.com/avatar/" . md5( strtolower( trim( $email ) ) ) . "?d=" . urlencode( $default ) . "&s=" . $size;
return $url;
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace Sookon\User\Handle;
use Sookon\Mail\Mail;
use Sookon\Helpers\View as view;
use Sookon\Helpers\Pdo;
use Sookon\Helpers\Config;
use Zend\EventManager\EventInterface;
class EditHandle implements \Sookon\User\Event\EditEvent
{
private $db; //传入PDO对象
public $tbl_member = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $FieldGravatarEmail = "gravatar_email";
private $DefaultFetchMode = \PDO::FETCH_BOTH; //默认检索模式防止出现sdtClass错误
private $config; //全局配置
function __construct($db = NULL)
{
$this->db = new Pdo;
$this->config = Config::get();
}
public function checkParam(EventInterface $e){
$data = $e->getParam('data');
$type = $e->getParam('type');
if($type == 'general')
{
if(empty($data['realname']))
{
return "起个响亮的名号吧";
}
if(mb_strlen($data['realname'],"UTF-8")>10 )
{
return "这名号也太长了吧不要超过10个字哦";
}
}
if($type == "password")
{
if(strlen($data['password'])>18 || strlen($data['password_new'])>18)
{
return "密码过长";
}
if(strlen($data['password_new'])<=6 || strlen($data['password_confirm'])<=6)
{
return "密码过短";
}
if(md5($data['password_new']) != md5($data['password_confirm']))
{
return "两次输入的密码不同";
}
$uid = view::User('id');
$sql = "SELECT {$this->FieldPasword} FROM {$this->tbl_member} WHERE id=$uid";
$rs = $this->db->query($sql);
$row = $rs->fetch();
if(md5($data['password']) != $row[$this->FieldPasword])
{
return "原密码不正确";
}
}
return true;
}//checkParam
public function editSuccess(EventInterface $e){
$data = $e->getParam('data');
return true;
}
}

View File

@ -0,0 +1,111 @@
<?php
namespace Sookon\User\Handle;
use Sookon\Helpers\Dbh as dbh;
use Sookon\Helpers\PDO as Db;
use Sookon\User\Gravatar;
use Sookon\Helpers\View as view;
use Zend\EventManager\EventInterface;
class LoginHandle implements \Sookon\User\Event\LoginEvent
{
private $db; //传入PDO对象
public $tbl_member = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $FieldGravatarEmail = "gravatar_email";
private $DefaultFetchMode = \PDO::FETCH_BOTH; //默认检索模式防止出现sdtClass错误
private $config; //全局配置
function __construct()
{
$this->db = new Db();
}
public function checkParam(EventInterface $e){
$data = $e->getParam('data');
if(!is_array($data))
{
return "参数错误";
}
if(empty($data['username']))
{
return array('error'=>"请输入用户名",'place'=>'username');
}
if(!empty($data['username']))
{
if(!preg_match("/^[a-zA-Z][a-zA-Z0-9_]{4,15}$/",$data['username']))
{
return array('error'=>"用户名应当以字母开头由字母数字和下划线组成并且长度在5到25个字符之间",'place'=>'username');
}
}
if(empty($data['password']))
{
return array('error'=>"请输入密码",'place'=>'password');
}
$sql = "SELECT id,{$this->FieldPasword},status FROM {$this->tbl_member} WHERE {$this->FieldUsername}=?";
$sth = $this->db->prepare($sql);
$rs = $sth->execute(array($data[$this->FieldUsername]));
$row = $sth->fetch();
if(isset($row['id']) && !empty($row['id']))
{
if(strlen($row[$this->FieldPasword]) !== 32)
{
return array('error'=>"您的密码或因安全原因或其他问题已经被重置,请先<a href='/account/forgotpassword'>重置密码</a>再登陆",'place'=>'password');
}
if($row[$this->FieldPasword] !== md5($data['password']))
{
return array('error'=>"密码错误",'place'=>'password');
}
if($row['status'] < 1 )
{
return array('error'=>'您的账号密码状态错误,无法登录');
}
return true;
}else{
return array('error'=>"用户不存在",'place'=>'username');
}
}//checkParam
public function updateStatus(EventInterface $e){
$id = (int)$e->getParam('id');
if(!is_numeric($id))
{
return false;
}
$update = array(
$this->FieldLastlogin => date("Y-m-d H:i:s"),
$this->FieldLastloginIp => $_SERVER["REMOTE_ADDR"]
);
$dbh = new dbh();
@$statusUpdate = $dbh->update($this->tbl_member,$update," id=$id ");
return true;
}//loginSuccess
public function createAvatar(EventInterface $e){
$email = $e->getParam('email');
$avatar = new Gravatar();
return $avatar->Get($email);
}//loginSuccess
}

View File

@ -0,0 +1,90 @@
<?php
namespace Sookon\User\Handle;
use Sookon\Mail\Mail;
use Sookon\Helpers\View as view;
use Sookon\Helpers\Pdo;
use Sookon\Helpers\Config;
class PwdHandle implements \Sookon\User\Event\PwdEvent
{
private $db; //传入PDO对象
public $tbl_member = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $FieldGravatarEmail = "gravatar_email";
private $DefaultFetchMode = \PDO::FETCH_BOTH; //默认检索模式防止出现sdtClass错误
private $config; //全局配置
function __construct($db = NULL)
{
$this->db = new Pdo;
$this->config = Config::get();
}
public function forgotPwdCheckParam(\Zend\EventManager\EventInterface $e){
$email = $e->getParam('email');
if(empty($email))
{
return array('error'=>"请输入电子邮箱,作为找回密码和接受通知的联系方式",'place'=>'email');
}
if (!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',$email))
{
return array('error'=>"请输入正确的电子邮件",'place'=>'email');
}
return true;
}//checkParam
public function sendGetPasswordMail(\Zend\EventManager\EventInterface $e){
$email = $e->getParam('email');
return true;
}
public function resetPwdCheckParam(\Zend\EventManager\EventInterface $e)
{
$data = $e->getParam('data');
if(empty($data['username']))
{
return array('error'=>"请输入用户名",'place'=>'username');
}
if(empty($data['password']))
{
return array('error'=>"请输入密码",'place'=>'password');
}
if(strlen($data['password']) < 6)
{
return array('error'=>"密码长度太短为了安全最少输入6位哦",'place'=>'password');
}
if(strlen($data['password']) > 14)
{
return array('error'=>"密码太长亲您记得住吗不要超过14位哦",'place'=>'password');
}
if(empty($data['confirm_password']))
{
return array('error'=>"请再次输入密码已确认输入正确",'place'=>'confirm_password');
}
if(md5($data['password']) != md5($data['confirm_password']))
{
return array('error'=>"两次输入的密码不同,请重新输入",'place'=>'confirm_password');
}
return true;
}
}

View File

@ -0,0 +1,190 @@
<?php
namespace Sookon\User\Handle;
use Sookon\Mail\Mail;
use Sookon\Helpers\Config;
use Sookon\Helpers\View as view;
use Sookon\Helpers\PDO as Db;
use Sookon\User\Event\RegisterEvent as Event;
use Zend\EventManager\EventInterface;
class RegisterHandle implements Event
{
private $db; //传入PDO对象
public $tbl_member = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $FieldGravatarEmail = "gravatar_email";
private $DefaultFetchMode = \PDO::FETCH_BOTH; //默认检索模式防止出现sdtClass错误
private $config; //全局配置
function __construct($db = NULL)
{
$this->db = new Db();
$this->config = Config::get();
}
public function checkParam(EventInterface $e){
$data = $e->getParam('data');
if(!is_array($data))
{
return "参数错误";
}
if(empty($data['username']))
{
return array('error'=>"请输入用户名",'place'=>'username');
}
if(!empty($data['username']))
{
if(!preg_match("/^[a-zA-Z][a-zA-Z0-9_]{4,15}$/",$data['username']))
{
return array('error'=>"用户名应当以字母开头由字母数字和下划线组成并且长度在5到16个字符之间",'place'=>'username');
}
}
if(empty($data['password']))
{
return array('error'=>"请输入密码",'place'=>'password');
}
if(strlen($data['password']) < 6)
{
return array('error'=>"密码长度太短为了安全最少输入6位哦",'place'=>'password');
}
if(strlen($data['password']) > 14)
{
return array('error'=>"密码太长亲您记得住吗不要超过14位哦",'place'=>'password');
}
if(empty($data['confirm_password']))
{
return array('error'=>"请再次输入密码已确认输入正确",'place'=>'confirm_password');
}
if(md5($data['password']) != md5($data['confirm_password']))
{
return array('error'=>"两次输入的密码不同,请重新输入",'place'=>'confirm_password');
}
if(empty($data['email']))
{
return array('error'=>"请输入电子邮箱,作为找回密码和接受通知的联系方式",'place'=>'email');
}
if (!preg_match('/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',$data['email']))
{
return array('error'=>"请输入正确的电子邮件推荐使用QQ邮箱和Gmail邮箱",'place'=>'email');
}
if(empty($data['realname']))
{
return array('error'=>"起个响亮的名号吧",'place'=>'realname');
}
if(mb_strlen($data['realname'],"UTF-8")>15 )
{
return array('error'=>":-(这名号也太长了吧不要超过15个字哦",'place'=>'realname');
}
return true;
}//checkParam
public function checkUser(EventInterface $e){
$data = $e->getParam('data');
if(!is_array($data))
{
return "用户信息验证失败,请重新尝试";
}
$sql = "SELECT id,{$this->FieldUsername},{$this->FieldEmail} FROM ".$this->tbl_member." WHERE {$this->FieldUsername}='{$data['username']}' OR {$this->FieldEmail}='{$data['email']}'";
$rs = $this->db->query($sql);
$row = $rs->fetch();
if(isset($row['id']) && !empty($row['id']))
{
if($row[$this->FieldUsername] == $data['username'])
{
return array('error'=>'您的用户名已经注册过账号,您是否<a href="/account/forgotpassword">忘记了密码?</a>','place'=>'username');
}
if($row[$this->FieldEmail] == $data['email'])
{
return array('error'=>'您的邮箱已经注册过账号,请换一个邮箱','place'=>'email');
}
return array('error'=>'您的用户名或邮箱已经使用过,注册马甲请换一个用户名');
}
return true;
}//checkUser
public function registerSuccess(EventInterface $e){
$data = $e->getParam('data');
if(!is_array($data))
{
return false;
}
$id = $e->getParam('id');
if(!is_numeric($id))
{
return false;
}
$mail_template = "register";
$mail_data = array(
'name'=>$data['realname'],
'content'=>''
);
$mail = new Mail();
$mail->loadTemplate($mail_template,$mail_data);
$mail->addTo($data['email'],$data['realname']);
$mail->send();
return true;
}//registerSuccess
//邮件内容
public function getMailContent()
{
$sql = "SELECT v.id,v.title,v.thumb,v.status,v.content,m.realname,m.username FROM tbl_voice v
LEFT JOIN tbl_member m ON v.userid = m.id
WHERE v.status > 0
ORDER BY v.id DESC
LIMIT 5";
$rs = $this->db->query($sql);
$latest = $rs->fetchAll();
$content = "";
foreach($latest as $k=>$v)
{
if($v['thumb'] != '[]')
{
$thumb = json_decode($v['thumb'],true);
$text = mb_strlen($v['content'],"UTF-8") > 100 ? mb_substr($v['content'],0,100,"UTF-8") : $v['content'];
$content .= '<p style="width:100%;overflow:hidden;"><img src="http://www.msgfm.com'.$this->config->upload->urlbase.$thumb[0]['thumb'][400]['url'].'" height="100" style="float:left;margin-right:10px;" />'.$v['title']. ' / ' .$v['realname'].'<br />'.$text.'<br /><a href="http://www.msgfm.com/voice/'.$v['id'].'.html">查看播放</a></p>';
}
}
return $content;
}//getMailContent();
}

View File

@ -0,0 +1,49 @@
<?php
namespace Sookon\User\Listener;
use Sookon\User\Handle\RegisterHandle;
use Sookon\User\Handle\LoginHandle;
use Zend\EventManager\EventCollection;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
class AccountListener implements ListenerAggregateInterface
{
private $type;
protected $listeners = array();
function __construct($type = "")
{
if(empty($type))
{
$type = "both";
}
$this->type = $type;
}
public function attach(EventManagerInterface $events)
{
$_Events = new RegisterHandle();
$this->listeners[] = $events->attach('register.checkParam', array($_Events, 'checkParam'), 100);
$this->listeners[] = $events->attach('register.checkUser', array($_Events, 'checkUser'), 80);
$this->listeners[] = $events->attach('register.success', array($_Events, 'registerSuccess'), 50);
$_Events = new LoginHandle();
$this->listeners[] = $events->attach('login.checkParam', array($_Events, 'checkParam'), 100);
$this->listeners[] = $events->attach('login.success.updateStatus', array($_Events, 'updateStatus'), 50);
$this->listeners[] = $events->attach('login.success.createAvatar', array($_Events, 'createAvatar'), 50);
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace Sookon\User\Listener;
use Sookon\User\Handle\EditHandle;
use Zend\EventManager\EventCollection;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
class EditListener implements ListenerAggregateInterface
{
protected $listeners = array();
function __construct($type = "")
{
}
public function attach(EventManagerInterface $events)
{
$_Events = new EditHandle();
$this->listeners[] = $events->attach('edit.checkParam', array($_Events, 'checkParam'), 100);
$this->listeners[] = $events->attach('edit.success', array($_Events, 'editSuccess'), 50);
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace Sookon\User\Listener;
use Sookon\User\Handle\PwdHandle;
use Zend\EventManager\EventCollection;
use Zend\EventManager\ListenerAggregateInterface;
use Zend\EventManager\EventInterface;
use Zend\EventManager\EventManagerInterface;
class PwdListener implements ListenerAggregateInterface
{
protected $listeners = array();
function __construct()
{
}
public function attach(EventManagerInterface $events)
{
$_Events = new PwdHandle();
$this->listeners[] = $events->attach('pwd.forgot.checkParam', array($_Events, 'forgotPwdCheckParam'), 100);
$this->listeners[] = $events->attach('pwd.forgot.sendmail', array($_Events, 'sendGetPasswordMail'), 50);
$this->listeners[] = $events->attach('pwd.reset.checkParam', array($_Events, 'resetPwdCheckParam'), 100);
$this->listeners[] = $events->attach('pwd.reset.sendmail', array($_Events, 'sendGetPasswordMail'), 50);
}
public function detach(EventManagerInterface $events)
{
foreach ($this->listeners as $index => $listener) {
if ($events->detach($listener)) {
unset($this->listeners[$index]);
}
}
}
}

135
Westdc/User/Member.php Normal file
View File

@ -0,0 +1,135 @@
<?php
namespace Sookon\User;
use Sookon\Helpers\Config;
use Sookon\Helpers\PDO as Db;
class Member
{
var $ck='Dxe8SqIcmyUf';
var $db; //传入PDO对象
var $mid; //会员ID
public $scr; //cookie 安全码 $_COOKIE['scr']
public $user;//cookie User $_COOKIE['user']
public $srpwd;//执行checkcookie后方可调用
public $memberTable = "tbl_member";
public $FieldUsername = "username";
public $FieldPasword = "password";
public $FieldLastlogin = "ts_last_login";
public $FieldEmail = "email";
public $FieldLastloginIp = "last_login_ip";
public $GravatarEmailField = "gravatar_email";
public $RoleMember = "member";
function __construct()
{
$this->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();
}
}