2008-03-31 01:18:04 +02:00
|
|
|
<?php
|
|
|
|
/**
|
|
|
|
* Sapphire's generic RESTful server.
|
|
|
|
*
|
|
|
|
* This class gives your application a RESTful API for free. All you have to do is define static $api_access = true on
|
|
|
|
* the appropriate DataObjects. You will need to ensure that all of your data manipulation and security is defined in
|
|
|
|
* your model layer (ie, the DataObject classes) and not in your Controllers. This is the recommended design for Sapphire
|
|
|
|
* applications.
|
|
|
|
*
|
2009-03-14 20:09:00 +01:00
|
|
|
* Enabling restful access on a model will also enable a SOAP API, see {@link SOAPModelAccess}.
|
|
|
|
*
|
2008-10-15 18:18:17 +02:00
|
|
|
* Example DataObject with simple api access, giving full access to all object properties and relations,
|
|
|
|
* unless explicitly controlled through model permissions.
|
|
|
|
* <code>
|
|
|
|
* class Article extends DataObject {
|
|
|
|
* static $db = array('Title'=>'Text','Published'=>'Boolean');
|
|
|
|
* static $api_access = true;
|
|
|
|
* }
|
|
|
|
* </code>
|
|
|
|
*
|
|
|
|
* * Example DataObject with advanced api access, limiting viewing and editing to Title attribute only:
|
|
|
|
* <code>
|
|
|
|
* class Article extends DataObject {
|
|
|
|
* static $db = array('Title'=>'Text','Published'=>'Boolean');
|
|
|
|
* static $api_access = array(
|
|
|
|
* 'view' => array('Title'),
|
|
|
|
* 'edit' => array('Title'),
|
|
|
|
* );
|
|
|
|
* }
|
|
|
|
* </code>
|
|
|
|
*
|
2010-10-15 05:55:22 +02:00
|
|
|
* <b>Supported operations</b>
|
|
|
|
*
|
2008-03-31 01:18:04 +02:00
|
|
|
* - GET /api/v1/(ClassName)/(ID) - gets a database record
|
2008-08-09 09:03:24 +02:00
|
|
|
* - GET /api/v1/(ClassName)/(ID)/(Relation) - get all of the records linked to this database record by the given reatlion
|
|
|
|
* - GET /api/v1/(ClassName)?(Field)=(Val)&(Field)=(Val) - searches for matching database records
|
2008-10-16 19:35:27 +02:00
|
|
|
* - POST /api/v1/(ClassName) - create a new database record
|
2008-08-09 09:03:24 +02:00
|
|
|
* - PUT /api/v1/(ClassName)/(ID) - updates a database record
|
2008-03-31 01:18:04 +02:00
|
|
|
* - PUT /api/v1/(ClassName)/(ID)/(Relation) - updates a relation, replacing the existing record(s) (NOT IMPLEMENTED YET)
|
|
|
|
* - POST /api/v1/(ClassName)/(ID)/(Relation) - updates a relation, appending to the existing record(s) (NOT IMPLEMENTED YET)
|
|
|
|
*
|
|
|
|
* - DELETE /api/v1/(ClassName)/(ID) - deletes a database record (NOT IMPLEMENTED YET)
|
|
|
|
* - DELETE /api/v1/(ClassName)/(ID)/(Relation)/(ForeignID) - remove the relationship between two database records, but don't actually delete the foreign object (NOT IMPLEMENTED YET)
|
|
|
|
*
|
|
|
|
* - POST /api/v1/(ClassName)/(ID)/(MethodName) - executes a method on the given object (e.g, publish)
|
2008-08-09 05:29:30 +02:00
|
|
|
*
|
2010-10-15 05:55:22 +02:00
|
|
|
* <b>Search</b>
|
|
|
|
*
|
2008-08-09 08:40:50 +02:00
|
|
|
* You can trigger searches based on the fields specified on {@link DataObject::searchable_fields} and passed
|
|
|
|
* through {@link DataObject::getDefaultSearchContext()}. Just add a key-value pair with the search-term
|
2008-09-22 18:05:16 +02:00
|
|
|
* to the url, e.g. /api/v1/(ClassName)/?Title=mytitle.
|
2008-08-09 08:40:50 +02:00
|
|
|
*
|
2010-10-15 05:55:22 +02:00
|
|
|
* <b>Other url-modifiers</b>
|
|
|
|
*
|
2008-08-09 08:40:50 +02:00
|
|
|
* - &limit=<numeric>: Limit the result set
|
|
|
|
* - &relationdepth=<numeric>: Displays links to existing has-one and has-many relationships to a certain depth (Default: 1)
|
2008-09-22 18:05:16 +02:00
|
|
|
* - &fields=<string>: Comma-separated list of fields on the output object (defaults to all database-columns).
|
|
|
|
* Handy to limit output for bandwidth and performance reasons.
|
|
|
|
* - &sort=<myfield>&dir=<asc|desc>
|
|
|
|
* - &add_fields=<string>: Comma-separated list of additional fields, for example dynamic getters.
|
2010-10-15 05:55:22 +02:00
|
|
|
*
|
|
|
|
* <b>Access control</b>
|
2008-09-22 18:05:16 +02:00
|
|
|
*
|
|
|
|
* Access control is implemented through the usual Member system with Basicauth authentication only.
|
|
|
|
* By default, you have to bear the ADMIN permission to retrieve or send any data.
|
|
|
|
*
|
|
|
|
* You should override the following built-in methods to customize permission control on a
|
|
|
|
* class- and object-level:
|
|
|
|
* - {@link DataObject::canView()}
|
|
|
|
* - {@link DataObject::canEdit()}
|
|
|
|
* - {@link DataObject::canDelete()}
|
|
|
|
* - {@link DataObject::canCreate()}
|
|
|
|
* See {@link DataObject} documentation for further details.
|
2008-08-09 08:40:50 +02:00
|
|
|
*
|
2008-10-16 19:35:27 +02:00
|
|
|
* You can specify the character-encoding for any input on the HTTP Content-Type.
|
|
|
|
* At the moment, only UTF-8 is supported. All output is made in UTF-8 regardless of Accept headers.
|
|
|
|
*
|
2008-08-09 08:40:50 +02:00
|
|
|
* @todo Finish RestfulServer_Item and RestfulServer_List implementation and re-enable $url_handlers
|
2008-08-09 09:03:24 +02:00
|
|
|
* @todo Implement PUT/POST/DELETE for relations
|
2008-09-22 18:05:16 +02:00
|
|
|
* @todo Access-Control for relations (you might be allowed to view Members and Groups, but not their relation with each other)
|
2008-08-09 08:40:50 +02:00
|
|
|
* @todo Make SearchContext specification customizeable for each class
|
|
|
|
* @todo Allow for range-searches (e.g. on Created column)
|
2008-08-09 09:03:24 +02:00
|
|
|
* @todo Allow other authentication methods (currently only HTTP BasicAuth)
|
2008-08-11 01:29:30 +02:00
|
|
|
* @todo Filter relation listings by $api_access and canView() permissions
|
|
|
|
* @todo Exclude relations when "fields" are specified through URL (they should be explicitly requested in this case)
|
|
|
|
* @todo Custom filters per DataObject subclass, e.g. to disallow showing unpublished pages in SiteTree/Versioned/Hierarchy
|
|
|
|
* @todo URL parameter namespacing for search-fields, limit, fields, add_fields (might all be valid dataobject properties)
|
|
|
|
* e.g. you wouldn't be able to search for a "limit" property on your subclass as its overlayed with the search logic
|
|
|
|
* @todo i18n integration (e.g. Page/1.xml?lang=de_DE)
|
2011-04-15 11:35:30 +02:00
|
|
|
* @todo Access to extendable methods/relations like SiteTree/1/Versions or SiteTree/1/Version/22
|
2008-10-15 18:18:17 +02:00
|
|
|
* @todo Respect $api_access array notation in search contexts
|
2010-04-23 02:11:41 +02:00
|
|
|
*
|
|
|
|
* @package sapphire
|
|
|
|
* @subpackage api
|
2008-03-31 01:18:04 +02:00
|
|
|
*/
|
|
|
|
class RestfulServer extends Controller {
|
2008-08-09 05:19:54 +02:00
|
|
|
static $url_handlers = array(
|
2008-08-09 05:29:30 +02:00
|
|
|
'$ClassName/$ID/$Relation' => 'handleAction'
|
|
|
|
#'$ClassName/#ID' => 'handleItem',
|
|
|
|
#'$ClassName' => 'handleList',
|
2008-08-09 05:19:54 +02:00
|
|
|
);
|
|
|
|
|
2008-03-31 01:18:04 +02:00
|
|
|
protected static $api_base = "api/v1/";
|
2008-08-09 05:19:54 +02:00
|
|
|
|
2008-08-09 08:53:26 +02:00
|
|
|
/**
|
|
|
|
* If no extension is given in the request, resolve to this extension
|
|
|
|
* (and subsequently the {@link self::$default_mimetype}.
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
2008-08-09 09:03:24 +02:00
|
|
|
public static $default_extension = "xml";
|
2008-08-09 08:53:26 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* If no extension is given, resolve the request to this mimetype.
|
|
|
|
*
|
|
|
|
* @var string
|
|
|
|
*/
|
|
|
|
protected static $default_mimetype = "text/xml";
|
|
|
|
|
2008-10-09 16:47:25 +02:00
|
|
|
/**
|
|
|
|
* @uses authenticate()
|
|
|
|
* @var Member
|
|
|
|
*/
|
|
|
|
protected $member;
|
|
|
|
|
2011-02-13 23:14:51 +01:00
|
|
|
static $allowed_actions = array(
|
|
|
|
'index'
|
|
|
|
);
|
|
|
|
|
2008-08-09 05:29:30 +02:00
|
|
|
/*
|
|
|
|
function handleItem($request) {
|
|
|
|
return new RestfulServer_Item(DataObject::get_by_id($request->param("ClassName"), $request->param("ID")));
|
2008-08-09 05:19:54 +02:00
|
|
|
}
|
|
|
|
|
2008-08-09 05:29:30 +02:00
|
|
|
function handleList($request) {
|
|
|
|
return new RestfulServer_List(DataObject::get($request->param("ClassName"),""));
|
2008-08-09 05:19:54 +02:00
|
|
|
}
|
2008-08-09 05:29:30 +02:00
|
|
|
*/
|
2008-03-31 01:18:04 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* This handler acts as the switchboard for the controller.
|
|
|
|
* Since no $Action url-param is set, all requests are sent here.
|
|
|
|
*/
|
|
|
|
function index() {
|
2008-08-09 04:00:40 +02:00
|
|
|
if(!isset($this->urlParams['ClassName'])) return $this->notFound();
|
2008-03-31 01:18:04 +02:00
|
|
|
$className = $this->urlParams['ClassName'];
|
2008-08-09 04:00:40 +02:00
|
|
|
$id = (isset($this->urlParams['ID'])) ? $this->urlParams['ID'] : null;
|
2008-08-09 04:16:46 +02:00
|
|
|
$relation = (isset($this->urlParams['Relation'])) ? $this->urlParams['Relation'] : null;
|
|
|
|
|
2009-02-02 00:49:53 +01:00
|
|
|
// Check input formats
|
|
|
|
if(!class_exists($className)) return $this->notFound();
|
|
|
|
if($id && !is_numeric($id)) return $this->notFound();
|
|
|
|
if($relation && !preg_match('/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/', $relation)) return $this->notFound();
|
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
// if api access is disabled, don't proceed
|
2008-10-15 18:18:17 +02:00
|
|
|
$apiAccess = singleton($className)->stat('api_access');
|
|
|
|
if(!$apiAccess) return $this->permissionFailure();
|
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
// authenticate through HTTP BasicAuth
|
2008-10-09 16:47:25 +02:00
|
|
|
$this->member = $this->authenticate();
|
2008-08-09 09:03:24 +02:00
|
|
|
|
|
|
|
// handle different HTTP verbs
|
2008-09-12 06:49:15 +02:00
|
|
|
if($this->request->isGET() || $this->request->isHEAD()) return $this->getHandler($className, $id, $relation);
|
2008-08-09 09:03:24 +02:00
|
|
|
if($this->request->isPOST()) return $this->postHandler($className, $id, $relation);
|
|
|
|
if($this->request->isPUT()) return $this->putHandler($className, $id, $relation);
|
|
|
|
if($this->request->isDELETE()) return $this->deleteHandler($className, $id, $relation);
|
|
|
|
|
|
|
|
// if no HTTP verb matches, return error
|
|
|
|
return $this->methodNotAllowed();
|
2008-03-31 01:18:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handler for object read.
|
|
|
|
*
|
|
|
|
* The data object will be returned in the following format:
|
|
|
|
*
|
|
|
|
* <ClassName>
|
|
|
|
* <FieldName>Value</FieldName>
|
|
|
|
* ...
|
|
|
|
* <HasOneRelName id="ForeignID" href="LinkToForeignRecordInAPI" />
|
|
|
|
* ...
|
|
|
|
* <HasManyRelName>
|
|
|
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
|
|
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
|
|
|
* </HasManyRelName>
|
|
|
|
* ...
|
|
|
|
* <ManyManyRelName>
|
|
|
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
|
|
|
* <ForeignClass id="ForeignID" href="LinkToForeignRecordInAPI" />
|
|
|
|
* </ManyManyRelName>
|
|
|
|
* </ClassName>
|
|
|
|
*
|
|
|
|
* Access is controlled by two variables:
|
|
|
|
*
|
|
|
|
* - static $api_access must be set. This enables the API on a class by class basis
|
|
|
|
* - $obj->canView() must return true. This lets you implement record-level security
|
2008-08-09 05:29:30 +02:00
|
|
|
*
|
2008-08-09 09:03:24 +02:00
|
|
|
* @todo Access checking
|
|
|
|
*
|
2008-08-09 05:29:30 +02:00
|
|
|
* @param String $className
|
|
|
|
* @param Int $id
|
|
|
|
* @param String $relation
|
|
|
|
* @return String The serialized representation of the requested object(s) - usually XML or JSON.
|
2008-03-31 01:18:04 +02:00
|
|
|
*/
|
2008-08-11 02:03:57 +02:00
|
|
|
protected function getHandler($className, $id, $relationName) {
|
2008-08-09 07:57:44 +02:00
|
|
|
$sort = array(
|
|
|
|
'sort' => $this->request->getVar('sort'),
|
|
|
|
'dir' => $this->request->getVar('dir')
|
|
|
|
);
|
|
|
|
$limit = array(
|
|
|
|
'start' => $this->request->getVar('start'),
|
|
|
|
'limit' => $this->request->getVar('limit')
|
|
|
|
);
|
2008-08-09 08:53:26 +02:00
|
|
|
|
2008-08-11 02:03:57 +02:00
|
|
|
$params = $this->request->getVars();
|
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
$responseFormatter = $this->getResponseDataFormatter($className);
|
2008-08-09 09:03:24 +02:00
|
|
|
if(!$responseFormatter) return $this->unsupportedMediaType();
|
|
|
|
|
2011-10-26 08:09:04 +02:00
|
|
|
// $obj can be either a DataObject or a SS_List,
|
2008-08-11 02:03:57 +02:00
|
|
|
// depending on the request
|
2008-08-09 04:16:46 +02:00
|
|
|
if($id) {
|
2008-08-11 02:03:57 +02:00
|
|
|
// Format: /api/v1/<MyClass>/<ID>
|
2011-03-21 09:41:18 +01:00
|
|
|
$obj = $this->getObjectQuery($className, $id, $params)->First();
|
2008-08-09 09:03:24 +02:00
|
|
|
if(!$obj) return $this->notFound();
|
|
|
|
if(!$obj->canView()) return $this->permissionFailure();
|
2008-08-11 01:29:30 +02:00
|
|
|
|
2008-08-11 02:03:57 +02:00
|
|
|
// Format: /api/v1/<MyClass>/<ID>/<Relation>
|
|
|
|
if($relationName) {
|
2011-03-21 09:41:18 +01:00
|
|
|
$obj = $this->getObjectRelationQuery($obj, $params, $sort, $limit, $relationName);
|
|
|
|
if(!$obj) return $this->notFound();
|
2011-11-13 13:54:29 +01:00
|
|
|
|
|
|
|
// TODO Avoid creating data formatter again for relation class (see above)
|
|
|
|
$responseFormatter = $this->getResponseDataFormatter($obj->dataClass());
|
2008-08-09 04:16:46 +02:00
|
|
|
}
|
|
|
|
|
2008-03-31 10:49:27 +02:00
|
|
|
} else {
|
2008-08-11 02:03:57 +02:00
|
|
|
// Format: /api/v1/<MyClass>
|
2011-03-21 09:41:18 +01:00
|
|
|
$obj = $this->getObjectsQuery($className, $params, $sort, $limit);
|
2008-08-09 04:16:46 +02:00
|
|
|
}
|
2008-08-09 08:40:50 +02:00
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
2008-09-16 14:10:58 +02:00
|
|
|
|
|
|
|
$rawFields = $this->request->getVar('fields');
|
|
|
|
$fields = $rawFields ? explode(',', $rawFields) : null;
|
2008-08-11 02:03:57 +02:00
|
|
|
|
2011-05-03 05:11:09 +02:00
|
|
|
if($obj instanceof SS_List) {
|
2011-03-21 09:41:18 +01:00
|
|
|
$responseFormatter->setTotalSize($obj->dataQuery()->query()->unlimitedRowCount());
|
2008-09-16 14:10:58 +02:00
|
|
|
return $responseFormatter->convertDataObjectSet($obj, $fields);
|
2008-09-12 06:49:15 +02:00
|
|
|
} else if(!$obj) {
|
|
|
|
$responseFormatter->setTotalSize(0);
|
2011-05-05 12:40:24 +02:00
|
|
|
return $responseFormatter->convertDataObjectSet(new ArrayList(), $fields);
|
2008-08-11 02:03:57 +02:00
|
|
|
} else {
|
2008-09-16 14:10:58 +02:00
|
|
|
return $responseFormatter->convertDataObject($obj, $fields);
|
2008-08-11 02:03:57 +02:00
|
|
|
}
|
2008-03-31 01:18:04 +02:00
|
|
|
}
|
2008-08-09 07:57:44 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Uses the default {@link SearchContext} specified through
|
|
|
|
* {@link DataObject::getDefaultSearchContext()} to augument
|
|
|
|
* an existing query object (mostly a component query from {@link DataObject})
|
|
|
|
* with search clauses.
|
|
|
|
*
|
|
|
|
* @todo Allow specifying of different searchcontext getters on model-by-model basis
|
|
|
|
*
|
|
|
|
* @param string $className
|
|
|
|
* @param array $params
|
2011-10-26 08:09:04 +02:00
|
|
|
* @return SS_List
|
2008-08-09 07:57:44 +02:00
|
|
|
*/
|
2008-08-11 02:03:57 +02:00
|
|
|
protected function getSearchQuery($className, $params = null, $sort = null, $limit = null, $existingQuery = null) {
|
2008-08-09 08:18:32 +02:00
|
|
|
if(singleton($className)->hasMethod('getRestfulSearchContext')) {
|
|
|
|
$searchContext = singleton($className)->{'getRestfulSearchContext'}();
|
|
|
|
} else {
|
|
|
|
$searchContext = singleton($className)->getDefaultSearchContext();
|
|
|
|
}
|
2011-11-13 13:54:29 +01:00
|
|
|
return $searchContext->getQuery($params, $sort, $limit, $existingQuery);
|
2008-08-09 07:57:44 +02:00
|
|
|
}
|
2008-08-11 02:03:57 +02:00
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
/**
|
|
|
|
* Returns a dataformatter instance based on the request
|
|
|
|
* extension or mimetype. Falls back to {@link self::$default_extension}.
|
|
|
|
*
|
|
|
|
* @param boolean $includeAcceptHeader Determines wether to inspect and prioritize any HTTP Accept headers
|
2011-11-13 13:54:29 +01:00
|
|
|
* @param String Classname of a DataObject
|
2008-08-09 09:03:24 +02:00
|
|
|
* @return DataFormatter
|
|
|
|
*/
|
2011-11-13 13:54:29 +01:00
|
|
|
protected function getDataFormatter($includeAcceptHeader = false, $className = null) {
|
2008-08-09 08:53:26 +02:00
|
|
|
$extension = $this->request->getExtension();
|
2008-10-16 19:35:27 +02:00
|
|
|
$contentTypeWithEncoding = $this->request->getHeader('Content-Type');
|
|
|
|
preg_match('/([^;]*)/',$contentTypeWithEncoding, $contentTypeMatches);
|
|
|
|
$contentType = $contentTypeMatches[0];
|
2008-08-09 09:03:24 +02:00
|
|
|
$accept = $this->request->getHeader('Accept');
|
2008-08-11 04:57:59 +02:00
|
|
|
$mimetypes = $this->request->getAcceptMimetypes();
|
2011-11-13 13:54:29 +01:00
|
|
|
if(!$className) $className = $this->urlParams['ClassName'];
|
2008-08-09 09:03:24 +02:00
|
|
|
|
|
|
|
// get formatter
|
|
|
|
if(!empty($extension)) {
|
|
|
|
$formatter = DataFormatter::for_extension($extension);
|
|
|
|
}elseif($includeAcceptHeader && !empty($accept) && $accept != '*/*') {
|
2008-08-11 04:57:59 +02:00
|
|
|
$formatter = DataFormatter::for_mimetypes($mimetypes);
|
2009-04-29 02:07:39 +02:00
|
|
|
if(!$formatter) $formatter = DataFormatter::for_extension(self::$default_extension);
|
2008-08-09 09:03:24 +02:00
|
|
|
} elseif(!empty($contentType)) {
|
|
|
|
$formatter = DataFormatter::for_mimetype($contentType);
|
|
|
|
} else {
|
|
|
|
$formatter = DataFormatter::for_extension(self::$default_extension);
|
|
|
|
}
|
2008-10-09 16:47:25 +02:00
|
|
|
|
|
|
|
if(!$formatter) return false;
|
2008-08-09 08:53:26 +02:00
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
// set custom fields
|
2008-08-11 00:49:59 +02:00
|
|
|
if($customAddFields = $this->request->getVar('add_fields')) $formatter->setCustomAddFields(explode(',',$customAddFields));
|
2008-08-09 08:53:26 +02:00
|
|
|
if($customFields = $this->request->getVar('fields')) $formatter->setCustomFields(explode(',',$customFields));
|
2011-11-13 13:54:29 +01:00
|
|
|
$formatter->setCustomRelations($this->getAllowedRelations($className));
|
2008-10-15 18:18:17 +02:00
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
$apiAccess = singleton($className)->stat('api_access');
|
2008-10-15 18:18:17 +02:00
|
|
|
if(is_array($apiAccess)) {
|
|
|
|
$formatter->setCustomAddFields(array_intersect((array)$formatter->getCustomAddFields(), (array)$apiAccess['view']));
|
|
|
|
if($formatter->getCustomFields()) {
|
|
|
|
$formatter->setCustomFields(array_intersect((array)$formatter->getCustomFields(), (array)$apiAccess['view']));
|
|
|
|
} else {
|
|
|
|
$formatter->setCustomFields((array)$apiAccess['view']);
|
|
|
|
}
|
|
|
|
if($formatter->getCustomRelations()) {
|
|
|
|
$formatter->setCustomRelations(array_intersect((array)$formatter->getCustomRelations(), (array)$apiAccess['view']));
|
|
|
|
} else {
|
|
|
|
$formatter->setCustomRelations((array)$apiAccess['view']);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
2008-08-09 09:03:24 +02:00
|
|
|
|
|
|
|
// set relation depth
|
2008-08-09 08:53:26 +02:00
|
|
|
$relationDepth = $this->request->getVar('relationdepth');
|
|
|
|
if(is_numeric($relationDepth)) $formatter->relationDepth = (int)$relationDepth;
|
|
|
|
|
|
|
|
return $formatter;
|
|
|
|
}
|
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
/**
|
|
|
|
* @param String Classname of a DataObject
|
|
|
|
* @return DataFormatter
|
|
|
|
*/
|
|
|
|
protected function getRequestDataFormatter($className = null) {
|
|
|
|
return $this->getDataFormatter(false, $className);
|
2008-08-09 09:03:24 +02:00
|
|
|
}
|
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
/**
|
|
|
|
* @param String Classname of a DataObject
|
|
|
|
* @return DataFormatter
|
|
|
|
*/
|
|
|
|
protected function getResponseDataFormatter($className = null) {
|
|
|
|
return $this->getDataFormatter(true, $className);
|
2008-08-09 09:03:24 +02:00
|
|
|
}
|
|
|
|
|
2008-03-31 01:18:04 +02:00
|
|
|
/**
|
|
|
|
* Handler for object delete
|
|
|
|
*/
|
|
|
|
protected function deleteHandler($className, $id) {
|
2008-08-09 09:03:24 +02:00
|
|
|
$obj = DataObject::get_by_id($className, $id);
|
|
|
|
if(!$obj) return $this->notFound();
|
|
|
|
if(!$obj->canDelete()) return $this->permissionFailure();
|
|
|
|
|
|
|
|
$obj->delete();
|
|
|
|
|
|
|
|
$this->getResponse()->setStatusCode(204); // No Content
|
|
|
|
return true;
|
2008-03-31 01:18:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Handler for object write
|
|
|
|
*/
|
|
|
|
protected function putHandler($className, $id) {
|
2008-08-09 09:03:24 +02:00
|
|
|
$obj = DataObject::get_by_id($className, $id);
|
|
|
|
if(!$obj) return $this->notFound();
|
|
|
|
if(!$obj->canEdit()) return $this->permissionFailure();
|
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
$reqFormatter = $this->getRequestDataFormatter($className);
|
2008-08-09 09:03:24 +02:00
|
|
|
if(!$reqFormatter) return $this->unsupportedMediaType();
|
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
$responseFormatter = $this->getResponseDataFormatter($className);
|
2008-08-09 09:03:24 +02:00
|
|
|
if(!$responseFormatter) return $this->unsupportedMediaType();
|
|
|
|
|
|
|
|
$obj = $this->updateDataObject($obj, $reqFormatter);
|
|
|
|
|
|
|
|
$this->getResponse()->setStatusCode(200); // Success
|
|
|
|
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
2010-10-19 02:32:18 +02:00
|
|
|
|
|
|
|
// Append the default extension for the output format to the Location header
|
|
|
|
// or else we'll use the default (XML)
|
|
|
|
$types = $responseFormatter->supportedExtensions();
|
|
|
|
$type = '';
|
|
|
|
if (count($types)) {
|
|
|
|
$type = ".{$types[0]}";
|
|
|
|
}
|
|
|
|
|
|
|
|
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
|
2008-08-09 09:03:24 +02:00
|
|
|
$this->getResponse()->addHeader('Location', $objHref);
|
|
|
|
|
|
|
|
return $responseFormatter->convertDataObject($obj);
|
2008-03-31 01:18:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2008-08-09 09:03:24 +02:00
|
|
|
* Handler for object append / method call.
|
|
|
|
*
|
|
|
|
* @todo Posting to an existing URL (without a relation)
|
|
|
|
* current resolves in creatig a new element,
|
|
|
|
* rather than a "Conflict" message.
|
2008-03-31 01:18:04 +02:00
|
|
|
*/
|
2009-04-29 01:40:35 +02:00
|
|
|
protected function postHandler($className, $id, $relation) {
|
2008-10-16 19:35:27 +02:00
|
|
|
if($id) {
|
2009-04-29 01:40:35 +02:00
|
|
|
if(!$relation) {
|
|
|
|
$this->response->setStatusCode(409);
|
|
|
|
return 'Conflict';
|
|
|
|
}
|
|
|
|
|
|
|
|
$obj = DataObject::get_by_id($className, $id);
|
|
|
|
if(!$obj) return $this->notFound();
|
|
|
|
|
|
|
|
if(!$obj->hasMethod($relation)) {
|
|
|
|
return $this->notFound();
|
|
|
|
}
|
|
|
|
|
|
|
|
if(!$obj->stat('allowed_actions') || !in_array($relation, $obj->stat('allowed_actions'))) {
|
|
|
|
return $this->permissionFailure();
|
|
|
|
}
|
|
|
|
|
|
|
|
$obj->$relation();
|
|
|
|
|
|
|
|
$this->getResponse()->setStatusCode(204); // No Content
|
|
|
|
return true;
|
|
|
|
} else {
|
|
|
|
if(!singleton($className)->canCreate()) return $this->permissionFailure();
|
|
|
|
$obj = new $className();
|
2008-08-09 09:03:24 +02:00
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
$reqFormatter = $this->getRequestDataFormatter($className);
|
2009-04-29 01:40:35 +02:00
|
|
|
if(!$reqFormatter) return $this->unsupportedMediaType();
|
2008-08-09 09:03:24 +02:00
|
|
|
|
2011-11-13 13:54:29 +01:00
|
|
|
$responseFormatter = $this->getResponseDataFormatter($className);
|
2008-08-09 09:03:24 +02:00
|
|
|
|
2009-04-29 01:40:35 +02:00
|
|
|
$obj = $this->updateDataObject($obj, $reqFormatter);
|
2008-08-09 09:03:24 +02:00
|
|
|
|
2009-04-29 01:40:35 +02:00
|
|
|
$this->getResponse()->setStatusCode(201); // Created
|
|
|
|
$this->getResponse()->addHeader('Content-Type', $responseFormatter->getOutputContentType());
|
2010-10-19 02:32:18 +02:00
|
|
|
|
|
|
|
// Append the default extension for the output format to the Location header
|
|
|
|
// or else we'll use the default (XML)
|
|
|
|
$types = $responseFormatter->supportedExtensions();
|
|
|
|
$type = '';
|
|
|
|
if (count($types)) {
|
|
|
|
$type = ".{$types[0]}";
|
|
|
|
}
|
|
|
|
|
|
|
|
$objHref = Director::absoluteURL(self::$api_base . "$obj->class/$obj->ID" . $type);
|
2009-04-29 01:40:35 +02:00
|
|
|
$this->getResponse()->addHeader('Location', $objHref);
|
2008-08-09 09:03:24 +02:00
|
|
|
|
2009-04-29 01:40:35 +02:00
|
|
|
return $responseFormatter->convertDataObject($obj);
|
|
|
|
}
|
2008-03-31 01:18:04 +02:00
|
|
|
}
|
2008-08-09 09:03:24 +02:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Converts either the given HTTP Body into an array
|
|
|
|
* (based on the DataFormatter instance), or returns
|
|
|
|
* the POST variables.
|
|
|
|
* Automatically filters out certain critical fields
|
|
|
|
* that shouldn't be set by the client (e.g. ID).
|
|
|
|
*
|
|
|
|
* @param DataObject $obj
|
|
|
|
* @param DataFormatter $formatter
|
|
|
|
* @return DataObject The passed object
|
|
|
|
*/
|
|
|
|
protected function updateDataObject($obj, $formatter) {
|
|
|
|
// if neither an http body nor POST data is present, return error
|
|
|
|
$body = $this->request->getBody();
|
|
|
|
if(!$body && !$this->request->postVars()) {
|
|
|
|
$this->getResponse()->setStatusCode(204); // No Content
|
|
|
|
return 'No Content';
|
|
|
|
}
|
|
|
|
|
|
|
|
if(!empty($body)) {
|
|
|
|
$data = $formatter->convertStringToArray($body);
|
|
|
|
} else {
|
|
|
|
// assume application/x-www-form-urlencoded which is automatically parsed by PHP
|
|
|
|
$data = $this->request->postVars();
|
|
|
|
}
|
|
|
|
|
|
|
|
// @todo Disallow editing of certain keys in database
|
|
|
|
$data = array_diff_key($data, array('ID','Created'));
|
|
|
|
|
2008-10-15 18:18:17 +02:00
|
|
|
$apiAccess = singleton($this->urlParams['ClassName'])->stat('api_access');
|
|
|
|
if(is_array($apiAccess) && isset($apiAccess['edit'])) {
|
|
|
|
$data = array_intersect_key($data, array_combine($apiAccess['edit'],$apiAccess['edit']));
|
|
|
|
}
|
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
$obj->update($data);
|
|
|
|
$obj->write();
|
|
|
|
|
|
|
|
return $obj;
|
|
|
|
}
|
|
|
|
|
2008-08-11 02:03:57 +02:00
|
|
|
/**
|
|
|
|
* Gets a single DataObject by ID,
|
|
|
|
* through a request like /api/v1/<MyClass>/<MyID>
|
|
|
|
*
|
|
|
|
* @param string $className
|
|
|
|
* @param int $id
|
|
|
|
* @param array $params
|
2011-03-21 09:41:18 +01:00
|
|
|
* @return DataList
|
2008-08-11 02:03:57 +02:00
|
|
|
*/
|
|
|
|
protected function getObjectQuery($className, $id, $params) {
|
2011-03-21 09:41:18 +01:00
|
|
|
return DataList::create($className)->byIDs(array($id));
|
2008-08-11 02:03:57 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param DataObject $obj
|
|
|
|
* @param array $params
|
|
|
|
* @param int|array $sort
|
|
|
|
* @param int|array $limit
|
|
|
|
* @return SQLQuery
|
|
|
|
*/
|
|
|
|
protected function getObjectsQuery($className, $params, $sort, $limit) {
|
|
|
|
return $this->getSearchQuery($className, $params, $sort, $limit);
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @param DataObject $obj
|
|
|
|
* @param array $params
|
|
|
|
* @param int|array $sort
|
|
|
|
* @param int|array $limit
|
|
|
|
* @param string $relationName
|
|
|
|
* @return SQLQuery|boolean
|
|
|
|
*/
|
|
|
|
protected function getObjectRelationQuery($obj, $params, $sort, $limit, $relationName) {
|
2011-11-13 13:52:07 +01:00
|
|
|
// The relation method will return a DataList, that getSearchQuery subsequently manipulates
|
2011-03-21 09:41:18 +01:00
|
|
|
if($obj->hasMethod($relationName)) {
|
2011-11-13 13:54:29 +01:00
|
|
|
if($relationClass = $obj->has_one($relationName)) {
|
|
|
|
$joinField = $relationName . 'ID';
|
|
|
|
$list = DataList::create($relationClass)->byIDs(array($obj->$joinField));
|
|
|
|
} else {
|
|
|
|
$list = $obj->$relationName();
|
|
|
|
}
|
|
|
|
|
|
|
|
$apiAccess = singleton($list->dataClass())->stat('api_access');
|
|
|
|
if(!$apiAccess) return false;
|
|
|
|
|
|
|
|
return $this->getSearchQuery($list->dataClass(), $params, $sort, $limit, $list);
|
2011-11-13 13:52:07 +01:00
|
|
|
}
|
2008-08-11 02:03:57 +02:00
|
|
|
}
|
|
|
|
|
2008-03-31 01:18:04 +02:00
|
|
|
protected function permissionFailure() {
|
|
|
|
// return a 401
|
2009-03-30 05:12:58 +02:00
|
|
|
$this->getResponse()->setStatusCode(401);
|
|
|
|
$this->getResponse()->addHeader('WWW-Authenticate', 'Basic realm="API Access"');
|
2010-12-09 09:40:28 +01:00
|
|
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
2008-03-31 01:18:04 +02:00
|
|
|
return "You don't have access to this item through the API.";
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function notFound() {
|
|
|
|
// return a 404
|
|
|
|
$this->getResponse()->setStatusCode(404);
|
2010-12-09 09:40:28 +01:00
|
|
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
2008-03-31 01:18:04 +02:00
|
|
|
return "That object wasn't found";
|
|
|
|
}
|
|
|
|
|
2008-08-09 09:03:24 +02:00
|
|
|
protected function methodNotAllowed() {
|
|
|
|
$this->getResponse()->setStatusCode(405);
|
2010-12-09 09:40:28 +01:00
|
|
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
2008-08-09 09:03:24 +02:00
|
|
|
return "Method Not Allowed";
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function unsupportedMediaType() {
|
|
|
|
$this->response->setStatusCode(415); // Unsupported Media Type
|
2010-12-09 09:40:28 +01:00
|
|
|
$this->getResponse()->addHeader('Content-Type', 'text/plain');
|
2008-08-09 09:03:24 +02:00
|
|
|
return "Unsupported Media Type";
|
|
|
|
}
|
|
|
|
|
|
|
|
protected function authenticate() {
|
|
|
|
if(!isset($_SERVER['PHP_AUTH_USER']) || !isset($_SERVER['PHP_AUTH_PW'])) return false;
|
|
|
|
|
2011-03-18 23:17:57 +01:00
|
|
|
if($member = Member::currentUser()) return $member;
|
2008-08-09 09:03:24 +02:00
|
|
|
$member = MemberAuthenticator::authenticate(array(
|
|
|
|
'Email' => $_SERVER['PHP_AUTH_USER'],
|
|
|
|
'Password' => $_SERVER['PHP_AUTH_PW'],
|
|
|
|
), null);
|
|
|
|
|
|
|
|
if($member) {
|
|
|
|
$member->LogIn(false);
|
|
|
|
return $member;
|
|
|
|
} else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2008-10-09 16:47:25 +02:00
|
|
|
/**
|
|
|
|
* Return only relations which have $api_access enabled.
|
|
|
|
* @todo Respect field level permissions once they are available in core
|
|
|
|
*
|
|
|
|
* @param string $class
|
|
|
|
* @param Member $member
|
|
|
|
* @return array
|
|
|
|
*/
|
|
|
|
protected function getAllowedRelations($class, $member = null) {
|
|
|
|
$allowedRelations = array();
|
|
|
|
$obj = singleton($class);
|
|
|
|
$relations = (array)$obj->has_one() + (array)$obj->has_many() + (array)$obj->many_many();
|
|
|
|
if($relations) foreach($relations as $relName => $relClass) {
|
|
|
|
if(singleton($relClass)->stat('api_access')) {
|
|
|
|
$allowedRelations[] = $relName;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return $allowedRelations;
|
|
|
|
}
|
|
|
|
|
2008-08-09 05:19:54 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2011-10-26 08:09:04 +02:00
|
|
|
* Restful server handler for a SS_List
|
2010-04-23 02:11:41 +02:00
|
|
|
*
|
|
|
|
* @package sapphire
|
|
|
|
* @subpackage api
|
2008-08-09 05:19:54 +02:00
|
|
|
*/
|
|
|
|
class RestfulServer_List {
|
|
|
|
static $url_handlers = array(
|
|
|
|
'#ID' => 'handleItem',
|
|
|
|
);
|
|
|
|
|
|
|
|
function __construct($list) {
|
|
|
|
$this->list = $list;
|
|
|
|
}
|
|
|
|
|
2008-08-09 05:29:30 +02:00
|
|
|
function handleItem($request) {
|
|
|
|
return new RestulServer_Item($this->list->getById($request->param('ID')));
|
2008-08-09 05:19:54 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Restful server handler for a single DataObject
|
2010-04-23 02:11:41 +02:00
|
|
|
*
|
|
|
|
* @package sapphire
|
|
|
|
* @subpackage api
|
2008-08-09 05:19:54 +02:00
|
|
|
*/
|
|
|
|
class RestfulServer_Item {
|
|
|
|
static $url_handlers = array(
|
|
|
|
'$Relation' => 'handleRelation',
|
|
|
|
);
|
|
|
|
|
|
|
|
function __construct($item) {
|
|
|
|
$this->item = $item;
|
|
|
|
}
|
|
|
|
|
2008-08-09 05:29:30 +02:00
|
|
|
function handleRelation($request) {
|
|
|
|
$funcName = $request('Relation');
|
2008-08-09 05:19:54 +02:00
|
|
|
$relation = $this->item->$funcName();
|
|
|
|
|
2011-10-26 08:09:04 +02:00
|
|
|
if($relation instanceof SS_List) return new RestfulServer_List($relation);
|
2008-08-09 05:29:30 +02:00
|
|
|
else return new RestfulServer_Item($relation);
|
2008-08-09 05:19:54 +02:00
|
|
|
}
|
|
|
|
}
|