Example #1
0
 /**
  * 执行任务
  * @param string $service MQ中的接口服务名称,如:Default.Index
  * @return array('total' => 总数量, 'fail' => 失败数量)
  */
 public function go($service)
 {
     $rs = array('total' => 0, 'fail' => 0);
     $todoList = $this->mq->pop($service, $this->step);
     $failList = array();
     while (!empty($todoList)) {
         $rs['total'] += count($todoList);
         foreach ($todoList as $params) {
             try {
                 $isFinish = $this->youGo($service, $params);
                 if (!$isFinish) {
                     $rs['fail']++;
                 }
             } catch (PhalApi_Exception_InternalServerError $ex) {
                 $rs['fail']++;
                 $failList[] = $params;
                 DI()->logger->error('task occur exception to go', array('service' => $service, 'params' => $params, 'error' => $ex->getMessage()));
             }
         }
         $todoList = $this->mq->pop($service, $this->step);
     }
     foreach ($failList as $params) {
         $this->mq->add($service, $params);
     }
     return $rs;
 }
Example #2
0
 /**
  * 创建服务器
  * 根据客户端提供的接口服务名称和需要调用的方法进行创建工作,如果创建失败,则抛出相应的自定义异常
  *
  * 创建过程主要如下:
  * - 1、 是否缺少控制器名称和需要调用的方法
  * - 2、 控制器文件是否存在,并且控制器是否存在
  * - 3、 方法是否可调用
  * - 4、 控制器是否初始化成功
  *
  * @param boolen $isInitialize 是否在创建后进行初始化
  * @param string $_REQUEST['service'] 接口服务名称,格式:XXX.XXX
  * @return PhalApi_Api 自定义的控制器
  *
  * @uses PhalApi_Api::init()
  * @throws PhalApi_Exception_BadRequest 非法请求下返回400
  */
 static function generateService($isInitialize = TRUE)
 {
     $service = DI()->request->get('service', 'Default.Index');
     $serviceArr = explode('.', $service);
     if (count($serviceArr) < 2) {
         throw new PhalApi_Exception_BadRequest(T('service ({service}) illegal', array('service' => $service)));
     }
     list($apiClassName, $action) = $serviceArr;
     $apiClassName = 'Api_' . ucfirst($apiClassName);
     $action = lcfirst($action);
     if (!class_exists($apiClassName)) {
         throw new PhalApi_Exception_BadRequest(T('no such service as {service}', array('service' => $service)));
     }
     $api = new $apiClassName();
     if (!is_subclass_of($api, 'PhalApi_Api')) {
         throw new PhalApi_Exception_InternalServerError(T('{class} should be subclass of PhalApi_Api', array('class' => $apiClassName)));
     }
     if (!method_exists($api, $action) || !is_callable(array($api, $action))) {
         throw new PhalApi_Exception_BadRequest(T('no such service as {service}', array('service' => $service)));
     }
     if ($isInitialize) {
         $api->init();
     }
     return $api;
 }
Example #3
0
 protected function request($type, $uri, $params, $timeoutMs)
 {
     $url = $this->host . '/' . ltrim($uri, '/');
     $params['client_id'] = $this->clientId;
     $curl = $this->curl;
     $apiRs = null;
     if ($type == 'get') {
         $apiRs = $curl->get($url . '?' . http_build_query($params), $timeoutMs);
     } else {
         $apiRs = $curl->post($url, $params, $timeoutMs);
     }
     if ($apiRs === false) {
         DI()->logger->debug("youku api {$type} timeout", $url . '?' . http_build_query($params));
         return array();
     }
     $apiRsArr = json_decode($apiRs, true);
     if (empty($apiRsArr) || !is_array($apiRsArr)) {
         DI()->logger->debug("youku api {$type} nothing return", $url . '?' . http_build_query($params));
         return array();
     }
     if (isset($apiRsArr['error'])) {
         DI()->logger->debug("youku  api {$type} error", array('error' => $apiRsArr['error'], 'url' => $url . '?' . http_build_query($params)));
     }
     return $apiRsArr;
 }
