first commit

This commit is contained in:
2024-11-05 12:22:50 +01:00
commit e5682a3912
19641 changed files with 2948548 additions and 0 deletions

View File

@@ -0,0 +1,83 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
declare(strict_types=1);
class SQLUtils
{
/**
* @param string $sqlId
* @param string $filterValue
* @param string $tableAlias = 'main.'
*
* @return string
*/
public static function getSQLRetrieveFilter($sqlId, $filterValue, $tableAlias = 'main.')
{
if (!empty($tableAlias)) {
$tableAlias = '`' . bqSQL(str_replace('.', '', $tableAlias)) . '`.';
}
$ret = '';
preg_match('/^(.*)\[(.*)\](.*)$/', $filterValue, $matches);
if (count($matches) > 1) {
if ($matches[1] == '%' || $matches[3] == '%') {
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '` LIKE "' . pSQL($matches[1] . $matches[2] . $matches[3]) . "\"\n";
} elseif ($matches[1] == '' && $matches[3] == '') {
if (strpos($matches[2], '|') > 0) {
$values = explode('|', $matches[2]);
$ret .= ' AND (';
$temp = '';
foreach ($values as $value) {
$temp .= $tableAlias . '`' . bqSQL($sqlId) . '` = "' . bqSQL($value) . '" OR ';
}
$ret .= rtrim($temp, 'OR ') . ')' . "\n";
} elseif (preg_match('/^([\d\.:\-\s]+),([\d\.:\-\s]+)$/', $matches[2], $matches3)) {
unset($matches3[0]);
if (count($matches3) > 0) {
sort($matches3);
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '` BETWEEN "' . pSQL($matches3[0]) . '" AND "' . pSQL($matches3[1]) . "\"\n";
}
} else {
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '`="' . pSQL($matches[2]) . '"' . "\n";
}
} elseif ($matches[1] == '>') {
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '` > "' . pSQL($matches[2]) . "\"\n";
} elseif ($matches[1] == '<') {
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '` < "' . pSQL($matches[2]) . "\"\n";
} elseif ($matches[1] == '!') {
$multiple_values = explode('|', $matches[2]);
foreach ($multiple_values as $value) {
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '` != "' . pSQL($value) . "\"\n";
}
}
} else {
$ret .= ' AND ' . $tableAlias . '`' . bqSQL($sqlId) . '` = "' . pSQL($filterValue) . "\"\n";
}
return $ret;
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
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;
}
}

View File

