[-] WS : Move classes to /webservice

git-svn-id: http://dev.prestashop.com/svn/v1/branches/1.5.x@8767 b9a71923-0436-4b27-9f14-aed3839534dd
This commit is contained in:
aKorczak
2011-09-26 12:27:25 +00:00
parent 12942dd4a8
commit 7d2e172321
9 changed files with 0 additions and 0 deletions
+87
View File
@@ -0,0 +1,87 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 6844 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @author Lucas Cherifi - Nans Pellicari - Anatole Korczak - PrestaShop Team
*/
class WebserviceExceptionCore extends Exception
{
protected $status;
protected $wrong_value;
protected $available_values;
protected $type;
const SIMPLE = 0;
const DID_YOU_MEAN = 1;
public function __construct($message, $code)
{
$exception_code = $code;
if (is_array($code))
{
$exception_code = $code[0];
$this->setStatus($code[1]);
}
parent::__construct($message, $exception_code);
$this->type = self::SIMPLE;
}
public function getType()
{
return $this->type;
}
public function setType($type)
{
$this->type = $type;
return $this;
}
public function setStatus($status)
{
if (Validate::isInt($status))
$this->status = $status;
return $this;
}
public function getStatus()
{
return $this->status;
}
public function getWrongValue()
{
return $this->wrong_value;
}
public function setDidYouMean($wrong_value, $available_values)
{
$this->type = self::DID_YOU_MEAN;
$this->wrong_value = $wrong_value;
$this->available_values = $available_values;
return $this;
}
public function getAvailableValues()
{
return $this->available_values;
}
}
+169
View File
@@ -0,0 +1,169 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 6844 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class WebserviceKeyCore extends ObjectModel
{
/** @var string Key */
public $key;
/** @var boolean Webservice Account statuts */
public $active = true;
/** @var string Webservice Account description */
public $description;
protected $fieldsRequired = array('key');
protected $fieldsSize = array('key' => 32);
protected $fieldsValidate = array('active' => 'isBool');
protected $table = 'webservice_account';
protected $identifier = 'id_webservice_account';
public function add($autodate = true, $nullValues = false)
{
if (WebserviceKey::keyExists($this->key))
return false;
return parent::add($autodate = true, $nullValues = false);
}
static public function keyExists($key)
{
return (!Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT `key`
FROM '._DB_PREFIX_.'webservice_account
WHERE `key` = \''.pSQL($key).'\'') ? false : true);
}
public function getFields()
{
$this->validateFields();
$fields['key'] = pSQL($this->key);
$fields['active'] = (int)($this->active);
$fields['description'] = pSQL($this->description);
return $fields;
}
public function delete()
{
if (!parent::delete() OR $this->deleteAssociations() === false)
return false;
return true;
}
public function deleteAssociations()
{
if (
Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'webservice_permission`
WHERE `id_webservice_account` = '.(int)($this->id)) === false
||
Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'webservice_permission`
WHERE `id_webservice_account` = '.(int)($this->id)) === false
)
return false;
return true;
}
public static function getPermissionForAccount($auth_key)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.*
FROM `'._DB_PREFIX_.'webservice_permission` p
LEFT JOIN `'._DB_PREFIX_.'webservice_account` a ON (a.id_webservice_account = p.id_webservice_account)
WHERE a.key = \''.pSQL($auth_key).'\'
');
$permissions = array();
if ($result)
foreach ($result as $row)
$permissions[$row['resource']][] = $row['method'];
return $permissions;
}
public static function isKeyActive($auth_key)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT a.active
FROM `'._DB_PREFIX_.'webservice_account` a
WHERE a.key = \''.pSQL($auth_key).'\'
');
if (!isset($result[0]))
return null;
else
{
return isset($result[0]['active']) && $result[0]['active'];
}
}
public static function getClassFromKey($auth_key)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT a.class_name as class
FROM `'._DB_PREFIX_.'webservice_account` a
WHERE a.key = \''.pSQL($auth_key).'\'
');
if (!isset($result[0]))
return null;
else
{
return $result[0]['class'];
}
}
public static function setPermissionForAccount($idAccount, $permissionsToSet)
{
$ok = true;
$sql = 'DELETE FROM `'._DB_PREFIX_.'webservice_permission` WHERE `id_webservice_account` = '.(int)($idAccount);
if(!Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql))
$ok = false;
if (isset($permissionsToSet))
{
$permissions = array();
$resources = WebserviceRequest::getResources();
$methods = array('GET', 'PUT', 'POST', 'DELETE', 'HEAD');
foreach ($permissionsToSet as $resourceName => $resource_methods)
if (in_array($resourceName, array_keys($resources)))
foreach (array_keys($resource_methods) as $methodName)
if (in_array($methodName, $methods))
$permissions[] = array($methodName, $resourceName);
$account = new WebserviceKey($idAccount);
if ($account->deleteAssociations() && $permissions)
{
$sql = 'INSERT INTO `'._DB_PREFIX_.'webservice_permission` (`id_webservice_permission` ,`resource` ,`method` ,`id_webservice_account`) VALUES ';
foreach ($permissions as $permission)
$sql .= '(NULL , \''.pSQL($permission[1]).'\', \''.pSQL($permission[0]).'\', '.(int)($idAccount).'), ';
$sql = rtrim($sql, ', ');
if(!Db::getInstance(_PS_USE_SQL_SLAVE_)->Execute($sql))
$ok = false;
}
}
return $ok;
}
}
+764
View File
@@ -0,0 +1,764 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 7040 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @todo : Create typed exception for more finer errors check
* @author Lucas Cherifi - Nans Pellicari - Anatole Korczak - PrestaShop Team
*/
class WebserviceOutputBuilderCore
{
/**
*
* @var int constant
*/
const VIEW_LIST = 1;
const VIEW_DETAILS = 2;
protected $wsUrl;
protected $output;
public $objectRender;
protected $wsResource;
protected $depth = 0;
protected $schemaToDisplay;
protected $fieldsToDisplay;
protected $specificFields = array();
protected $virtualFields = array();
// Header properties
protected $headerParams = array(
'Access-Time' => 0,
'X-Powered-By' => 0,
'PSWS-Version' => 0,
'Content-Type' => 0,
);
/**
* @var string Status header sent at return
*/
protected $status;
public function __construct($ws_url)
{
$this->status = $_SERVER['SERVER_PROTOCOL'].' 200 OK';
$this->wsUrl = $ws_url;
}
/**
* Set the render object for set the output format.
* Set the Content-type for the http header.
*
* @param WebserviceOutputInterface $obj_render
* @throw WebserviceException if the object render is not an instance of WebserviceOutputInterface
* @return $this
*/
public function setObjectRender(WebserviceOutputInterface $obj_render)
{
if (!$obj_render instanceof WebserviceOutputInterface)
throw new WebserviceException('Obj_render param must be an WebserviceOutputInterface object type', array(83, 500));
$this->objectRender = $obj_render;
$this->objectRender->setWsUrl($this->wsUrl);
if ($this->objectRender->getContentType())
$this->setHeaderParams('Content-Type', $this->objectRender->getContentType());
return $this;
}
/**
* getter
* @return WebserviceOutputInterface
*/
public function getObjectRender()
{
return $this->objectRender;
}
/**
* Need to have the resource list to get the class name for an entity,
* To build
*
* @param array $resources
* @return $this
*/
public function setWsResources($resources)
{
$this->wsResource = $resources;
return $this;
}
/**
* This method return an array with each http header params for a content.
* This check each required params.
*
* If this method is overrided don't forget to check required specific params (for xml etc...)
*
* @return array
*/
public function buildHeader()
{
$return = array();
$return[] = $this->status;
foreach ($this->headerParams as $key => $param)
{
$return[] = trim($key).': '.$param;
}
return $return;
}
/**
* @param $key The normalized key expected for an http response
* @param $value
* @throw WebserviceException if the key or the value are corrupted
* (use Validate::isCleanHtml method)
* @return $this
*/
public function setHeaderParams($key, $value)
{
if (!Validate::isCleanHtml($key) OR !Validate::isCleanHtml($value))
throw new WebserviceException('the key or your value is corrupted.', array(94, 500));
$this->headerParams[$key] = $value;
return $this;
}
/**
* @param null|string $key if null get all header params otherwise the params specified by the key
* @throw WebserviceException if the key is corrupted (use Validate::isCleanHtml method)
* @throw WebserviceException if the asked key does'nt exists.
* @return array|string
*/
public function getHeaderParams($key = null)
{
$return = '';
if (!is_null($key))
{
if (!is_null($key) && Validate::isCleanHtml($key))
throw new WebserviceException('the key you write is a corrupted text.', array(95, 500));
if (!array_key_exists($key, $this->headerParams))
throw new WebserviceException(sprintf('The key %s does\'nt exist', $key), array(96, 500));
$return = $this->headerParams[$key];
}
else
$return = $this->headerParams;
return $return;
}
/**
* Delete all Header parameters previously set.
*
* @return $this
*/
public function resetHeaderParams()
{
$this->headerParams = array();
return $this;
}
/**
* @return string the normalized status for http request
*/
public function getStatus()
{
return $this->status;
}
/**
* Set the return header status
*
* @param int $num the Http status code
* @return void
*/
public function setStatus($num)
{
switch ($num)
{
case 200 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 200 OK';
break;
case 201 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 201 Created';
break;
case 204 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 204 No Content';
break;
case 304 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 304 Not Modified';
break;
case 400 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 400 Bad Request';
break;
case 401 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 401 Unauthorized';
break;
case 403 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 403 Forbidden';
break;
case 404 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 404 Not Found';
break;
case 405 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 405 Method Not Allowed';
break;
case 500 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 500 Internal Server Error';
break;
case 501 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 501 Not Implemented';
break;
case 503 :
$this->status = $_SERVER['SERVER_PROTOCOL'].' 503 Service Unavailable';
break;
}
}
/**
* Build errors output using an error array
*
* @param array $errors
* @return string output in the format specified by WebserviceOutputBuilder::objectRender
*/
public function getErrors($errors)
{
if (!empty($errors))
{
if (isset($this->objectRender))
{
$str_output = $this->objectRender->renderErrorsHeader();
foreach ($errors as $error)
{
if (is_array($error))
$str_output .= $this->objectRender->renderErrors($error[1], $error[0]);
else
$str_output .= $this->objectRender->renderErrors($error);
}
$str_output .= $this->objectRender->renderErrorsFooter();
$str_output = $this->objectRender->overrideContent($str_output);
}
else
{
$str_output = '<pre>'.print_r($errors, true).'</pre>';
}
}
return $str_output;
}
/**
* Build the resource list in the output format specified by WebserviceOutputBuilder::objectRender
* @param $key_permissions
* @return string
*/
public function getResourcesList($key_permissions)
{
if (is_null($this->wsResource))
throw new WebserviceException ('You must set web service resource for get the resources list.', array(82, 500));
$output = '';
$more_attr = array('shop_name' => Configuration::get('PS_SHOP_NAME'));
$output .= $this->objectRender->renderNodeHeader('api', array(), $more_attr);
foreach ($this->wsResource as $resourceName => $resource)
{
if (in_array($resourceName, array_keys($key_permissions)))
{
$more_attr = array(
'xlink_resource' => $this->wsUrl.$resourceName,
'get' => (in_array('GET', $key_permissions[$resourceName]) ? 'true' : 'false'),
'put' => (in_array('PUT', $key_permissions[$resourceName]) ? 'true' : 'false'),
'post' => (in_array('POST', $key_permissions[$resourceName]) ? 'true' : 'false'),
'delete' => (in_array('DELETE', $key_permissions[$resourceName]) ? 'true' : 'false'),
'head' => (in_array('HEAD', $key_permissions[$resourceName]) ? 'true' : 'false'),
);
$output .= $this->objectRender->renderNodeHeader($resourceName, array(), $more_attr);
$output .= $this->objectRender->renderNodeHeader('description', array(), $more_attr);
$output .= $resource['description'];
$output .= $this->objectRender->renderNodeFooter('description', array());
if (!isset($resource['specific_management']) || !$resource['specific_management'])
{
$more_attr_schema = array(
'xlink_resource' => $this->wsUrl.$resourceName.'?schema=blank',
'type' => 'blank',
);
$output .= $this->objectRender->renderNodeHeader('schema', array(), $more_attr_schema, false);
$more_attr_schema = array(
'xlink_resource' => $this->wsUrl.$resourceName.'?schema=synopsis',
'type' => 'synopsis',
);
$output .= $this->objectRender->renderNodeHeader('schema', array(), $more_attr_schema, false);
}
$output .= $this->objectRender->renderNodeFooter($resourceName, array());
}
}
$output .= $this->objectRender->renderNodeFooter('api', array());
$output = $this->objectRender->overrideContent($output);
return $output;
}
/**
* Method is used for each content type
* Different content types are :
* - list of entities,
* - tree diagram of entity details (full or minimum),
* - schema (synopsis & blank),
*
* @param array $objects each object created by entity asked
* @see WebserviceOutputBuilder::executeEntityGetAndHead
* @param null|string $schema_to_display if null display the entities list or entity details.
* @param string|array $fields_to_display the fields allow for the output
* @param int $depth depth for the tree diagram output.
* @param int $type_of_view use the 2 constants WebserviceOutputBuilder::VIEW_LIST WebserviceOutputBuilder::VIEW_DETAILS
* @return string in the output format specified by WebserviceOutputBuilder::objectRender
*/
public function getContent($objects, $schema_to_display = null, $fields_to_display = 'minimum', $depth = 0, $type_of_view = self::VIEW_LIST, $override = true)
{
$this->fieldsToDisplay = $fields_to_display;
$this->depth = $depth;
$output = '';
if ($schema_to_display != null)
{
$this->schemaToDisplay = $schema_to_display;
$this->objectRender->setSchemaToDisplay($this->schemaToDisplay);
// If a shema is asked the view must be an details type
$type_of_view = self::VIEW_DETAILS;
}
$ws_params = $objects['empty']->getWebserviceParameters();
// If a list is asked, need to wrap with a plural node
if ($type_of_view === self::VIEW_LIST)
$output .= $this->setIndent($depth).$this->objectRender->renderNodeHeader($ws_params['objectsNodeName'], $ws_params);
if (is_null($this->schemaToDisplay))
{
foreach ($objects as $key => $object)
{
if ($key !== 'empty')
{
if ($this->fieldsToDisplay === 'minimum')
$output .= $this->renderEntityMinimum($object, $depth);
else
$output .= $this->renderEntity($object, $depth);
}
}
}
else
{
$output .= $this->renderSchema($objects['empty'], $ws_params);
}
// If a list is asked, need to wrap with a plural node
if ($type_of_view === self::VIEW_LIST)
$output .= $this->setIndent($depth).$this->objectRender->renderNodeFooter($ws_params['objectsNodeName'], $ws_params);
if ($override)
$output = $this->objectRender->overrideContent($output);
return $output;
}
/**
* Create the tree diagram with no details
*
* @param $object create by the entity
* @param $depth the depth for the tree diagram
* @return string
*/
public function renderEntityMinimum($object, $depth)
{
$ws_params = $object->getWebserviceParameters();
$more_attr['id'] = $object->id;
$more_attr['xlink_resource'] = $this->wsUrl.$ws_params['objectsNodeName'].'/'.$object->id;
$output = $this->setIndent($depth).$this->objectRender->renderNodeHeader($ws_params['objectNodeName'], $ws_params, $more_attr, false);
return $output;
}
/**
* Build a schema blank or synopsis
*
* @param $object create by the entity
* @param $ws_params webserviceParams from the entity
* @return string
*/
private function renderSchema($object, $ws_params)
{
$output = $this->objectRender->renderNodeHeader($ws_params['objectNodeName'], $ws_params);
foreach ($ws_params['fields'] as $field_name => $field)
{
$output .= $this->renderField($object, $ws_params, $field_name, $field, 0);
}
if (isset($ws_params['associations']) && count($ws_params['associations']) > 0)
{
$this->fieldsToDisplay = 'full';
$output .= $this->renderAssociations($object, 0, $ws_params['associations'], $ws_params);
}
$output .= $this->objectRender->renderNodeFooter($ws_params['objectNodeName'], $ws_params);
return $output;
}
/**
* Build the entity detail.
*
* @param ObjectModel $object create by the entity
* @param int $depth the depth for the tree diagram
* @return string
*/
public function renderEntity($object, $depth)
{
$output = '';
$ws_params = $object->getWebserviceParameters();
$output .= $this->setIndent($depth).$this->objectRender->renderNodeHeader($ws_params['objectNodeName'], $ws_params);
if ($object->id != 0)
{
// This to add virtual Fields for a particular entity.
$virtual_fields = $this->addVirtualFields($ws_params['objectsNodeName'], $object);
if (!empty($virtual_fields))
$ws_params['fields'] = array_merge($ws_params['fields'], $virtual_fields);
foreach ($ws_params['fields'] as $field_name => $field)
{
if ($this->fieldsToDisplay === 'full' || array_key_exists($field_name, $this->fieldsToDisplay))
{
$field['object_id'] = $object->id;
$field['entity_name'] = $ws_params['objectNodeName'];
$field['entities_name'] = $ws_params['objectsNodeName'];
$output .= $this->renderField($object, $ws_params, $field_name, $field, $depth);
}
}
}
$subexists = false;
if (is_array($this->fieldsToDisplay))
foreach ($this->fieldsToDisplay as $fields)
if (is_array($fields))
$subexists = true;
if (isset($ws_params['associations'])
&& ($this->fieldsToDisplay == 'full'
|| $subexists))
{
$output .= $this->renderAssociations($object, $depth, $ws_params['associations'], $ws_params);
}
$output .= $this->setIndent($depth).$this->objectRender->renderNodeFooter($ws_params['objectNodeName'], $ws_params);
return $output;
}
/**
* Build a field and use recursivity depend on the depth parameter.
*
* @param ObjectModel $object create by the entity
* @param array $ws_params webserviceParams from the entity
* @param string $field_name
* @param array $field
* @param int $depth
* @return string
*/
private function renderField($object, $ws_params, $field_name, $field, $depth)
{
$output = '';
$show_field = true;
if (isset($ws_params['hidden_fields']) && in_array($field_name, $ws_params['hidden_fields']))
return;
if ($this->schemaToDisplay === 'synopsis')
{
$field['synopsis_details'] = $this->getSynopsisDetails($field);
if ($field_name === 'id')
$show_field = false;
elseif (isset($field['setter']) && !$field['setter'])
$show_field = false;
}
// don't set any value for a schema
if (isset($field['synopsis_details']) || $this->schemaToDisplay === 'blank')
{
$field['value'] = '';
if (isset($field['xlink_resource']))
unset($field['xlink_resource']);
}
elseif (isset($field['getter']) && $object != null && method_exists($object, $field['getter']))
$field['value'] = $object->$field['getter']();
elseif (!isset($field['value']))
$field['value'] = $object->$field_name;
// this apply specific function for a particular field on a choosen entity
$field = $this->overrideSpecificField($ws_params['objectsNodeName'], $field_name, $field, $object, $ws_params);
// don't display informations for a not existant id
if (substr($field['sqlId'], 0, 3) == 'id_' && $field['value'] == 0)
{
$field['value'] = '';
// delete the xlink except for schemas
if (isset($field['xlink_resource']) && is_null($this->schemaToDisplay))
unset($field['xlink_resource']);
}
// set "id" for each node name which display the id of the entity
if ($field_name === 'id')
$field['sqlId'] = 'id';
// don't display the node id for a synopsis schema
if ($show_field)
$output .= $this->setIndent($depth-1).$this->objectRender->renderField($field);
return $output;
}
/**
*
*
* @param $object
* @param $depth
* @param $associations
* @param $ws_params
* @return string
*/
private function renderAssociations($object, $depth, $associations, $ws_params)
{
$output = $this->objectRender->renderAssociationWrapperHeader();
foreach ($associations as $assoc_name => $association)
{
if ($this->fieldsToDisplay == 'full' || is_array($this->fieldsToDisplay) && array_key_exists($assoc_name, $this->fieldsToDisplay))
{
$getter = $association['getter'];
$objects_assoc = array();
$fields_assoc = array();
if (isset($association['fields']))
$fields_assoc = $association['fields'];
$parent_details = array(
'object_id' => $object->id,
'entity_name' => $ws_params['objectNodeName'],
'entities_name' => $ws_params['objectsNodeName'],
);
if (method_exists($object, $getter) && is_null($this->schemaToDisplay))
{
$association_resources = $object->$getter();
if (is_array($association_resources) && !empty($association_resources))
{
foreach ($association_resources as $association_resource)
{
$objects_assoc[] = $association_resource;
}
}
}
else
{
$objects_assoc[] = '';
}
$class_name = null;
if (isset($this->wsResource[$assoc_name]['class']) && class_exists($this->wsResource[$assoc_name]['class'], true))
$class_name = $this->wsResource[$assoc_name]['class'];
$output_details = '';
foreach ($objects_assoc as $object_assoc)
{
if ($depth == 0 || $class_name === null)
{
$value = null;
if (!empty($object_assoc))
$value = $object_assoc;
if (empty($fields_assoc))
$fields_assoc = array(array('id' => $value['id']));
$output_details .= $this->renderFlatAssociation($object, $depth, $assoc_name, $association['resource'], $fields_assoc, $value, $parent_details);
}
else
{
foreach ($object_assoc as $id)
{
if ($class_name !== null)
{
$child_object = new $class_name($id);
$output_details .= $this->renderEntity($child_object, ($depth-2 ? 0 : $depth-2));
}
}
}
}
if ($output_details != '')
{
$output .= $this->setIndent($depth).$this->objectRender->renderAssociationHeader($object, $ws_params, $assoc_name);
$output .= $output_details;
$output .= $this->setIndent($depth).$this->objectRender->renderAssociationFooter($object, $ws_params, $assoc_name);
}
else
{
$output .= $this->setIndent($depth).$this->objectRender->renderAssociationHeader($object, $ws_params, $assoc_name, true);
}
}
}
$output .= $this->objectRender->renderAssociationWrapperFooter();
return $output;
}
private function renderFlatAssociation($object, $depth, $assoc_name, $resource_name, $fields_assoc, $object_assoc, $parent_details)
{
$output = '';
$more_attr = array();
if (isset($this->wsResource[$assoc_name]) && is_null($this->schemaToDisplay))
{
if ($assoc_name == 'images')
$more_attr['xlink_resource'] = $this->wsUrl.$assoc_name.'/'.$parent_details['entities_name'].'/'.$parent_details['object_id'].'/'.$object_assoc['id'];
else
$more_attr['xlink_resource'] = $this->wsUrl.$assoc_name.'/'.$object_assoc['id'];
}
$output .= $this->setIndent($depth-1).$this->objectRender->renderNodeHeader($resource_name, array(), $more_attr);
foreach ($fields_assoc as $field_name=>$field)
{
if (!is_array($this->fieldsToDisplay) || in_array($field_name, $this->fieldsToDisplay[$assoc_name]))
{
if ($field_name == 'id' && !isset($field['sqlId']))
{
$field['sqlId'] = 'id';
$field['value'] = $object_assoc['id'];
}
elseif (!isset($field['sqlId']))
{
$field['sqlId'] = $field_name;
$field['value'] = $object_assoc[$field_name];
}
$field['entities_name'] = $assoc_name;
$field['entity_name'] = $resource_name;
if (!is_null($this->schemaToDisplay))
$field['synopsis_details'] = $this->getSynopsisDetails($field);
$output .= $this->setIndent($depth-1).$this->objectRender->renderField($field);
}
}
$output .= $this->setIndent($depth-1).$this->objectRender->renderNodeFooter($resource_name, array());
return $output;
}
public function setIndent($depth)
{
$string = '';
$number_of_tabs = $this->depth - $depth;
for ($i = 0; $i < $number_of_tabs; $i++)
$string .= "\t";
return $string;
}
public function getSynopsisDetails($field)
{
$arr_details = '';
if (array_key_exists('required', $field) && $field['required'])
$arr_details['required'] = 'true';
if (array_key_exists('maxSize', $field) && $field['maxSize'])
$arr_details['maxSize'] = $field['maxSize'];
if (array_key_exists('validateMethod', $field) && $field['validateMethod'])
$arr_details['format'] = $field['validateMethod'];
return $arr_details;
}
/**
*
* @param string|object $object
* @param string $method
* @return $this
*/
public function setSpecificField($object, $method, $field_name, $entity_name)
{
try {
$this->validateObjectAndMethod($object, $method);
} catch (WebserviceException $e) {
throw $e;
}
$this->specificFields[$field_name] = array('entity'=>$entity_name, 'object' => $object, 'method' => $method, 'type' => gettype($object));
return $this;
}
private function validateObjectAndMethod($object, $method)
{
if (is_string($object) && !class_exists($object))
throw new WebserviceException ('The object you want to set in '.__METHOD__.' is not allowed.', array(98, 500));
if (!method_exists($object, $method))
throw new WebserviceException ('The method you want to set in '.__METHOD__.' is not allowed.', array(99, 500));
}
public function getSpecificField()
{
return $this->specificFields;
}
private function overrideSpecificField($entity_name, $field_name, $field, $entity_object, $ws_params)
{
if (array_key_exists($field_name, $this->specificFields) && $this->specificFields[$field_name]['entity'] == $entity_name)
{
if ($this->specificFields[$field_name]['type'] == 'string')
$object = new $this->specificFields[$field_name]['object']();
elseif ($this->specificFields[$field_name]['type'] == 'object')
$object= $this->specificFields[$field_name]['object'];
$field = $object->{$this->specificFields[$field_name]['method']}($field, $entity_object, $ws_params);
}
return $field;
}
public function setVirtualField($object, $method, $entity_name, $parameters)
{
try {
$this->validateObjectAndMethod($object, $method);
} catch (WebserviceException $e) {
throw $e;
}
$this->virtualFields[$entity_name][] = array('parameters' => $parameters, 'object' => $object, 'method' => $method, 'type' => gettype($object));
}
public function getVirtualFields()
{
return $this->virtualFields;
}
public function addVirtualFields($entity_name, $entity_object)
{
$arr_return = array();
$virtual_fields = $this->getVirtualFields();
if (array_key_exists($entity_name, $virtual_fields))
{
foreach ($virtual_fields[$entity_name] as $function_infos)
{
if ($function_infos['type'] == 'string')
$object = new $function_infos['object']();
elseif ($function_infos['type'] == 'object')
$object= $function_infos['object'];
$return_fields = $object->{$function_infos['method']}($entity_object, $function_infos['parameters']);
foreach ($return_fields as $field_name => $value)
{
if (Validate::isConfigName($field_name))
$arr_return[$field_name] = $value;
else
throw new WebserviceException('Name for the virtual field is not allow', array(128, 400));
}
}
}
return $arr_return;
}
public function setFieldsToDisplay($fields)
{
$this->fieldsToDisplay = $fields;
}
}
+49
View File
@@ -0,0 +1,49 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 6844 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @author Lucas Cherifi - Nans Pellicari - Anatole Korczak - PrestaShop Team
*/
interface WebserviceOutputInterface
{
public function __construct($languages = array());
public function setWsUrl($url);
public function getWsUrl();
public function getContentType();
public function setSchemaToDisplay($schema);
public function getSchemaToDisplay();
public function renderField($field);
public function renderNodeHeader($obj, $params ,$more_attr = null);
public function renderNodeFooter($obj, $params);
public function renderAssociationHeader($obj, $params, $assoc_name);
public function renderAssociationFooter($obj, $params, $assoc_name);
public function overrideContent($content);
public function renderErrorsHeader();
public function renderErrorsFooter();
public function renderErrors($message, $code = null);
}
+201
View File
@@ -0,0 +1,201 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 7040 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @author Lucas Cherifi - Nans Pellicari - Anatole Korczak - PrestaShop Team
*/
class WebserviceOutputXMLCore implements WebserviceOutputInterface
{
public $docUrl = '';
public $languages = array();
protected $wsUrl;
protected $schemaToDisplay;
public function setSchemaToDisplay($schema)
{
if (is_string($schema))
$this->schemaToDisplay = $schema;
return $this;
}
public function getSchemaToDisplay()
{
return $this->schemaToDisplay;
}
public function setWsUrl($url)
{
$this->wsUrl = $url;
return $this;
}
public function getWsUrl()
{
return $this->wsUrl;
}
public function getContentType()
{
return 'text/xml';
}
public function __construct($languages = array())
{
$this->languages = $languages;
}
public function setLanguages($languages)
{
$this->languages = $languages;
return $this;
}
public function renderErrorsHeader()
{
return '<errors>'."\n";
}
public function renderErrorsFooter()
{
return '</errors>'."\n";
}
public function renderErrors($message, $code = null)
{
$str_output = '<error>'."\n";
if ($code !== null)
$str_output .= '<code><![CDATA['.$code.']]></code>'."\n";
$str_output .= '<message><![CDATA['.$message.']]></message>'."\n";
$str_output .= '</error>'."\n";
return $str_output;
}
public function renderField($field)
{
$ret = '';
$node_content = '';
$ret .= '<'.$field['sqlId'];
// display i18n fields
if (isset($field['i18n']) && $field['i18n'])
{
foreach ($this->languages as $language)
{
$more_attr = '';
if (isset($field['synopsis_details']) || (isset($field['value']) AND is_array($field['value'])))
{
$more_attr .= ' xlink:href="'.$this->getWsUrl().'languages/'.$language.'"';
if (isset($field['synopsis_details']) && $this->schemaToDisplay != 'blank')
$more_attr .= ' format="isUnsignedId" ';
}
$node_content .= '<language id="'.$language.'"'.$more_attr.'>';
if (isset($field['value']) AND is_array($field['value']) AND isset($field['value'][$language]))
$node_content .= '<![CDATA['.$field['value'][$language].']]>';
$node_content .= '</language>'."";
}
}
// display not i18n fields value
else
{
if (array_key_exists('xlink_resource', $field) && $this->schemaToDisplay != 'blank')
{
if (!is_array($field['xlink_resource']))
$ret .= ' xlink:href="'.$this->getWsUrl().$field['xlink_resource'].'/'. $field['value'] .'"';
else
$ret .= ' xlink:href="'.$this->getWsUrl().$field['xlink_resource']['resourceName'].'/'.
(isset($field['xlink_resource']['subResourceName']) ? $field['xlink_resource']['subResourceName'].'/'.$field['object_id'].'/' : '').$field['value'].'"';
}
if (isset($field['getter']) && $this->schemaToDisplay != 'blank')
$ret .= ' not_filterable="true"';
if ($field['value'] != '')
$node_content .= '<![CDATA['.$field['value'].']]>';
}
if (isset($field['synopsis_details']) && !empty($field['synopsis_details']) && $this->schemaToDisplay !== 'blank')
{
foreach ($field['synopsis_details'] as $name => $detail)
{
$ret .= ' '.$name.'="'.(is_array($detail) ? implode(' ', $detail) : $detail).'"';
}
}
$ret .= '>';
$ret .= $node_content;
$ret .= '</'.$field['sqlId'].'>'."\n";
return $ret;
}
public function renderNodeHeader($node_name, $params, $more_attr = null, $has_child = true)
{
$string_attr = '';
if (is_array($more_attr))
{
foreach($more_attr as $key=>$attr)
{
if ($key === 'xlink_resource')
$string_attr .= ' xlink:href="'.$attr.'"';
else
$string_attr .= ' '.$key.'="'.$attr.'"';
}
}
$end_tag = (!$has_child) ? '/>' : '>';
return '<'.$node_name.$string_attr.$end_tag."\n";
}
public function getNodeName($params)
{
$node_name = '';
if (isset($params['objectNodeName']))
$node_name = $params['objectNodeName'];
return $node_name;
}
public function renderNodeFooter($node_name, $params)
{
return '</'.$node_name.'>'."\n";
}
public function overrideContent($content)
{
$xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$xml .= '<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">'."\n";
$xml .= $content;
$xml .= '</prestashop>'."\n";
return $xml;
}
public function renderAssociationWrapperHeader()
{
return '<associations>'."\n";
}
public function renderAssociationWrapperFooter()
{
return '</associations>'."\n";
}
public function renderAssociationHeader($obj, $params, $assoc_name, $closed_tags = false)
{
$end_tag = ($closed_tags) ? '/>' : '>';
$more = '';
if ($this->schemaToDisplay != 'blank')
{
$more .= (isset($params['associations'][$assoc_name]['virtual_entity']) && $params['associations'][$assoc_name]['virtual_entity'] ? ' virtual_entity="true"' : '');
$more .= ' node_type="'.$params['associations'][$assoc_name]['resource'].'"';
}
return '<'.$assoc_name.$more.$end_tag."\n";
}
public function renderAssociationFooter($obj, $params, $assoc_name)
{
return '</'.$assoc_name.'>'."\n";
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,47 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 6844 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @author Lucas Cherifi - Nans Pellicari - Anatole Korczak - PrestaShop Team
*/
interface WebserviceSpecificManagementInterface
{
public function setObjectOutput(WebserviceOutputBuilderCore $obj);
public function getObjectOutput();
public function setWsObject(WebserviceRequestCore $obj);
public function getWsObject();
public function manage();
/**
* This must be return an array with specific values as WebserviceRequest expects.
*
* @return array
*/
public function getContent();
}
+125
View File
@@ -0,0 +1,125 @@
<?php
/*
* 2007-2011 PrestaShop
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@prestashop.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade PrestaShop to newer
* versions in the future. If you wish to customize PrestaShop for your
* needs please refer to http://www.prestashop.com for more information.
*
* @author PrestaShop SA <contact@prestashop.com>
* @copyright 2007-2011 PrestaShop SA
* @version Release: $Revision: 6844 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @author Lucas Cherifi - Nans Pellicari - Anatole Korczak - PrestaShop Team
*/
class WebserviceSpecificManagementSearchCore implements WebserviceSpecificManagementInterface
{
protected $objOutput;
protected $output;
protected $wsObject;
// ------------------------------------------------
// GETTERS & SETTERS
// ------------------------------------------------
public function setObjectOutput(WebserviceOutputBuilderCore $obj)
{
$this->objOutput = $obj;
return $this;
}
public function setWsObject(WebserviceRequestCore $obj)
{
$this->wsObject = $obj;
return $this;
}
public function getWsObject()
{
return $this->wsObject;
}
public function getObjectOutput()
{
return $this->objOutput;
}
public function setUrlSegment($segments)
{
$this->urlSegment = $segments;
return $this;
}
public function getUrlSegment()
{
return $this->urlSegment;
}
/**
* Management of search
*
*/
public function manage()
{
if (!isset($this->wsObject->urlFragments['query']) || !isset($this->wsObject->urlFragments['language']))
throw new WebserviceException('You have to set both the \'language\' and \'query\' parameters to get a result', array(100, 400));
$objects_products = array();
$objects_categories = array();
$objects_products['empty'] = new Product();
$objects_categories['empty'] = new Category();
$this->_resourceConfiguration = $objects_products['empty']->getWebserviceParameters();
if (!$this->wsObject->setFieldsToDisplay())
return false;
$results = Search::find($this->wsObject->urlFragments['language'], $this->wsObject->urlFragments['query'], 1, 1, 'position', 'desc', true, false);
$categories = array();
foreach ($results AS $result)
{
$current = new Product($result['id_product']);
$objects_products[] = $current;
$categories_result = $current->getWsCategories();
foreach ($categories_result as $category_result)
foreach ($category_result as $id)
$categories[] = $id;
}
$categories = array_unique($categories);
foreach ($categories as $id)
$objects_categories[] = new Category($id);
$this->output .= $this->objOutput->getContent($objects_products, null, $this->wsObject->fieldsToDisplay, $this->wsObject->depth, WebserviceOutputBuilder::VIEW_LIST, false);
// @todo allow fields of type category and product
// $this->_resourceConfiguration = $objects_categories['empty']->getWebserviceParameters();
// if (!$this->setFieldsToDisplay())
// return false;
$this->output .= $this->objOutput->getContent($objects_categories, null, $this->wsObject->fieldsToDisplay, $this->wsObject->depth, WebserviceOutputBuilder::VIEW_LIST, false);
}
/**
* This must be return an array with specific values as WebserviceRequest expects.
*
* @return array
*/
public function getContent()
{
return $this->objOutput->getObjectRender()->overrideContent($this->output);
}
}