Example #4
0
 protected function runAllWaittingItems()
 {
     $waittingItems = $this->model->getAllWaittingItems();
     foreach ($waittingItems as $item) {
         //
         if (!$this->model->isRunnable($item['id'])) {
             continue;
         }
         $class = $item['trigger_class'];
         $params = $item['fire_params'];
         if (empty($class) || !class_exists($class)) {
             DI()->logger->error('Error: task can not run illegal class', $item);
             $this->model->updateExceptionItem($item['id'], 'task can not run illegal class');
             continue;
         }
         $trigger = new $class();
         if (!is_callable(array($class, 'fire'))) {
             DI()->logger->error('Error: task can not call fire()', $item);
             $this->model->updateExceptionItem($item['id'], 'task can not call fire()');
             continue;
         }
         $this->model->setRunningState($item['id']);
         try {
             $result = call_user_func(array($trigger, 'fire'), $params);
             $this->model->updateFinishItem($item['id'], $result);
         } catch (Exception $ex) {
             throw $ex;
             $this->model->updateExceptionItem($item['id'], $ex->getMessage());
         }
     }
 }
Example #5
0
 /**
  * 发送邮件
  * @param array/string $addresses 待发送的邮箱地址
  * @param sting $title 标题
  * @param string $content 内容
  * @param boolean $isHtml 是否使用HTML格式,默认是
  * @return boolean 是否成功
  */
 public function send($addresses, $title, $content, $isHtml = TRUE)
 {
     $mail = new PHPMailer();
     $cfg = $this->config;
     $mail->isSMTP();
     $mail->Host = $cfg['host'];
     $mail->SMTPAuth = true;
     $mail->Username = $cfg['username'];
     $mail->Password = $cfg['password'];
     $mail->CharSet = 'utf-8';
     $mail->From = $cfg['username'];
     $mail->FromName = $cfg['fromName'];
     $addresses = is_array($addresses) ? $addresses : array($addresses);
     foreach ($addresses as $address) {
         $mail->addAddress($address);
     }
     $mail->WordWrap = 50;
     $mail->isHTML($isHtml);
     $mail->Subject = trim($title);
     $mail->Body = $content . $cfg['sign'];
     if (!$mail->send()) {
         if ($this->debug) {
             DI()->logger->debug('Fail to send email with error: ' . $mail->ErrorInfo);
         }
         return false;
     }
     if ($this->debug) {
         DI()->logger->debug('Succeed to send email', array('addresses' => $addresses, 'title' => $title));
     }
     return true;
 }
Example #6
0
 /**
  * 为代理指定委托的缓存组件,默认情况下使用DI()->cache
  */
 public function __construct(PhalApi_Cache $cache = NULL)
 {
     $this->cache = $cache !== NULL ? $cache : DI()->cache;
     //退而求其次
     if ($this->cache === NULL) {
         $this->cache = new PhalApi_Cache_None();
     }
 }
 public function testCheckWithRightSign()
 {
     $data = array('service' => 'PhalApi_Api_Impl.Add', 'left' => 1, 'right' => 1, 'sign' => 'd5c2ea888a6390de5210b9496a1b787a');
     DI()->request = new PhalApi_Request($data);
     $api = new PhalApi_Api_Impl();
     $api->init();
     $rs = $api->add();
     $this->assertEquals(2, $rs);
 }
Example #8
0
 /**
  * 续期
  *
  * - 当有效期为当前时间时,即退出
  */
 protected static function _renewalTo($newExpiresTime)
 {
     $userId = DI()->request->get('user_id');
     $token = DI()->request->get('token');
     if (empty($userId) || empty($token)) {
         return;
     }
     $model = new Model_User_UserSession();
     $model->updateExpiresTime($userId, $token, $newExpiresTime);
 }
Example #9
0
 /**
  * 统一分发处理
  * @param string $type 类型
  * @param string $value 值
  * @param array $rule 规则配置
  * @return mixed
  */
 protected static function formatAllType($type, $value, $rule)
 {
     $diKey = '_formatter' . ucfirst($type);
     $diDefautl = 'PhalApi_Request_Formatter_' . ucfirst($type);
     $formatter = DI()->get($diKey, $diDefautl);
     if (!$formatter instanceof Phalapi_Request_Formatter) {
         throw new PhalApi_Exception_InternalServerError(T('invalid type: {type} for rule: {name}', array('type' => $type, 'name' => $rule['name'])));
     }
     return $formatter->parse($value, $rule);
 }
Example #10
0
 public function getByUserIdWithCache($userId)
 {
     $key = 'userbaseinfo_' . $userId;
     $rs = DI()->cache->get($key);
     if ($rs === NULL) {
         $rs = $this->getByUserId($userId);
         DI()->cache->set($key, $rs, 600);
     }
     return $rs;
 }