@@ -0,0 +1,186 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
class WebserviceKeyCore extends ObjectModel
{
/** @var string Key */
public $key;
/** @var bool Webservice Account statuts */
public $active = true;
/** @var string Webservice Account description */
public $description;
/**
* @see ObjectModel::$definition
*/
public static $definition = [
'table' => 'webservice_account',
'primary' => 'id_webservice_account',
'fields' => [
'active' => ['type' => self::TYPE_BOOL, 'validate' => 'isBool'],
'key' => ['type' => self::TYPE_STRING, 'required' => true, 'size' => 32],
'description' => ['type' => self::TYPE_STRING],
],
];
public function add($autodate = true, $nullValues = false)
{
if (WebserviceKey::keyExists($this->key)) {
return false;
}
$result = parent::add($autodate = true, $nullValues = false);
if ($result) {
PrestaShopLogger::addLog(
Context::getContext()->getTranslator()->trans(
'Webservice key created: %s',
[
$this->key,
],
'Admin.Advparameters.Feature'
),
1,
0,
'WebserviceKey',
(int) $this->id,
false,
(int) Context::getContext()->employee->id
);
}
return $result;
}
public static function keyExists($key)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `key`
FROM ' . _DB_PREFIX_ . 'webservice_account
WHERE `key` = "' . pSQL($key) . '"');
}
public function delete()
{
$result = parent::delete() && ($this->deleteAssociations() !== false);
if ($result) {
PrestaShopLogger::addLog(
Context::getContext()->getTranslator()->trans(
'Webservice key %s has been deleted',
[
$this->key,
],
'Admin.Advparameters.Feature'
),
1,
0,
'WebserviceKey',
(int) $this->id,
false,
(int) Context::getContext()->employee->id
);
}
return $result;
}
public function deleteAssociations()
{
return Db::getInstance()->delete('webservice_permission', 'id_webservice_account = ' . (int) $this->id);
}
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 = [];
if ($result) {
foreach ($result as $row) {
$permissions[$row['resource']][] = $row['method'];
}
}
return $permissions;
}
public static function isKeyActive($auth_key)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT active
FROM `' . _DB_PREFIX_ . 'webservice_account`
WHERE `key` = "' . pSQL($auth_key) . '"');
}
public static function getClassFromKey($auth_key)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT class_name
FROM `' . _DB_PREFIX_ . 'webservice_account`
WHERE `key` = "' . pSQL($auth_key) . '"');
}
public static function setPermissionForAccount($id_account, $permissions_to_set)
{
$ok = true;
$sql = 'DELETE FROM `' . _DB_PREFIX_ . 'webservice_permission` WHERE `id_webservice_account` = ' . (int) $id_account;
if (!Db::getInstance()->execute($sql)) {
$ok = false;
}
if (isset($permissions_to_set)) {
$permissions = [];
$resources = WebserviceRequest::getResources();
$methods = ['GET', 'PUT', 'POST', 'DELETE', 'HEAD'];
foreach ($permissions_to_set as $resource_name => $resource_methods) {
if (in_array($resource_name, array_keys($resources))) {
foreach (array_keys($resource_methods) as $method_name) {
if (in_array($method_name, $methods)) {
$permissions[] = [$method_name, $resource_name];
}
}
}
}
$account = new WebserviceKey($id_account);
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) $id_account . '), ';
}
$sql = rtrim($sql, ', ');
if (!Db::getInstance()->execute($sql)) {
$ok = false;
}
}
}
return $ok;
}
}

View File

