<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <hide@address.com>
// +----------------------------------------------------------------------
// $Id: RestAction.class.php 2795 2012-03-02 15:34:18Z liu21st $
/**
+------------------------------------------------------------------------------
* ThinkPHP RESTFul æ§å¶å¨æ©å±ç±»
+------------------------------------------------------------------------------
*/
abstract class RestAction {
// å½åActionåç§°
private $name = '';
// è§å¾å®ä¾
protected $view = null;
protected $_method = ''; // å½å请æ±ç±»å
protected $_type = ''; // å½åèµæºç±»å
// è¾åºç±»å
protected $_types = array();
/**
+----------------------------------------------------------
* æ¶æå½æ° å徿¨¡æ¿å¯¹è±¡å®ä¾
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
*/
public function __construct() {
//å®ä¾åè§å¾ç±»
$this->view = Think::instance('View');
if(!defined('__EXT__')) define('__EXT__','');
// èµæºç±»åæ£æµ
if(''==__EXT__) { // èªå¨æ£æµèµæºç±»å
$this->_type = $this->getAcceptType();
}elseif(false === stripos(C('REST_CONTENT_TYPE_LIST'),__EXT__)) {
// èµæºç±»åéæ³ åç¨é»è®¤èµæºç±»å访é®
$this->_type = C('REST_DEFAULT_TYPE');
}else{
// æ£æµå®é
èµæºç±»å
if($this->getAcceptType() == __EXT__) {
$this->_type = __EXT__;
}else{
$this->_type = C('REST_DEFAULT_TYPE');
}
}
// è¯·æ±æ¹å¼æ£æµ
$method = strtolower($_SERVER['REQUEST_METHOD']);
if(false === stripos(C('REST_METHOD_LIST'),$method)) {
// è¯·æ±æ¹å¼éæ³ åç¨é»è®¤è¯·æ±æ¹æ³
$method = C('REST_DEFAULT_METHOD');
}
$this->_method = $method;
// å
许è¾åºçèµæºç±»å
$this->_types = C('REST_OUTPUT_TYPE');
//æ§å¶å¨åå§å
if(method_exists($this,'_initialize'))
$this->_initialize();
}
/**
+----------------------------------------------------------
* è·åå½åActionåç§°
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
*/
protected function getActionName() {
if(empty($this->name)) {
// è·åActionåç§°
$this->name = substr(get_class($this),0,-6);
}
return $this->name;
}
/**
+----------------------------------------------------------
* æ¯å¦AJAX请æ±
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @return bool
+----------------------------------------------------------
*/
protected function isAjax() {
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) ) {
if('xmlhttprequest' == strtolower($_SERVER['HTTP_X_REQUESTED_WITH']))
return true;
}
if(!empty($_POST[C('VAR_AJAX_SUBMIT')]) || !empty($_GET[C('VAR_AJAX_SUBMIT')]))
// 夿Ajaxæ¹å¼æäº¤
return true;
return false;
}
/**
+----------------------------------------------------------
* éæ¯æ¹æ³ æä¸åå¨çæä½çæ¶åæ§è¡
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $method æ¹æ³å
* @param array $args åæ°
+----------------------------------------------------------
* @return mixed
+----------------------------------------------------------
*/
public function __call($method,$args) {
if( 0 === strcasecmp($method,ACTION_NAME)) {
if(method_exists($this,$method.'_'.$this->_method.'_'.$this->_type)) { // RESTFulæ¹æ³æ¯æ
$fun = $method.'_'.$this->_method.'_'.$this->_type;
$this->$fun();
}elseif($this->_method == C('REST_DEFAULT_METHOD') && method_exists($this,$method.'_'.$this->_type) ){
$fun = $method.'_'.$this->_type;
$this->$fun();
}elseif($this->_type == C('REST_DEFAULT_TYPE') && method_exists($this,$method.'_'.$this->_method) ){
$fun = $method.'_'.$this->_method;
$this->$fun();
}elseif(method_exists($this,'_empty')) {
// 妿å®ä¹äº_emptyæä½ åè°ç¨
$this->_empty($method,$args);
}elseif(file_exists_case(C('TMPL_FILE_NAME'))){
// æ£æ¥æ¯å¦åå¨é»è®¤æ¨¡ç 妿æç´æ¥è¾åºæ¨¡ç
$this->display();
}else{
// æåºå¼å¸¸
throw_exception(L('_ERROR_ACTION_').ACTION_NAME);
}
}else{
switch(strtolower($method)) {
// è·ååé æ¯æè¿æ»¤åé»è®¤å¼ è°ç¨æ¹å¼ $this->_post($key,$filter,$default);
case '_get': $input =& $_GET;break;
case '_post':$input =& $_POST;break;
case '_put':
case '_delete':parse_str(file_get_contents('php://input'), $input);break;
case '_request': $input =& $_REQUEST;break;
case '_session': $input =& $_SESSION;break;
case '_cookie': $input =& $_COOKIE;break;
case '_server': $input =& $_SERVER;break;
default:
throw_exception(__CLASS__.':'.$method.L('_METHOD_NOT_EXIST_'));
}
if(isset($input[$args[0]])) { // å弿ä½
$data = $input[$args[0]];
$fun = $args[1]?$args[1]:C('DEFAULT_FILTER');
$data = $fun($data); // åæ°è¿æ»¤
}else{ // åéé»è®¤å¼
$data = isset($args[2])?$args[2]:NULL;
}
return $data;
}
}
/**
+----------------------------------------------------------
* æ¨¡æ¿æ¾ç¤º
* è°ç¨å
ç½®çæ¨¡æ¿å¼ææ¾ç¤ºæ¹æ³ï¼
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param string $templateFile æå®è¦è°ç¨çæ¨¡æ¿æä»¶
* é»è®¤ä¸ºç©º ç±ç³»ç»èªå¨å®ä½æ¨¡æ¿æä»¶
* @param string $charset è¾åºç¼ç
* @param string $contentType è¾åºç±»å
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function display($templateFile='',$charset='',$contentType='') {
$this->view->display($templateFile,$charset,$contentType);
}
/**
+----------------------------------------------------------
* 模æ¿åéèµå¼
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $name è¦æ¾ç¤ºç模æ¿åé
* @param mixed $value åéçå¼
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function assign($name,$value='') {
$this->view->assign($name,$value);
}
public function __set($name,$value) {
$this->view->assign($name,$value);
}
/**
+----------------------------------------------------------
* 设置页é¢è¾åºçCONTENT_TYPEåç¼ç
+----------------------------------------------------------
* @access public
+----------------------------------------------------------
* @param string $type content_type ç±»å对åºçæ©å±å
* @param string $charset 页é¢è¾åºç¼ç
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
public function setContentType($type, $charset=''){
if(headers_sent()) return;
if(empty($charset)) $charset = C('DEFAULT_CHARSET');
$type = strtolower($type);
if(isset($this->_types[$type])) //è¿æ»¤content_type
header('Content-Type: '.$this->_types[$type].'; charset='.$charset);
}
/**
+----------------------------------------------------------
* è¾åºè¿åæ°æ®
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data è¦è¿åçæ°æ®
* @param String $type è¿åç±»å JSON XML
* @param integer $code HTTPç¶æ
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function response($data,$type='',$code=200) {
// ä¿åæ¥å¿
if(C('LOG_RECORD')) Log::save();
$this->sendHttpStatus($code);
exit($this->encodeData($data,strtolower($type)));
}
/**
+----------------------------------------------------------
* ç¼ç æ°æ®
+----------------------------------------------------------
* @access protected
+----------------------------------------------------------
* @param mixed $data è¦è¿åçæ°æ®
* @param String $type è¿åç±»å JSON XML
+----------------------------------------------------------
* @return void
+----------------------------------------------------------
*/
protected function encodeData($data,$type='') {
if(empty($data)) return '';
if('json' == $type) {
// è¿åJSONæ°æ®æ ¼å¼å°å®¢æ·ç«¯ å
å«ç¶æä¿¡æ¯
$data = json_encode($data);
}elseif('xml' == $type){
// è¿åxmlæ ¼å¼æ°æ®
$data = xml_encode($data);
}elseif('php'==$type){
$data = serialize($data);
}// é»è®¤ç´æ¥è¾åº
$this->setContentType($type);
header('Content-Length: ' . strlen($data));
return $data;
}
// åéHttpç¶æä¿¡æ¯
protected function sendHttpStatus($status) {
static $_status = array(
// Informational 1xx
100 => 'Continue',
101 => 'Switching Protocols',
// Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Moved Temporarily ', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',
// Client Error 4xx
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
// Server Error 5xx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded'
);
if(isset($_status[$code])) {
header('HTTP/1.1 '.$code.' '.$_status[$code]);
// ç¡®ä¿FastCGI模å¼ä¸æ£å¸¸
header('Status:'.$code.' '.$_status[$code]);
}
}
/**
+----------------------------------------------------------
* è·åå½å请æ±çAccept头信æ¯
+----------------------------------------------------------
* @return string
+----------------------------------------------------------
*/
protected function getAcceptType(){
$type = array(
'html'=>'text/html,application/xhtml+xml,*/*',
'xml'=>'application/xml,text/xml,application/x-xml',
'json'=>'application/json,text/x-json,application/jsonrequest,text/json',
'js'=>'text/javascript,application/javascript,application/x-javascript',
'css'=>'text/css',
'rss'=>'application/rss+xml',
'yaml'=>'application/x-yaml,text/yaml',
'atom'=>'application/atom+xml',
'pdf'=>'application/pdf',
'text'=>'text/plain',
'png'=>'image/png',
'jpg'=>'image/jpg,image/jpeg,image/pjpeg',
'gif'=>'image/gif',
'csv'=>'text/csv'
);
foreach($type as $key=>$val){
$array = explode(',',$val);
foreach($array as $k=>$v){
if(stristr($_SERVER['HTTP_ACCEPT'], $v)) {
return $key;
}
}
}
return false;
}
}