Example #11
0
 /**
  * @param $config['crypt'] 加密的服务,如果未设置,默认取DI()->crypt,须实现PhalApi_Crypt接口
  * @param $config['key'] $config['crypt']用的密钥,未设置时有一个md5串
  */
 public function __construct($config = array())
 {
     parent::__construct($config);
     $this->config['crypt'] = isset($config['crypt']) ? $config['crypt'] : DI()->crypt;
     if (isset($config['crypt']) && $config['crypt'] instanceof PhalApi_Crypt) {
         $this->config['key'] = isset($config['key']) ? $config['key'] : 'debcf37743b7c835ba367548f07aadc3';
     } else {
         $this->config['crypt'] = NULL;
     }
 }
Example #12
0
 public function response($params = NULL)
 {
     $paramsArr = json_decode($params, TRUE);
     if ($paramsArr !== FALSE) {
         DI()->request = new PhalApi_Request(array_merge($_GET, $paramsArr));
     } else {
         DI()->request = new PhalApi_Request($_GET);
     }
     $rs = $this->phalapi->response();
     return $rs->getResult();
 }
 /**
  * demo
  */
 public function testDecryptAfterEncrypt()
 {
     $keyG = new PhalApi_Crypt_RSA_KeyGenerator();
     $privkey = $keyG->getPriKey();
     $pubkey = $keyG->getPubKey();
     DI()->crypt = new PhalApi_Crypt_RSA_MultiPri2Pub();
     $data = 'AHA! I have $2.22 dollars!';
     $encryptData = DI()->crypt->encrypt($data, $privkey);
     $decryptData = DI()->crypt->decrypt($encryptData, $pubkey);
     $this->assertEquals($data, $decryptData);
 }
Example #14
0
 public function __construct($queryArr = array())
 {
     $this->timestamp = $_SERVER['REQUEST_TIME'];
     if (DI()->debug) {
         $this->readCache = FALSE;
         $this->writeCache = FALSE;
     }
     foreach ($queryArr as $key => $value) {
         $this->{$key} = $value;
     }
 }
Example #15
0
 protected function youGo($service, $params)
 {
     $rs = $this->contector->request($service, $params, $this->timeoutMS);
     if ($this->contector->getRet() == 404) {
         throw PhalApi_Exception_InternalServerError('task request api time out', array('url' => $this->contector->getUrl()));
     }
     $isOk = $this->contector->getRet() == 200 ? TRUE : FALSE;
     if (!$isOk) {
         DI()->logger->debug('task remote request not ok', array('url' => $this->contector->getUrl(), 'ret' => $this->contector->getRet(), 'msg' => $this->contector->getMsg()));
     }
     return $isOk;
 }
Example #16
0
 public function render()
 {
     $service = DI()->request->get('service', 'Default.Index');
     $rules = array();
     $returns = array();
     $description = '';
     $descComment = '//请使用@desc 注释';
     $typeMaps = array('string' => '字符串', 'int' => '整型', 'float' => '浮点型', 'boolean' => '布尔型', 'date' => '日期', 'array' => '数组', 'fixed' => '固定值', 'enum' => '枚举类型', 'object' => '对象');
     try {
         $api = PhalApi_ApiFactory::generateService(false);
         $rules = $api->getApiRules();
     } catch (PhalApi_Exception $ex) {
         $service .= ' - ' . $ex->getMessage();
         include dirname(__FILE__) . '/api_desc_tpl.php';
         return;
     }
     list($className, $methodName) = explode('.', $service);
     $className = 'Api_' . $className;
     $rMethod = new ReflectionMethod($className, $methodName);
     $docComment = $rMethod->getDocComment();
     $docCommentArr = explode("\n", $docComment);
     foreach ($docCommentArr as $comment) {
         $comment = trim($comment);
         //标题描述
         if (empty($description) && strpos($comment, '@') === false && strpos($comment, '/') === false) {
             $description = substr($comment, strpos($comment, '*') + 1);
             continue;
         }
         //@desc注释
         $pos = stripos($comment, '@desc');
         if ($pos !== false) {
             $descComment = substr($comment, $pos + 5);
             continue;
         }
         //@return注释
         $pos = stripos($comment, '@return');
         if ($pos === false) {
             continue;
         }
         $returnCommentArr = explode(' ', substr($comment, $pos + 8));
         if (count($returnCommentArr) < 2) {
             continue;
         }
         if (!isset($returnCommentArr[2])) {
             $returnCommentArr[2] = '';
             //可选的字段说明
         }
         $returns[] = $returnCommentArr;
     }
     include dirname(__FILE__) . '/api_desc_tpl.php';
 }
Example #17
0
 public function testApiImpl()
 {
     $data = array();
     $data['service'] = 'Impl.Add';
     $data['version'] = '1.1.0';
     $data['left'] = '6';
     $data['right'] = '1';
     DI()->request = new PhalApi_Request($data);
     DI()->filter = 'PhalApi_Filter_Impl';
     $impl = new PhalApi_Api_Impl();
     $impl->init();
     $rs = $impl->add();
     $this->assertEquals(7, $rs);
 }