@@ -0,0 +1,866 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
/**
* @todo : Create typed exception for more finer errors check
*/
class WebserviceOutputBuilderCore
{
/**
* @var int constant
*/
const VIEW_LIST = 1;
const VIEW_DETAILS = 2;
protected $wsUrl;
protected $output;
/** @var WebserviceOutputInterface|WebserviceOutputXML|WebserviceOutputJSON */
public $objectRender;
protected $wsResource;
protected $depth = 0;
protected $schemaToDisplay;
protected $fieldsToDisplay;
protected $specificFields = [];
protected $virtualFields = [];
protected $statusInt;
protected $wsParamOverrides;
protected static $_cache_ws_parameters = [];
/* Header properties */
protected $headerParams = [
'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->statusInt = 200;
$this->status = $_SERVER['SERVER_PROTOCOL'] . ' 200 OK';
$this->wsUrl = $ws_url;
$this->wsParamOverrides = [];
}
/**
* 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 WebserviceOutputBuilder
*
* @throws WebserviceException
*/
public function setObjectRender(WebserviceOutputInterface $obj_render)
{
if (!$obj_render instanceof WebserviceOutputInterface) {
throw new WebserviceException('Obj_render param must be an WebserviceOutputInterface object type', [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 WebserviceOutputBuilder
*/
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 = [];
$return[] = $this->status;
foreach ($this->headerParams as $key => $param) {
$return[] = trim($key) . ': ' . $param;
}
return $return;
}
/**
* @param string $key The normalized key expected for an http response
* @param string $value
*
* @return WebserviceOutputBuilder
*
* @throws WebserviceException If the key or the value are corrupted (use Validate::isCleanHtml method)
*/
public function setHeaderParams($key, $value)
{
if (!Validate::isCleanHtml($key) || !Validate::isCleanHtml($value)) {
throw new WebserviceException('the key or your value is corrupted.', [94, 500]);
}
$this->headerParams[$key] = $value;
return $this;
}
/**
* @param string|null $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 (null !== $key) {
if (!Validate::isCleanHtml($key)) {
throw new WebserviceException('the key you write is a corrupted text.', [95, 500]);
}
if (!array_key_exists($key, $this->headerParams)) {
throw new WebserviceException(sprintf('The key %s does\'nt exist', $key), [96, 500]);
}
$return = $this->headerParams[$key];
} else {
$return = $this->headerParams;
}
return $return;
}
/**
* Delete all Header parameters previously set.
*
* @return WebserviceOutputBuilder
*/
public function resetHeaderParams()
{
$this->headerParams = [];
return $this;
}
/**
* @return string the normalized status for http request
*/
public function getStatus()
{
return $this->status;
}
public function getStatusInt()
{
return $this->statusInt;
}
/**
* Set the return header status.
*
* @param int $num the Http status code
*/
public function setStatus($num)
{
$this->statusInt = (int) $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 (null === $this->wsResource) {
throw new WebserviceException('You must set web service resource for get the resources list.', [82, 500]);
}
$output = '';
$more_attr = ['shopName' => htmlspecialchars(Configuration::get('PS_SHOP_NAME'))];
$output .= $this->objectRender->renderNodeHeader('api', [], $more_attr);
foreach ($this->wsResource as $resourceName => $resource) {
if (in_array($resourceName, array_keys($key_permissions))) {
$more_attr = [
'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, [], $more_attr);
$output .= $this->objectRender->renderNodeHeader('description', [], $more_attr);
$output .= $resource['description'];
$output .= $this->objectRender->renderNodeFooter('description', []);
if (!isset($resource['specific_management']) || !$resource['specific_management']) {
$more_attr_schema = [
'xlink_resource' => $this->wsUrl . $resourceName . '?schema=blank',
'type' => 'blank',
];
$output .= $this->objectRender->renderNodeHeader('schema', [], $more_attr_schema, false);
$more_attr_schema = [
'xlink_resource' => $this->wsUrl . $resourceName . '?schema=synopsis',
'type' => 'synopsis',
];
$output .= $this->objectRender->renderNodeHeader('schema', [], $more_attr_schema, false);
}
$output .= $this->objectRender->renderNodeFooter($resourceName, []);
}
}
$output .= $this->objectRender->renderNodeFooter('api', []);
$output = $this->objectRender->overrideContent($output);
return $output;
}
public function registerOverrideWSParameters($wsrObject, $method)
{
$this->wsParamOverrides[] = ['object' => $wsrObject, 'method' => $method];
}
/**
* 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 string|null $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;
}
$class = get_class($objects['empty']);
if (!isset(WebserviceOutputBuilder::$_cache_ws_parameters[$class])) {
WebserviceOutputBuilder::$_cache_ws_parameters[$class] = $objects['empty']->getWebserviceParameters();
}
$ws_params = WebserviceOutputBuilder::$_cache_ws_parameters[$class];
foreach ($this->wsParamOverrides as $p) {
$object = $p['object'];
$ws_params = $object->{$p['method']}($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->renderNodeHeader($ws_params['objectsNodeName'], $ws_params);
}
if (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 ObjectModel $object create by the entity
* @param int $depth the depth for the tree diagram
*
* @return string
*/
public function renderEntityMinimum($object, $depth)
{
$class = get_class($object);
if (!isset(WebserviceOutputBuilder::$_cache_ws_parameters[$class])) {
WebserviceOutputBuilder::$_cache_ws_parameters[$class] = $object->getWebserviceParameters();
}
$ws_params = WebserviceOutputBuilder::$_cache_ws_parameters[$class];
$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 ObjectModel $object create by the entity
* @param array $ws_params webserviceParams from the entity
*
* @return string
*/
protected 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 = '';
$class = get_class($object);
if (!isset(WebserviceOutputBuilder::$_cache_ws_parameters[$class])) {
WebserviceOutputBuilder::$_cache_ws_parameters[$class] = $object->getWebserviceParameters();
}
$ws_params = WebserviceOutputBuilder::$_cache_ws_parameters[$class];
foreach ($this->wsParamOverrides as $p) {
$o = $p['object'];
$ws_params = $o->{$p['method']}($ws_params);
}
$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
*/
protected 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;
}
}
if ($this->schemaToDisplay === 'blank') {
if (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']) {
if ($field['value'] === null) {
$field['value'] = '';
}
// delete the xlink except for schemas
if (isset($field['xlink_resource']) && 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
*/
protected 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 = [];
$fields_assoc = [];
if (isset($association['fields'])) {
$fields_assoc = $association['fields'];
}
$parent_details = [
'object_id' => $object->id,
'entity_name' => $ws_params['objectNodeName'],
'entities_name' => $ws_params['objectsNodeName'],
];
if (is_array($getter)) {
$association_resources = call_user_func($getter, $object);
if (is_array($association_resources) && !empty($association_resources)) {
foreach ($association_resources as $association_resource) {
$objects_assoc[] = $association_resource;
}
}
} else {
if (method_exists($object, $getter) && 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 = [['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;
}
protected function renderFlatAssociation($object, $depth, $assoc_name, $resource_name, $fields_assoc, $object_assoc, $parent_details)
{
$output = '';
$more_attr = [];
if (isset($this->wsResource[$assoc_name]) && null === $this->schemaToDisplay) {
if ($assoc_name == 'images') {
if ($parent_details['entities_name'] == 'combinations') {
$more_attr['xlink_resource'] = $this->wsUrl . $assoc_name . '/products/' . $object->id_product . '/' . $object_assoc['id'];
} else {
$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, [], $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 (null !== $this->schemaToDisplay) {
$field['synopsis_details'] = $this->getSynopsisDetails($field);
}
$field['is_association'] = true;
$output .= $this->setIndent($depth - 1) . $this->objectRender->renderField($field);
}
}
$output .= $this->setIndent($depth - 1) . $this->objectRender->renderNodeFooter($resource_name, []);
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'];
}
if (array_key_exists('setter', $field) && !$field['setter']) {
$arr_details['readOnly'] = 'true';
}
return $arr_details;
}
/**
* @param string|object $object
* @param string $method
* @param $field_name
* @param $entity_name
*
* @return WebserviceOutputBuilder
*
* @throws Exception
* @throws WebserviceException
*/
public function setSpecificField($object, $method, $field_name, $entity_name)
{
try {
$this->validateObjectAndMethod($object, $method);
} catch (WebserviceException $e) {
throw $e;
}
$this->specificFields[$field_name] = ['entity' => $entity_name, 'object' => $object, 'method' => $method, 'type' => gettype($object)];
return $this;
}
protected 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.', [98, 500]);
}
if (!method_exists($object, $method)) {
throw new WebserviceException('The method you want to set in ' . __METHOD__ . ' is not allowed.', [99, 500]);
}
}
public function getSpecificField()
{
return $this->specificFields;
}
protected 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][] = ['parameters' => $parameters, 'object' => $object, 'method' => $method, 'type' => gettype($object)];
}
public function getVirtualFields()
{
return $this->virtualFields;
}
public function addVirtualFields($entity_name, $entity_object)
{
$arr_return = [];
$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', [128, 400]);
}
}
}
}
return $arr_return;
}
public function setFieldsToDisplay($fields)
{
$this->fieldsToDisplay = $fields;
}
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
interface WebserviceOutputInterface
{
public function __construct($languages = []);
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);
}

View File

@@ -0,0 +1,216 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
class WebserviceOutputJSONCore implements WebserviceOutputInterface
{
public $docUrl = '';
public $languages = [];
protected $wsUrl;
protected $schemaToDisplay;
/**
* Current entity.
*/
protected $currentEntity;
/**
* Current association.
*/
protected $currentAssociatedEntity = [];
/**
* Json content.
*/
protected $content = [];
public function __construct($languages = [])
{
$this->languages = $languages;
}
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 'application/json';
}
public function renderErrors($message, $code = null)
{
$this->content['errors'][] = ['code' => $code, 'message' => $message];
return '';
}
public function renderField($field)
{
$is_association = (isset($field['is_association']) && $field['is_association'] == true);
if (is_array($field['value'])) {
$tmp = [];
foreach ($this->languages as $id_lang) {
$tmp[] = ['id' => $id_lang, 'value' => $field['value'][$id_lang]];
}
if (count($tmp) == 1) {
$field['value'] = $tmp[0]['value'];
} else {
$field['value'] = $tmp;
}
}
// Case 1 : fields of the current entity (not an association)
if (!$is_association) {
$this->currentEntity[$field['sqlId']] = $field['value'];
} else { // Case 2 : fields of an associated entity to the current one
$this->currentAssociatedEntity[] = ['name' => $field['entities_name'], 'key' => $field['sqlId'], 'value' => $field['value']];
}
return '';
}
public function renderNodeHeader($node_name, $params, $more_attr = null, $has_child = true)
{
// api ?
static $isAPICall = false;
if ($node_name == 'api' && ($isAPICall == false)) {
$isAPICall = true;
}
if ($isAPICall && !in_array($node_name, ['description', 'schema', 'api'])) {
$this->content[] = $node_name;
}
if (isset($more_attr, $more_attr['id'])) {
$this->content[$params['objectsNodeName']][] = ['id' => $more_attr['id']];
}
return '';
}
public function getNodeName($params)
{
$node_name = '';
if (isset($params['objectNodeName'])) {
$node_name = $params['objectNodeName'];
}
return $node_name;
}
public function renderNodeFooter($node_name, $params)
{
if (isset($params['objectNodeName']) && $params['objectNodeName'] == $node_name) {
if (array_key_exists('display', $_GET)) {
$this->content[$params['objectsNodeName']][] = $this->currentEntity;
} else {
$this->content[$params['objectNodeName']] = $this->currentEntity;
}
$this->currentEntity = [];
}
if (is_countable($this->currentAssociatedEntity) && count($this->currentAssociatedEntity)) {
$current = [];
foreach ($this->currentAssociatedEntity as $element) {
$current[$element['key']] = $element['value'];
}
//$this->currentEntity['associations'][$element['name']][][$element['key']] = $element['value'];
$this->currentEntity['associations'][$element['name']][] = $current;
$this->currentAssociatedEntity = [];
}
}
public function overrideContent($content)
{
$content = json_encode($this->content, JSON_UNESCAPED_UNICODE);
return (false !== $content) ? $content : '';
}
public function setLanguages($languages)
{
$this->languages = $languages;
return $this;
}
public function renderAssociationWrapperHeader()
{
return '';
}
public function renderAssociationWrapperFooter()
{
return '';
}
public function renderAssociationHeader($obj, $params, $assoc_name, $closed_tags = false)
{
return '';
}
public function renderAssociationFooter($obj, $params, $assoc_name)
{
}
public function renderErrorsHeader()
{
return '';
}
public function renderErrorsFooter()
{
return '';
}
public function renderAssociationField($field)
{
return '';
}
public function renderi18nField($field)
{
return '';
}
}

