PageRenderTime 50ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/platform/bae.class.php

https://github.com/ueffort/fn-php
PHP | 575 lines | 457 code | 10 blank | 108 comment | 46 complexity | 3587bfbbee25abaf5655fbe0238e6823 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception
  1. <?php
  2. //百度云平台,云平台环境Paas,用以扩展服务接口
  3. class FN_platform_bae extends FN_platform{
  4. private $accesskey = null;
  5. private $securekey = null;
  6. private $appid = null;
  7. protected $PlatformSelf = 'bae';
  8. public function __construct($config){
  9. $this->accesskey = $config['accesskey'];
  10. $this->securekey = $config['securekey'];
  11. $this->appid = $config['appid'];
  12. }
  13. //统一调用云平台服务
  14. /**
  15. * 获取基础服务
  16. * @param string $servername 调用的服务名称
  17. * @param string $config 映射名称,默认为default
  18. * @return class
  19. */
  20. public function server($servername,&$config){
  21. switch($servername){
  22. case 'cache':
  23. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/cache
  24. if(!$this->isCloudSelf()) return false;
  25. require_once ('BaeMemcache.class.php');
  26. return new BaeMemcache();
  27. case 'count':
  28. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/counter
  29. if(!$this->isCloudSelf()) return false;
  30. require_once ('BaeCounter.class.php');
  31. return new BaeCounter();
  32. case 'rank':
  33. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/rank
  34. if(!$this->isCloudSelf()) return false;
  35. require_once ('BaeRankManager.class.php');
  36. return BaeRankManager::getInstance();
  37. case 'database':
  38. if(!$this->isCloudSelf()) return false;
  39. switch($config['drive']){
  40. case 'mysql':
  41. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/mysql
  42. $config['host'] = getenv('HTTP_BAE_ENV_ADDR_SQL_IP');
  43. $config['port'] = getenv('HTTP_BAE_ENV_ADDR_SQL_PORT');
  44. $config['user'] = $this->accesskey;
  45. $config['pass'] = $this->securekey;
  46. break;
  47. case 'mongodb':
  48. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/mongodb
  49. $config['host'] = getenv('HTTP_BAE_ENV_ADDR_MONGO_IP');
  50. $config['port'] = getenv('HTTP_BAE_ENV_ADDR_MONGO_PORT');
  51. $config['user'] = $this->accesskey;
  52. $config['pass'] = $this->securekey;
  53. break;
  54. case 'redis':
  55. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/redis
  56. $config['host'] = getenv('HTTP_BAE_ENV_ADDR_REDIS_IP');
  57. $config['port'] = getenv('HTTP_BAE_ENV_ADDR_REDIS_PORT');
  58. $config['pass'] = $this->accesskey . '-' . $this->securekey . '' . $config['dbname'];
  59. break;
  60. }
  61. break;
  62. case 'template':
  63. if(!$this->isCloudSelf()) return false;
  64. switch($config['drive']){
  65. case 'smarty':
  66. $config['compile_dir'] = '%template/';
  67. $config['cache_dir'] = '%cache/';
  68. unset($config['platform']);
  69. break;
  70. }
  71. break;
  72. case 'log':
  73. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/log
  74. if(!$this->isCloudSelf()) return false;
  75. require_once ('BaeLog.class.php');
  76. /*
  77. //打印一条警告日志,包括日志级别和日志内容
  78. $logger ->logWrite(2, "this is for warning log print ");
  79. //打印一条轨迹日志
  80. $logger ->logTrace("this is for trace log print ");
  81. //打印一条通知日志
  82. $logger ->logNotice("this is for notice log print ");
  83. //打印一条调试日志
  84. $logger ->logDebug("this is for debug log print ");
  85. //打印一条警告日志
  86. $logger ->logWarning("this is for warning log print ");
  87. //打印一条致命日志
  88. $logger ->logFatal("this is for fatal log print ");
  89. */
  90. return BaeLog::getInstance();
  91. case 'image':
  92. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/image
  93. if(!$this->isCloudSelf()) return false;
  94. require_once ('BaeImageService.class.php');
  95. return new FN_platform_baeimage();
  96. case 'vcode'://是image服务中的一款,但操作方式所以独立出来
  97. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/image#.E9.AA.8C.E8.AF.81.E7.A0.81.E5.8A.9F.E8.83.BD.EF.BC.88.E5.8F.AA.E6.94.AF.E6.8C.81.E5.8F.82.E6.95.B0.E6.95.B0.E7.BB.84.E6.96.B9.E5.BC.8F.EF.BC.89
  98. if(!$this->isCloudSelf()) return false;
  99. require_once ('BaeImageService.class.php');
  100. return new FN_platform_baeVCode();
  101. case 'taskqueue'://异步操作,一对一
  102. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/rt/php/taskqueue
  103. if(!$this->isCloudSelf()) return false;
  104. require_once ('BaeTaskQueueManager.class.php');
  105. return BaeTaskQueueManager::getInstance();
  106. case 'storage'://BCS云存储
  107. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/stor/api
  108. $config['accesskey'] = $this->accesskey;
  109. $config['securekey'] = $this->securekey;
  110. return new FN_platform_baeStorage($config);
  111. case 'queue'://云消息,异步操作,多对多
  112. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/mq/api
  113. $config['accesskey'] = $this->accesskey;
  114. $config['securekey'] = $this->securekey;
  115. return new FN_platform_baeQueue($config);
  116. case 'mail':
  117. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/mq/api#mail
  118. $config['accesskey'] = $this->accesskey;
  119. $config['securekey'] = $this->securekey;
  120. return new FN_platform_baeMail($config);
  121. case 'channel'://云推送
  122. //http://developer.baidu.com/wiki/index.php?title=docs/cplat/push/api
  123. $config['accesskey'] = $this->accesskey;
  124. $config['securekey'] = $this->securekey;
  125. return new FN_platform_baeChannel($config);
  126. case 'map'://LBS地图
  127. //http://lbsyun.baidu.com/
  128. return false;
  129. }
  130. }
  131. public function parsePath($dir,$Symbol){
  132. switch($Symbol){
  133. case '%':
  134. return sys_get_temp_dir().'/'.substr($dir,1);//缓存目录
  135. default:
  136. default:return $dir;
  137. }
  138. }
  139. }
  140. class FN_platform_baeimage{
  141. private $image = null;
  142. private $type = null;
  143. private $Service = null;
  144. public function __construct(){
  145. $this->Service = new BaeImageService();
  146. }
  147. public function __call($fname,$argus){
  148. call_user_func_array(array(&$this->image,$fname),$argus);
  149. return $this;
  150. }
  151. //获取文字水印功能类: http://phpsdkdoc.duapp.com/?BaeAPI/BaeImageAnnotate.html
  152. public function getAnnotate($text=null){
  153. $this->type = 'Annotate';
  154. $this->image = new BaeImageAnnotate($text);
  155. return $this;
  156. }
  157. //获取图片合成功能类: http://phpsdkdoc.duapp.com/?BaeAPI/BaeImageComposite.html
  158. //多个图片合成反复调用此函数设定参数
  159. public function getComposite($url = NULL){
  160. $this->type = 'Composite';
  161. $this->image[] = new BaeImageComposite($url);
  162. return $this;
  163. }
  164. //获取二维码功能类: http://phpsdkdoc.duapp.com/?BaeAPI/BaeImageQRCode.html
  165. public function getQRCode($text = NULL){
  166. $this->type = 'QRCode';
  167. $this->image = new BaeImageQRCode();
  168. return $this;
  169. }
  170. //获取图形变换处理功能类: http://phpsdkdoc.duapp.com/?BaeAPI/BaeImageTransform.html
  171. public function getTransform(){
  172. $this->type = 'Transform';
  173. $this->image = new BaeImageTransform();
  174. return $this;
  175. }
  176. //获取静态参数: http://phpsdkdoc.duapp.com/?BaeAPI/BaeImageConstant.html
  177. public function get($const=null){
  178. return constant('BaeImageConstant::'. $const);
  179. }
  180. //面向对象调用后的统一执行函数
  181. public function apply(){
  182. if(!isset($this->image) || !isset($this->type)) return -3;//未选择类型
  183. $num = func_num_args();
  184. $params = func_get_args();
  185. switch($this->type){
  186. case 'Annotate':
  187. if($num == 0) return -2;
  188. //params = [url]
  189. $return = $this->Service->applyAnnotateByObject($params[0], $this->image);
  190. break;
  191. case 'Composite':
  192. if($num == 0) return -2;
  193. //params = [width,height,outptcode,quality]
  194. if($num < 4){
  195. $default = array(1000,1000,$this->get('JPG'),80);
  196. foreach($default as $key=>$param){
  197. if(empty($params[$key])) $params[$key] = $param;
  198. }
  199. }
  200. $return = $this->Service->applyCompositeByObject($this->image,$params[0],$params[1],$params[2],$params[3]);
  201. break;
  202. case 'QRCode':
  203. $return = $this->Service->applyQRCodeByObject($this->image);
  204. break;
  205. case 'Transform':
  206. if($num == 0) return -2;//参数错误
  207. //params = [url]
  208. $return = $this->Service->applyTransformByObject($params[0],$this->image);
  209. break;
  210. default:
  211. return -1;//类型错误
  212. }
  213. unset($this->image);
  214. unset($this->type);
  215. //header("Content-type:image/jpg");
  216. //$imageSrc = base64_decode($return['image_data']);
  217. if($return !== false && isset($return['response_params']) && isset($return['response_params']['image_data'])) return $return['response_params'];
  218. //调用error;
  219. return false;
  220. }
  221. public function error(){
  222. return $this->Service->errmsg();
  223. }
  224. }
  225. class FN_platform_baeVCode{
  226. private $image = null;
  227. public function __construct(){
  228. $this->image = new BaeImageService();
  229. }
  230. //生成验证码
  231. public function generateVCode($length,$pattern){
  232. $return = $this->image->generateVCode(array(BaeImageConstant::VCODE_LEN=>$length,BaeImageConstant::VCODE_PATTERN=>$pattern));
  233. //echo "imgurl:" . $return['imgurl'] . "\n";用于显示的url
  234. //echo "secret:" . $return['secret'] . "\n";用于输入后的校验
  235. if($return !== false && isset($return['response_params']) && isset($return['response_params']['imgurl'])) return $return['response_params'];
  236. //调用error;
  237. return false;
  238. }
  239. //校验验证码
  240. public function verifyVCode($input,$secret){
  241. $return = $this->image->verifyVCode(array(BaeImageConstant::VCODE_INPUT=>$input,BaeImageConstant::VCODE_SECRET=>$secret));
  242. if($return !== false && isset($return['response_params']) && isset($return['response_params']['imgurl'])) return $return['response_params'];
  243. //调用error;
  244. return false;
  245. }
  246. public function error(){
  247. return $this->Service->errmsg();
  248. }
  249. }
  250. //暂无权限接口设计
  251. class FN_platform_baeStorage extends FN_tools_rest{
  252. private $accesskey = null;
  253. private $securekey = null;
  254. private $bucket = null;
  255. const DEFAULT_URL = 'http://bcs.duapp.com';
  256. protected function init(){
  257. $this->accesskey = $this->config['accesskey'];
  258. $this->securekey = $this->config['securekey'];
  259. }
  260. /**
  261. * 校验bucket是否合法,bucket规范
  262. * 1. 由小写字母,数字和横线'-'组成,长度为6~63位
  263. * 2. 不能以数字作为Bucket开头
  264. * 3. 不能以'-'作为Bucket的开头或者结尾
  265. * @param string $bucket
  266. * @return boolean
  267. */
  268. public static function validate_bucket($bucket) {
  269. //bucket 正则
  270. $pattern1 = '/^[a-z][-a-z0-9]{4,61}[a-z0-9]$/';
  271. if (! preg_match ( $pattern1, $bucket )) {
  272. return false;
  273. }
  274. return true;
  275. }
  276. //创建bucket
  277. public function creatDir($dirname,$acl='public-read'){
  278. if(!$this->validate_bucket($dirname)) return false;
  279. $sign = $this->sign('PUT',$dirname,'');
  280. $url = $this->formatURL($dirname,'');
  281. $params = array('sign'=>$sign);
  282. $header = array('x-bs-acl'=>$acl);
  283. $options = array('header'=>$header);
  284. $response = $this->put($url,$params,$options);
  285. return $response->isOK();
  286. }
  287. //列出所有bucket
  288. public function listDir(){
  289. $sign = $this->sign('GET','','');
  290. $url = $this->formatURL('','');
  291. $params = array('sign'=>$sign);
  292. $response = $this->get($url,$params);
  293. return $response->isOK() ? $response->getBodyJson():false;
  294. }
  295. //删除bucket
  296. public function deleteDir($dirname){
  297. $sign = $this->sign('DELETE',$dirname,'');
  298. $url = $this->formatURL($dirname,'');
  299. $params = array('sign'=>$sign);
  300. $response = $this->delete($url,$params);
  301. return $response->isOK();
  302. }
  303. //设置文件操作的bucket
  304. public function setDir($dirname){
  305. $this->bucket = $dirname;
  306. }
  307. //添加object
  308. public function addFile($filename,$file,$acl=false,$header=array()){
  309. $sign = $this->sign('PUT',$this->bucket,$filename);
  310. $url = $this->formatURL($this->bucket,$filename);
  311. $params = array('sign'=>$sign);
  312. if ($acl) {
  313. $header['x-bs-acl'] = $acl;
  314. }
  315. $options = array('header'=>$header);
  316. $options ['fileUpload'] = $file;
  317. $head['Content-Disposition'] = 'attachment; filename='.substr($filename,0,strrpos($filename,'/'));
  318. $response = $this->put ($url,$params,$options);
  319. return $response->isOK ();
  320. }
  321. //添加object通过byte
  322. public function addFileBytes($filename,$bytes,$acl=false,$header=array()){
  323. $sign = $this->sign('PUT',$this->bucket,$filename);
  324. $url = $this->formatURL($this->bucket,$filename);
  325. $params = array('sign'=>$sign);
  326. if ($acl) {
  327. $header['x-bs-acl'] = $acl;
  328. }
  329. $options = array('header'=>$header);
  330. $options ['content'] = $bytes;
  331. $head['Content-Disposition'] = 'attachment; filename='.substr($filename,0,strrpos($filename,'/'));
  332. $response = $this->put ($url,$params,$options);
  333. return $response->isOK ();
  334. }
  335. //复制object
  336. public function copyFile($source,$filename,$etag=false){
  337. $source = $this->parseURL($source);
  338. $sign = $this->sign('PUT',$this->bucket,$filename);
  339. $url = $this->formatURL($this->bucket,$filename);
  340. $params = array('sign'=>$sign);
  341. $header = array('x-bs-copy-source'=>$this->formatURL($source['bucket'],$source['object']));
  342. if($etag) $header['x-bs-copy-source-tag'] = $etag;
  343. $options = array('header'=>$header);
  344. $response = $this->put($url,$params,$options);
  345. return $response->isOK();
  346. }
  347. //删除object
  348. public function deleteFile($filename){
  349. $sign = $this->sign('DELETE',$this->bucket,$filename);
  350. $url = $this->formatURL($this->bucket,$filename);
  351. $params = array('sign'=>$sign);
  352. $response = $this->delete($url,$params);
  353. return $response->isOK();
  354. }
  355. //列出所有object
  356. //prefix可以作为路劲参数设置
  357. public function listFile($prefix = '',$start=0,$limit=0,$list_model = 2) {
  358. $sign = $this->sign('GET',$this->bucket,'');
  359. $url = $this->formatURL($this->bucket,'');
  360. $params = array('sign'=>$sign);
  361. if ($start) {
  362. $params['start'] = $start;
  363. }
  364. if ($limit) {
  365. $params['limit'] = $limit;
  366. }
  367. $params['prefix'] = rawurlencode ('/'. $prefix );
  368. $params['dir'] = $list_model;
  369. $response = $this->get($url,$params);
  370. return $response->isOK() ? $response->getBodyJson():false;
  371. }
  372. //获取object元数据
  373. public function getHead($filename,$header=array()){
  374. $sign = $this->sign('HEAD',$this->bucket,$filename);
  375. $url = $this->formatURL($this->bucket,$filename);
  376. $params = array('sign'=>$sign);
  377. $options = array('header'=>$header);
  378. $response = $this->head($url,$params,$options);
  379. return $response->isOK() ? $response->getHeader() : false;
  380. }
  381. //获取object
  382. public function getFile($filename,$range=false,$header=array()){
  383. $sign = $this->sign('HEAD',$this->bucket,$filename);
  384. $url = $this->formatURL($this->bucket,$filename);
  385. $params = array('sign'=>$sign);
  386. if(is_array($range)) {
  387. $header['Range'] = $range[0].'-'.($range[1] ? $range[1] : 'end');
  388. }elseif($range){
  389. $header['Range'] = '0-'.$range;
  390. }
  391. $options = array('header'=>$header);
  392. $response = $this->head($url,$params,$options);
  393. return $response->isOK() ? $response->getBody() : false;
  394. }
  395. //返回当前基本url
  396. public function getURL(){
  397. return self::DEFAULT_URL.'/' . $this->bucket.'/';
  398. }
  399. /**
  400. * 构造url
  401. * @param string $bucket
  402. * @param string $object
  403. * @return boolean string
  404. */
  405. private function formatURL($bucket,$object) {
  406. return self::DEFAULT_URL.'/' . $bucket.'/' . rawurlencode ( $object );
  407. }
  408. /**
  409. * 解析url为百度的bucket+object
  410. * @param string $url
  411. * @return boolean string
  412. */
  413. private function parseURL($url) {
  414. $url = str_replace(self::DEFAULT_URL.'/','',$url);
  415. $pos = strpos($url,'/');
  416. $bucket = substr($url,0,$pos-1);
  417. $object = substr($url,$pos);
  418. return array('bucket'=>$bucket,'object'=>$object);
  419. }
  420. //生成签名
  421. //time为有效时间,Unix时间戳
  422. //ip访问白名单
  423. //size限制上传object大小,单位B
  424. private function sign($method,$bucket,$object,$time=false,$ip=false,$size=false){
  425. $flag = 'MBO';
  426. $content = 'Method='.$method.'\n'
  427. .'Bucket='.$bucket.'\n'
  428. .'Object=/'.$object.'\n';
  429. if($time){
  430. $flag.='T';
  431. $content .= 'Time='.$time.'\n';
  432. }
  433. if($ip){
  434. $flag.='I';
  435. $content .= 'Ip='.$ip.'\n';
  436. }
  437. if($size){
  438. $flag.='S';
  439. $content .= 'Size='.$size.'\n';
  440. }
  441. $content = $flag.'\n'.$content;
  442. $signature=urlencode(base64_encode(hash_hmac('sha1',$content, $this->secretKey,true)));
  443. return $flag.':'.$this->accesskey.':'.$signature;
  444. }
  445. }
  446. class FN_platform_baeQueue extends FN_tools_rest{
  447. protected $accesskey = null;
  448. protected $securekey = null;
  449. private $queue = null;
  450. const DEFAULT_URL = 'http://bcms.api.duapp.com/rest/2.0/bcms';
  451. protected function init(){
  452. $this->accesskey = $this->config['accesskey'];
  453. $this->securekey = $this->config['securekey'];
  454. }
  455. public function setQueue($queuename){
  456. $this->queue = $queuename;
  457. }
  458. /**
  459. * 构造url
  460. * @return boolean string
  461. */
  462. protected function formatURL() {
  463. return self::DEFAULT_URL.'/' . $this->queue;
  464. }
  465. //生成签名
  466. protected function sign($method,$url,$params){
  467. $basic_string = $method.$url;
  468. ksort($params);
  469. foreach($params as $key=>$value){
  470. $basic_string .= $key.'='.$value;
  471. }
  472. $basic_string .= $this->securekey;
  473. return md5((urlencode($basic_string)));
  474. }
  475. //统一请求函数
  476. protected function requestProxy($params){
  477. //access_token string  是 开发者准入token,https调用时必须存在
  478. $url = $this->formatURL();
  479. $params['client_id'] = $this->accesskey;
  480. $params['timestamp'] = FNbase::getTime();
  481. $sign = $this->sign('POST',$url,$params);
  482. $params['sign'] = $sign;
  483. $header = array();
  484. $header['Host'] = 'bcms.api.duapp.com';
  485. $header['Content-Type'] = 'application/x-www-form-urlencoded';
  486. $options = array('header'=>$header);
  487. $options['method'] = 'POST';
  488. $options['url'] = $url;
  489. if($options['method'] == 'GET'){
  490. $options['url'] = $this->combineURL($options['url'],$params);
  491. }else{
  492. $options['content'] = $this->combineParams($params);
  493. }
  494. $response = $this->request($options);
  495. return $response->isOK() ? $response->getBodyJson():false;
  496. }
  497. }
  498. class FN_platform_baeMail extends FN_platform_baeQueue{
  499. private $from = null;
  500. protected function init(){
  501. parent::init();
  502. if(isset($this->config['queue'])) $this->setQueue($this->config['queue']);
  503. $this->setFrom($this->config['from']);
  504. }
  505. public function setFrom($from){
  506. $this->from = $from;
  507. return $this;
  508. }
  509. public function mail($address,$subject,$message,$ishtml=false){
  510. if(is_array($address)){
  511. $address = json_encode($address);
  512. }
  513. $params['address'] = $address;
  514. $params['method'] = 'mail';
  515. $params['message'] = ($ishtml ? '<!--HTML-->':'').$message;//如果是二进制内容,需要将内容先做BASE64编码成文本再发布消息
  516. $params['mail_subject'] = $subject;
  517. if($this->from) $params['from'] = $this->from;
  518. return $this->requestProxy($params);
  519. }
  520. }
  521. class FN_platform_beaChannel extends FN_tools_rest{
  522. protected $accesskey = null;
  523. protected $securekey = null;
  524. const DEFAULT_URL = 'http://channel.api.duapp.com/rest/2.0/channel';
  525. protected function init(){
  526. $this->accesskey = $this->config['accesskey'];
  527. $this->securekey = $this->config['securekey'];
  528. }
  529. /**
  530. * 构造url
  531. * @param string $channel
  532. * @return boolean string
  533. */
  534. protected function formatURL($channel) {
  535. return self::DEFAULT_URL.'/' . $channel;
  536. }
  537. //生成签名
  538. protected function sign($method,$url,$params){
  539. $basic_string = $method.$url;
  540. sort($params);
  541. foreach($params as $key=>$value){
  542. $basic_string .= $key.'='.$value;
  543. }
  544. $basic_string .= $this->securekey;
  545. return md5((urlencode($basic_string)));
  546. }
  547. //统一请求函数
  548. protected function requestProxy($params,$channel){
  549. $url = $this->formatURL($channel);
  550. $params['apikey'] = $this->accesskey;
  551. $params['timestamp'] = FNbase::getTime();
  552. $sign = $this->sign('POST',$url,$params);
  553. $params['sign'] = $sign;
  554. $options = array();
  555. $options['url'] = $url;
  556. $options['method'] = $params['method'];
  557. if($params['method'] == 'GET'){
  558. $options['url'] = $this->combineURL($options['url'],$params);
  559. }else{
  560. $options['content'] = $this->combineParams($params);
  561. }
  562. $response = $this->request($options);
  563. return $response->isOK() ? $response->getBodyJson():false;
  564. }
  565. }