Example #18
0
 public function __construct(PhalApi_Cache_File $fileCache = NULL)
 {
     if ($fileCache === NULL) {
         $config = DI()->config->get('app.Task.mq.file');
         if (!isset($config['path'])) {
             $config['path'] = API_ROOT . '/Runtime';
         }
         if (!isset($config['prefix'])) {
             $config['prefix'] = 'phalapi_task';
         }
         $fileCache = new PhalApi_Cache_File($config);
     }
     $this->fileCache = $fileCache;
 }
Example #19
0
 /**
  * 获取用户基本信息
  * @return int code 操作码,0表示成功,1表示用户不存在
  * @return object info 用户信息对象
  * @return int info.id 用户ID
  * @return string info.name 用户名字
  * @return string info.from 用户来源
  * @return string msg 提示信息
  */
 public function getBaseInfo()
 {
     $rs = array('code' => 0, 'msg' => '', 'info' => array());
     $domain = new Domain_User();
     $info = $domain->getBaseInfo($this->userId);
     if (empty($info)) {
         DI()->logger->debug('user not found', $this->userId);
         $rs['code'] = 1;
         $rs['msg'] = T('user not exists');
         return $rs;
     }
     $rs['info'] = $info;
     return $rs;
 }
Example #20
0
 protected function youGo($service, $params)
 {
     $params['service'] = $service;
     DI()->request = new PhalApi_Request($params);
     DI()->response = new PhalApi_Response_Json();
     $phalapi = new PhalApi();
     $rs = $phalapi->response();
     $apiRs = $rs->getResult();
     if ($apiRs['ret'] != 200) {
         DI()->logger->debug('task local go fail', array('servcie' => $service, 'params' => $params, 'rs' => $apiRs));
         return FALSE;
     }
     return TRUE;
 }
Example #21
0
 public function check()
 {
     $allParams = DI()->request->getAll();
     if (empty($allParams)) {
         return;
     }
     $sign = isset($allParams[$this->signName]) ? $allParams[$this->signName] : '';
     unset($allParams[$this->signName]);
     $expectSign = $this->encryptAppKey($allParams);
     if ($expectSign != $sign) {
         DI()->logger->debug('Wrong Sign', array('needSign' => $expectSign));
         throw new PhalApi_Exception_BadRequest(T('wrong sign'), 6);
     }
 }
Example #22
0
 /**
  * @param string $url 请求的链接
  * @param array $param 额外POST的数据
  * @return array 接口的返回结果
  */
 public static function go($url, $params = array())
 {
     parse_str($url, $urlParams);
     if (!isset($urlParams['service'])) {
         throw new Exception('miss service in url');
     }
     DI()->request = new PhalApi_Request(array_merge($urlParams, $params));
     list($api, $action) = explode('.', $urlParams['service']);
     $class = 'Api_' . $api;
     $apiObj = new $class();
     $apiObj->init();
     $rs = $apiObj->{$action}();
     return $rs;
 }
Example #23
0
 /**
  * 添加一个计划任务到MQ队列
  * @param string $service 接口服务名称,如:Default.Index
  * @param array $params 接口服务参数
  */
 public function add($service, $params = array())
 {
     if (empty($service) || count(explode('.', $service)) < 2) {
         return FALSE;
     }
     if (!is_array($params)) {
         return FALSE;
     }
     $rs = $this->mq->add($service, $params);
     if (!$rs) {
         DI()->logger->debug('task add a new mq', array('service' => $service, 'params' => $params));
         return FALSE;
     }
     return TRUE;
 }
Example #24
0
 /**
  * 用户信息
  */
 public function getUserInfo()
 {
     $rs = array('code' => 0, 'info' => array(), 'msg' => '');
     DI()->userLite->check(true);
     $domain = new Domain_User_User_Info();
     $info = $domain->getUserInfo($this->otherUserId);
     if (empty($info)) {
         $rs['code'] = 1;
         $rs['msg'] = T('can not get user info');
         DI()->logger->debug('can not get user info', $this->otherUserId);
         return $rs;
     }
     $rs['info'] = $info;
     return $rs;
 }