View File

@@ -0,0 +1,240 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
class WebserviceOutputXMLCore implements WebserviceOutputInterface
{
public $docUrl = '';
public $languages = [];
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 = [])
{
$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']) && 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 . '>';
$node_content .= '<![CDATA[';
if (isset($field['value'][$language])) {
$node_content .= $field['value'][$language];
}
$node_content .= ']]>';
$node_content .= '</language>';
}
} else {
// display not i18n fields value
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 .= ' notFilterable="true"';
}
if (isset($field['setter']) && $field['setter'] == false && $this->schemaToDisplay == 'synopsis') {
$ret .= ' read_only="true"';
}
if (array_key_exists('value', $field)) {
$node_content .= '<![CDATA[' . $field['value'] . ']]>';
}
}
if (isset($field['encode'])) {
$ret .= ' encode="' . $field['encode'] . '"';
}
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') {
if (array_key_exists('setter', $params['associations'][$assoc_name]) && !$params['associations'][$assoc_name]['setter']) {
$more .= ' readOnly="true"';
}
$more .= ' nodeType="' . $params['associations'][$assoc_name]['resource'] . '"';
if (isset($params['associations'][$assoc_name]['virtual_entity']) && $params['associations'][$assoc_name]['virtual_entity']) {
$more .= ' virtualEntity="true"';
} else {
if (isset($params['associations'][$assoc_name]['api'])) {
$more .= ' api="' . $params['associations'][$assoc_name]['api'] . '"';
} else {
$more .= ' api="' . $assoc_name . '"';
}
}
}
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

View File

@@ -0,0 +1,371 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
declare(strict_types=1);
use PrestaShop\PrestaShop\Core\File\FileUploader;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\Response;
/**
* This class is responsible for managing Attachement through webservice
*/
class WebserviceSpecificManagementAttachmentsCore implements WebserviceSpecificManagementInterface
{
/**
* @var WebserviceOutputBuilder
*/
protected $objOutput;
/**
* @var WebserviceRequest
*/
protected $wsObject;
/**
* The configuration parameters of the current resource
*
* @var array
*/
public $resourceConfiguration;
/**
* @var int
*/
protected $attachmentId;
/**
* @var array|null
*/
protected $displayFile;
/*
* ------------------------------------------------
* GETTERS & SETTERS
* ------------------------------------------------
*/
/**
* @param WebserviceOutputBuilder $obj
*
* @return WebserviceSpecificManagementInterface
*/
public function setObjectOutput(WebserviceOutputBuilderCore $obj)
{
$this->objOutput = $obj;
return $this;
}
/**
* Get Object Output
*/
public function getObjectOutput()
{
return $this->objOutput;
}
/**
* Set Webservice Object
*
* @param WebserviceRequestCore $obj
*/
public function setWsObject(WebserviceRequestCore $obj)
{
$this->wsObject = $obj;
return $this;
}
/**
* Get Webservice Object
*/
public function getWsObject()
{
return $this->wsObject;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
if ($this->displayFile) {
// if displayFile is set, present the file (download)
$this->getObjectOutput()->setHeaderParams('Content-Type', $this->displayFile['mime']);
$this->getObjectOutput()->setHeaderParams('Content-Length', $this->displayFile['file_size']);
$this->getObjectOutput()->setHeaderParams('Content-Disposition', 'attachment; filename="' . utf8_decode($this->displayFile['file_name']) . '"');
return file_get_contents($this->displayFile['file']);
}
// Emulate non-specific management
$this->getWsObject()->setObjectSpecificManagement(null);
return '';
}
/**
* Manage attachements
*
* @return bool
*/
public function manage()
{
$this->manageAttachments();
return $this->getWsObject()->getOutputEnabled();
}
/**
* That part was inherited from WebserviceSpecificManagementImages (which uses deeper api path).
* Looping for 6 segments is excessive as only the [1] and [2] indices is used for attachments.
*
* The explanation for the mapping can be seen further down "Available cases api/...".
* If urlSegment[1] is set to 'file', binary operations are done (file upload/download)
* Otherwise default webservice operations are done (read/write Model information using XML/json).
*
* Examples:
* [GET] https://domain.tld/api/attachments/ give a response in XML/json with all attachments.
* [POST] https://domain.tld/api/attachments/ only creates model information (similar to any other default api), no file information.
* [POST] https://domain.tld/api/attachments/file creates an attachment AND uploads a file for it.
*
* [PUT] https://domain.tld/api/attachments/$id_attachment here urlSegment[1] is id_attachment, updates model information only.
* [PUT] https://domain.tld/api/attachments/file/$id_attachment here urlSegment[1] is 'file' and urlSegment[2] is id_attachment, updates file (binary) only.
*
* [GET] https://domain.tld/api/attachments/$id_attachment gives a response in XML/json for the attachment model information.
* [GET] https://domain.tld/api/attachments/file/$id_attachment downloads the id_attachment file
*/
public function manageAttachments()
{
if (isset($this->getWsObject()->urlSegment)) {
for ($i = 1; $i < 6; ++$i) {
if (count($this->getWsObject()->urlSegment) == $i) {
$this->getWsObject()->urlSegment[$i] = '';
}
}
}
if ($this->getWsObject()->urlSegment[0] != '') {
/** @var ObjectModel */
$object = new Attachment();
$this->getWsObject()->resourceConfiguration = $object->getWebserviceParameters();
}
/*
* Available cases api/...:
*
* [Utilizes default webservice handling by emulating non-specific management]
* attachments/ ("attachment_list")
* GET (xml/json) (list of attachments)
* attachments/[1,+] ("attachment_description") (N-3)
* GET (xml/json)
* PUT (xml/json) (update)
* DELETE
*
* [Specific management for file upload/download}
* attachments/file/
* POST (bin) (create new attachment)
* POST (multipart) (create new attachment)
* attachments/file/[1,+] (file management)
* GET (bin) (download file)
* PUT (bin) (upload/update file)
* PUT (multipart) (upload/update file)
* DELETE
*/
if ($this->getWsObject()->urlSegment[1] == 'file') {
// File handling (upload/download)
switch ($this->getWsObject()->method) {
case 'GET':
case 'HEAD':
$this->displayFile = $this->executeFileGetAndHead();
break;
case 'POST':
case 'PUT':
$this->executeFileAddAndEdit();
// Emulate get/head to return output
$this->getWsObject()->method = 'GET';
$this->getWsObject()->urlSegment[1] = $this->attachmentId;
$this->getWsObject()->urlSegment[2] = '';
$this->getWsObject()->executeEntityGetAndHead();
break;
case 'DELETE':
$attachment = new Attachment((int) $this->getWsObject()->urlSegment[1]);
$attachment->delete();
break;
}
} else {
// Default handling via WebserviceRequest
switch ($this->getWsObject()->method) {
case 'GET':
case 'HEAD':
$this->getWsObject()->executeEntityGetAndHead();
break;
case 'PUT':
$this->getWsObject()->executeEntityPut();
break;
case 'DELETE':
$this->getWsObject()->executeEntityDelete();
break;
}
}
// Need to set an object for the WebserviceOutputBuilder object in any case
// because schema need to get webserviceParameters of this object
if (isset($object)) {
$this->getWsObject()->objects['empty'] = $object;
}
}
/**
* Handles attachment file download
*
* @throws WebserviceException if attachment is not existing or file not available
*
* @return array<string, string> File details
*/
public function executeFileGetAndHead(): array
{
$attachmentId = (int) $this->getWsObject()->urlSegment[2];
$attachment = new Attachment($attachmentId);
if (empty($attachment->id)) {
throw new WebserviceException(
sprintf(
'Attachment %d not found',
$attachmentId
),
[
1,
Response::HTTP_INTERNAL_SERVER_ERROR,
]
);
}
// Physical file location
$file = _PS_DOWNLOAD_DIR_ . $attachment->file;
// Check if file exists
if (!file_exists($file)) {
throw new WebserviceException(
sprintf(
'Unable to load the attachment file for attachment %d',
$attachmentId
),
[
1,
Response::HTTP_INTERNAL_SERVER_ERROR,
]
);
}
// Return file details
return [
'file' => $file,
'mime' => $attachment->mime,
'file_name' => $attachment->file_name,
'file_size' => $attachment->file_size,
];
}
/**
* Handles file upload
*
* Creates new attachment or replaces existing with a new file.
* [PUT] update existing attachment file
* [POST] create new attachment
*/
public function executeFileAddAndEdit(): void
{
// Load attachment without checking the method, because of
// PUT which is cleared the $_FILES var in multipart/form context
$attachmentId = null;
if (isset($this->getWsObject()->urlSegment[2])) {
$attachmentId = (int) $this->getWsObject()->urlSegment[2];
}
$attachment = new Attachment($attachmentId);
$maximumSize = ((int) Configuration::get('PS_ATTACHMENT_MAXIMUM_SIZE')) * 1024 * 1024;
$uploader = new FileUploader(
_PS_DOWNLOAD_DIR_,
$maximumSize
);
if (isset($_FILES['file'])) {
// Standard HTTP upload
$fileToUpload = $_FILES['file'];
} else {
// Get data from binary
$fileToUpload = file_get_contents('php://input');
}
try {
$file = $uploader->upload($fileToUpload);
if (!empty($attachment->id)) {
unlink(_PS_DOWNLOAD_DIR_ . $attachment->file);
}
$attachment->file = $file['id'];
$attachment->file_name = $file['file_name'];
$attachment->mime = $file['mime_type'];
$attachment->name[Configuration::get('PS_LANG_DEFAULT')] = $_POST['name'] ?? $file['file_name'];
if (!empty($attachment->id)) {
$attachment->update();
} else {
$attachment->add();
}
// Remember affected entity
$this->attachmentId = $attachment->id;
} catch (MaximumSizeExceeded $e) {
$this->getWsObject()->errors[] = $this->trans(
'The file you are trying to upload is %2$d KB, which is larger than the maximum size allowed of %1$d KB.',
[$maximumSize, $e->getMessage()],
'Admin.Notifications.Error'
);
} catch (FailedToCopyException $e) {
$this->getWsObject()->errors[] = $this->trans(
'Failed to copy the file.',
[],
'Admin.Catalog.Notification'
);
}
}
/**
* @param string $message
* @param array $params
* @param string $domain
*
* @return string
*/
protected function trans(string $message, array $params, string $domain): string
{
return Context::getContext()->getTranslator()->trans($message, $params, $domain);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,44 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
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();
}

View File

@@ -0,0 +1,134 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
class WebserviceSpecificManagementSearchCore implements WebserviceSpecificManagementInterface
{
/** @var WebserviceOutputBuilder */
protected $objOutput;
protected $output;
/** @var WebserviceRequest */
protected $wsObject;
/* ------------------------------------------------
* GETTERS & SETTERS
* ------------------------------------------------ */
/**
* @param WebserviceOutputBuilderCore $obj
*
* @return WebserviceSpecificManagementInterface
*/
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', [100, 400]);
}
$objects_products = [];
$objects_categories = [];
$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 = [];
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 a string with specific values as WebserviceRequest expects.
*
* @return string
*/
public function getContent()
{
return $this->objOutput->getObjectRender()->overrideContent($this->output);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* Copyright since 2007 PrestaShop SA and Contributors
* PrestaShop is an International Registered Trademark & Property of PrestaShop SA
*
* 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.md.
* It is also available through the world-wide-web at this URL:
* https://opensource.org/licenses/OSL-3.0
* 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 https://devdocs.prestashop.com/ for more information.
*
* @author PrestaShop SA and Contributors <contact@prestashop.com>
* @copyright Since 2007 PrestaShop SA and Contributors
* @license https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
*/
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache');
header('Location: ../../');
exit;