Example #25
0
 public function updateExpiresTime($userId, $token, $newExpiresTime)
 {
     $mcKey = $this->getExpiresTimeMcKey($userId, $token);
     if (isset(DI()->cache)) {
         DI()->cache->set($mcKey, $newExpiresTime, 3600);
     }
     $row = $this->getORM($userId)->select('times')->where('user_id = ?', $userId)->where('token = ?', $token)->fetch();
     if (empty($row)) {
         return;
     }
     $data = array();
     $data['expires_time'] = $newExpiresTime;
     $data['times'] = $row['times'] + 1;
     $this->getORM($userId)->where('user_id = ?', $userId)->where('token = ?', $token)->update($data);
 }
Example #26
0
 /**
  *
  * @param $apkName
  * @param $apkAuthor
  * @param $apkSize
  * @param $apkMd5
  * @param $apkUrl
  */
 function addItem($apkName, $apkAuthor, $apkSize, $apkMd5, $apkUrl)
 {
     $marketModel = new Model_Market();
     DI()->logger->debug('market.getList', array("apkName" => $apkName, "apkAuthor" => $apkAuthor, "apkSize" => $apkSize, "apkMd5" => $apkMd5, "apkUrl" => $apkUrl));
     //        $ret = $marketModel->insert(
     //            array(
     //                "apkName"    => $apkName,
     //                "apkAuthor"  => $apkAuthor,
     //                "apkSize"    => $apkSize,
     //                "apkMd5"     => $apkMd5,
     //                "apkUrl"     => $apkUrl,
     //            )
     //        );
     $ret = $marketModel->addItem(array("apkName" => $apkName, "apkAuthor" => $apkAuthor, "apkSize" => $apkSize, "apkMd5" => $apkMd5, "apkUrl" => $apkUrl));
     return true;
 }
Example #27
0
 /**
 * 响应操作
 *
 * 通过工厂方法创建合适的控制器,然后调用指定的方法,最后返回格式化的数据。
 *
 * @return mixed 根据配置的或者手动设置的返回格式,将结果返回
 *  其结果包含以下元素:
 ```
 *  array(
 *      'ret'   => 200,	            //服务器响应状态
 *      'data'  => array(),	        //正常并成功响应后,返回给客户端的数据	
 *      'msg'   => '',		        //错误提示信息
 *  );
 ```
 */
 public function response()
 {
     $rs = DI()->response;
     try {
         $api = PhalApi_ApiFactory::generateService();
         $service = DI()->request->get('service', 'Default.Index');
         list($apiClassName, $action) = explode('.', $service);
         $rs->setData(call_user_func(array($api, $action)));
     } catch (PhalApi_Exception $ex) {
         $rs->setRet($ex->getCode());
         $rs->setMsg($ex->getMessage());
     } catch (Exception $ex) {
         throw $ex;
     }
     return $rs;
 }
Example #28
0
 /**
  * @group testIndex
  */
 public function testIndex()
 {
     $str = 'service=Default.Index&username=dogstar';
     parse_str($str, $params);
     DI()->request = new PhalApi_Request($params);
     $api = new Api_Default();
     //自己进行初始化
     $api->init();
     $rs = $api->index();
     $this->assertNotEmpty($rs);
     $this->assertArrayHasKey('title', $rs);
     $this->assertArrayHasKey('content', $rs);
     $this->assertArrayHasKey('version', $rs);
     $this->assertArrayHasKey('time', $rs);
     $this->assertEquals('dogstar您好,欢迎使用PhalApi!', $rs['content']);
 }
Example #29
0
 /**
  * 默认接口服务
  * @return int id
  * @return string title 标题
  * @return string coverurl 封面url
  * @return int nid 新闻的id
  */
 public function getList()
 {
     DI()->logger->debug('main.getList', $this->page);
     $domain = new Domain_Main();
     $maxPageResult = $domain->getMaxPage();
     $maxPage = floor(($maxPageResult["id"] - 1) / 10) + 1;
     if (intval($this->page) == intval($maxPage)) {
         return array("status" => self::LISTS_STATUS_ERROR);
     }
     if (intval($this->page) == 0) {
         $page = $maxPage;
     } else {
         $page = $this->page;
     }
     $lists = $domain->getList($this->page);
     return array("lists" => $lists, "page" => $page, "status" => self::LISTS_STATUS_NORMAL);
 }
Example #30
0
 public function __construct(PhalApi_Cache_Redis $redisCache = NULL)
 {
     if ($redisCache === NULL) {
         $config = DI()->config->get('app.Task.mq.redis');
         if (!isset($config['host'])) {
             $config['host'] = '127.0.0.1';
         }
         if (!isset($config['port'])) {
             $config['port'] = 6379;
         }
         if (!isset($config['prefix'])) {
             $config['prefix'] = 'phalapi_task';
         }
         $redisCache = new PhalApi_Cache_Redis($config);
     }
     $this->redisCache = $redisCache;
 }