This commit is contained in:
rGaillard
2011-07-06 10:54:11 +00:00
parent 4d2c770c6f
commit 8fc7f11014
5398 changed files with 482149 additions and 0 deletions
+2
View File
@@ -0,0 +1,2 @@
Order deny,allow
Deny from all
+111
View File
@@ -0,0 +1,111 @@
<?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
*/
abstract class AbstractLoggerCore
{
public $level;
protected $level_value = array(0 => 'DEBUG',
1 => 'INFO',
2 => 'WARNING',
3 => 'ERROR');
const DEBUG = 0;
const INFO = 1;
const WARNING = 2;
const ERROR = 3;
public function __construct($level = self::INFO)
{
if (array_key_exists((int)$level, $this->level_value))
$this->level = $level;
else
$this->level = self::INFO;
}
/**
* Log the message
*
* @param string message
* @param level
*/
abstract protected function logMessage($message, $level);
/**
* Check the level and log the message if needed
*
* @param string message
* @param level
*/
public function log($message, $level = self::DEBUG)
{
if ($level >= $this->level)
{
$this->logMessage($message, $level);
}
}
/**
* Log a debug message
*
* @param string message
*/
public function logDebug($message)
{
$this->log($message, self::DEBUG);
}
/**
* Log an info message
*
* @param string message
*/
public function logInfo($message)
{
$this->log($message, self::INFO);
}
/**
* Log a warning message
*
* @param string message
*/
public function logWarning($message)
{
$this->log($message, self::WARNING);
}
/**
* Log an error message
*
* @param string message
*/
public function logError($message)
{
$this->log($message, self::ERROR);
}
}
+329
View File
@@ -0,0 +1,329 @@
<?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 AddressCore extends ObjectModel
{
/** @var integer Customer id which address belongs */
public $id_customer = NULL;
/** @var integer Manufacturer id which address belongs */
public $id_manufacturer = NULL;
/** @var integer Supplier id which address belongs */
public $id_supplier = NULL;
/** @var integer Country id */
public $id_country;
/** @var integer State id */
public $id_state;
/** @var string Country name */
public $country;
/** @var string Alias (eg. Home, Work...) */
public $alias;
/** @var string Company (optional) */
public $company;
/** @var string Lastname */
public $lastname;
/** @var string Firstname */
public $firstname;
/** @var string Address first line */
public $address1;
/** @var string Address second line (optional) */
public $address2;
/** @var string Postal code */
public $postcode;
/** @var string City */
public $city;
/** @var string Any other useful information */
public $other;
/** @var string Phone number */
public $phone;
/** @var string Mobile phone number */
public $phone_mobile;
/** @var string VAT number */
public $vat_number;
/** @var string DNI number */
public $dni;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
/** @var boolean True if address has been deleted (staying in database as deleted) */
public $deleted = 0;
protected static $_idZones = array();
protected static $_idCountries = array();
protected $fieldsRequired = array('id_country', 'alias', 'lastname', 'firstname', 'address1', 'city');
protected $fieldsSize = array('alias' => 32, 'company' => 32, 'lastname' => 32, 'firstname' => 32,
'address1' => 128, 'address2' => 128, 'postcode' => 12, 'city' => 64,
'other' => 300, 'phone' => 16, 'phone_mobile' => 16, 'dni' => 16);
protected $fieldsValidate = array('id_customer' => 'isNullOrUnsignedId', 'id_manufacturer' => 'isNullOrUnsignedId',
'id_supplier' => 'isNullOrUnsignedId', 'id_country' => 'isUnsignedId', 'id_state' => 'isNullOrUnsignedId',
'alias' => 'isGenericName', 'company' => 'isGenericName', 'lastname' => 'isName','vat_number' => 'isGenericName',
'firstname' => 'isName', 'address1' => 'isAddress', 'address2' => 'isAddress', 'postcode'=>'isPostCode',
'city' => 'isCityName', 'other' => 'isMessage',
'phone' => 'isPhoneNumber', 'phone_mobile' => 'isPhoneNumber', 'deleted' => 'isBool', 'dni' => 'isDniLite');
protected $table = 'address';
protected $identifier = 'id_address';
protected $_includeVars = array('addressType' => 'table');
protected $_includeContainer = false;
protected $webserviceParameters = array(
'objectsNodeName' => 'addresses',
'fields' => array(
'id_customer' => array('xlink_resource'=> 'customers'),
'id_manufacturer' => array('xlink_resource'=> 'manufacturers'),
'id_supplier' => array('xlink_resource'=> 'suppliers'),
'id_country' => array('xlink_resource'=> 'countries'),
'id_state' => array('xlink_resource'=> 'states'),
),
);
/**
* Build an address
*
* @param integer $id_address Existing address id in order to load object (optional)
*/
public function __construct($id_address = NULL, $id_lang = NULL)
{
parent::__construct($id_address);
/* Get and cache address country name */
if ($this->id)
{
$result = Db::getInstance()->getRow('SELECT `name` FROM `'._DB_PREFIX_.'country_lang`
WHERE `id_country` = '.(int)($this->id_country).'
AND `id_lang` = '.($id_lang ? (int)($id_lang) : Configuration::get('PS_LANG_DEFAULT')));
$this->country = $result['name'];
}
}
public function add($autodate = true, $nullValues = false)
{
if (!parent::add($autodate, $nullValues))
return false;
if (Validate::isUnsignedId($this->id_customer))
Customer::resetAddressCache($this->id_customer);
return true;
}
public function delete()
{
if (Validate::isUnsignedId($this->id_customer))
Customer::resetAddressCache($this->id_customer);
if (!$this->isUsed())
return parent::delete();
else
{
$this->deleted = true;
return $this->update();
}
}
/**
* Returns fields required for an address in an array hash
* @return array hash values
*/
public static function getFieldsValidate()
{
$tmp_addr = new Address();
$out = ($tmp_addr->fieldsValidate);
unset($tmp_addr);
return $out;
}
public function getFields()
{
parent::validateFields();
if (isset($this->id))
$fields['id_address'] = (int)($this->id);
$fields['id_customer'] = is_null($this->id_customer) ? 0 : (int)($this->id_customer);
$fields['id_manufacturer'] = is_null($this->id_manufacturer) ? 0 : (int)($this->id_manufacturer);
$fields['id_supplier'] = is_null($this->id_supplier) ? 0 : (int)($this->id_supplier);
$fields['id_country'] = (int)($this->id_country);
$fields['id_state'] = (int)($this->id_state);
$fields['alias'] = pSQL($this->alias);
$fields['company'] = pSQL($this->company);
$fields['lastname'] = pSQL($this->lastname);
$fields['firstname'] = pSQL($this->firstname);
$fields['address1'] = pSQL($this->address1);
$fields['address2'] = pSQL($this->address2);
$fields['postcode'] = pSQL($this->postcode);
$fields['city'] = pSQL($this->city);
$fields['other'] = pSQL($this->other);
$fields['phone'] = pSQL($this->phone);
$fields['phone_mobile'] = pSQL($this->phone_mobile);
$fields['vat_number'] = pSQL($this->vat_number);
$fields['dni'] = pSQL($this->dni);
$fields['deleted'] = (int)($this->deleted);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
public function validateController($htmlentities = true)
{
$errors = parent::validateController($htmlentities);
if (!Configuration::get('VATNUMBER_CHECKING'))
return $errors;
include_once(_PS_MODULE_DIR_.'vatnumber/vatnumber.php');
if (class_exists('VatNumber', false))
return array_merge($errors, VatNumber::WebServiceCheck($this->vat_number));
return $errors;
}
/**
* Get zone id for a given address
*
* @param integer $id_address Address id for which we want to get zone id
* @return integer Zone id
*/
public static function getZoneById($id_address)
{
if (isset(self::$_idZones[$id_address]))
return self::$_idZones[$id_address];
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT s.`id_zone` AS id_zone_state, c.`id_zone`
FROM `'._DB_PREFIX_.'address` a
LEFT JOIN `'._DB_PREFIX_.'country` c ON c.`id_country` = a.`id_country`
LEFT JOIN `'._DB_PREFIX_.'state` s ON s.`id_state` = a.`id_state`
WHERE a.`id_address` = '.(int)($id_address));
self::$_idZones[$id_address] = (int)((int)($result['id_zone_state']) ? $result['id_zone_state'] : $result['id_zone']);
return self::$_idZones[$id_address];
}
/**
* Check if country is active for a given address
*
* @param integer $id_address Address id for which we want to get country status
* @return integer Country status
*/
public static function isCountryActiveById($id_address)
{
if (!$result = Db::getInstance()->getRow('
SELECT c.`active`
FROM `'._DB_PREFIX_.'address` a
LEFT JOIN `'._DB_PREFIX_.'country` c ON c.`id_country` = a.`id_country`
WHERE a.`id_address` = '.(int)($id_address)))
return false;
return ($result['active']);
}
/**
* Check if address is used (at least one order placed)
*
* @return integer Order count for this address
*/
public function isUsed()
{
$result = Db::getInstance()->getRow('
SELECT COUNT(`id_order`) AS used
FROM `'._DB_PREFIX_.'orders`
WHERE `id_address_delivery` = '.(int)($this->id).'
OR `id_address_invoice` = '.(int)($this->id));
return isset($result['used']) ? $result['used'] : false;
}
/**
* @param int $id_address
* @return int
* @deprecated
*/
static public function getManufacturerIdByAddress($id_address)
{
Tools::displayAsDeprecated();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_manufacturer` FROM `'._DB_PREFIX_.'address`
WHERE `id_address` = '.(int)($id_address));
return isset($result['id_manufacturer']) ? $result['id_manufacturer'] : false;
}
static public function getCountryAndState($id_address)
{
if (isset(self::$_idCountries[$id_address]))
return self::$_idCountries[$id_address];
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_country`, `id_state`, `vat_number`, `postcode` FROM `'._DB_PREFIX_.'address`
WHERE `id_address` = '.(int)($id_address));
self::$_idCountries[$id_address] = $result;
return $result;
}
/**
* Specify if an address is already in base
*
* @param $id_address Address id
* @return boolean
*/
static public function addressExists($id_address)
{
$row = Db::getInstance()->getRow('
SELECT `id_address`
FROM '._DB_PREFIX_.'address a
WHERE a.`id_address` = '.(int)($id_address));
return isset($row['id_address']);
}
static public function getFirstCustomerAddressId($id_customer, $active = true)
{
return Db::getInstance()->getValue('
SELECT `id_address`
FROM `'._DB_PREFIX_.'address`
WHERE `id_customer` = '.(int)($id_customer).' AND `deleted` = 0'.($active ? ' AND `active` = 1' : '')
);
}
}
+439
View File
@@ -0,0 +1,439 @@
<?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: 7310 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AddressFormatCore extends ObjectModel
{
/** @var integer */
public $id_address_format;
/** @var integer */
public $id_country;
/** @var string */
public $format;
private $_errorFormatList = array();
protected $fieldsRequired = array ('format');
protected $fieldsValidate = array ('format' => 'isGenericName');
/* MySQL does not allow 'order detail' for a table name */
protected $table = 'address_format';
protected $identifier = 'id_country';
static public $requireFormFieldsList = array(
'firstname',
'name',
'address1',
'city',
'postcode',
'Country:name',
'State:name');
static public $forbiddenProperyList = array(
'deleted',
'date_add',
'other',
'alias',
'secure_key',
'note',
'newsletter',
'ip_registration_newsletter',
'newsletter_date_add',
'optin',
'passwd',
'last_passwd_gen',
'active',
'is_guest',
'date_upd',
'years',
'days',
'months',
'description',
'meta_description',
'short_description',
'link_rewrite',
'meta_title',
'meta_keywords',
'display_tax_label',
'need_zip_code',
'contains_states',
'call_prefixes',
'call_prefix');
static public $forbiddenClassList = array(
'Manufacturer',
'Supplier');
public function getFields()
{
parent::validateFields();
$fields['id_country'] = (int)($this->id_country);
$fields['format'] = pSQL($this->format);
return $fields;
}
/*
* Check if the the association of the field name and a class name
* is valide
* @className is the name class
* @fieldName is a property name
* @isIdField boolean to know if we have to allowed a property name started by 'id_'
*/
private function _checkValidateClassField($className, $fieldName, $isIdField)
{
$isValide = false;
if (!class_exists($className))
$this->_errorFormatList[] = Tools::displayError('This class name doesn\'t exist').
': '.$className;
else
{
$obj = new $className();
$reflect = new ReflectionObject($obj);
// Check if the property is accessible
$publicProperties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach($publicProperties as $property)
{
$propertyName = $property->getName();
if (($propertyName == $fieldName) && ($isIdField ||
(!preg_match('#id|id_\w#', $propertyName, $match))))
$isValide = true;
}
if (!$isValide)
$this->_errorFormatList[] = Tools::displayError('This property doesn\'t exist in the class or is forbidden').
': '.$className.': '.$fieldName;
unset($obj);
unset($reflect);
}
return $isValide;
}
/*
* Verify the existence of a field name and check the availability
* of an association between a field name and a class (ClassName:fieldName)
* if the separator is overview
* @patternName is the composition of the class and field name
* @fieldsValidate contains the list of available field for the Address class
*/
private function _checkLiableAssociation($patternName, $fieldsValidate)
{
$patternName = trim($patternName);
$cleanedLine = '';
if ($associationName = explode(':', $patternName))
{
$totalNameUsed = count($associationName);
if ($totalNameUsed > 2)
$this->_errorFormatList[] = Tools::displayError('This assocation contains too much key name');
else if ($totalNameUsed == 1)
{
$associationName[0] = strtolower($associationName[0]);
$cleanedLine = $associationName[0];
if (in_array($associationName[0], self::$forbiddenProperyList) ||
!$this->_checkValidateClassField('Address', $associationName[0], false))
$this->_errorFormatList[] = Tools::displayError('This name isn\'t allowed').': '.
$associationName[0];
}
else if ($totalNameUsed == 2)
{
if (empty($associationName[0]) || empty($associationName[1]))
$this->_errorFormatList[] = Tools::displayError('Syntax error with this pattern').': '.$patternName;
else
{
$associationName[0] = ucfirst($associationName[0]);
$associationName[1] = strtolower($associationName[1]);
if (in_array($associationName[0], self::$forbiddenClassList))
$this->_errorFormatList[] = Tools::displayError('This name isn\'t allowed').': '.
$associationName[0];
else
{
// Check if the id field name exist in the Address class
$this->_checkValidateClassField('Address', 'id_'.strtolower($associationName[0]), true);
// Check if the field name exist in the class write by the user
$this->_checkValidateClassField($associationName[0], $associationName[1], false);
$cleanedLine = $associationName[0].':'.$associationName[1];
}
}
}
}
return (strlen($cleanedLine)) ? $cleanedLine.' ' : '';
}
/*
* Check if the set fields are valide
*/
public function checkFormatFields()
{
$cleanedContent = '';
$this->_errorFormatList = array();
$fieldsValidate = Address::getFieldsValidate();
$multipleLineFields = explode("\n", $this->format);
if ($multipleLineFields && is_array($multipleLineFields))
foreach($multipleLineFields as $lineField)
{
$lineField = str_replace(array("\n", "\t", "\r\n", "\r"), '', $lineField);
if (strlen($lineField))
{
$patternsName = explode(' ', trim($lineField));
if ($patternsName && is_array($patternsName))
{
foreach($patternsName as $patternName)
$cleanedContent .= $this->_checkLiableAssociation($patternName, $fieldsValidate);
$cleanedContent = trim($cleanedContent)."\r\n";
}
}
}
$this->format = $cleanedContent;
return (count($this->_errorFormatList)) ? false : true;
}
/*
* Returns the error list
*/
public function getErrorList()
{
return $this->_errorFormatList;
}
/*
* Returns the formatted fields with associated values
*
* @address is an instancied Address object
* @addressFormat is the format
* @return double Array
*/
public static function getFormattedAddressFieldsValues($address, $addressFormat)
{
global $cookie;
$tab = array();
$temporyObject = array();
// Check if $address exist and it's an instanciate object of Address
if ($address && ($address instanceof Address))
foreach($addressFormat as $lineNum => $line)
{
if (($keyList = explode(' ', $line)) && is_array($keyList))
foreach($keyList as $pattern)
if ($associateName = explode(':', $pattern))
{
$totalName = count($associateName);
if ($totalName == 1 && isset($address->{$associateName[0]}))
$tab[$associateName[0]] = $address->{$associateName[0]};
else
{
$tab[$pattern] = '';
// Check if the property exist in both classes
if (($totalName == 2) && class_exists($associateName[0]) &&
Tools::property_exists($associateName[0], $associateName[1]) &&
Tools::property_exists($address, 'id_'.strtolower($associateName[0])))
{
$idFieldName = 'id_'.strtolower($associateName[0]);
if (!isset($temporyObject[$associateName[0]]))
$temporyObject[$associateName[0]] = new $associateName[0]($address->{$idFieldName});
if ($temporyObject[$associateName[0]])
$tab[$pattern] = (is_array($temporyObject[$associateName[0]]->{$associateName[1]})) ?
((isset($temporyObject[$associateName[0]]->{$associateName[1]}[(isset($cookie) ? $cookie->id_lang : Configuration::get('PS_LANG_DEFAULT'))])) ?
$temporyObject[$associateName[0]]->{$associateName[1]}[(isset($cookie) ? $cookie->id_lang : Configuration::get('PS_LANG_DEFAULT'))] : '') :
$temporyObject[$associateName[0]]->{$associateName[1]};
}
}
}
}
// Free the instanciate objects
foreach($temporyObject as $objectName => &$object)
unset($object);
return $tab;
}
/*
* Generates the full address text
* @address is an instanciate object of Address class
* @patternrules is a defined rules array to avoid some pattern
* @newLine is a string containing the newLine format
* @separator is a string containing the separator format
*/
public static function generateAddress(Address $address, $patternRules, $newLine = "\r\n", $separator = ' ', $style = array())
{
$addressFields = AddressFormat::getOrderedAddressFields($address->id_country);
$addressFormatedValues = AddressFormat::getFormattedAddressFieldsValues($address, $addressFields);
$addressText = '';
foreach ($addressFields as $line)
if (($patternsList = explode(' ', $line)))
{
$tmpText = '';
foreach($patternsList as $pattern)
if (!in_array($pattern, $patternRules['avoid']))
$tmpText .= (isset($addressFormatedValues[$pattern])) ?
(((isset($style[$pattern])) ?
(sprintf($style[$pattern], $addressFormatedValues[$pattern])) :
$addressFormatedValues[$pattern]).$separator) : '';
$tmpText = trim($tmpText);
$addressText .= (!empty($tmpText)) ? $tmpText.$newLine: '';
}
return $addressText;
}
/**
* Returns selected fields required for an address in an array according to a selection hash
* @return array String values
*/
public static function getValidateFields($className)
{
$propertyList = array();
if (class_exists($className))
{
$object = new $className();
$reflect = new ReflectionObject($object);
// Check if the property is accessible
$publicProperties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach($publicProperties as $property)
{
$propertyName = $property->getName();
if ((!in_array($propertyName, AddressFormat::$forbiddenProperyList)) &&
(!preg_match('#id|id_\w#', $propertyName, $match)))
$propertyList[] = $propertyName;
}
unset($object);
unset($reflect);
}
return $propertyList;
}
/*
* Return a list of liable class of the className
*/
public static function getLiableClass($className)
{
$objectList = array();
if (class_exists($className))
{
$object = new $className();
$reflect = new ReflectionObject($object);
// Get all the name object liable to the Address class
$publicProperties = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
foreach($publicProperties as $property)
{
$propertyName = $property->getName();
if (preg_match('#id_\w#', $propertyName, $match) && strlen($propertyName) > 3)
{
$nameObject = ucfirst(substr($propertyName, 3));
if (!in_array($nameObject, self::$forbiddenClassList) &&
class_exists($nameObject))
$objectList[$nameObject] = new $nameObject();
}
}
unset($object);
unset($reflect);
}
return $objectList;
}
/**
* Returns address format fields in array by country
*
* @param Integer PS_COUNTRY.id if null using default country
* @return Array String field address format
*/
public static function getOrderedAddressFields($id_country = 0, $split_all = false)
{
$out = array();
$field_set = explode("\n", self::getAddressCountryFormat($id_country));
foreach ($field_set as $field_item)
if ($split_all)
foreach(explode(' ',$field_item) as $word_item)
$out[] = trim($word_item);
else
$out[] = trim($field_item);
return $out;
}
/**
* Returns address format by country if not defined using default country
*
* @param Integer PS_COUNTRY.id
* @return String field address format
*/
public static function getAddressCountryFormat($id_country = 0)
{
$out = '';
$id_country = (int) $id_country;
if ($id_country <= 0)
{
$selectedCountry = (int)(Configuration::get('PS_COUNTRY_DEFAULT'));
}
$tmp_obj = new AddressFormat();
$tmp_obj->id_country = $id_country;
$out = $tmp_obj->getFormat($tmp_obj->id_country);
unset($tmp_obj);
return $out;
}
/**
* Returns address format by country
*
* @param Integer PS_COUNTRY.id
* @return String field address format
*/
public function getFormat($id_country)
{
$out = $this->_getFormatDB($id_country);
if (strlen(trim($out)) == 0)
$out = $this->_getFormatDB(Configuration::get('PS_COUNTRY_DEFAULT'));
return $out;
}
private function _getFormatDB($id_country)
{
$result = Db::getInstance()->getRow('
SELECT format
FROM `'._DB_PREFIX_.$this->table.'`
WHERE `id_country` = '.(int)($id_country));
return isset($result['format']) ? trim($result['format']) : '';
}
}
+2226
View File
File diff suppressed because it is too large Load Diff
+95
View File
@@ -0,0 +1,95 @@
<?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 AliasCore extends ObjectModel
{
public $alias;
public $search;
public $active = true;
protected $fieldsRequired = array('alias', 'search');
protected $fieldsSize = array('alias' => 255, 'search' => 255);
protected $fieldsValidate = array('search' => 'isValidSearch', 'alias' => 'isValidSearch', 'active' => 'isBool');
protected $table = 'alias';
protected $identifier = 'id_alias';
function __construct($id = NULL, $alias = NULL, $search = NULL, $id_lang = NULL)
{
if ($id)
parent::__construct($id);
elseif ($alias AND Validate::isValidSearch($alias))
{
$row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT a.id_alias, a.search, a.alias
FROM `'._DB_PREFIX_.'alias` a
WHERE `alias` LIKE \''.pSQL($alias).'\' AND `active` = 1');
if ($row)
{
$this->id = (int)($row['id_alias']);
$this->search = $search ? trim($search) : $row['search'];
$this->alias = $row['alias'];
}
else
{
$this->alias = trim($alias);
$this->search = trim($search);
}
}
}
static public function deleteAliases($search)
{
return Db::getInstance()->Execute('
DELETE
FROM `'._DB_PREFIX_.'alias`
WHERE `search` LIKE \''.pSQL($search).'\'');
}
public function getAliases()
{
$aliases = Db::getInstance()->ExecuteS('
SELECT a.alias
FROM `'._DB_PREFIX_.'alias` a
WHERE `search` = \''.pSQL($this->search).'\'');
$aliases = array_map('implode', $aliases);
return implode(', ', $aliases);
}
public function getFields()
{
parent::validateFields();
$fields['alias'] = pSQL($this->alias);
$fields['search'] = pSQL($this->search);
$fields['active'] = (int)($this->active);
return $fields;
}
}
+106
View File
@@ -0,0 +1,106 @@
<?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 AttachmentCore extends ObjectModel
{
public $file;
public $file_name;
public $name;
public $mime;
public $description;
/** @var integer position */
public $position;
protected $fieldsRequired = array('file', 'mime');
protected $fieldsSize = array('file' => 40, 'mime' => 64, 'file_name' => 128);
protected $fieldsValidate = array('file' => 'isGenericName', 'mime' => 'isCleanHtml', 'file_name' => 'isGenericName');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 32);
protected $fieldsValidateLang = array('name' => 'isGenericName', 'description' => 'isCleanHtml');
protected $table = 'attachment';
protected $identifier = 'id_attachment';
public function getFields()
{
parent::validateFields();
$fields['file_name'] = pSQL($this->file_name);
$fields['file'] = pSQL($this->file);
$fields['mime'] = pSQL($this->mime);
return $fields;
}
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name', 'description'));
}
public function delete()
{
@unlink(_PS_DOWNLOAD_DIR_.$this->file);
Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'product_attachment WHERE id_attachment = '.(int)($this->id));
return parent::delete();
}
public function deleteSelection($attachments)
{
$return = 1;
foreach ($attachments AS $id_attachment)
{
$attachment = new Attachment((int)($id_attachment));
$return &= $attachment->delete();
}
return $return;
}
public static function getAttachments($id_lang, $id_product, $include = true)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM '._DB_PREFIX_.'attachment a
LEFT JOIN '._DB_PREFIX_.'attachment_lang al ON (a.id_attachment = al.id_attachment AND al.id_lang = '.(int)($id_lang).')
WHERE a.id_attachment '.($include ? 'IN' : 'NOT IN').' (SELECT pa.id_attachment FROM '._DB_PREFIX_.'product_attachment pa WHERE id_product = '.(int)($id_product).')');
}
public static function attachToProduct($id_product, $array)
{
$result1 = Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'product_attachment WHERE id_product = '.(int)($id_product));
if (is_array($array))
{
$ids = array();
foreach ($array as $id_attachment)
$ids[] = '('.(int)($id_product).','.(int)($id_attachment).')';
Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'product SET cache_has_attachments = '.(count($ids) ? '1' : '0').' WHERE id_product = '.(int)($id_product).' LIMIT 1');
return ($result1 && Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'product_attachment (id_product, id_attachment) VALUES '.implode(',',$ids)));
}
return $result1;
}
}
+205
View File
@@ -0,0 +1,205 @@
<?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: 7307 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class AttributeCore extends ObjectModel
{
/** @var integer Group id which attribute belongs */
public $id_attribute_group;
/** @var string Name */
public $name;
public $color;
public $default;
protected $fieldsRequired = array('id_attribute_group');
protected $fieldsValidate = array('id_attribute_group' => 'isUnsignedId', 'color' => 'isColor');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 64);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $table = 'attribute';
protected $identifier = 'id_attribute';
protected $webserviceParameters = array(
'objectsNodeName' => 'product_option_values',
'objectNodeName' => 'product_option_value',
'fields' => array(
'id_attribute_group' => array('xlink_resource'=> 'product_options'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_attribute_group'] = (int)($this->id_attribute_group);
$fields['color'] = pSQL($this->color);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
public function delete()
{
if (($result = Db::getInstance()->ExecuteS('SELECT `id_product_attribute` FROM `'._DB_PREFIX_.'product_attribute_combination` WHERE `'.$this->identifier.'` = '.(int)($this->id))) === false)
return false;
$combinationIds = array();
if (Db::getInstance()->numRows())
{
foreach ($result AS $row)
$combinationIds[] = (int)($row['id_product_attribute']);
if (Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'product_attribute_combination` WHERE `'.$this->identifier.'` = '.(int)($this->id)) === false)
return false;
if (Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'product_attribute` WHERE `id_product_attribute` IN ('.implode(', ', $combinationIds).')') === false)
return false;
}
return parent::delete();
}
/**
* Get all attributes for a given language
*
* @param integer $id_lang Language id
* @param boolean $notNull Get only not null fields if true
* @return array Attributes
*/
static public function getAttributes($id_lang, $notNull = false)
{
return Db::getInstance()->ExecuteS('
SELECT ag.*, agl.*, a.`id_attribute`, al.`name`, agl.`name` AS `attribute_group`
FROM `'._DB_PREFIX_.'attribute_group` ag
LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND agl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'attribute` a ON a.`id_attribute_group` = ag.`id_attribute_group`
LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = '.(int)($id_lang).')
'.($notNull ? 'WHERE a.`id_attribute` IS NOT NULL AND al.`name` IS NOT NULL' : '').'
ORDER BY agl.`name` ASC, al.`name` ASC');
}
/**
* Get quantity for a given attribute combinaison
* Check if quantity is enough to deserve customer
*
* @param integer $id_product_attribute Product attribute combinaison id
* @param integer $qty Quantity needed
* @return boolean Quantity is available or not
*/
static public function checkAttributeQty($id_product_attribute, $qty)
{
$sql = 'SELECT quantity
FROM '._DB_PREFIX_.'stock
WHERE id_product_attribute = '.(int)$id_product_attribute
.Shop::sqlSharedStock();
$result = (int)Db::getInstance()->getValue($sql);
return ($result AND $qty <= $result);
}
/**
* Get quantity for product with attributes quantity
*
* @deprecated since 1.5.0, use Product->getStock()
* @param integer $id_product
* @return mixed Quantity or false
*/
static public function getAttributeQty($id_product)
{
Tools::displayAsDeprecated();
$row = Db::getInstance()->getRow('
SELECT SUM(quantity) as quantity
FROM `'._DB_PREFIX_.'product_attribute`
WHERE `id_product` = '.(int)($id_product));
if ($row['quantity'] !== NULL)
return (int)($row['quantity']);
return false;
}
/**
* Update array with veritable quantity
*
* @deprecated since 1.5.0
* @param array &$arr
* return bool
*/
static public function updateQtyProduct(&$arr)
{
Tools::displayAsDeprecated();
$id_product = (int)($arr['id_product']);
$qty = self::getAttributeQty($id_product);
if ($qty !== false)
{
$arr['quantity'] = (int)($qty);
return true;
}
return false;
}
public function isColorAttribute()
{
if (!Db::getInstance()->getRow('
SELECT `is_color_group` FROM `'._DB_PREFIX_.'attribute_group` WHERE `id_attribute_group` = (
SELECT `id_attribute_group` FROM `'._DB_PREFIX_.'attribute` WHERE `id_attribute` = '.(int)($this->id).')
AND is_color_group = 1'))
return false;
return Db::getInstance()->NumRows();
}
/**
* Get minimal quantity for product with attributes quantity
*
* @acces public static
* @param integer $id_product_attribute
* @return mixed Minimal Quantity or false
*/
static public function getAttributeMinimalQty($id_product_attribute)
{
$minimal_quantity = Db::getInstance()->getValue('
SELECT `minimal_quantity`
FROM `'._DB_PREFIX_.'product_attribute`
WHERE `id_product_attribute` = '.(int)($id_product_attribute));
if ($minimal_quantity > 1)
return (int)$minimal_quantity;
return false;
}
}
+195
View File
@@ -0,0 +1,195 @@
<?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 AttributeGroupCore extends ObjectModel
{
/** @var string Name */
public $name;
public $is_color_group;
/** @var string Public Name */
public $public_name;
protected $fieldsRequired = array();
protected $fieldsValidate = array('is_color_group' => 'isBool');
protected $fieldsRequiredLang = array('name', 'public_name');
protected $fieldsSizeLang = array('name' => 64, 'public_name' => 64);
protected $fieldsValidateLang = array('name' => 'isGenericName', 'public_name' => 'isGenericName');
protected $table = 'attribute_group';
protected $identifier = 'id_attribute_group';
protected $webserviceParameters = array(
'objectsNodeName' => 'product_options',
'objectNodeName' => 'product_option',
'fields' => array(),
'associations' => array(
'product_option_values' => array('resource' => 'product_option_value',
'fields' => array(
'id' => array(),
),
),
),
);
public function getFields()
{
parent::validateFields();
$fields['is_color_group'] = (int)($this->is_color_group);
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
return parent::add($autodate, true);
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name', 'public_name'));
}
static public function cleanDeadCombinations()
{
$attributeCombinations = Db::getInstance()->ExecuteS('SELECT pac.`id_attribute`, pa.`id_product_attribute` FROM `'._DB_PREFIX_.'product_attribute` pa LEFT JOIN `'._DB_PREFIX_.'product_attribute_combination` pac ON (pa.`id_product_attribute` = pac.`id_product_attribute`)');
$toRemove = array();
foreach ($attributeCombinations AS $attributeCombination)
if ((int)($attributeCombination['id_attribute']) == 0)
$toRemove[] = (int)($attributeCombination['id_product_attribute']);
if (!empty($toRemove) AND Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'product_attribute` WHERE `id_product_attribute` IN ('.implode(', ', $toRemove).')') === false)
return false;
return true;
}
public function delete()
{
/* Select children in order to find linked combinations */
$attributeIds = Db::getInstance()->ExecuteS('SELECT `id_attribute` FROM `'._DB_PREFIX_.'attribute` WHERE `id_attribute_group` = '.(int)($this->id));
if ($attributeIds === false)
return false;
/* Removing attributes to the found combinations */
$toRemove = array();
foreach ($attributeIds AS $attribute)
$toRemove[] = (int)($attribute['id_attribute']);
if (!empty($toRemove) AND Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'product_attribute_combination` WHERE `id_attribute` IN ('.implode(', ', $toRemove).')') === false)
return false;
/* Remove combinations if they do not possess attributes anymore */
if (!self::cleanDeadCombinations())
return false;
/* Also delete related attributes */
if (Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'attribute_lang` WHERE `id_attribute` IN (SELECT id_attribute FROM `'._DB_PREFIX_.'attribute` WHERE `id_attribute_group` = '.(int)($this->id).')') === false OR Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'attribute` WHERE `id_attribute_group` = '.(int)($this->id)) === false)
return false;
return parent::delete();
}
/**
* Get all attributes for a given language / group
*
* @param integer $id_lang Language id
* @param boolean $id_attribute_group Attribute group id
* @return array Attributes
*/
static public function getAttributes($id_lang, $id_attribute_group)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'attribute` a
LEFT JOIN `'._DB_PREFIX_.'attribute_lang` al ON (a.`id_attribute` = al.`id_attribute` AND al.`id_lang` = '.(int)($id_lang).')
WHERE a.`id_attribute_group` = '.(int)($id_attribute_group).'
ORDER BY `name`');
}
/**
* Get all attributes groups for a given language
*
* @param integer $id_lang Language id
* @return array Attributes groups
*/
static public function getAttributesGroups($id_lang)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'attribute_group` ag
LEFT JOIN `'._DB_PREFIX_.'attribute_group_lang` agl ON (ag.`id_attribute_group` = agl.`id_attribute_group` AND `id_lang` = '.(int)($id_lang).')
ORDER BY `name` ASC');
}
/**
* Delete several objects from database
*
* return boolean Deletion result
*/
public function deleteSelection($selection)
{
/* Also delete Attributes */
foreach ($selection AS $value) {
$obj = new AttributeGroup($value);
if (!$obj->delete())
return false;
}
return true;
}
public function setWsProductOptionValues($values)
{
$ids = array();
foreach ($values as $value)
$ids[] = intval($value['id']);
Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'attribute`
WHERE `id_attribute_group` = '.(int)$this->id.'
AND `id_attribute` NOT IN ('.implode(',', $ids).')'
);
$ok = true;
foreach ($values as $value)
{
$result = Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'attribute`
SET `id_attribute_group` = '.(int)$this->id.'
WHERE `id_attribute` = '.(int)$value['id']
);
if ($result === false)
$ok = false;
}
return $ok;
}
public function getWsProductOptionValues()
{
$result = Db::getInstance()->executeS('SELECT id_attribute AS id from `'._DB_PREFIX_.'attribute` WHERE id_attribute_group = '.(int)$this->id);
return $result;
}
}
+252
View File
@@ -0,0 +1,252 @@
<?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 BackupCore
{
/** @var integer Object id */
public $id;
/** @var string Last error messages */
public $error;
/**
* Creates a new backup object
*
* @param string $filename Filename of the backup file
*/
public function __construct($filename = NULL)
{
if ($filename)
$this->id = self::getBackupPath($filename);
}
/**
* Get the full path of the backup file
*
* @param string $filename Filename of the backup file
* @return The full path of the backup file, or false if the backup file does not exists
*/
public static function getBackupPath($filename)
{
$backupdir = realpath(PS_ADMIN_DIR.'/backups/');
if ($backupdir === false)
die(Tools::displayError('Backups directory does not exist.'));
// Check the realpath so we can validate the backup file is under the backup directory
$backupfile = realpath($backupdir.'/'.$filename);
if ($backupfile === false OR strncmp($backupdir, $backupfile, strlen($backupdir)) != 0)
die (Tools::displayError());
return $backupfile;
}
/**
* Get the URL used to retreive this backup file
*
* @return The url used to request the backup file
*/
public function getBackupURL()
{
$adminDir = __PS_BASE_URI__.substr($_SERVER['SCRIPT_NAME'], strlen(__PS_BASE_URI__) );
$adminDir = substr($adminDir, 0, strrpos($adminDir, '/'));
return $adminDir.'/backup.php?filename='.basename($this->id);
}
/**
* Delete the current backup file
*
* @return boolean Deletion result, true on success
*/
public function delete()
{
if (!$this->id || !unlink($this->id))
{
$this->error = Tools::displayError('Error deleting').' '.($this->id ? '"'.$this->id.'"' : Tools::displayError('Invalid ID'));
return false;
}
return true;
}
/**
* Deletes a range of backup files
*
* @return boolean True on success
*/
public function deleteSelection($list)
{
foreach ($list as $file)
{
$backup = new Backup($file);
if (!$backup->delete())
{
$this->error = $backup->error;
return false;
}
}
return true;
}
/**
* Creates a new backup file
*
* @return boolean true on successful backup
*/
public function add()
{
if ( _DB_TYPE_ !== 'MySQL' )
{
$this->error = Tools::displayError('Sorry, backup currently only supports MySQL database types. You are using') . ' "' . _DB_TYPE_ . '"';
return false;
}
if (!Configuration::get('PS_BACKUP_ALL'))
$ignore_insert_table = array(_DB_PREFIX_.'connections', _DB_PREFIX_.'connections_page', _DB_PREFIX_.'connections_source', _DB_PREFIX_.'guest', _DB_PREFIX_.'statssearch');
else
$ignore_insert_table = array();
// Generate some random number, to make it extra hard to guess backup file names
$rand = dechex ( mt_rand(0, min(0xffffffff, mt_getrandmax() ) ) );
$date = time();
$backupfile = PS_ADMIN_DIR . '/backups/' . $date . '-' . $rand . '.sql';
// Figure out what compression is available and open the file
if (function_exists('bzopen'))
{
$backupfile .= '.bz2';
$fp = @bzopen($backupfile, 'w');
}
else if (function_exists('gzopen'))
{
$backupfile .= '.gz';
$fp = @gzopen($backupfile, 'w');
}
else
$fp = @fopen($backupfile, 'w');
if ($fp === false)
{
echo Tools::displayError('Unable to create backup file') . ' "' . addslashes($backupfile) . '"';
return false;
}
$this->id = realpath($backupfile);
fwrite($fp, '/* Backup for ' . Tools::getHttpHost(false, false) . __PS_BASE_URI__ . "\n * at " . date($date) . "\n */\n");
fwrite($fp, "\n".'SET NAMES \'utf8\';'."\n\n");
// Find all tables
$tables = Db::getInstance()->ExecuteS('SHOW TABLES');
$found = 0;
foreach ($tables AS $table)
{
$table = current($table);
// Skip tables which do not start with _DB_PREFIX_
if (strlen($table) < strlen(_DB_PREFIX_) || strncmp($table, _DB_PREFIX_, strlen(_DB_PREFIX_)) != 0)
continue;
// Export the table schema
$schema = Db::getInstance()->ExecuteS('SHOW CREATE TABLE `' . $table . '`');
if (count($schema) != 1 || !isset($schema[0]['Table']) || !isset($schema[0]['Create Table']))
{
fclose($fp);
$this->delete();
echo Tools::displayError('An error occurred while backing up. Unable to obtain the schema of').' "'.$table;
return false;
}
fwrite($fp, '/* Scheme for table ' . $schema[0]['Table'] . " */\n");
if (Configuration::get('PS_BACKUP_DROP_TABLE'))
fwrite($fp, 'DROP TABLE IF EXISTS `'.$schema[0]['Table'].'`;'."\n");
fwrite($fp, $schema[0]['Create Table'] . ";\n\n");
if (!in_array($schema[0]['Table'], $ignore_insert_table))
{
$data = Db::getInstance()->ExecuteS('SELECT * FROM `' . $schema[0]['Table'] . '`', false);
$sizeof = DB::getInstance()->NumRows();
$lines = explode("\n", $schema[0]['Create Table']);
if ($data AND $sizeof > 0)
{
// Export the table data
fwrite($fp, 'INSERT INTO `' . $schema[0]['Table'] . "` VALUES\n");
$i = 1;
while ($row = DB::getInstance()->nextRow($data))
{
$s = '(';
foreach ($row AS $field => $value)
{
$tmp = "'" . mysql_real_escape_string($value) . "',";
if($tmp != "'',")
$s .= $tmp;
else
{
foreach($lines AS $line)
if (strpos($line, '`'.$field.'`') !== false)
{
if (preg_match('/(.*NOT NULL.*)/Ui', $line))
$s .= "'',";
else
$s .= 'NULL,';
break;
}
}
}
$s = rtrim($s, ',');
if ($i%200 == 0 AND $i < $sizeof)
$s .= ");\nINSERT INTO `".$schema[0]['Table']."` VALUES\n";
elseif ($i < $sizeof)
$s .= "),\n";
else
$s .= ");\n";
fwrite($fp, $s);
++$i;
}
}
}
$found++;
}
fclose($fp);
if ($found == 0)
{
$this->delete();
echo Tools::displayError('No valid tables were found to backup.' );
return false;
}
return true;
}
}
+484
View File
@@ -0,0 +1,484 @@
<?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
*/
define('PS_UNPACK_NATIVE', 1);
define('PS_UNPACK_MODIFIED', 2);
class Crypt_Blowfish
{
var $_P = array(
0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344,
0xA4093822, 0x299F31D0, 0x082EFA98, 0xEC4E6C89,
0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C,
0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5, 0xB5470917,
0x9216D5D9, 0x8979FB1B
);
var $_S = array(
array(
0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7,
0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99,
0x24A19947, 0xB3916CF7, 0x0801F2E2, 0x858EFC16,
0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E,
0x0D95748F, 0x728EB658, 0x718BCD58, 0x82154AEE,
0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013,
0xC5D1B023, 0x286085F0, 0xCA417918, 0xB8DB38EF,
0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E,
0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60,
0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440,
0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE,
0xA15486AF, 0x7C72E993, 0xB3EE1411, 0x636FBC2A,
0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E,
0xAFD6BA33, 0x6C24CF5C, 0x7A325381, 0x28958677,
0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193,
0x61D809CC, 0xFB21A991, 0x487CAC60, 0x5DEC8032,
0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88,
0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239,
0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E,
0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0,
0x6A51A0D2, 0xD8542F68, 0x960FA728, 0xAB5133A3,
0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98,
0xA1F1651D, 0x39AF0176, 0x66CA593E, 0x82430E88,
0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE,
0xE06F75D8, 0x85C12073, 0x401A449F, 0x56C16AA6,
0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D,
0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B,
0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7,
0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA,
0xC1A94FB6, 0x409F60C4, 0x5E5C9EC2, 0x196A2463,
0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F,
0x6DFC511F, 0x9B30952C, 0xCC814544, 0xAF5EBD09,
0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3,
0xC0CBA857, 0x45C8740F, 0xD20B5F39, 0xB9D3FBDB,
0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279,
0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8,
0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB,
0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82,
0x9E5C57BB, 0xCA6F8CA0, 0x1A87562E, 0xDF1769DB,
0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573,
0x695B27B0, 0xBBCA58C8, 0xE1FFA35D, 0xB8F011A0,
0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B,
0x9A53E479, 0xB6F84565, 0xD28E49BC, 0x4BFB9790,
0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8,
0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4,
0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0,
0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7,
0x8FF6E2FB, 0xF2122B64, 0x8888B812, 0x900DF01C,
0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD,
0x2F2F2218, 0xBE0E1777, 0xEA752DFE, 0x8B021FA1,
0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299,
0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81, 0xD2ADA8D9,
0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477,
0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF,
0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49,
0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF,
0x2464369B, 0xF009B91E, 0x5563911D, 0x59DFA6AA,
0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5,
0x83260376, 0x6295CFA9, 0x11C81968, 0x4E734A41,
0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915,
0xD60F573F, 0xBC9BC6E4, 0x2B60A476, 0x81E67400,
0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915,
0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664,
0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A
),
array(
0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623,
0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266,
0xECAA8C71, 0x699A17FF, 0x5664526C, 0xC2B19EE1,
0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E,
0x3F54989A, 0x5B429D65, 0x6B8FE4D6, 0x99F73FD6,
0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1,
0x4CDD2086, 0x8470EB26, 0x6382E9C6, 0x021ECC5E,
0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1,
0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737,
0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8,
0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF,
0xAE0CF51A, 0x3CB574B2, 0x25837A58, 0xDC0921BD,
0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701,
0x3AE5E581, 0x37C2DADC, 0xC8B57634, 0x9AF3DDA7,
0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41,
0xE238CD99, 0x3BEA0E2F, 0x3280BBA1, 0x183EB331,
0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF,
0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF,
0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E,
0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87,
0x7A584718, 0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C,
0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2,
0xEF1C1847, 0x3215D908, 0xDD433B37, 0x24C2BA16,
0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD,
0x71DFF89E, 0x10314E55, 0x81AC77D6, 0x5F11199B,
0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509,
0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E,
0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3,
0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F,
0x803E89D6, 0x5266C825, 0x2E4CC978, 0x9C10B36A,
0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4,
0xF2F74EA7, 0x361D2B3D, 0x1939260F, 0x19C27960,
0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66,
0xE3BC4595, 0xA67BC883, 0xB17F37D1, 0x018CFF28,
0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802,
0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84,
0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510,
0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF,
0xB5735C90, 0x4C70A239, 0xD59E9E0B, 0xCBAADE14,
0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E,
0x648B1EAF, 0x19BDF0CA, 0xA02369B9, 0x655ABB50,
0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7,
0x9B540B19, 0x875FA099, 0x95F7997E, 0x623D7DA8,
0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281,
0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99,
0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696,
0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128,
0x58EBF2EF, 0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73,
0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0,
0x45EEE2B6, 0xA3AAABEA, 0xDB6C4F15, 0xFACB4FD0,
0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105,
0xD81E799E, 0x86854DC7, 0xE44B476A, 0x3D816250,
0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3,
0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285,
0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00,
0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061,
0x3372F092, 0x8D937E41, 0xD65FECF1, 0x6C223BDB,
0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E,
0xA6078084, 0x19F8509E, 0xE8EFD855, 0x61D99735,
0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC,
0x9E447A2E, 0xC3453484, 0xFDD56705, 0x0E1E9EC9,
0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340,
0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20,
0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7
),
array(
0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934,
0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068,
0xD4082471, 0x3320F46A, 0x43B7D4B7, 0x500061AF,
0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840,
0x4D95FC1D, 0x96B591AF, 0x70F4DDD3, 0x66A02F45,
0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504,
0x96EB27B3, 0x55FD3941, 0xDA2547E6, 0xABCA0A9A,
0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB,
0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE,
0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6,
0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42,
0x20FE9E35, 0xD9F385B9, 0xEE39D7AB, 0x3B124E8B,
0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2,
0x3A6EFA74, 0xDD5B4332, 0x6841E7F7, 0xCA7820FB,
0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527,
0x55533A3A, 0x20838D87, 0xFE6BA9B7, 0xD096954B,
0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33,
0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C,
0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3,
0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC,
0x07F9C9EE, 0x41041F0F, 0x404779A4, 0x5D886E17,
0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564,
0x257B7834, 0x602A9C60, 0xDFF8E8A3, 0x1F636C1B,
0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115,
0x6B2395E0, 0x333E92E1, 0x3B240B62, 0xEEBEB922,
0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728,
0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0,
0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E,
0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37,
0xA812DC60, 0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D,
0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804,
0xF1290DC7, 0xCC00FFA3, 0xB5390F92, 0x690FED0B,
0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3,
0xBB132F88, 0x515BAD24, 0x7B9479BF, 0x763BD6EB,
0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D,
0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C,
0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350,
0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9,
0x44421659, 0x0A121386, 0xD90CEC6E, 0xD5ABEA2A,
0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE,
0x9DBC8057, 0xF0F7C086, 0x60787BF8, 0x6003604D,
0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC,
0x83426B33, 0xF01EAB71, 0xB0804187, 0x3C005E5F,
0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61,
0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2,
0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9,
0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2,
0x466E598E, 0x20B45770, 0x8CD55591, 0xC902DE4C,
0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E,
0xB77F19B6, 0xE0A9DC09, 0x662D09A1, 0xC4324633,
0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10,
0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F, 0x2868F169,
0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52,
0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027,
0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5,
0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62,
0x11E69ED7, 0x2338EA63, 0x53C2DD94, 0xC2C21634,
0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76,
0x6F05E409, 0x4B7C0188, 0x39720A3D, 0x7C927C24,
0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC,
0xED545578, 0x08FCA5B5, 0xD83D7CD3, 0x4DAD0FC4,
0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C,
0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837,
0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0
),
array(
0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B,
0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE,
0xD5118E9D, 0xBF0F7315, 0xD62D1C7E, 0xC700C47B,
0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4,
0x5748AB2F, 0xBC946E79, 0xC6A376D2, 0x6549C2C8,
0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6,
0x2939BBDB, 0xA9BA4650, 0xAC9526E8, 0xBE5EE304,
0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22,
0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4,
0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6,
0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9,
0xC72FEFD3, 0xF752F7DA, 0x3F046F69, 0x77FA0A59,
0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593,
0xE990FD5A, 0x9E34D797, 0x2CF0B7D9, 0x022B8B51,
0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28,
0x1F9F25CF, 0xADF2B89B, 0x5AD6B472, 0x5A88F54C,
0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B,
0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28,
0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C,
0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD,
0xC3EB9E15, 0x3C9057A2, 0x97271AEC, 0xA93A072A,
0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319,
0x7533D928, 0xB155FDF5, 0x03563482, 0x8ABA3CBB,
0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F,
0x4DE81751, 0x3830DC8E, 0x379D5862, 0x9320F991,
0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32,
0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680,
0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166,
0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE,
0x5BBEF7DD, 0x1B588D40, 0xCCD2017F, 0x6BB4E3BB,
0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5,
0x72EACEA8, 0xFA6484BB, 0x8D6612AE, 0xBF3C6F47,
0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370,
0x740E0D8D, 0xE75B1357, 0xF8721671, 0xAF537D5D,
0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84,
0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048,
0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8,
0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD,
0xA08839E1, 0x51CE794B, 0x2F32C9B7, 0xA01FBAC9,
0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7,
0x1A908749, 0xD44FBD9A, 0xD0DADECB, 0xD50ADA38,
0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F,
0xF79E59B7, 0x43F5BB3A, 0xF2D519FF, 0x27D9459C,
0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525,
0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1,
0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442,
0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964,
0x9F1F9532, 0xE0D392DF, 0xD3A0342B, 0x8971F21E,
0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8,
0xDF359F8D, 0x9B992F2E, 0xE60B6F47, 0x0FE3F11D,
0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F,
0x1618B166, 0xFD2C1D05, 0x848FD2C5, 0xF6FB2299,
0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02,
0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC,
0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614,
0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A,
0xC9AA53FD, 0x62A80F00, 0xBB25BFE2, 0x35BDD2F6,
0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B,
0x53113EC0, 0x1640E3D3, 0x38ABBD60, 0x2547ADF0,
0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060,
0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0, 0x4CF9AA7E,
0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9,
0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F,
0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6
)
);
var $_iv = NULL;
protected $_unpackMode = PS_UNPACK_NATIVE;
function __construct($key, $iv)
{
$_iv = $iv;
$len = strlen($key);
$k = 0;
$data = 0;
$datal = 0;
$datar = 0;
if (PHP_VERSION_ID == '50201' OR PHP_VERSION_ID == '50206')
$this->_unpackMode = PS_UNPACK_MODIFIED;
for ($i = 0; $i < 18; $i++)
{
$data = 0;
for ($j = 4; $j > 0; $j--)
{
$data = $data << 8 | ord($key{$k});
$k = ($k + 1) % $len;
}
$this->_P[$i] ^= $data;
}
for ($i = 0; $i <= 16; $i += 2) {
$this->_encipher($datal, $datar);
$this->_P[$i] = $datal;
$this->_P[$i+1] = $datar;
}
for ($i = 0; $i < 256; $i += 2) {
$this->_encipher($datal, $datar);
$this->_S[0][$i] = $datal;
$this->_S[0][$i+1] = $datar;
}
for ($i = 0; $i < 256; $i += 2) {
$this->_encipher($datal, $datar);
$this->_S[1][$i] = $datal;
$this->_S[1][$i+1] = $datar;
}
for ($i = 0; $i < 256; $i += 2) {
$this->_encipher($datal, $datar);
$this->_S[2][$i] = $datal;
$this->_S[2][$i+1] = $datar;
}
for ($i = 0; $i < 256; $i += 2) {
$this->_encipher($datal, $datar);
$this->_S[3][$i] = $datal;
$this->_S[3][$i+1] = $datar;
}
}
function _encipher(&$Xl, &$Xr)
{
for ($i = 0; $i < 16; $i++) {
$temp = $Xl ^ $this->_P[$i];
$Xl = ((($this->_S[0][($temp>>24) & 255] +
$this->_S[1][($temp>>16) & 255]) ^
$this->_S[2][($temp>>8) & 255]) +
$this->_S[3][$temp & 255]) ^ $Xr;
$Xr = $temp;
}
$Xr = $Xl ^ $this->_P[16];
$Xl = $temp ^ $this->_P[17];
}
function _decipher(&$Xl, &$Xr)
{
for ($i = 17; $i > 1; $i--)
{
$temp = $Xl ^ $this->_P[$i];
$Xl = ((($this->_S[0][($temp>>24) & 255] +
$this->_S[1][($temp>>16) & 255]) ^
$this->_S[2][($temp>>8) & 255]) +
$this->_S[3][$temp & 255]) ^ $Xr;
$Xr = $temp;
}
$Xr = $Xl ^ $this->_P[1];
$Xl = $temp ^ $this->_P[0];
}
function encrypt($plainText)
{
$cipherText = '';
$len = strlen($plainText);
$plainText .= str_repeat(chr(0), (8 - ($len % 8)) % 8);
for ($i = 0; $i < $len; $i += 8)
{
list(, $Xl, $Xr) = ($this->_unpackMode == PS_UNPACK_NATIVE ? unpack('N2', substr($plainText, $i, 8)) : $this->myUnpackN2(substr($plainText, $i, 8)));
$this->_encipher($Xl, $Xr);
$cipherText .= pack('N2', $Xl, $Xr);
}
return $cipherText;
}
function decrypt($cipherText)
{
$plainText = '';
$len = strlen($cipherText);
$cipherText .= str_repeat(chr(0), (8 - ($len % 8)) % 8);
for ($i = 0; $i < $len; $i += 8)
{
list(, $Xl, $Xr) = ($this->_unpackMode == PS_UNPACK_NATIVE ? unpack('N2', substr($cipherText, $i, 8)) : $this->myUnpackN2(substr($cipherText, $i, 8)));
$this->_decipher($Xl, $Xr);
$plainText .= pack('N2', $Xl, $Xr);
}
return $plainText;
}
function myUnpackN($str)
{
if (pack('L', 0x6162797A) == pack('V', 0x6162797A))
return ((ord($str) << 24) | (ord(substr($str, 1)) << 16) | (ord(substr($str, 2)) << 8) | ord(substr($str, 3)));
else
return (ord($str) | (ord(substr($str, 1)) << 8) | (ord(substr($str, 2)) << 16) | (ord(substr($str, 3)) << 24));
}
function myUnpackN2($str)
{
return array('1' => $this->myUnpackN($str), '2' => $this->myUnpackN(substr($str, 4)));
}
}
class BlowfishCore extends Crypt_Blowfish
{
function encrypt($plaintext)
{
if (($length = strlen($plaintext)) >= 1048576)
return false;
$ciphertext = '';
$paddedtext = $this->maxi_pad($plaintext);
$strlen = strlen($paddedtext);
for($x = 0; $x < $strlen; $x += 8)
{
$piece = substr($paddedtext, $x, 8);
$cipher_piece = parent::encrypt($piece);
$encoded = base64_encode($cipher_piece);
$ciphertext = $ciphertext.$encoded;
}
return $ciphertext.sprintf('%06d', $length);
}
function decrypt($ciphertext)
{
$plainTextLength = intval(substr($ciphertext, -6));
$ciphertext = substr($ciphertext, 0, -6);
$plaintext = '';
$chunks = explode('=', $ciphertext);
$ending_value = sizeof($chunks) ;
for($counter = 0; $counter < ($ending_value - 1); $counter++)
{
$chunk = $chunks[$counter].'=';
$decoded = base64_decode($chunk);
$piece = parent::decrypt($decoded);
$plaintext = $plaintext.$piece;
}
return substr($plaintext, 0, $plainTextLength);
}
function maxi_pad($plaintext)
{
$str_len = sizeof($plaintext);
$pad_len = $str_len % 8;
for($x = 0; $x < $pad_len; $x++)
$plaintext = $plaintext.' ';
return $plaintext;
}
}
+255
View File
@@ -0,0 +1,255 @@
<?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
*/
class CMSCore extends ObjectModel
{
/** @var string Name */
public $meta_title;
public $meta_description;
public $meta_keywords;
public $content;
public $link_rewrite;
public $id_cms_category;
public $position;
public $active;
protected $fieldsValidate = array('id_cms_category' => 'isUnsignedInt');
protected $fieldsRequiredLang = array('meta_title', 'link_rewrite');
protected $fieldsSizeLang = array('meta_description' => 255, 'meta_keywords' => 255, 'meta_title' => 128, 'link_rewrite' => 128, 'content' => 3999999999999);
protected $fieldsValidateLang = array('meta_description' => 'isGenericName', 'meta_keywords' => 'isGenericName', 'meta_title' => 'isGenericName', 'link_rewrite' => 'isLinkRewrite', 'content' => 'isString');
protected $table = 'cms';
protected $identifier = 'id_cms';
public function getFields()
{
parent::validateFields();
$fields['id_cms'] = (int)($this->id);
$fields['id_cms_category'] = (int)($this->id_cms_category);
$fields['position'] = (int)($this->position);
$fields['active'] = (int)($this->active);
return $fields;
}
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
$fieldsArray = array('meta_title', 'meta_description', 'meta_keywords', 'link_rewrite');
$fields = array();
$languages = Language::getLanguages(false);
$defaultLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));
foreach ($languages as $language)
{
$fields[$language['id_lang']]['id_lang'] = (int)($language['id_lang']);
$fields[$language['id_lang']][$this->identifier] = (int)($this->id);
$fields[$language['id_lang']]['content'] = (isset($this->content[$language['id_lang']])) ? pSQL($this->content[$language['id_lang']], true) : '';
foreach ($fieldsArray as $field)
{
if (!Validate::isTableOrIdentifier($field))
die(Tools::displayError());
if (isset($this->{$field}[$language['id_lang']]) AND !empty($this->{$field}[$language['id_lang']]))
$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$language['id_lang']]);
elseif (in_array($field, $this->fieldsRequiredLang))
$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$defaultLanguage]);
else
$fields[$language['id_lang']][$field] = '';
}
}
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
$this->position = CMS::getLastPosition((int)$this->id_cms_category);
return parent::add($autodate, true);
}
public function update($nullValues = false)
{
if (parent::update($nullValues))
return $this->cleanPositions($this->id_cms_category);
return false;
}
public function delete()
{
if (parent::delete())
return $this->cleanPositions($this->id_cms_category);
return false;
}
public static function getLinks($id_lang, $selection = NULL, $active = true, $id_shop = false)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.id_cms, cl.link_rewrite, cl.meta_title
FROM '._DB_PREFIX_.'cms c
LEFT JOIN '._DB_PREFIX_.'cms_lang cl ON (c.id_cms = cl.id_cms AND cl.id_lang = '.(int)($id_lang).')
WHERE 1
'.(($selection !== NULL) ? ' AND c.id_cms IN ('.implode(',', array_map('intval', $selection)).')' : '').
($active ? ' AND c.`active` = 1 ' : '').
'ORDER BY c.`position`');
$link = new Link();
$links = array();
if ($result)
foreach ($result as $row)
{
$row['link'] = $link->getCMSLink((int)($row['id_cms']), $row['link_rewrite']);
$links[] = $row;
}
return $links;
}
public static function listCms($id_lang = NULL, $id_block = false, $active = true)
{
if (empty($id_lang))
$id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.id_cms, l.meta_title
FROM '._DB_PREFIX_.'cms c
JOIN '._DB_PREFIX_.'cms_lang l ON (c.id_cms = l.id_cms)
'.(($id_block) ? 'JOIN '._DB_PREFIX_.'block_cms b ON (c.id_cms = b.id_cms)' : '').'
WHERE l.id_lang = '.(int)($id_lang).(($id_block) ? ' AND b.id_block = '.(int)($id_block) : '').($active ? ' AND c.`active` = 1 ' : '').'
ORDER BY c.`position`');
}
/**
* @deprecated
*/
public static function isInBlock($id_cms, $id_block)
{
Tools::displayAsDeprecated();
Db::getInstance()->getRow('
SELECT id_cms FROM '._DB_PREFIX_.'block_cms
WHERE id_block = '.(int)($id_block).' AND id_cms = '.(int)($id_cms));
return (Db::getInstance()->NumRows());
}
/**
* @deprecated
*/
public static function updateCmsToBlock($cms, $id_block)
{
Tools::displayAsDeprecated();
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'block_cms` WHERE `id_block` = '.(int)($id_block));
$list = '';
foreach ($cms AS $id_cms)
$list .= '('.(int)($id_block).', '.(int)($id_cms).'),';
$list = rtrim($list, ',');
if (!empty($list))
Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'block_cms (id_block, id_cms) VALUES '.pSQL($list));
return true;
}
public function updatePosition($way, $position)
{
if (!$res = Db::getInstance()->ExecuteS('
SELECT cp.`id_cms`, cp.`position`, cp.`id_cms_category`
FROM `'._DB_PREFIX_.'cms` cp
WHERE cp.`id_cms_category` = '.(int)$this->id_cms_category.'
ORDER BY cp.`position` ASC'
))
return false;
foreach ($res AS $cms)
if ((int)($cms['id_cms']) == (int)($this->id))
$movedCms = $cms;
if (!isset($movedCms) || !isset($position))
return false;
// < and > statements rather than BETWEEN operator
// since BETWEEN is treated differently according to databases
return (Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'cms`
SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position`
'.($way
? '> '.(int)($movedCms['position']).' AND `position` <= '.(int)($position)
: '< '.(int)($movedCms['position']).' AND `position` >= '.(int)($position)).'
AND `id_cms_category`='.(int)($movedCms['id_cms_category']))
AND Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'cms`
SET `position` = '.(int)($position).'
WHERE `id_cms` = '.(int)($movedCms['id_cms']).'
AND `id_cms_category`='.(int)($movedCms['id_cms_category'])));
}
static public function cleanPositions($id_category)
{
$result = Db::getInstance()->ExecuteS('
SELECT `id_cms`
FROM `'._DB_PREFIX_.'cms`
WHERE `id_cms_category` = '.(int)($id_category).'
ORDER BY `position`');
$sizeof = sizeof($result);
for ($i = 0; $i < $sizeof; ++$i){
$sql = '
UPDATE `'._DB_PREFIX_.'cms`
SET `position` = '.(int)($i).'
WHERE `id_cms_category` = '.(int)($id_category).'
AND `id_cms` = '.(int)($result[$i]['id_cms']);
Db::getInstance()->Execute($sql);
}
return true;
}
static public function getLastPosition($id_category)
{
return (Db::getInstance()->getValue('SELECT MAX(position)+1 FROM `'._DB_PREFIX_.'cms` WHERE `id_cms_category` = '.(int)($id_category)));
}
static public function getCMSPages($id_lang = NULL, $id_cms_category = NULL, $active = true)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'cms` c
JOIN `'._DB_PREFIX_.'cms_lang` l ON (c.id_cms = l.id_cms)'.
(isset($id_cms_category) ? 'WHERE `id_cms_category` = '.(int)($id_cms_category) : '').
($active ? ' AND c.`active` = 1 ' : '').'
AND l.id_lang = '.(int)($id_lang).'
ORDER BY `position`');
}
public static function getUrlRewriteInformations($id_cms)
{
$sql = '
SELECT l.`id_lang`, c.`link_rewrite`
FROM `'._DB_PREFIX_.'cms_lang` AS c
LEFT JOIN `'._DB_PREFIX_.'lang` AS l ON c.`id_lang` = l.`id_lang`
WHERE c.`id_cms` = '.(int)$id_cms.'
AND l.`active` = 1';
$arr_return = Db::getInstance()->ExecuteS($sql);
return $arr_return;
}
}
+658
View File
@@ -0,0 +1,658 @@
<?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
*/
class CMSCategoryCore extends ObjectModel
{
public $id;
/** @var integer CMSCategory ID */
public $id_cms_category;
/** @var string Name */
public $name;
/** @var boolean Status for display */
public $active = 1;
/** @var string Description */
public $description;
/** @var integer Parent CMSCategory ID */
public $id_parent;
/** @var integer category position */
public $position;
/** @var integer Parents number */
public $level_depth;
/** @var string string used in rewrited URL */
public $link_rewrite;
/** @var string Meta title */
public $meta_title;
/** @var string Meta keywords */
public $meta_keywords;
/** @var string Meta description */
public $meta_description;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected static $_links = array();
protected $tables = array ('cms_category', 'cms_category_lang');
protected $fieldsRequired = array('id_parent', 'active');
protected $fieldsSize = array('id_parent' => 10, 'active' => 1);
protected $fieldsValidate = array('active' => 'isBool', 'id_parent' => 'isUnsignedInt');
protected $fieldsRequiredLang = array('name', 'link_rewrite');
protected $fieldsSizeLang = array('name' => 64, 'link_rewrite' => 64, 'meta_title' => 128, 'meta_description' => 255, 'meta_keywords' => 255);
protected $fieldsValidateLang = array('name' => 'isCatalogName', 'link_rewrite' => 'isLinkRewrite', 'description' => 'isCleanHtml',
'meta_title' => 'isGenericName', 'meta_description' => 'isGenericName', 'meta_keywords' => 'isGenericName');
protected $table = 'cms_category';
protected $identifier = 'id_cms_category';
public function __construct($id_cms_category = NULL, $id_lang = NULL)
{
parent::__construct($id_cms_category, $id_lang);
}
public function getFields()
{
parent::validateFields();
if (isset($this->id))
$fields['id_cms_category'] = (int)($this->id);
$fields['active'] = (int)($this->active);
$fields['id_parent'] = (int)($this->id_parent);
$fields['position'] = (int)($this->position);
$fields['level_depth'] = (int)($this->level_depth);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name', 'description', 'link_rewrite', 'meta_title', 'meta_keywords', 'meta_description'));
}
public function add($autodate = true, $nullValues = false)
{
$this->position = self::getLastPosition((int)$this->id_parent);
$this->level_depth = $this->calcLevelDepth();
foreach ($this->name AS $k => $value)
if (preg_match('/^[1-9]\./', $value))
$this->name[$k] = '0'.$value;
$ret = parent::add($autodate);
$this->cleanPositions($this->id_parent);
return $ret;
}
public function update($nullValues = false)
{
$this->level_depth = $this->calcLevelDepth();
foreach ($this->name AS $k => $value)
if (preg_match('/^[1-9]\./', $value))
$this->name[$k] = '0'.$value;
return parent::update();
}
/**
* Recursive scan of subcategories
*
* @param integer $maxDepth Maximum depth of the tree (i.e. 2 => 3 levels depth)
* @param integer $currentDepth specify the current depth in the tree (don't use it, only for rucursivity!)
* @param array $excludedIdsArray specify a list of ids to exclude of results
* @param integer $idLang Specify the id of the language used
*
* @return array Subcategories lite tree
*/
function recurseLiteCategTree($maxDepth = 3, $currentDepth = 0, $idLang = NULL, $excludedIdsArray = NULL)
{
global $link;
//get idLang
$idLang = is_null($idLang) ? _USER_ID_LANG_ : (int)($idLang);
//recursivity for subcategories
$children = array();
if (($maxDepth == 0 OR $currentDepth < $maxDepth) AND $subcats = $this->getSubCategories($idLang, true) AND sizeof($subcats))
foreach ($subcats as &$subcat)
{
if (!$subcat['id_cms_category'])
break;
elseif ( !is_array($excludedIdsArray) || !in_array($subcat['id_cms_category'], $excludedIdsArray) )
{
$categ = new CMSCategory($subcat['id_cms_category'] ,$idLang);
$categ->name = CMSCategory::hideCMSCategoryPosition($categ->name);
$children[] = $categ->recurseLiteCategTree($maxDepth, $currentDepth + 1, $idLang, $excludedIdsArray);
}
}
return array(
'id' => $this->id_cms_category,
'link' => $link->getCMSCategoryLink($this->id, $this->link_rewrite),
'name' => $this->name,
'desc'=> $this->description,
'children' => $children
);
}
static public function getRecurseCategory($id_lang = _USER_ID_LANG_, $current = 1, $active = 1, $links = 0, $id_shop = false)
{
$category = Db::getInstance()->getRow('
SELECT c.`id_cms_category`, c.`id_parent`, c.`level_depth`, cl.`name`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms_category` c
JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON c.`id_cms_category` = cl.`id_cms_category`
WHERE c.`id_cms_category` = '.(int)($current).'
AND `id_lang` = '.(int)($id_lang));
$result = Db::getInstance()->ExecuteS('
SELECT c.`id_cms_category`
FROM `'._DB_PREFIX_.'cms_category` c
WHERE c.`id_parent` = '.(int)($current).
($active ? ' AND c.`active` = 1' : ''));
foreach ($result as $row)
$category['children'][] = self::getRecurseCategory($id_lang, $row['id_cms_category'], $active, $links);
$category['cms'] = Db::getInstance()->ExecuteS('
SELECT c.`id_cms`, cl.`meta_title`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms` c
'.($id_shop ? 'LEFT JOIN '._DB_PREFIX_.'cms_shop cs ON (cs.id_cms = c.id_cms)' : '').'
JOIN `'._DB_PREFIX_.'cms_lang` cl ON c.`id_cms` = cl.`id_cms`
WHERE `id_cms_category` = '.(int)($current).'
'.($id_shop ? ' AND cs.id_shop='.(int)$id_shop : '').'
AND cl.`id_lang` = '.(int)($id_lang).($active ? ' AND c.`active` = 1' : '').'
ORDER BY c.`position`');
if ($links == 1)
{
$link = new Link();
$category['link'] = $link->getCMSCategoryLink($current, $category['link_rewrite']);
foreach($category['cms'] as $key => $cms)
$category['cms'][$key]['link'] = $link->getCMSLink($cms['id_cms'], $cms['link_rewrite']);
}
return $category;
}
static public function recurseCMSCategory($categories, $current, $id_cms_category = 1, $id_selected = 1, $is_html = 0)
{
global $currentIndex;
$html = '<option value="'.$id_cms_category.'"'.(($id_selected == $id_cms_category) ? ' selected="selected"' : '').'>'.
str_repeat('&nbsp;', $current['infos']['level_depth'] * 5).self::hideCMSCategoryPosition(stripslashes($current['infos']['name'])).'</option>';
if ($is_html == 0)
echo $html;
if (isset($categories[$id_cms_category]))
foreach ($categories[$id_cms_category] AS $key => $row)
$html .= self::recurseCMSCategory($categories, $categories[$id_cms_category][$key], $key, $id_selected, $is_html);
return $html;
}
/**
* Recursively add specified CMSCategory childs to $toDelete array
*
* @param array &$toDelete Array reference where categories ID will be saved
* @param array $id_cms_category Parent CMSCategory ID
*/
protected function recursiveDelete(&$toDelete, $id_cms_category)
{
if (!is_array($toDelete) OR !$id_cms_category)
die(Tools::displayError());
$result = Db::getInstance()->ExecuteS('
SELECT `id_cms_category`
FROM `'._DB_PREFIX_.'cms_category`
WHERE `id_parent` = '.(int)($id_cms_category));
foreach ($result AS $k => $row)
{
$toDelete[] = (int)($row['id_cms_category']);
$this->recursiveDelete($toDelete, (int)($row['id_cms_category']));
}
}
public function delete()
{
if ($this->id == 1) return false;
$this->clearCache();
/* Get childs categories */
$toDelete = array((int)($this->id));
$this->recursiveDelete($toDelete, (int)($this->id));
$toDelete = array_unique($toDelete);
/* Delete CMS Category and its child from database */
$list = sizeof($toDelete) > 1 ? implode(',', $toDelete) : (int)($this->id);
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'cms_category` WHERE `id_cms_category` IN ('.$list.')');
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'cms_category_lang` WHERE `id_cms_category` IN ('.$list.')');
self::cleanPositions($this->id_parent);
/* Delete pages which are in categories to delete */
$result = Db::getInstance()->ExecuteS('
SELECT `id_cms`
FROM `'._DB_PREFIX_.'cms`
WHERE `id_cms_category` IN ('.$list.')');
foreach ($result as $p)
{
$product = new CMS((int)($p['id_cms']));
if (Validate::isLoadedObject($product))
$product->delete();
}
return true;
}
/**
* Delete several categories from database
*
* return boolean Deletion result
*/
public function deleteSelection($categories)
{
$return = 1;
foreach ($categories AS $id_category_cms)
{
$category_cms = new CMSCategory((int)($id_category_cms));
$return &= $category_cms->delete();
}
return $return;
}
/**
* Get the number of parent categories
*
* @return integer Level depth
*/
public function calcLevelDepth()
{
$parentCMSCategory = new CMSCategory((int)($this->id_parent));
if (!$parentCMSCategory)
die('parent CMS Category does not exist');
return $parentCMSCategory->level_depth + 1;
}
/**
* Return available categories
*
* @param integer $id_lang Language ID
* @param boolean $active return only active categories
* @return array Categories
*/
static public function getCategories($id_lang, $active = true, $order = true)
{
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON c.`id_cms_category` = cl.`id_cms_category`
WHERE `id_lang` = '.(int)($id_lang).'
'.($active ? 'AND `active` = 1' : '').'
ORDER BY `name` ASC');
if (!$order)
return $result;
$categories = array();
foreach ($result AS $row)
$categories[$row['id_parent']][$row['id_cms_category']]['infos'] = $row;
return $categories;
}
static public function getSimpleCategories($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.`id_cms_category`, cl.`name`
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON (c.`id_cms_category` = cl.`id_cms_category`)
WHERE cl.`id_lang` = '.(int)($id_lang).'
ORDER BY cl.`name`');
}
/**
* Return current CMSCategory childs
*
* @param integer $id_lang Language ID
* @param boolean $active return only active categories
* @return array Categories
*/
public function getSubCategories($id_lang, $active = true)
{
global $cookie;
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.*, cl.id_lang, cl.name, cl.description, cl.link_rewrite, cl.meta_title, cl.meta_keywords, cl.meta_description
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON (c.`id_cms_category` = cl.`id_cms_category` AND `id_lang` = '.(int)($id_lang).')
WHERE `id_parent` = '.(int)($this->id).'
'.($active ? 'AND `active` = 1' : '').'
GROUP BY c.`id_cms_category`
ORDER BY `name` ASC');
/* Modify SQL result */
foreach ($result AS &$row)
{
$row['name'] = CMSCategory::hideCMSCategoryPosition($row['name']);
}
return $result;
}
/**
* Hide CMSCategory prefix used for position
*
* @param string $name CMSCategory name
* @return string Name without position
*/
static public function hideCMSCategoryPosition($name)
{
return preg_replace('/^[0-9]+\./', '', $name);
}
/**
* Return main categories
*
* @param integer $id_lang Language ID
* @param boolean $active return only active categories
* @return array categories
*/
static public function getHomeCategories($id_lang, $active = true)
{
return self::getChildren(1, $id_lang, $active);
}
/**
* @deprecated
**/
static public function getRootCMSCategory($id_lang = NULL)
{
Tools::displayAsDeprecated();
//get idLang
$id_lang = is_null($id_lang) ? _USER_ID_LANG_ : (int)($id_lang);
return new CMSCategory (1, $id_lang);
}
static public function getChildren($id_parent, $id_lang, $active = true)
{
if (!Validate::isBool($active))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.`id_cms_category`, cl.`name`, cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON c.`id_cms_category` = cl.`id_cms_category`
WHERE `id_lang` = '.(int)($id_lang).'
AND c.`id_parent` = '.(int)($id_parent).'
'.($active ? 'AND `active` = 1' : '').'
ORDER BY `name` ASC');
/* Modify SQL result */
$resultsArray = array();
foreach ($result AS $row)
{
$row['name'] = CMSCategory::hideCMSCategoryPosition($row['name']);
$resultsArray[] = $row;
}
return $resultsArray;
}
/**
* Check if CMSCategory can be moved in another one
*
* @param integer $id_parent Parent candidate
* @return boolean Parent validity
*/
public static function checkBeforeMove($id_cms_category, $id_parent)
{
if ($id_cms_category == $id_parent) return false;
if ($id_parent == 1) return true;
$i = (int)($id_parent);
while (42)
{
$result = Db::getInstance()->getRow('SELECT `id_parent` FROM `'._DB_PREFIX_.'cms_category` WHERE `id_cms_category` = '.(int)($i));
if (!isset($result['id_parent'])) return false;
if ($result['id_parent'] == $id_cms_category) return false;
if ($result['id_parent'] == 1) return true;
$i = $result['id_parent'];
}
}
public static function getLinkRewrite($id_cms_category, $id_lang)
{
if (!Validate::isUnsignedId($id_cms_category) OR !Validate::isUnsignedId($id_lang))
return false;
if (isset(self::$_links[$id_cms_category.'-'.$id_lang]))
return self::$_links[$id_cms_category.'-'.$id_lang];
$result = Db::getInstance()->getRow('
SELECT cl.`link_rewrite`
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON c.`id_cms_category` = cl.`id_cms_category`
WHERE `id_lang` = '.(int)($id_lang).'
AND c.`id_cms_category` = '.(int)($id_cms_category));
self::$_links[$id_cms_category.'-'.$id_lang] = $result['link_rewrite'];
return $result['link_rewrite'];
}
public function getLink()
{
global $link;
return $link->getCMSCategoryLink($this->id, $this->link_rewrite);
}
public function getName($id_lang = NULL)
{
if (!$id_lang)
{
global $cookie;
if (isset($this->name[$cookie->id_lang]))
$id_lang = $cookie->id_lang;
else
$id_lang = (int)(Configuration::get('PS_LANG_DEFAULT'));
}
return isset($this->name[$id_lang]) ? $this->name[$id_lang] : '';
}
/**
* Light back office search for categories
*
* @param integer $id_lang Language ID
* @param string $query Searched string
* @param boolean $unrestricted allows search without lang and includes first CMSCategory and exact match
* @return array Corresponding categories
*/
static public function searchByName($id_lang, $query, $unrestricted = false)
{
if ($unrestricted === true)
return Db::getInstance()->getRow('
SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON (c.`id_cms_category` = cl.`id_cms_category`)
WHERE `name` LIKE \''.pSQL($query).'\'');
else
return Db::getInstance()->ExecuteS('
SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON (c.`id_cms_category` = cl.`id_cms_category` AND `id_lang` = '.(int)($id_lang).')
WHERE `name` LIKE \'%'.pSQL($query).'%\' AND c.`id_cms_category` != 1');
}
/**
* Retrieve CMSCategory by name and parent CMSCategory id
*
* @param integer $id_lang Language ID
* @param string $CMSCategory_name Searched CMSCategory name
* @param integer $id_parent_CMSCategory parent CMSCategory ID
* @return array Corresponding CMSCategory
* @deprecated
*/
static public function searchByNameAndParentCMSCategoryId($id_lang, $CMSCategory_name, $id_parent_CMSCategory)
{
Tools::displayAsDeprecated();
return Db::getInstance()->getRow('
SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON (c.`id_cms_category` = cl.`id_cms_category` AND `id_lang` = '.(int)($id_lang).')
WHERE `name` LIKE \''.pSQL($CMSCategory_name).'\'
AND c.`id_cms_category` != 1
AND c.`id_parent` = '.(int)($id_parent_CMSCategory));
}
/**
* Get Each parent CMSCategory of this CMSCategory until the root CMSCategory
*
* @param integer $id_lang Language ID
* @return array Corresponding categories
*/
public function getParentsCategories($idLang = null)
{
//get idLang
$idLang = is_null($idLang) ? _USER_ID_LANG_ : (int)($idLang);
$categories = null;
$idCurrent = (int)($this->id);
while (true)
{
$query = '
SELECT c.*, cl.*
FROM `'._DB_PREFIX_.'cms_category` c
LEFT JOIN `'._DB_PREFIX_.'cms_category_lang` cl ON (c.`id_cms_category` = cl.`id_cms_category` AND `id_lang` = '.(int)($idLang).')
WHERE c.`id_cms_category` = '.$idCurrent.' AND c.`id_parent` != 0
';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
$categories[] = $result[0];
if(!$result OR $result[0]['id_parent'] == 1)
return $categories;
$idCurrent = $result[0]['id_parent'];
}
}
/**
* Specify if a CMSCategory already in base
*
* @param $id_cms_category CMSCategory id
* @return boolean
* @deprecated
*/
static public function CMSCategoryExists($id_cms_category)
{
Tools::displayAsDeprecated();
$row = Db::getInstance()->getRow('
SELECT `id_cms_category`
FROM '._DB_PREFIX_.'cms_category c
WHERE c.`id_cms_category` = '.(int)($id_cms_category));
return isset($row['id_cms_category']);
}
public function updatePosition($way, $position)
{
if (!$res = Db::getInstance()->ExecuteS('
SELECT cp.`id_cms_category`, cp.`position`, cp.`id_parent`
FROM `'._DB_PREFIX_.'cms_category` cp
WHERE cp.`id_parent` = '.(int)$this->id_parent.'
ORDER BY cp.`position` ASC'
))
return false;
foreach ($res AS $category)
if ((int)($category['id_cms_category']) == (int)($this->id))
$movedCategory = $category;
if (!isset($movedCategory) || !isset($position))
return false;
// < and > statements rather than BETWEEN operator
// since BETWEEN is treated differently according to databases
return (Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'cms_category`
SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position`
'.($way
? '> '.(int)($movedCategory['position']).' AND `position` <= '.(int)($position)
: '< '.(int)($movedCategory['position']).' AND `position` >= '.(int)($position)).'
AND `id_parent`='.(int)($movedCategory['id_parent']))
AND Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'cms_category`
SET `position` = '.(int)($position).'
WHERE `id_parent` = '.(int)($movedCategory['id_parent']).'
AND `id_cms_category`='.(int)($movedCategory['id_cms_category'])));
}
static public function cleanPositions($id_category_parent)
{
$result = Db::getInstance()->ExecuteS('
SELECT `id_cms_category`
FROM `'._DB_PREFIX_.'cms_category`
WHERE `id_parent` = '.(int)($id_category_parent).'
ORDER BY `position`');
$sizeof = sizeof($result);
for ($i = 0; $i < $sizeof; ++$i){
$sql = '
UPDATE `'._DB_PREFIX_.'cms_category`
SET `position` = '.(int)($i).'
WHERE `id_parent` = '.(int)($id_category_parent).'
AND `id_cms_category` = '.(int)($result[$i]['id_cms_category']);
Db::getInstance()->Execute($sql);
}
return true;
}
static public function getLastPosition($id_category_parent)
{
return (Db::getInstance()->getValue('SELECT MAX(position)+1 FROM `'._DB_PREFIX_.'cms_category` WHERE `id_parent` = '.(int)($id_category_parent)));
}
public static function getUrlRewriteInformations($id_category)
{
$sql = '
SELECT l.`id_lang`, c.`link_rewrite`
FROM `'._DB_PREFIX_.'cms_category_lang` AS c
LEFT JOIN `'._DB_PREFIX_.'lang` AS l ON c.`id_lang` = l.`id_lang`
WHERE c.`id_cms_category` = '.(int)$id_category.'
AND l.`active` = 1';
$arr_return = Db::getInstance()->ExecuteS($sql);
return $arr_return;
}
}
+80
View File
@@ -0,0 +1,80 @@
<?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
*/
abstract class CacheCore
{
protected static $_instance;
protected $_keysCached;
protected $_tablesCached = array();
protected $_blackList = array('cart',
'cart_discount',
'cart_product',
'connections',
'connections_source',
'connections_page',
'customer',
'customer_group',
'customized_data',
'guest',
'pagenotfound',
'page_viewed');
public static function getInstance()
{
if(!isset(self::$_instance))
{
$caching_system = _PS_CACHING_SYSTEM_;
self::$_instance = new $caching_system();
}
return self::$_instance;
}
protected function __construct()
{
}
protected function __destruct()
{
}
protected function isBlacklist($query)
{
foreach ($this->_blackList AS $find)
if (strpos($query, $find))
return true;
return false;
}
abstract public function get($key);
abstract public function delete($key, $timeout = 0);
abstract public function set($key, $value, $expire = 0);
abstract public function flush();
abstract public function setQuery($query, $result);
abstract public function deleteQuery($query);
}
+175
View File
@@ -0,0 +1,175 @@
<?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 CacheFSCore extends Cache {
protected $_depth;
protected function __construct()
{
parent::__construct();
$this->_init();
}
protected function _init()
{
$this->_depth = Db::getInstance()->getValue('SELECT value FROM '._DB_PREFIX_.'configuration WHERE name=\'PS_CACHEFS_DIRECTORY_DEPTH\'', false);
return $this->_setKeys();
}
public function set($key, $value, $expire = 0)
{
$path = _PS_CACHEFS_DIRECTORY_;
for ($i = 0; $i < $this->_depth; $i++)
{
$path.=$key[$i].'/';
}
if(file_put_contents($path.$key, serialize($value)))
{
$this->_keysCached[$key] = true;
return $key;
}
return false;
}
public function setNumRows($key, $value, $expire = 0)
{
return $this->set($key.'_nrows', $value, $expire);
}
public function getNumRows($key)
{
return $this->get($key.'_nrows');
}
public function get($key)
{
if (!isset($this->_keysCached[$key]))
return false;
$path = _PS_CACHEFS_DIRECTORY_;
for ($i = 0; $i < $this->_depth; $i++)
$path.=$key[$i].'/';
if (!file_exists($path.$key))
{
unset($this->_keysCached[$key]);
return false;
}
$file = file_get_contents($path.$key);
return unserialize($file);
}
protected function _setKeys()
{
if (file_exists(_PS_CACHEFS_DIRECTORY_.'keysCached'))
{
$file = file_get_contents(_PS_CACHEFS_DIRECTORY_.'keysCached');
$this->_keysCached = unserialize($file);
}
if (file_exists(_PS_CACHEFS_DIRECTORY_.'tablesCached'))
{
$file = file_get_contents(_PS_CACHEFS_DIRECTORY_.'tablesCached');
$this->_tablesCached = unserialize($file);
}
return true;
}
public function setQuery($query, $result)
{
$md5_query = md5($query);
if (isset($this->_keysCached[$md5_query]))
return true;
if ($this->isBlacklist($query))
return true;
$key = $this->set($md5_query, $result);
if (preg_match_all('/('._DB_PREFIX_.'[a-z_-]*)`?.*/i', $query, $res))
foreach($res[1] AS $table)
if(!isset($this->_tablesCached[$table][$key]))
$this->_tablesCached[$table][$key] = true;
}
public function delete($key, $timeout = 0)
{
$path = _PS_CACHEFS_DIRECTORY_;
if (!isset($this->_keysCached[$key]))
return;
for ($i = 0; $i < $this->_depth; $i++)
$path.=$key[$i].'/';
if (!file_exists($path.$key))
return true;
if (!unlink($path.$key))
return false;
unset($this->_keysCached[$key]);
return true;
}
public function deleteQuery($query)
{
if (preg_match_all('/('._DB_PREFIX_.'[a-z_-]*)`?.*/i', $query, $res))
foreach ($res[1] AS $table)
if (isset($this->_tablesCached[$table]))
{
foreach ($this->_tablesCached[$table] AS $fsKey => $foo)
{
$this->delete($fsKey);
$this->delete($fsKey.'_nrows');
}
unset($this->_tablesCached[$table]);
}
}
public function flush()
{
}
public function __destruct()
{
parent::__destruct();
file_put_contents(_PS_CACHEFS_DIRECTORY_.'keysCached', serialize($this->_keysCached));
file_put_contents(_PS_CACHEFS_DIRECTORY_.'tablesCached', serialize($this->_tablesCached));
}
public static function deleteCacheDirectory()
{
Tools::deleteDirectory(_PS_CACHEFS_DIRECTORY_, false);
}
public static function createCacheDirectories($level_depth, $directory = false)
{
if (!$directory)
$directory = _PS_CACHEFS_DIRECTORY_;
$chars = '0123456789abcdefghijklmnopqrstuvwxyz';
for ($i = 0; $i < strlen($chars); $i++)
{
$new_dir = $directory.$chars[$i].'/';
if (mkdir($new_dir))
if (chmod($new_dir, 0777))
if ($level_depth - 1 > 0)
self::createCacheDirectories($level_depth - 1, $new_dir);
}
}
}
+711
View File
@@ -0,0 +1,711 @@
<?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 CarrierCore extends ObjectModel
{
const SHIPPING_METHOD_DEFAULT = 0;
const SHIPPING_METHOD_WEIGHT = 1;
const SHIPPING_METHOD_PRICE = 2;
const SHIPPING_METHOD_FREE = 3;
/** @var int Tax id (none = 0) */
public $id_tax_rules_group;
/** @var string Name */
public $name;
/** @var string URL with a '@' for */
public $url;
/** @var string Delay needed to deliver customer */
public $delay;
/** @var boolean Carrier statuts */
public $active = true;
/** @var boolean True if carrier has been deleted (staying in database as deleted) */
public $deleted = 0;
/** @var boolean Active or not the shipping handling */
public $shipping_handling = true;
/** @var int Behavior taken for unknown range */
public $range_behavior;
/** @var boolean Carrier module */
public $is_module;
/** @var boolean Free carrier */
public $is_free = false;
/** @var int shipping behavior: by weight or by price */
public $shipping_method = 0;
/** @var boolean Shipping external */
public $shipping_external = 0;
/** @var string Shipping external */
public $external_module_name = NULL;
/** @var boolean Need Range */
public $need_range = 0;
protected $fieldsRequired = array('name', 'active');
protected $fieldsSize = array('name' => 64);
protected $fieldsValidate = array('id_tax_rules_group' => 'isInt', 'name' => 'isCarrierName', 'active' => 'isBool', 'is_free' => 'isBool', 'url' => 'isAbsoluteUrl', 'shipping_handling' => 'isBool', 'range_behavior' => 'isBool', 'shipping_method' => 'isUnsignedInt');
protected $fieldsRequiredLang = array('delay');
protected $fieldsSizeLang = array('delay' => 128);
protected $fieldsValidateLang = array('delay' => 'isGenericName');
protected $table = 'carrier';
protected $identifier = 'id_carrier';
protected static $priceByWeight = array();
protected static $priceByWeight2 = array();
protected static $priceByPrice = array();
protected static $priceByPrice2 = array();
protected static $_cache_tax_rule = array();
protected $webserviceParameters = array(
'fields' => array(
'id_tax_rules_group' => array(),
'deleted' => array(),
'is_module' => array(),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_tax_rules_group'] = (int)($this->id_tax_rules_group);
$fields['name'] = pSQL($this->name);
$fields['url'] = pSQL($this->url);
$fields['active'] = (int)($this->active);
$fields['deleted'] = (int)($this->deleted);
$fields['shipping_handling'] = (int)($this->shipping_handling);
$fields['range_behavior'] = (int)($this->range_behavior);
$fields['shipping_method'] = (int)($this->shipping_method);
$fields['is_module'] = (int)($this->is_module);
$fields['is_free'] = (int)($this->is_free);
$fields['shipping_external'] = (int)($this->shipping_external);
$fields['external_module_name'] = $this->external_module_name;
$fields['need_range'] = $this->need_range;
return $fields;
}
public function __construct($id = NULL, $id_lang = NULL)
{
parent::__construct($id, $id_lang);
if ($this->name == '0')
$this->name = Configuration::get('PS_SHOP_NAME');
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('delay'));
}
public function add($autodate = true, $nullValues = false)
{
if (!parent::add($autodate, $nullValues) OR !Validate::isLoadedObject($this))
return false;
if (!$result = Db::getInstance()->ExecuteS('SELECT `id_carrier` FROM `'._DB_PREFIX_.$this->table.'` WHERE `deleted` = 0'))
return false;
if (!$numRows = Db::getInstance()->NumRows())
return false;
if ((int)($numRows) == 1)
Configuration::updateValue('PS_CARRIER_DEFAULT', (int)($this->id));
return true;
}
/**
* Change carrier id in delivery prices when updating a carrier
*
* @param integer $id_old Old id carrier
*/
public function setConfiguration($id_old)
{
Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.'delivery` SET `id_carrier` = '.(int)($this->id).' WHERE `id_carrier` = '.(int)($id_old));
}
/**
* Get delivery prices for a given order
*
* @param floatval $totalWeight Order total weight
* @param integer $id_zone Zone id (for customer delivery address)
* @return float Delivery price
*/
public function getDeliveryPriceByWeight($totalWeight, $id_zone)
{
$cache_key = $this->id.'_'.$totalWeight.'_'.$id_zone;
if (!isset(self::$priceByWeight[$cache_key]))
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT d.`price`
FROM `'._DB_PREFIX_.'delivery` d
LEFT JOIN `'._DB_PREFIX_.'range_weight` w ON (d.`id_range_weight` = w.`id_range_weight`)
WHERE d.`id_zone` = '.(int)($id_zone).'
AND '.(float)($totalWeight).' >= w.`delimiter1`
AND '.(float)($totalWeight).' < w.`delimiter2`
AND d.`id_carrier` = '.(int)($this->id).'
ORDER BY w.`delimiter1` ASC');
if (!isset($result['price']))
self::$priceByWeight[$cache_key] = $this->getMaxDeliveryPriceByWeight($id_zone);
else
self::$priceByWeight[$cache_key] = $result['price'];
}
return self::$priceByWeight[$cache_key];
}
static public function checkDeliveryPriceByWeight($id_carrier, $totalWeight, $id_zone)
{
$cache_key = $id_carrier.'_'.$totalWeight.'_'.$id_zone;
if (!isset(self::$priceByWeight2[$cache_key]))
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT d.`price`
FROM `'._DB_PREFIX_.'delivery` d
LEFT JOIN `'._DB_PREFIX_.'range_weight` w ON d.`id_range_weight` = w.`id_range_weight`
WHERE d.`id_zone` = '.(int)($id_zone).'
AND '.(float)($totalWeight).' >= w.`delimiter1`
AND '.(float)($totalWeight).' < w.`delimiter2`
AND d.`id_carrier` = '.(int)($id_carrier).'
ORDER BY w.`delimiter1` ASC');
self::$priceByWeight2[$cache_key] = (isset($result['price']));
}
return self::$priceByWeight2[$cache_key];
}
public function getMaxDeliveryPriceByWeight($id_zone)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT d.`price`
FROM `'._DB_PREFIX_.'delivery` d
INNER JOIN `'._DB_PREFIX_.'range_weight` w ON d.`id_range_weight` = w.`id_range_weight`
WHERE d.`id_zone` = '.(int)($id_zone).'
AND d.`id_carrier` = '.(int)($this->id).'
ORDER BY w.`delimiter2` DESC LIMIT 1');
if (!isset($result[0]['price']))
return false;
return $result[0]['price'];
}
/**
* Get delivery prices for a given order
*
* @param floatval $orderTotal Order total to pay
* @param integer $id_zone Zone id (for customer delivery address)
* @return float Delivery price
*/
public function getDeliveryPriceByPrice($orderTotal, $id_zone, $id_currency = NULL)
{
$cache_key = $this->id.'_'.$orderTotal.'_'.$id_zone.'_'.$id_currency;
if (!isset(self::$priceByPrice[$cache_key]))
{
if (!empty($id_currency))
$orderTotal = Tools::convertPrice($orderTotal, $id_currency, false);
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT d.`price`
FROM `'._DB_PREFIX_.'delivery` d
LEFT JOIN `'._DB_PREFIX_.'range_price` r ON d.`id_range_price` = r.`id_range_price`
WHERE d.`id_zone` = '.(int)($id_zone).'
AND '.(float)($orderTotal).' >= r.`delimiter1`
AND '.(float)($orderTotal).' < r.`delimiter2`
AND d.`id_carrier` = '.(int)($this->id).'
ORDER BY r.`delimiter1` ASC');
if (!isset($result['price']))
self::$priceByPrice[$cache_key] = $this->getMaxDeliveryPriceByPrice($id_zone);
else
self::$priceByPrice[$cache_key] = $result['price'];
}
return self::$priceByPrice[$cache_key];
}
/**
* Check delivery prices for a given order
*
* @param id_carrier
* @param floatval $orderTotal Order total to pay
* @param integer $id_zone Zone id (for customer delivery address)
* @param integer $id_currency
* @return float Delivery price
*/
static public function checkDeliveryPriceByPrice($id_carrier, $orderTotal, $id_zone, $id_currency = NULL)
{
$cache_key = $id_carrier.'_'.$orderTotal.'_'.$id_zone.'_'.$id_currency;
if (!isset(self::$priceByPrice2[$cache_key]))
{
if (!empty($id_currency))
$orderTotal = Tools::convertPrice($orderTotal, $id_currency, false);
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT d.`price`
FROM `'._DB_PREFIX_.'delivery` d
LEFT JOIN `'._DB_PREFIX_.'range_price` r ON d.`id_range_price` = r.`id_range_price`
WHERE d.`id_zone` = '.(int)($id_zone).'
AND '.(float)($orderTotal).' >= r.`delimiter1`
AND '.(float)($orderTotal).' < r.`delimiter2`
AND d.`id_carrier` = '.(int)($id_carrier).'
ORDER BY r.`delimiter1` ASC');
self::$priceByPrice2[$cache_key] = (isset($result['price']));
}
return self::$priceByPrice2[$cache_key];
}
public function getMaxDeliveryPriceByPrice($id_zone)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT d.`price`
FROM `'._DB_PREFIX_.'delivery` d
INNER JOIN `'._DB_PREFIX_.'range_price` r ON d.`id_range_price` = r.`id_range_price`
WHERE d.`id_zone` = '.(int)($id_zone).'
AND d.`id_carrier` = '.(int)($this->id).'
ORDER BY r.`delimiter2` DESC LIMIT 1');
if (!isset($result[0]['price']))
return false;
return $result[0]['price'];
}
/**
* Get delivery prices for a given shipping method (price/weight)
*
* @param string $rangeTable Table name (price or weight)
* @return array Delivery prices
*/
public static function getDeliveryPriceByRanges($rangeTable, $id_carrier)
{
$rangeTable = pSQL($rangeTable);
return Db::getInstance()->ExecuteS('
SELECT d.`id_'.$rangeTable.'`, d.`id_carrier`, d.`id_zone`, d.`price`
FROM `'._DB_PREFIX_.'delivery` d
LEFT JOIN `'._DB_PREFIX_.$rangeTable.'` r ON r.`id_'.$rangeTable.'` = d.`id_'.$rangeTable.'`
WHERE (d.`id_'.$rangeTable.'` IS NOT NULL AND d.`id_'.$rangeTable.'` != 0 AND d.`id_carrier` = '.(int)($id_carrier).')
ORDER BY r.`delimiter1` ASC');
}
/**
* Get all carriers in a given language
*
* @param integer $id_lang Language id
* @param $modules_filters, possible values:
PS_CARRIERS_ONLY
CARRIERS_MODULE
CARRIERS_MODULE_NEED_RANGE
PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE
ALL_CARRIERS
* @param boolean $active Returns only active carriers when true
* @return array Carriers
*/
public static function getCarriers($id_lang, $active = false, $delete = false, $id_zone = false, $ids_group = NULL, $modules_filters = 1)
{
if (!Validate::isBool($active))
die(Tools::displayError());
if ($ids_group)
{
$ids = '';
foreach ($ids_group as $id)
$ids .= (int)($id).', ';
$ids = rtrim($ids, ', ');
if ($ids == '')
return (array());
}
$sql = '
SELECT c.*, cl.delay
FROM `'._DB_PREFIX_.'carrier` c
LEFT JOIN `'._DB_PREFIX_.'carrier_lang` cl ON (c.`id_carrier` = cl.`id_carrier` AND cl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)'.
($id_zone ? 'LEFT JOIN `'._DB_PREFIX_.'zone` z ON (z.`id_zone` = '.(int)($id_zone).')' : '').'
WHERE c.`deleted` '.($delete ? '= 1' : ' = 0').
($active ? ' AND c.`active` = 1' : '').
($id_zone ? ' AND cz.`id_zone` = '.(int)($id_zone).'
AND z.`active` = 1 ' : ' ');
switch ($modules_filters)
{
case 1 :
$sql .= 'AND c.is_module = 0 ';
break;
case 2 :
$sql .= 'AND c.is_module = 1 ';
break;
case 3 :
$sql .= 'AND c.is_module = 1 AND c.need_range = 1 ';
break;
case 4 :
$sql .= 'AND (c.is_module = 0 OR c.need_range = 1) ';
break;
case 5 :
$sql .= '';
break;
}
$sql .= ($ids_group ? ' AND c.id_carrier IN (SELECT id_carrier FROM '._DB_PREFIX_.'carrier_group WHERE id_group IN ('.$ids.')) ' : '').'
GROUP BY c.`id_carrier`';
$carriers = Db::getInstance()->ExecuteS($sql);
if (is_array($carriers) AND count($carriers))
{
foreach ($carriers as $key => $carrier)
if ($carrier['name'] == '0')
$carriers[$key]['name'] = Configuration::get('PS_SHOP_NAME');
}
else
$carriers = array();
return $carriers;
}
public static function getCarriersForOrder($id_zone, $groups = NULL)
{
global $cookie, $cart;
if (is_array($groups) AND !empty($groups))
$result = Carrier::getCarriers((int)$cookie->id_lang, true, false, (int)$id_zone, $groups, PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
else
$result = Carrier::getCarriers((int)$cookie->id_lang, true, false, (int)$id_zone, array(1), PS_CARRIERS_AND_CARRIER_MODULES_NEED_RANGE);
$resultsArray = array();
foreach ($result AS $k => $row)
{
$carrier = new Carrier((int)$row['id_carrier']);
$shippingMethod = $carrier->getShippingMethod();
if ($shippingMethod != Carrier::SHIPPING_METHOD_FREE)
{
// Get only carriers that are compliant with shipping method
if (($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT AND $carrier->getMaxDeliveryPriceByWeight($id_zone) === false)
OR ($shippingMethod == Carrier::SHIPPING_METHOD_PRICE AND $carrier->getMaxDeliveryPriceByPrice($id_zone) === false))
{
unset($result[$k]);
continue ;
}
// If out-of-range behavior carrier is set on "Desactivate carrier"
if ($row['range_behavior'])
{
// Get id zone
if (!$id_zone)
$id_zone = (int)$defaultCountry->id_zone;
// Get only carriers that have a range compatible with cart
if (($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT AND (!Carrier::checkDeliveryPriceByWeight($row['id_carrier'], $cart->getTotalWeight(), $id_zone)))
OR ($shippingMethod == Carrier::SHIPPING_METHOD_PRICE AND (!Carrier::checkDeliveryPriceByPrice($row['id_carrier'], $cart->getOrderTotal(true, Cart::BOTH_WITHOUT_SHIPPING), $id_zone, $cart->id_currency))))
{
unset($result[$k]);
continue ;
}
}
}
$row['name'] = (strval($row['name']) != '0' ? $row['name'] : Configuration::get('PS_SHOP_NAME'));
$row['price'] = ($shippingMethod == Carrier::SHIPPING_METHOD_FREE ? 0 : $cart->getOrderShippingCost((int)$row['id_carrier']));
$row['price_tax_exc'] = ($shippingMethod == Carrier::SHIPPING_METHOD_FREE ? 0 : $cart->getOrderShippingCost((int)$row['id_carrier'], false));
$row['img'] = file_exists(_PS_SHIP_IMG_DIR_.(int)($row['id_carrier']).'.jpg') ? _THEME_SHIP_DIR_.(int)($row['id_carrier']).'.jpg' : '';
// If price is false, then the carrier is unavailable (carrier module)
if ($row['price'] === false)
{
unset($result[$k]);
continue ;
}
$resultsArray[] = $row;
}
return $resultsArray;
}
/**
* @param int $id_country
* @param array $groups
* @return Array carriers list
* @deprecated
*/
public static function getCarriersOpc($id_country, $groups = NULL)
{
Tools::displayAsDeprecated();
return self::getCarriersForOrder((int)Country::getIdZone((int)($id_country)), $groups);
}
public static function checkCarrierZone($id_carrier, $id_zone)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.`id_carrier`
FROM `'._DB_PREFIX_.'carrier` c
LEFT JOIN `'._DB_PREFIX_.'carrier_zone` cz ON (cz.`id_carrier` = c.`id_carrier`)
LEFT JOIN `'._DB_PREFIX_.'zone` z ON (z.`id_zone` = '.(int)($id_zone).')
WHERE c.`id_carrier` = '.(int)($id_carrier).'
AND c.`deleted` = 0
AND c.`active` = 1
AND cz.`id_zone` = '.(int)($id_zone).'
AND z.`active` = 1'
);
}
/**
* Get all zones
*
* @return array Zones
*/
public function getZones()
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'carrier_zone` cz
LEFT JOIN `'._DB_PREFIX_.'zone` z ON cz.`id_zone` = z.`id_zone`
WHERE cz.`id_carrier` = '. (int)($this->id));
}
/**
* Get a specific zones
*
* @return array Zone
*/
public function getZone($id_zone)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'carrier_zone`
WHERE `id_carrier` = '.(int)($this->id).'
AND `id_zone` = '.(int)($id_zone));
}
/**
* Add zone
*/
public function addZone($id_zone)
{
return Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier` , `id_zone`)
VALUES ('.(int)($this->id).', '.(int)($id_zone).')');
}
/**
* Delete zone
*/
public function deleteZone($id_zone)
{
return Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'carrier_zone`
WHERE `id_carrier` = '.(int)($this->id).'
AND `id_zone` = '.(int)($id_zone).' LIMIT 1');
}
/**
* Clean delivery prices (weight/price)
*
* @param string $rangeTable Table name to clean (weight or price according to shipping method)
* @return boolean Deletion result
*/
public function deleteDeliveryPrice($rangeTable)
{
return Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'delivery` WHERE `id_carrier` = '.(int)($this->id).' AND (`id_'.$rangeTable.'` IS NOT NULL OR `id_'.$rangeTable.'` = 0)');
}
/**
* Add new delivery prices
*
* @param string $priceList Prices list separated by commas
* @return boolean Insertion result
*/
public function addDeliveryPrice($priceList)
{
if (!Validate::isValuesList($priceList))
die(Tools::displayError());
return Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'delivery` (`id_range_price`, `id_range_weight`, `id_carrier`, `id_zone`, `price`)
VALUES '.$priceList);
}
/**
* Copy old carrier informations when update carrier
*
* @param integer $oldId Old id carrier (copy from that id)
*/
public function copyCarrierData($oldId)
{
if (!Validate::isUnsignedId($oldId))
die(Tools::displayError());
$oldLogo = _PS_SHIP_IMG_DIR_.'/'.(int)($oldId).'.jpg';
if (file_exists($oldLogo))
copy($oldLogo, _PS_SHIP_IMG_DIR_.'/'.(int)($this->id).'.jpg');
// Copy existing ranges price
$res = Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'range_price`
WHERE id_carrier = '.(int)($oldId));
foreach ($res AS $val)
{
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'range_price` (`id_carrier`, `delimiter1`, `delimiter2`)
VALUES ('.(int)($this->id).','.(float)($val['delimiter1']).','.(float)($val['delimiter2']).')');
$maxRangePrice = Db::getInstance()->Insert_ID();
$res2 = Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'delivery`
WHERE id_carrier = '.(int)($oldId).'
AND id_range_price = '.(int)($val['id_range_price']));
foreach ($res2 AS $val2)
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'delivery` (`id_carrier`,`id_range_price`,`id_range_weight`,`id_zone`, `price`)
VALUES ('.(int)($this->id).','.(int)($maxRangePrice).',NULL,'.(int)($val2['id_zone']).','.(float)($val2['price']).')');
}
// Copy existing ranges weight
$res = Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'range_weight`
WHERE id_carrier = '.(int)($oldId));
foreach ($res as $val)
{
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'range_weight` (`id_carrier`, `delimiter1`, `delimiter2`)
VALUES ('.(int)($this->id).','.(float)($val['delimiter1']).','.(float)($val['delimiter2']).')');
$maxRangeWeight = Db::getInstance()->Insert_ID();
$res2 = Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'delivery`
WHERE id_carrier = '.(int)($oldId).'
AND id_range_weight = '.(int)($val['id_range_weight']));
foreach ($res2 as $val2)
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'delivery` (`id_carrier`,`id_range_price`,`id_range_weight`,`id_zone`, `price`)
VALUES ('.(int)($this->id).',NULL,'.(int)($maxRangeWeight).','.(int)($val2['id_zone']).','.(float)($val2['price']).')');
}
// Copy existing zones
$res = Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'carrier_zone`
WHERE id_carrier = '.(int)($oldId));
foreach ($res as $val)
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'carrier_zone` (`id_carrier`, `id_zone`)
VALUES ('.(int)($this->id).','.(int)($val['id_zone']).')');
//Copy default carrier
if ((int)(Configuration::get('PS_CARRIER_DEFAULT')) == $oldId)
Configuration::updateValue('PS_CARRIER_DEFAULT', (int)($this->id));
}
/**
* Check if carrier is used (at least one order placed)
*
* @return integer Order count for this carrier
*/
public function isUsed()
{
$row = Db::getInstance()->getRow('
SELECT COUNT(`id_carrier`) AS total
FROM `'._DB_PREFIX_.'orders`
WHERE `id_carrier` = '.(int)($this->id));
return (int)($row['total']);
}
/**
* Get the price without taxes defined in carrier
* @deprecated
**/
public function getPriceWithoutTaxes($productPrice)
{
Tools::displayAsDeprecated();
$tax = new Tax($this->id_tax);
return round($productPrice - ($productPrice * $tax->rate / 100), 2);
}
public function getShippingMethod()
{
if ($this->is_free)
return Carrier::SHIPPING_METHOD_FREE;
$method = (int)$this->shipping_method;
if ($this->shipping_method == Carrier::SHIPPING_METHOD_DEFAULT)
{
// backward compatibility
if ((int)Configuration::get('PS_SHIPPING_METHOD'))
$method = Carrier::SHIPPING_METHOD_WEIGHT;
else
$method = Carrier::SHIPPING_METHOD_PRICE;
}
return $method;
}
public function getRangeTable()
{
$shippingMethod = $this->getShippingMethod();
if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT)
return 'range_weight';
elseif ($shippingMethod == Carrier::SHIPPING_METHOD_PRICE)
return 'range_price';
return false;
}
public function getRangeObject()
{
$shippingMethod = $this->getShippingMethod();
if ($shippingMethod == Carrier::SHIPPING_METHOD_WEIGHT)
return new RangeWeight();
elseif ($shippingMethod == Carrier::SHIPPING_METHOD_PRICE)
return new RangePrice();
return false;
}
public function getRangeSuffix()
{
$suffix = Configuration::get('PS_WEIGHT_UNIT');
if ($this->getShippingMethod() == Carrier::SHIPPING_METHOD_PRICE)
{
$currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));
$suffix = $currency->sign;
}
return $suffix;
}
public static function getIdTaxRulesGroupByIdCarrier($id_carrier)
{
if (!isset(self::$_cache_tax_rule[(int)$id_carrier]))
{
self::$_cache_tax_rule[$id_carrier] = Db::getInstance()->getValue('
SELECT `id_tax_rules_group`
FROM `'._DB_PREFIX_.'carrier`
WHERE `id_carrier` = '.(int)$id_carrier);
}
return self::$_cache_tax_rule[$id_carrier];
}
}
+33
View File
@@ -0,0 +1,33 @@
<?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
*/
abstract class CarrierModuleCore extends Module
{
abstract function getOrderShippingCost($params,$shipping_cost);
abstract function getOrderShippingCostExternal($params);
}
+1708
View File
File diff suppressed because it is too large Load Diff
+1048
View File
File diff suppressed because it is too large Load Diff
+178
View File
@@ -0,0 +1,178 @@
<?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 ChartCore
{
protected static $poolId = 0;
protected $width = 600;
protected $height = 300;
// Time mode
protected $timeMode = false;
protected $from;
protected $to;
protected $format;
protected $granularity;
protected $curves = array();
/** @prototype void public static function init(void) */
public static function init()
{
if (!self::$poolId)
{
++self::$poolId;
echo '
<!--[if IE]><script type="text/javascript" src="'.PS_BASE_URI.'js/jquery/excanvas.min.js"></script><![endif]-->
<script type="text/javascript" src="'.PS_BASE_URI.'js/jquery/jquery.flot.min.js"></script>';
}
}
/** @prototype void public function __construct() */
public function __construct()
{
self::init();
++self::$poolId;
}
/** @prototype void public function setSize(int $width, int $height) */
public function setSize($width, $height)
{
$this->width = (int)$width;
$this->height = (int)$height;
}
/** @prototype void public function setTimeMode($from, $to, $granularity) */
public function setTimeMode($from, $to, $granularity)
{
$this->granularity = $granularity;
if (Validate::isDate($from))
$from = strtotime($from);
$this->from = $from;
if (Validate::isDate($to))
$to = strtotime($to);
$this->to = $to;
if ($granularity == 'd')
$this->format = '%d/%m/%y';
if ($granularity == 'w')
$this->format = '%d/%m/%y';
if ($granularity == 'm')
$this->format = '%m/%y';
if ($granularity == 'y')
$this->format = '%y';
$this->timeMode = true;
}
public function getCurve($i)
{
if (!array_key_exists($i, $this->curves))
$this->curves[$i] = new Curve();
return $this->curves[$i];
}
/** @prototype void public function display() */
public function display()
{
$options = '';
if ($this->timeMode)
{
$options = 'xaxis:{mode:"time",timeformat:\''.addslashes($this->format).'\',min:'.$this->from.'000,max:'.$this->to.'000}';
if ($this->granularity == 'd')
foreach ($this->curves as $curve)
for ($i = $this->from; $i <= $this->to; $i += 86400)
if (!$curve->getPoint($i))
$curve->setPoint($i, 0);
}
$jsCurves = array();
foreach ($this->curves as $curve)
$jsCurves[] = $curve->getValues($this->timeMode);
if (count($jsCurves))
echo '
<div id="flot'.self::$poolId.'" style="width:'.$this->width.'px;height:'.$this->height.'px"></div>
<script type="text/javascript">
$(function () {
$.plot($(\'#flot'.self::$poolId.'\'), ['.implode(',', $jsCurves).'], {'.$options.'});
});
</script>';
else
echo ErrorFacade::Display(PS_ERROR_UNDEFINED, 'No values for this chart.');
}
}
class Curve
{
protected $values = array();
protected $label;
protected $type;
/** @prototype void public function setValues($values) */
public function setValues($values)
{
$this->values = $values;
}
public function getValues($timeMode = false)
{
ksort($this->values);
$string = '';
foreach ($this->values as $key => $value)
$string .= '['.addslashes((string)$key).($timeMode ? '000' : '').','.(float)$value.'],';
return '{data:['.rtrim($string, ',').']'.(!empty($this->label) ? ',label:"'.$this->label.'"' : '').''.(!empty($this->type) ? ','.$this->type : '').'}';
}
/** @prototype void public function setPoint(float $x, float $y) */
public function setPoint($x, $y)
{
$this->values[(string)$x] = (float)$y;
}
public function setLabel($label)
{
$this->label = $label;
}
public function setType($type)
{
$this->type = '';
if ($type == 'bars')
$this->type = 'bars:{show:true}';
if ($type == 'steps')
$this->type = 'lines:{show:true,steps:true}';
}
public function getPoint($x)
{
if (array_key_exists((string)$x, $this->values))
return $this->values[(string)$x];
}
}
+180
View File
@@ -0,0 +1,180 @@
<?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 CombinationCore extends ObjectModel
{
public $id_product;
public $reference;
public $supplier_reference;
public $location;
public $ean13;
public $upc;
public $wholesale_price;
public $price;
public $ecotax;
public $quantity;
public $weight;
public $default_on;
protected $fieldsRequired = array(
'id_product',
);
protected $fieldsSize = array(
'reference' => 32,
'supplier_reference' => 32,
'location' => 64,
'ean13' => 13,
'upc' => 12,
'wholesale_price' => 27,
'price' => 20,
'ecotax' => 20,
'quantity' => 10
);
protected $fieldsValidate = array(
'id_product' => 'isUnsignedId',
'location' => 'isGenericName',
'ean13' => 'isEan13',
'upc' => 'isUpc',
'wholesale_price' => 'isPrice',
'price' => 'isPrice',
'ecotax' => 'isPrice',
'quantity' => 'isUnsignedInt',
'weight' => 'isFloat',
'default_on' => 'isBool',
);
protected $table = 'product_attribute';
protected $identifier = 'id_product_attribute';
protected $webserviceParameters = array(
'objectNodeName' => 'combination',
'objectsNodeName' => 'combinations',
'fields' => array(
'id_product' => array('required' => true, 'xlink_resource'=> 'products'),
),
'associations' => array(
'product_option_values' => array('resource' => 'product_option_value'),
'images' => array('resource' => 'image'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_product'] = (int)($this->id_product);
$fields['reference'] = pSQL($this->reference);
$fields['supplier_reference'] = pSQL($this->supplier_reference);
$fields['location'] = pSQL($this->location);
$fields['ean13'] = pSQL($this->ean13);
$fields['upc'] = pSQL($this->upc);
$fields['wholesale_price'] = pSQL($this->wholesale_price);
$fields['price'] = pSQL($this->price);
$fields['ecotax'] = pSQL($this->ecotax);
$fields['quantity'] = (int)($this->quantity);
$fields['weight'] = pSQL($this->weight);
$fields['default_on'] = (int)($this->default_on);
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_.'product_attribute_combination`
WHERE `id_product_attribute` = '.(int)($this->id)) === false
)
return false;
return true;
}
public function setWsProductOptionValues($values)
{
if ($this->deleteAssociations())
{
$sqlValues = array();
foreach ($values as $value)
$sqlValues[] = '('.(int)$value['id'].', '.(int)$this->id.')';
$result = Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'product_attribute_combination` (`id_attribute`, `id_product_attribute`)
VALUES '.implode(',', $sqlValues)
);
return $result;
}
return false;
}
public function getWsProductOptionValues()
{
$result = Db::getInstance()->executeS('SELECT id_attribute AS id from `'._DB_PREFIX_.'product_attribute_combination` WHERE id_product_attribute = '.(int)$this->id);
return $result;
}
public function getWsImages()
{
return Db::getInstance()->ExecuteS('
SELECT `id_image` as id
FROM `'._DB_PREFIX_.'product_attribute_image`
WHERE `id_product_attribute` = '.(int)($this->id).'
');
}
public function setWsImages($values)
{
if (Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'product_attribute_image`
WHERE `id_product_attribute` = '.(int)($this->id)) === false)
return false;
$sqlValues = array();
foreach ($values as $value)
$sqlValues[] = '('.(int)$this->id.', '.(int)$value['id'].')';
$result = Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'product_attribute_image` (`id_product_attribute`, `id_image`)
VALUES '.implode(',', $sqlValues)
);
return true;
}
}
+494
View File
@@ -0,0 +1,494 @@
<?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: 7227 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ConfigurationCore extends ObjectModel
{
public $id;
/** @var string Key */
public $name;
public $id_group_shop;
public $id_shop;
/** @var string Value */
public $value;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $fieldsRequired = array('name');
protected $fieldsSize = array('name' => 32);
protected $fieldsValidate = array('name' => 'isConfigName', 'id_group_shop' => 'isUnsignedId', 'id_shop' => 'isUnsignedId');
protected $table = 'configuration';
protected $identifier = 'id_configuration';
/** @var array Configuration cache */
protected static $_CONF;
/** @var array Vars types */
protected static $types = array();
protected $webserviceParameters = array(
'fields' => array(
'value' => array(),
)
);
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
$fields['id_group_shop'] = $this->id_group_shop;
$fields['id_shop'] = $this->id_shop;
$fields['value'] = pSQL($this->value);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
if (!is_array($this->value))
return true;
parent::validateFieldsLang();
return parent::getTranslationsFields(array('value'));
}
/**
* Return ID a configuration key
*
* @param string $key
* @param int $shopGroupID
* @param int $shopID
*/
public static function getIdByName($key, $shopGroupID = null, $shopID = null)
{
self::getShopFromContext($shopGroupID, $shopID);
$sql = 'SELECT id_configuration
FROM '._DB_PREFIX_.'configuration
WHERE name = \''.pSQL($key).'\''
.Configuration::sqlRestriction($shopGroupID, $shopID);
return (int)Db::getInstance()->getValue($sql);
}
/**
* Load all configuration data
*/
static public function loadConfiguration()
{
self::$_CONF = array();
$sql = 'SELECT c.`name`, cl.`id_lang`, IF(cl.`id_lang` IS NULL, c.`value`, cl.`value`) AS value, c.id_group_shop, c.id_shop
FROM `'._DB_PREFIX_.'configuration` c
LEFT JOIN `'._DB_PREFIX_.'configuration_lang` cl ON (c.id_configuration = cl.id_configuration)';
if (!$results = Db::getInstance()->ExecuteS($sql))
return;
foreach ($results as $row)
{
$lang = ($row['id_lang']) ? $row['id_lang'] : 0;
self::$types[$row['name']] = ($lang) ? 'lang' : 'normal';
if (!isset(self::$_CONF[$lang]))
self::$_CONF[$lang] = array(
'global' => array(),
'group' => array(),
'shop' => array(),
);
// Do not remove (int) cast
Configuration::set($row['name'], array($lang => $row['value']), (int)$row['id_group_shop'], (int)$row['id_shop']);
}
}
/**
* Get a single configuration value (in one language only)
*
* @param string $key Key wanted
* @param integer $id_lang Language ID
* @return string Value
*/
static public function get($key, $langID = NULL, $shopGroupID = NULL, $shopID = NULL)
{
self::getShopFromContext($shopGroupID, $shopID);
$langID = (int)$langID;
if (!isset(self::$_CONF[$langID]))
$langID = 0;
if ($shopID && Configuration::hasKey($key, $langID, null, $shopID))
return self::$_CONF[$langID]['shop'][$shopID][$key];
else if ($shopGroupID && Configuration::hasKey($key, $langID, $shopGroupID))
return self::$_CONF[$langID]['group'][$shopGroupID][$key];
else if (Configuration::hasKey($key, $langID))
return self::$_CONF[$langID]['global'][$key];
return false;
}
/**
* Get a single configuration value (in multiple languages)
*
* @param string $key Key wanted
* @param int $shopGroupID
* @param int $shopID
* @return array Values in multiple languages
*/
static public function getInt($key, $id_group_shop = NULL, $id_shop = NULL)
{
$languages = Language::getLanguages();
$resultsArray = array();
foreach ($languages as $language)
$resultsArray[$language['id_lang']] = self::get($key, $language['id_lang'], $id_group_shop, $id_shop);
return $resultsArray;
}
/**
* Get several configuration values (in one language only)
*
* @param array $keys Keys wanted
* @param integer $id_lang Language ID
* @return array Values
*/
static public function getMultiple($keys, $langID = NULL, $shopGroupID = NULL, $shopID = NULL)
{
if (!is_array($keys))
die(Tools::displayError());
$langID = (int)$langID;
self::getShopFromContext($shopGroupID, $shopID);
$results = array();
foreach ($keys as $key)
$results[$key] = Configuration::get($key, $langID, $shopGroupID, $shopID);
return $results;
}
/**
* Check if key exists in configuration
*
* @param string $key
* @param int $id_lang
* @param int $shopGroupID
* @param int $shopID
* @return bool
*/
public static function hasKey($key, $langID = null, $shopGroupID = null, $shopID = null)
{
$langID = (int)$langID;
if ($shopID)
return isset(self::$_CONF[$langID]['shop'][$shopID]) && array_key_exists($key, self::$_CONF[$langID]['shop'][$shopID]);
else if ($shopGroupID)
return isset(self::$_CONF[$langID]['group'][$shopGroupID]) && array_key_exists($key, self::$_CONF[$langID]['group'][$shopGroupID]);
return isset(self::$_CONF[$langID]['global']) && array_key_exists($key, self::$_CONF[$langID]['global']);
}
/**
* Set TEMPORARY a single configuration value (in one language only)
*
* @param string $key Key wanted
* @param mixed $values $values is an array if the configuration is multilingual, a single string else.
* @param int $shopGroupID
* @param int $shopID
*/
static public function set($key, $values, $id_group_shop = NULL, $id_shop = NULL)
{
if (!Validate::isConfigName($key))
die(Tools::displayError());
self::getShopFromContext($id_group_shop, $id_shop);
if (!is_array($values))
$values = array($values);
foreach ($values as $lang => $value)
{
if ($id_shop)
self::$_CONF[$lang]['shop'][$id_shop][$key] = $value;
else if ($id_group_shop)
self::$_CONF[$lang]['group'][$id_group_shop][$key] = $value;
else
self::$_CONF[$lang]['global'][$key] = $value;
}
}
/**
* Update configuration key for global context only
*
* @param string $key
* @param mixed $values
* @param bool $html
* @return bool
*/
static public function updateGlobalValue($key, $values, $html = false)
{
return Configuration::updateValue($key, $values, $html, 0, 0);
}
/**
* Update configuration key and value into database (automatically insert if key does not exist)
*
* @param string $key Key
* @param mixed $values $values is an array if the configuration is multilingual, a single string else.
* @param boolean $html Specify if html is authorized in value
* @param int $shopGroupID
* @param int $shopID
* @return boolean Update result
*/
static public function updateValue($key, $values, $html = false, $shopGroupID = NULL, $shopID = NULL)
{
if (!Validate::isConfigName($key))
die(Tools::displayError());
self::getShopFromContext($shopGroupID, $shopID);
if (!is_array($values))
$values = array($values);
$result = true;
foreach ($values as $lang => $value)
{
if ($value == Configuration::get($key, $lang, $shopGroupID, $shopID))
continue;
// If key already exists, update value
if (Configuration::hasKey($key, $lang, $shopGroupID, $shopID))
{
if (!$lang)
{
// Update config not linked to lang
$result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.'configuration', array(
'value' => pSQL($value, $html),
'date_upd' => date('Y-m-d H:i:s'),
), 'UPDATE', '`name` = \''.pSQL($key).'\''.Configuration::sqlRestriction($shopGroupID, $shopID), true, true);
}
else
{
// Update multi lang
$sql = 'UPDATE '._DB_PREFIX_.'configuration_lang cl
SET cl.value = \''.pSQL($value, $html).'\',
cl.date_upd = NOW()
WHERE cl.id_lang = '.(int)$lang.'
AND cl.id_configuration = (
SELECT c.id_configuration
FROM '._DB_PREFIX_.'configuration c
WHERE c.name = \''.pSQL($key).'\''
.Configuration::sqlRestriction($shopGroupID, $shopID)
.')';
$result &= Db::getInstance()->Execute($sql);
}
}
// If key does not exists, create it
else
{
if (!$configID = Configuration::getIdByName($key, $shopGroupID, $shopID))
{
$newConfig = new Configuration();
$newConfig->name = $key;
if ($shopID)
$newConfig->id_shop = (int)$shopID;
if ($shopGroupID)
$newConfig->id_group_shop = (int)$shopGroupID;
if (!$lang)
$newConfig->value = $value;
$result &= $newConfig->add(true, true);
$configID = $newConfig->id;
}
if ($lang)
{
$result &= Db::getInstance()->autoExecute(_DB_PREFIX_.'configuration_lang', array(
'id_configuration' => $configID,
'id_lang' => $lang,
'value' => pSQL($value, $html),
'date_upd' => date('Y-m-d H:i:s'),
), 'INSERT');
}
}
Configuration::set($key, $value, $shopGroupID, $shopID);
}
return $result;
}
/**
* Delete a configuration key in database (with or without language management)
*
* @param string $key Key to delete
* @return boolean Deletion result
*/
static public function deleteByName($key)
{
if (!Validate::isConfigName($key))
return false;
$sql = 'DELETE FROM `'._DB_PREFIX_.'configuration_lang`
WHERE `id_configuration` = (
SELECT `id_configuration`
FROM `'._DB_PREFIX_.'configuration`
WHERE `name` = \''.pSQL($key).'\'
)';
$result = Db::getInstance()->Execute($sql);
$sql = 'DELETE FROM `'._DB_PREFIX_.'configuration`
WHERE `name` = \''.pSQL($key).'\'';
$result2 = Db::getInstance()->Execute($sql);
return ($result && $result2);
}
/**
* Delete configuration key from current context.
*
* @param string $key
*/
public static function deleteFromContext($key)
{
list($shopID, $shopGroupID) = Shop::retrieveContext();
if (!$shopID && !$shopGroupID)
return;
$id = Configuration::getIdByName($key, $shopGroupID, $shopID);
$sql = 'DELETE FROM '._DB_PREFIX_.'configuration
WHERE id_configuration = '.$id;
Db::getInstance()->Execute($sql);
$sql = 'DELETE FROM '._DB_PREFIX_.'configuration_lang
WHERE id_configuration = '.$id;
Db::getInstance()->Execute($sql);
}
/**
* Check if configuration var is defined in given context
*
* @param string $key
* @param int $langID
* @param int $context
*/
public static function hasContext($key, $langID, $context)
{
list($shopID, $shopGroupID) = Shop::retrieveContext();
if ($context == Shop::CONTEXT_SHOP && Configuration::hasKey($key, $langID, null, $shopID))
return true;
else if ($context == Shop::CONTEXT_GROUP && Configuration::hasKey($key, $langID, $shopGroupID))
return true;
else if ($context == Shop::CONTEXT_ALL && Configuration::hasKey($key, $langID))
return true;
return false;
}
/**
* Check if a key was loaded as multi lang
*
* @param string $key
* @return bool
*/
public static function isLangKey($key)
{
return (isset(self::$types[$key]) && self::$types[$key] == 'lang') ? true : false;
}
/**
* Fill $id_group_shop and $id_shop vars from correct context
*
* @param int $id_group_shop
* @param int $id_shop
*/
protected static function getShopFromContext(&$id_group_shop, &$id_shop)
{
list($shopID, $shopGroupID) = Shop::retrieveContext();
if (is_null($id_shop))
$id_shop = $shopID;
if (is_null($id_group_shop))
$id_group_shop = $shopGroupID;
$id_shop = (int)$id_shop;
$id_group_shop = (int)$id_group_shop;
}
/**
* Add SQL restriction on shops for configuration table
*
* @param int $shopGroupID
* @param int $shopID
* @return string
*/
protected static function sqlRestriction($shopGroupID, $shopID)
{
if ($shopID)
return ' AND id_shop = '.$shopID;
else if ($shopGroupID)
return ' AND id_group_shop = '.$shopGroupID.' AND id_shop IS NULL';
else
return ' AND id_group_shop IS NULL AND id_shop IS NULL';
}
/**
* This method is override to allow TranslatedConfiguration entity
*
* @param $sql_join
* @param $sql_filter
* @param $sql_sort
* @param $sql_limit
* @return array
*/
public function getWebserviceObjectList($sql_join, $sql_filter, $sql_sort, $sql_limit)
{
$query = '
SELECT DISTINCT main.`'.$this->identifier.'` FROM `'._DB_PREFIX_.$this->table.'` main
'.$sql_join.'
WHERE id_configuration NOT IN
( SELECT id_configuration
FROM '._DB_PREFIX_.$this->table.'_lang
) '.$sql_filter.'
'.($sql_sort != '' ? $sql_sort : '').'
'.($sql_limit != '' ? $sql_limit : '').'
';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
}
/**
* Get several configuration values (in multiple languages)
*
* @param array $keys Keys wanted
* @return array Values in multiple languages
* @deprecated
*/
static public function getMultipleInt($keys)
{
Tools::displayAsDeprecated();
$languages = Language::getLanguages();
$resultsArray = array();
foreach($languages as $language)
$resultsArray[$language['id_lang']] = self::getMultiple($keys, $language['id_lang']);
return $resultsArray;
}
}
+184
View File
@@ -0,0 +1,184 @@
<?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: 6883 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ConnectionCore extends ObjectModel
{
/** @var integer */
public $id_guest;
/** @var integer */
public $id_page;
/** @var string */
public $ip_address;
/** @var string */
public $http_referer;
/** @var int */
public $id_shop;
/** @var int */
public $id_group_shop;
/** @var string */
public $date_add;
protected $fieldsRequired = array ('id_guest', 'id_page', 'id_shop', 'id_group_shop');
protected $fieldsValidate = array ('id_guest' => 'isUnsignedId', 'id_page' => 'isUnsignedId',
'ip_address' => 'isInt', 'http_referer' => 'isAbsoluteUrl');
/* MySQL does not allow 'connection' for a table name */
protected $table = 'connections';
protected $identifier = 'id_connections';
public function getFields()
{
parent::validateFields();
$fields['id_guest'] = (int)($this->id_guest);
$fields['id_page'] = (int)($this->id_page);
$fields['ip_address'] = (int)($this->ip_address);
if (Validate::isAbsoluteUrl($this->http_referer))
$fields['http_referer'] = pSQL($this->http_referer);
$fields['date_add'] = pSQL($this->date_add);
$fields['id_shop'] = (int)$this->id_shop;
$fields['id_group_shop'] = (int)$this->id_group_shop;
return $fields;
}
public static function setPageConnection($cookie, $full = true)
{
// The connection is created if it does not exist yet and we get the current page id
if (!isset($cookie->id_connections) OR !strstr(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '', Tools::getHttpHost(false, false)))
$id_page = Connection::setNewConnection($cookie);
if (!isset($id_page) OR !$id_page)
$id_page = Page::getCurrentId();
if (!Configuration::get('PS_STATSDATA_CUSTOMER_PAGESVIEWS'))
return array('id_page' => $id_page);
// The ending time will be updated by an ajax request when the guest will close the page
$time_start = date('Y-m-d H:i:s');
Db::getInstance()->AutoExecute(_DB_PREFIX_.'connections_page', array('id_connections' => (int)($cookie->id_connections), 'id_page' => (int)($id_page), 'time_start' => $time_start), 'INSERT');
// This array is serialized and used by the ajax request to identify the page
return array(
'id_connections' => (int)($cookie->id_connections),
'id_page' => (int)($id_page),
'time_start' => $time_start);
}
public static function setNewConnection($cookie)
{
if (isset($_SERVER['HTTP_USER_AGENT'])
AND preg_match('/BotLink|ahoy|AlkalineBOT|anthill|appie|arale|araneo|AraybOt|ariadne|arks|ATN_Worldwide|Atomz|bbot|Bjaaland|Ukonline|borg\-bot\/0\.9|boxseabot|bspider|calif|christcrawler|CMC\/0\.01|combine|confuzzledbot|CoolBot|cosmos|Internet Cruiser Robot|cusco|cyberspyder|cydralspider|desertrealm, desert realm|digger|DIIbot|grabber|downloadexpress|DragonBot|dwcp|ecollector|ebiness|elfinbot|esculapio|esther|fastcrawler|FDSE|FELIX IDE|ESI|fido|H�m�h�kki|KIT\-Fireball|fouineur|Freecrawl|gammaSpider|gazz|gcreep|golem|googlebot|griffon|Gromit|gulliver|gulper|hambot|havIndex|hotwired|htdig|iajabot|INGRID\/0\.1|Informant|InfoSpiders|inspectorwww|irobot|Iron33|JBot|jcrawler|Teoma|Jeeves|jobo|image\.kapsi\.net|KDD\-Explorer|ko_yappo_robot|label\-grabber|larbin|legs|Linkidator|linkwalker|Lockon|logo_gif_crawler|marvin|mattie|mediafox|MerzScope|NEC\-MeshExplorer|MindCrawler|udmsearch|moget|Motor|msnbot|muncher|muninn|MuscatFerret|MwdSearch|sharp\-info\-agent|WebMechanic|NetScoop|newscan\-online|ObjectsSearch|Occam|Orbsearch\/1\.0|packrat|pageboy|ParaSite|patric|pegasus|perlcrawler|phpdig|piltdownman|Pimptrain|pjspider|PlumtreeWebAccessor|PortalBSpider|psbot|Getterrobo\-Plus|Raven|RHCS|RixBot|roadrunner|Robbie|robi|RoboCrawl|robofox|Scooter|Search\-AU|searchprocess|Senrigan|Shagseeker|sift|SimBot|Site Valet|skymob|SLCrawler\/2\.0|slurp|ESI|snooper|solbot|speedy|spider_monkey|SpiderBot\/1\.0|spiderline|nil|suke|http:\/\/www\.sygol\.com|tach_bw|TechBOT|templeton|titin|topiclink|UdmSearch|urlck|Valkyrie libwww\-perl|verticrawl|Victoria|void\-bot|Voyager|VWbot_K|crawlpaper|wapspider|WebBandit\/1\.0|webcatcher|T\-H\-U\-N\-D\-E\-R\-S\-T\-O\-N\-E|WebMoose|webquest|webreaper|webs|webspider|WebWalker|wget|winona|whowhere|wlm|WOLP|WWWC|none|XGET|Nederland\.zoek/i', $_SERVER['HTTP_USER_AGENT']))
{
// This is a bot and we have to retrieve its connection ID
$sql = 'SELECT `id_connections` FROM `'._DB_PREFIX_.'connections` c
WHERE ip_address = '.ip2long(Tools::getRemoteAddr()).'
AND DATE_ADD(c.`date_add`, INTERVAL 30 MINUTE) > \''.pSQL(date('Y-m-d H:i:00')).'\'
AND id_shop = '.Shop::getCurrentShop().'
ORDER BY c.`date_add` DESC';
if ($id_connections = Db::getInstance()->getValue($sql))
{
$cookie->id_connections = (int)$id_connections;
return Page::getCurrentId();
}
}
// A new connection is created if the guest made no actions during 30 minutes
$sql = 'SELECT c.`id_guest`
FROM `'._DB_PREFIX_.'connections` c
WHERE c.`id_guest` = '.(int)($cookie->id_guest).'
AND DATE_ADD(c.`date_add`, INTERVAL 30 MINUTE) > \''.pSQL(date('Y-m-d H:i:00')).'\'
AND id_shop = '.Shop::getCurrentShop().'
ORDER BY c.`date_add` DESC';
$result = Db::getInstance()->getRow($sql);
if (!$result['id_guest'] AND (int)($cookie->id_guest))
{
// The old connections details are removed from the database in order to spare some memory
Connection::cleanConnectionsPages();
$referer = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '';
$arrayUrl = parse_url($referer);
if (!isset($arrayUrl['host']) OR preg_replace('/^www./', '', $arrayUrl['host']) == preg_replace('/^www./', '', Tools::getHttpHost(false, false)))
$referer = '';
$connection = new Connection();
$connection->id_guest = (int)($cookie->id_guest);
$connection->id_page = Page::getCurrentId();
$connection->ip_address = Tools::getRemoteAddr() ? ip2long(Tools::getRemoteAddr()) : '';
$connection->id_shop = Shop::getCurrentShop();
$connection->id_group_shop = Shop::getCurrentGroupShop();
if (Validate::isAbsoluteUrl($referer))
$connection->http_referer = $referer;
$connection->add();
$cookie->id_connections = $connection->id;
return $connection->id_page;
}
}
public static function setPageTime($id_connections, $id_page, $time_start, $time)
{
if (!Validate::isUnsignedId($id_connections)
OR !Validate::isUnsignedId($id_page)
OR !Validate::isDate($time_start))
return;
// Limited to 5 minutes because more than 5 minutes is considered as an error
if ($time > 300000)
$time = 300000;
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'connections_page`
SET `time_end` = `time_start` + INTERVAL '.(int)($time / 1000).' SECOND
WHERE `id_connections` = '.(int)($id_connections).'
AND `id_page` = '.(int)($id_page).'
AND `time_start` = \''.pSQL($time_start).'\'');
}
public static function cleanConnectionsPages()
{
$period = Configuration::get('PS_STATS_OLD_CONNECT_AUTO_CLEAN');
if ($period === 'week')
$interval = '1 WEEK';
else if ($period === 'month')
$interval = '1 MONTH';
else if ($period === 'year')
$interval = '1 YEAR';
else
return;
if ($interval != null)
{
// Records of connections details older than the beginning of the specified interval are deleted
Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'connections_page`
WHERE time_start < LAST_DAY(DATE_SUB(NOW(), INTERVAL '.$interval.'))');
}
}
}
+112
View File
@@ -0,0 +1,112 @@
<?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 ConnectionsSourceCore extends ObjectModel
{
public $id_connections;
public $http_referer;
public $request_uri;
public $keywords;
public $date_add;
// Controler les keywords
protected $fieldsRequired = array('id_connections', 'date_add');
protected $fieldsValidate = array('id_connections' => 'isUnsignedId', 'http_referer' => 'isAbsoluteUrl', 'request_uri' => 'isUrl', 'keywords' => 'isMessage');
protected $table = 'connections_source';
protected $identifier = 'id_connections_source';
public function getFields()
{
parent::validateFields();
$fields['id_connections'] = (int)($this->id_connections);
$fields['http_referer'] = pSQL($this->http_referer);
$fields['request_uri'] = pSQL($this->request_uri);
$fields['keywords'] = pSQL($this->keywords);
$fields['date_add'] = pSQL($this->date_add);
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
if($result = parent::add($autodate, $nullValues))
Referrer::cacheNewSource($this->id);
return $result;
}
public static function logHttpReferer()
{
global $cookie;
if (!isset($cookie->id_connections) OR !Validate::isUnsignedId($cookie->id_connections))
return false;
if (!isset($_SERVER['HTTP_REFERER']) AND !Configuration::get('TRACKING_DIRECT_TRAFFIC'))
return false;
$source = new ConnectionsSource();
if (isset($_SERVER['HTTP_REFERER']) AND Validate::isAbsoluteUrl($_SERVER['HTTP_REFERER']))
{
$parsed = parse_url($_SERVER['HTTP_REFERER']);
$parsed_host = parse_url(Tools::getProtocol().Tools::getHttpHost(false, false).__PS_BASE_URI__);
if ((preg_replace('/^www./', '', $parsed['host']) == preg_replace('/^www./', '', Tools::getHttpHost(false, false)))
AND !strncmp($parsed['path'], $parsed_host['path'], strlen(__PS_BASE_URI__)))
return false;
if (Validate::isAbsoluteUrl(strval($_SERVER['HTTP_REFERER'])))
{
$source->http_referer = strval($_SERVER['HTTP_REFERER']);
$source->keywords = trim(SearchEngine::getKeywords(strval($_SERVER['HTTP_REFERER'])));
if (!Validate::isMessage($source->keywords))
return false;
}
}
$source->id_connections = (int)($cookie->id_connections);
$source->request_uri = Tools::getHttpHost(false, false);
if (isset($_SERVER['REDIRECT_URL']))
$source->request_uri .= strval($_SERVER['REDIRECT_URL']);
elseif (isset($_SERVER['REQUEST_URI']))
$source->request_uri .= strval($_SERVER['REQUEST_URI']);
if (!Validate::isUrl($source->request_uri))
$source->request_uri = '';
return $source->add();
}
public static function getOrderSources($id_order)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT cos.http_referer, cos.request_uri, cos.keywords, cos.date_add
FROM '._DB_PREFIX_.'orders o
INNER JOIN '._DB_PREFIX_.'guest g ON g.id_customer = o.id_customer
INNER JOIN '._DB_PREFIX_.'connections co ON co.id_guest = g.id_guest
INNER JOIN '._DB_PREFIX_.'connections_source cos ON cos.id_connections = co.id_connections
WHERE id_order = '.(int)($id_order).'
ORDER BY cos.date_add DESC');
}
}
+89
View File
@@ -0,0 +1,89 @@
<?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 ContactCore extends ObjectModel
{
public $id;
/** @var string Name */
public $name;
/** @var string e-mail */
public $email;
/** @var string Detailed description */
public $description;
public $customer_service;
protected $fieldsRequired = array();
protected $fieldsSize = array('email' => 128);
protected $fieldsValidate = array('email' => 'isEmail', 'customer_service' => 'isBool');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 32);
protected $fieldsValidateLang = array('name' => 'isGenericName', 'description' => 'isCleanHtml');
protected $table = 'contact';
protected $identifier = 'id_contact';
public function getFields()
{
parent::validateFields();
$fields['email'] = pSQL($this->email);
$fields['customer_service'] = (int)($this->customer_service);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name', 'description'));
}
/**
* Return available contacts
*
* @param integer $id_lang Language ID
* @return array Contacts
*/
static public function getContacts($id_lang, $id_shop = false)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'contact` c
'.($id_shop ? 'LEFT JOIN '._DB_PREFIX_.'contact_shop cs ON (cs.id_contact = c.id_contact)' : '').'
LEFT JOIN `'._DB_PREFIX_.'contact_lang` cl ON (c.`id_contact` = cl.`id_contact`)
WHERE cl.`id_lang` = '.(int)($id_lang).($id_shop ? ' AND cs.id_shop='.(int)$id_shop : '').'
ORDER BY `name` ASC');
}
}
+53
View File
@@ -0,0 +1,53 @@
<?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 ControllerFactoryCore
{
public static function includeController($className)
{
if (!class_exists($className, false))
{
require_once(dirname(__FILE__).'/../controllers/'.$className.'.php');
if (file_exists(dirname(__FILE__).'/../override/controllers/'.$className.'.php'))
require_once(dirname(__FILE__).'/../override/controllers/'.$className.'.php');
else
{
$coreClass = new ReflectionClass($className.'Core');
if ($coreClass->isAbstract())
eval('abstract class '.$className.' extends '.$className.'Core {}');
else
eval('class '.$className.' extends '.$className.'Core {}');
}
}
}
public static function getController($className, $auth = false, $ssl = false)
{
ControllerFactory::includeController($className);
return new $className($auth, $ssl);
}
}
+354
View File
@@ -0,0 +1,354 @@
<?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
*/
class CookieCore
{
/** @var array Contain cookie content in a key => value format */
protected $_content;
/** @var array Crypted cookie name for setcookie() */
protected $_name;
/** @var array expiration date for setcookie() */
protected $_expire;
/** @var array Website domain for setcookie() */
protected $_domain;
/** @var array Path for setcookie() */
protected $_path;
/** @var array cipher tool instance */
protected $_cipherTool;
/** @var array cipher tool initialization key */
protected $_key;
/** @var array cipher tool initilization vector */
protected $_iv;
protected $_modified = false;
/**
* Get data if the cookie exists and else initialize an new one
*
* @param $name Cookie name before encrypting
* @param $path
*/
public function __construct($name, $path = '', $expire = NULL)
{
$this->_content = array();
$this->_expire = isset($expire) ? (int)($expire) : (time() + 1728000);
$this->_name = md5($name);
$this->_path = trim(__PS_BASE_URI__.$path, '/\\').'/';
if ($this->_path{0} != '/') $this->_path = '/'.$this->_path;
$this->_path = rawurlencode($this->_path);
$this->_path = str_replace('%2F', '/', $this->_path);
$this->_path = str_replace('%7E', '~', $this->_path);
$this->_key = _COOKIE_KEY_;
$this->_iv = _COOKIE_IV_;
$this->_domain = $this->getDomain();
if (Configuration::get('PS_CIPHER_ALGORITHM'))
$this->_cipherTool = new Rijndael(_RIJNDAEL_KEY_, _RIJNDAEL_IV_);
else
$this->_cipherTool = new Blowfish($this->_key, $this->_iv);
$this->update();
}
protected function getDomain()
{
$r = '!(?:(\w+)://)?(?:(\w+)\:(\w+)@)?([^/:]+)?(?:\:(\d*))?([^#?]+)?(?:\?([^#]+))?(?:#(.+$))?!i';
preg_match ($r, Tools::getHttpHost(false, false), $out);
if (preg_match('/^(((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]{1}[0-9]|[1-9]).)'.
'{1}((25[0-5]|2[0-4][0-9]|[1]{1}[0-9]{2}|[1-9]{1}[0-9]|[0-9]).)'.
'{2}((25[0-5]|2[0-4][0-9]|[1]{1}[0-9]{2}|[1-9]{1}[0-9]|[0-9]){1}))$/', $out[4]))
return false;
if (!strstr(Tools::getHttpHost(false, false), '.'))
return false;
$domain = $out[4];
$subDomains = SubDomain::getSubDomains();
if ($subDomains === false)
die(Tools::displayError('Bad SubDomain SQL query.'));
foreach ($subDomains AS $subDomain)
{
$subDomainLength = strlen($subDomain) + 1;
if (strncmp($subDomain.'.', $domain, $subDomainLength) == 0)
$domain = substr($domain, $subDomainLength);
}
return $domain;
}
/**
* Set expiration date
*
* @param integer $expire Expiration time from now
*/
function setExpire($expire)
{
$this->_expire = (int)($expire);
}
/**
* Magic method wich return cookie data from _content array
*
* @param $key key wanted
* @return string value corresponding to the key
*/
public function __get($key)
{
return isset($this->_content[$key]) ? $this->_content[$key] : false;
}
/**
* Magic method which check if key exists in the cookie
*
* @param $key key wanted
* @return boolean key existence
*/
public function __isset($key)
{
return isset($this->_content[$key]);
}
/**
* Magic method wich add data into _content array
*
* @param $key key desired
* @param $value value corresponding to the key
*/
public function __set($key, $value)
{
if (is_array($value))
die(Tools::displayError());
if (preg_match('/¤|\|/', $key.$value))
throw new Exception('Forbidden chars in cookie');
if (!$this->_modified AND (!isset($this->_content[$key]) OR (isset($this->_content[$key]) AND $this->_content[$key] != $value)))
$this->_modified = true;
$this->_content[$key] = $value;
$this->write();
}
/**
* Magic method wich delete data into _content array
*
* @param $key key wanted
*/
public function __unset($key)
{
if (isset($this->_content[$key]))
$this->_modified = true;
unset($this->_content[$key]);
$this->write();
}
/**
* Check customer informations saved into cookie and return customer validity
*
* @return boolean customer validity
*/
public function isLogged($withGuest = false)
{
if (!$withGuest AND $this->is_guest == 1)
return false;
/* Customer is valid only if it can be load and if cookie password is the same as database one */
if ($this->logged == 1 AND $this->id_customer AND Validate::isUnsignedId($this->id_customer) AND Customer::checkPassword((int)($this->id_customer), $this->passwd))
return true;
return false;
}
/**
* Check employee informations saved into cookie and return employee validity
*
* @return boolean employee validity
*/
public function isLoggedBack()
{
/* Employee is valid only if it can be load and if cookie password is the same as database one */
return ($this->id_employee
AND Validate::isUnsignedId($this->id_employee)
AND Employee::checkPassword((int)$this->id_employee, $this->passwd)
AND (!isset($this->_content['remote_addr']) OR $this->_content['remote_addr'] == ip2long(Tools::getRemoteAddr()) OR !Configuration::get('PS_COOKIE_CHECKIP'))
);
}
/**
* Delete cookie
*/
public function logout()
{
$this->_content = array();
$this->_setcookie();
unset($_COOKIE[$this->_name]);
$this->_modified = true;
$this->write();
}
/**
* Soft logout, delete everything links to the customer
* but leave there affiliate's informations
*/
public function mylogout()
{
unset($this->_content['id_customer']);
unset($this->_content['id_guest']);
unset($this->_content['is_guest']);
unset($this->_content['id_connections']);
unset($this->_content['customer_lastname']);
unset($this->_content['customer_firstname']);
unset($this->_content['passwd']);
unset($this->_content['logged']);
unset($this->_content['email']);
unset($this->_content['id_cart']);
unset($this->_content['id_address_invoice']);
unset($this->_content['id_address_delivery']);
$this->_modified = true;
$this->write();
}
function makeNewLog()
{
unset($this->_content['id_customer']);
unset($this->_content['id_guest']);
Guest::setNewGuest($this);
$this->_modified = true;
}
/**
* Get cookie content
*/
function update($nullValues = false)
{
if (isset($_COOKIE[$this->_name]))
{
/* Decrypt cookie content */
$content = $this->_cipherTool->decrypt($_COOKIE[$this->_name]);
/* Get cookie checksum */
$checksum = crc32($this->_iv.substr($content, 0, strrpos($content, '¤') + 2));
/* Unserialize cookie content */
$tmpTab = explode('¤', $content);
foreach ($tmpTab AS $keyAndValue)
{
$tmpTab2 = explode('|', $keyAndValue);
if (sizeof($tmpTab2) == 2)
$this->_content[$tmpTab2[0]] = $tmpTab2[1];
}
/* Blowfish fix */
if (isset($this->_content['checksum']))
$this->_content['checksum'] = (int)($this->_content['checksum']);
/* Check if cookie has not been modified */
if (!isset($this->_content['checksum']) OR $this->_content['checksum'] != $checksum)
$this->logout();
if (!isset($this->_content['date_add']))
$this->_content['date_add'] = date('Y-m-d H:i:s');
}
else
$this->_content['date_add'] = date('Y-m-d H:i:s');
//checks if the language exists, if not choose the default language
if (!Language::getLanguage((int)$this->id_lang))
$this->id_lang = Configuration::get('PS_LANG_DEFAULT');
}
/**
* Setcookie according to php version
*/
protected function _setcookie($cookie = NULL)
{
if ($cookie)
{
$content = $this->_cipherTool->encrypt($cookie);
$time = $this->_expire;
}
else
{
$content = 0;
$time = time() - 1;
}
if (PHP_VERSION_ID <= 50200) /* PHP version > 5.2.0 */
return setcookie($this->_name, $content, $time, $this->_path, $this->_domain, 0);
else
return setcookie($this->_name, $content, $time, $this->_path, $this->_domain, 0, true);
}
/**
* Save cookie with setcookie()
*/
public function write()
{
$cookie = '';
/* Serialize cookie content */
if (isset($this->_content['checksum'])) unset($this->_content['checksum']);
foreach ($this->_content AS $key => $value)
$cookie .= $key.'|'.$value.'¤';
/* Add checksum to cookie */
$cookie .= 'checksum|'.crc32($this->_iv.$cookie);
/* Cookies are encrypted for evident security reasons */
return $this->_setcookie($cookie);
}
/**
* Get a family of variables (e.g. "filter_")
*/
public function getFamily($origin)
{
$result = array();
if (count($this->_content) == 0)
return $result;
foreach ($this->_content AS $key => $value)
if (strncmp($key, $origin, strlen($origin)) == 0)
$result[$key] = $value;
return $result;
}
/**
*
*/
public function unsetFamily($origin)
{
$family = $this->getFamily($origin);
foreach ($family AS $member => $value)
unset($this->$member);
}
/**
*
* @return String name of cookie
*/
public function getName()
{
return $this->_name;
}
}
+333
View File
@@ -0,0 +1,333 @@
<?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 CountryCore extends ObjectModel
{
public $id;
/** @var integer Zone id which country belongs */
public $id_zone;
/** @var integer Currency id which country belongs */
public $id_currency;
/** @var string 2 letters iso code */
public $iso_code;
/** @var integer international call prefix */
public $call_prefix;
/** @var string Name */
public $name;
/** @var boolean Contain states */
public $contains_states;
/** @var boolean Need identification number dni/nif/nie */
public $need_identification_number;
/** @var boolean Need Zip Code */
public $need_zip_code;
/** @var string Zip Code Format */
public $zip_code_format;
/** @var boolean Display or not the tax incl./tax excl. mention in the front office */
public $display_tax_label = true;
/** @var boolean Status for delivery */
public $active = true;
protected static $_idZones = array();
protected $tables = array ('country', 'country_lang');
protected $fieldsRequired = array('id_zone', 'id_currency', 'iso_code', 'contains_states', 'need_identification_number', 'display_tax_label');
protected $fieldsSize = array('iso_code' => 3);
protected $fieldsValidate = array('id_zone' => 'isUnsignedId', 'id_currency' => 'isUnsignedId', 'call_prefix' => 'isInt', 'iso_code' => 'isLanguageIsoCode', 'active' => 'isBool', 'contains_states' => 'isBool', 'need_identification_number' => 'isBool', 'need_zip_code' => 'isBool', 'zip_code_format' => 'isZipCodeFormat', 'display_tax_label' => 'isBool');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 64);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $webserviceParameters = array(
'objectsNodeName' => 'countries',
'fields' => array(
'id_zone' => array('sqlId' => 'id_zone', 'xlink_resource'=> 'zones'),
'id_currency' => array('sqlId' => 'id_currency', 'xlink_resource'=> 'currencies'),
),
);
protected $table = 'country';
protected $identifier = 'id_country';
public function getFields()
{
parent::validateFields();
$fields['id_zone'] = (int)($this->id_zone);
$fields['id_currency'] = (int)($this->id_currency);
$fields['iso_code'] = pSQL(strtoupper($this->iso_code));
$fields['call_prefix'] = (int)($this->call_prefix);
$fields['active'] = (int)($this->active);
$fields['contains_states'] = (int)($this->contains_states);
$fields['need_identification_number'] = (int)($this->need_identification_number);
$fields['need_zip_code'] = (int)($this->need_zip_code);
$fields['zip_code_format'] = $this->zip_code_format;
$fields['display_tax_label'] = $this->display_tax_label;
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
/**
* Return available countries
*
* @param integer $id_lang Language ID
* @param boolean $active return only active coutries
* @return array Countries and corresponding zones
*/
static public function getCountries($id_lang, $active = false, $containStates = NULL, $id_shop = false)
{
if (!Validate::isBool($active))
die(Tools::displayError());
$states = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT s.*
FROM `'._DB_PREFIX_.'state` s
ORDER BY s.`name` ASC');
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT cl.*,c.*, cl.`name` AS country, z.`name` AS zone
FROM `'._DB_PREFIX_.'country` c
'.($id_shop ? 'LEFT JOIN '._DB_PREFIX_.'country_shop cs ON (cs.id_country = c.id_country)' : '').'
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (c.`id_country` = cl.`id_country` AND cl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'zone` z ON z.`id_zone` = c.`id_zone`
WHERE 1
'.($active ? ' AND c.active = 1' : '')
.($id_shop ? ' AND cs.id_shop='.(int)$id_shop : '')
.(!is_null($containStates) ? 'AND c.`contains_states` = '.(int)($containStates) : '').'
ORDER BY cl.name ASC');
$countries = array();
foreach ($result AS &$country)
$countries[$country['id_country']] = $country;
foreach ($states AS &$state)
if (isset($countries[$state['id_country']])) /* Does not keep the state if its country has been disabled and not selected */
$countries[$state['id_country']]['states'][] = $state;
return $countries;
}
/**
* Get a country ID with its iso code
*
* @param string $iso_code Country iso code
* @return integer Country ID
*/
static public function getByIso($iso_code)
{
if (!Validate::isLanguageIsoCode($iso_code))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_country`
FROM `'._DB_PREFIX_.'country`
WHERE `iso_code` = \''.pSQL(strtoupper($iso_code)).'\'');
return $result['id_country'];
}
static public function getIdZone($id_country)
{
if (!Validate::isUnsignedId($id_country))
die(Tools::displayError());
if (isset(self::$_idZones[$id_country]))
return self::$_idZones[$id_country];
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_zone`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)($id_country));
self::$_idZones[$id_country] = $result['id_zone'];
return $result['id_zone'];
}
/**
* Get a country name with its ID
*
* @param integer $id_lang Language ID
* @param integer $id_country Country ID
* @return string Country name
*/
static public function getNameById($id_lang, $id_country)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `name`
FROM `'._DB_PREFIX_.'country_lang`
WHERE `id_lang` = '.(int)($id_lang).'
AND `id_country` = '.(int)($id_country));
return $result['name'];
}
/**
* Get a country iso with its ID
*
* @param integer $id_country Country ID
* @return string Country iso
*/
static public function getIsoById($id_country)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `iso_code`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)($id_country));
return $result['iso_code'];
}
/**
* Get a country id with its name
*
* @param integer $id_lang Language ID
* @param string $country Country Name
* @return intval Country id
*/
static public function getIdByName($id_lang = NULL, $country)
{
$sql = '
SELECT `id_country`
FROM `'._DB_PREFIX_.'country_lang`
WHERE `name` LIKE \''.pSQL($country).'\'';
if ($id_lang)
$sql .= ' AND `id_lang` = '.(int)($id_lang);
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
return ((int)($result['id_country']));
}
/**
* @param $id_country
* @deprecated
*/
static public function getNeedIdentifcationNumber($id_country)
{
Tools::displayAsDeprecated();
return self::isNeedDniByCountryId($id_country);
}
static public function getNeedZipCode($id_country)
{
if (!(int)($id_country))
return false;
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `need_zip_code`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)($id_country));
}
static public function getZipCodeFormat($id_country)
{
if (!(int)($id_country))
return false;
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `zip_code_format`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)($id_country));
}
public static function displayCallPrefix($prefix)
{
return ((int)($prefix) ? '+'.$prefix : '-');
}
/**
* Returns the default country Id
*
* @return integer default country id
*/
public static function getDefaultCountryId()
{
global $cookie;
if (Configuration::get('PS_GEOLOCATION_ENABLED') AND Validate::isLanguageIsoCode($cookie->iso_code_country))
$id_country = (int)Country::getByIso($cookie->iso_code_country);
else
$id_country = (int)Configuration::get('PS_COUNTRY_DEFAULT');
return $id_country;
}
public static function getCountriesByZoneId($id_zone, $id_lang, $id_shop = false)
{
if (empty($id_zone) OR empty($id_lang))
die(Tools::displayError());
return Db::getInstance()->ExecuteS('
SELECT DISTINCT c.*, cl.*
FROM `'._DB_PREFIX_.'country` c
'.($id_shop ? ' LEFT JOIN '._DB_PREFIX_.'country_shop cs ON (cs.id_country = c.id_country)' : '').'
LEFT JOIN `'._DB_PREFIX_.'state` s ON (s.`id_country` = c.`id_country`)
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (c.`id_country` = cl.`id_country`)
WHERE (c.`id_zone` = '.(int)$id_zone.' OR s.`id_zone` = '.(int)$id_zone.')
'.($id_shop ? ' AND cs.id_shop='.(int)$id_shop : '').'
AND `id_lang` = '.(int)$id_lang);
}
public function isNeedDni()
{
return (bool)self::isNeedDniByCountryId($this->id);
}
static public function isNeedDniByCountryId($id_country)
{
return (bool)Db::getInstance()->getValue('
SELECT `need_identification_number`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)$id_country);
}
static public function containsStates($id_country)
{
return (bool)Db::getInstance()->getValue('
SELECT `contains_states`
FROM `'._DB_PREFIX_.'country`
WHERE `id_country` = '.(int)$id_country);
}
}
+244
View File
@@ -0,0 +1,244 @@
<?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 CountyCore extends ObjectModel
{
public $id;
public $name;
public $id_state;
public $active;
protected $fieldsRequired = array('name');
protected $fieldsSize = array('name' => 64);
protected $fieldsValidate = array('name' => 'isGenericName', 'id_state' => 'isUnsignedId', 'active' => 'isBool');
protected $table = 'county';
protected $identifier = 'id_county';
private static $_cache_get_counties = array();
private static $_cache_county_zipcode = array();
const USE_BOTH_TAX = 0;
const USE_COUNTY_TAX = 1;
const USE_STATE_TAX = 2;
protected $webserviceParameters = array(
'fields' => array(
'id_state' => array('xlink_resource'=> 'states'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_state'] = (int)($this->id_state);
$fields['name'] = pSQL($this->name);
$fields['active'] = (int)($this->active);
return $fields;
}
public function delete()
{
$id = $this->id;
parent::delete();
// remove associated zip codes & tax rule
return (County::deleteZipCodeByIdCounty($id) AND TaxRule::deleteTaxRuleByIdCounty($id));
}
public static function getCounties($id_state)
{
if (!isset(self::$_cache_get_counties[$id_state]))
{
self::$_cache_get_counties[$id_state] = Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'county`
WHERE `id_state` = '.(int)$id_state
);
}
return self::$_cache_get_counties[$id_state];
}
// return the list of associated zipcode
public function getZipCodes()
{
return Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'county_zip_code`
WHERE `id_county` = '.(int)$this->id.'
ORDER BY `from_zip_code` ASC'
);
}
public function addZipCodes($zip_codes)
{
list($from, $to) = $this->breakDownZipCode($zip_codes);
if ($from == 0)
return false;
return Db::getInstance()->Execute(
'INSERT INTO `'._DB_PREFIX_.'county_zip_code` (`id_county`, `from_zip_code`, `to_zip_code`)
VALUES ('.(int)$this->id.','.(int)$from.','.(int)$to.')'
);
}
public function removeZipCodes($zip_codes)
{
list($from, $to) = $this->breakDownZipCode($zip_codes);
if ($from == 0)
return false;
return Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'county_zip_code`
WHERE `id_county` = '.(int)$this->id.'
AND `from_zip_code` = '.(int)$from.'
AND `to_zip_code` = '.(int)$to
);
}
public function breakDownZipCode($zip_codes)
{
$zip_codes = preg_split('/-/', $zip_codes);
if (sizeof($zip_codes) == 2)
{
$from = $zip_codes[0];
$to = $zip_codes[1];
if ($zip_codes[0] > $zip_codes[1])
{
$from = $zip_codes[1];
$to = $zip_codes[0];
}
else if ($zip_codes[0] == $zip_codes[1])
{
$from = $zip_codes[0];
$to = 0;
}
}
else if (sizeof($zip_codes) == 1)
{
$from = $zip_codes[0];
$to = 0;
}
if (!Validate::isInt($from) OR !Validate::isInt($to))
{
$from = 0;
$to = 0;
}
return array($from, $to);
}
public static function getIdCountyByZipCode($id_state, $zip_code)
{
if (!isset(self::$_cache_county_zipcode[$id_state.'-'.$zip_code]))
{
self::$_cache_county_zipcode[$id_state.'-'.$zip_code] = Db::getInstance()->getValue('
SELECT DISTINCT c.`id_county` FROM `'._DB_PREFIX_.'county` c
LEFT JOIN `'._DB_PREFIX_.'county_zip_code` cz ON (c.`id_county` = cz.`id_county`)
WHERE `id_state` = '.(int)$id_state.'
AND cz.`from_zip_code` >= '.(int)$zip_code.'
AND cz.`to_zip_code` <= '.(int)$zip_code
);
}
return self::$_cache_county_zipcode[$id_state.'-'.$zip_code];
}
public function isZipCodeRangePresent($zip_codes)
{
$res = false;
list($from, $to) = $this->breakDownZipCode($zip_codes);
if ($from == 0)
return false;
if ($to != 0)
{
$res = Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'county_zip_code` cz
LEFT JOIN `'._DB_PREFIX_.'county` c ON (c.`id_county` = cz.`id_county`)
LEFT JOIN `'._DB_PREFIX_.'state` s ON (s.`id_state` = c.`id_state`)
WHERE `from_zip_code` >= '.(int)$from.'
AND `to_zip_code` <= '.(int)$to.'
AND s.`id_country` = (SELECT `id_country`
FROM `'._DB_PREFIX_.'state` s
LEFT JOIN `'._DB_PREFIX_.'county` c ON (c.`id_state` = s.`id_state`)
WHERE `id_county` = '.(int)$this->id.'
)'
);
}
return ($res OR County::isZipCodePresent($from) OR County::isZipCodePresent($to));
}
public function isZipCodePresent($zip_code)
{
if ($zip_code == 0)
return false;
return (bool) Db::getInstance()->getValue('
SELECT COUNT(*) FROM `'._DB_PREFIX_.'county_zip_code` cz
LEFT JOIN `'._DB_PREFIX_.'county` c ON (c.`id_county` = cz.`id_county`)
LEFT JOIN `'._DB_PREFIX_.'state` s ON (s.`id_state` = c.`id_state`)
WHERE
(`from_zip_code` <= '.(int)$zip_code.' AND `to_zip_code` >= '.(int)$zip_code.')
OR
(`from_zip_code` = '.(int)$zip_code.')
AND s.`id_country` = (SELECT `id_country`
FROM `'._DB_PREFIX_.'state` s
LEFT JOIN `'._DB_PREFIX_.'county` c ON (c.`id_state` = s.`id_state`)
WHERE `id_county` = '.(int)$this->id.'
)'
);
}
public static function deleteZipCodeByIdCounty($id_county)
{
return Db::getInstance()->Execute(
'DELETE FROM `'._DB_PREFIX_.'county_zip_code`
WHERE `id_county` = '.(int)$id_county
);
}
public static function getIdCountyByNameAndIdState($name, $id_state)
{
return Db::getInstance()->getValue('
SELECT `id_county` FROM `'._DB_PREFIX_.'county`
WHERE `name` = \''.pSQL($name).'\'
AND `id_state` = '.(int)$id_state
);
}
}
+377
View File
@@ -0,0 +1,377 @@
<?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: 7503 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class CurrencyCore extends ObjectModel
{
public $id;
/** @var string Name */
public $name;
/** @var string Iso code */
public $iso_code;
/** @var string Iso code numeric */
public $iso_code_num;
/** @var string Symbol for short display */
public $sign;
/** @var int bool used for displaying blank between sign and price */
public $blank;
/** @var string Conversion rate from euros */
public $conversion_rate;
/** @var boolean True if currency has been deleted (staying in database as deleted) */
public $deleted = 0;
/** @var int ID used for displaying prices */
public $format;
/** @var int bool Display decimals on prices */
public $decimals;
/** @var int bool active */
public $active;
protected $fieldsRequired = array('name', 'iso_code', 'sign', 'conversion_rate', 'format', 'decimals');
protected $fieldsSize = array('name' => 32, 'iso_code' => 3, 'iso_code_num' => 3, 'sign' => 8);
protected $fieldsValidate = array('name' => 'isGenericName', 'iso_code' => 'isLanguageIsoCode', 'iso_code_num' => 'isNumericIsoCode', 'blank' => 'isInt', 'sign' => 'isGenericName',
'format' => 'isUnsignedId', 'decimals' => 'isBool', 'conversion_rate' => 'isFloat', 'deleted' => 'isBool', 'active' => 'isBool');
protected $table = 'currency';
protected $identifier = 'id_currency';
/** @var Currency Current currency */
static protected $current = NULL;
/** @var array Currency cache */
static protected $currencies = array();
protected $webserviceParameters = array(
'objectsNodeName' => 'currencies',
);
/**
* Overriding check if currency with the same iso code already exists.
* If it's true, currency is doesn't added.
*
* @see ObjectModelCore::add()
*/
public function add($autodate = true, $nullValues = false)
{
return Currency::exists($this->iso_code) ? false : parent::add();
}
/**
* Check if a curency already exists.
*
* @param int|string $iso_code int for iso code number string for iso code
* @return boolean
*/
public static function exists ($iso_code)
{
if(is_int($iso_code))
$id_currency_exists = Currency::getIdByIsoCodeNum($iso_code);
else
$id_currency_exists = Currency::getIdByIsoCode($iso_code);
if ($id_currency_exists){
return true;
} else {
return false;
}
}
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
$fields['iso_code'] = pSQL($this->iso_code);
$fields['iso_code_num'] = pSQL($this->iso_code_num);
$fields['sign'] = pSQL($this->sign);
$fields['format'] = (int)($this->format);
$fields['decimals'] = (int)($this->decimals);
$fields['blank'] = (int)($this->blank);
$fields['conversion_rate'] = (float)($this->conversion_rate);
$fields['deleted'] = (int)($this->deleted);
$fields['active'] = (int)($this->active);
return $fields;
}
public function deleteSelection($selection)
{
if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$result = true;
foreach ($selection AS $id)
{
$obj = new Currency((int)($id));
$res[$id] = $obj->delete();
}
foreach ($res AS $value)
if (!$value)
return false;
return true;
}
public function delete()
{
if ($this->id == Configuration::get('PS_CURRENCY_DEFAULT'))
{
$result = Db::getInstance()->getRow('SELECT `id_currency` FROM '._DB_PREFIX_.'currency WHERE `id_currency` != '.(int)($this->id).' AND `deleted` = 0');
if (!$result['id_currency'])
return false;
Configuration::updateValue('PS_CURRENCY_DEFAULT', $result['id_currency']);
}
$this->deleted = 1;
return $this->update();
}
/**
* Return formated sign
*
* @param string $side left or right
* @return string formated sign
*/
public function getSign($side=NULL)
{
if (!$side)
return $this->sign;
$formated_strings = array(
'left' => $this->sign.' ',
'right' => ' '.$this->sign
);
$formats = array(
1 => array('left' => &$formated_strings['left'], 'right' => ''),
2 => array('left' => '', 'right' => &$formated_strings['right']),
3 => array('left' => &$formated_strings['left'], 'right' => ''),
4 => array('left' => '', 'right' => &$formated_strings['right']),
);
return ($formats[$this->format][$side]);
}
/**
* Return available currencies
*
* @return array Currencies
*/
static public function getCurrencies($object = false, $active = 1, $id_shop = false)
{
$tab = Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'currency` c
'.($id_shop ? 'LEFT JOIN '._DB_PREFIX_.'currency_shop cs ON (c.id_currency = cs.id_currency)' : '').'
WHERE `deleted` = 0
'.($active == 1 ? 'AND c.`active` = 1' : '').($id_shop ? ' AND cs.id_shop='.(int)$id_shop : '').'
ORDER BY `name` ASC');
if ($object)
foreach ($tab as $key => $currency)
$tab[$key] = Currency::getCurrencyInstance($currency['id_currency']);
return $tab;
}
static public function getPaymentCurrenciesSpecial($id_module, $id_shop = null)
{
if (is_null($id_shop))
$id_shop = Shop::getCurrentShop(true);
$sql = 'SELECT *
FROM '._DB_PREFIX_.'module_currency
WHERE id_module = '.(int)$id_module.'
AND id_shop ='.(int)$id_shop;
return Db::getInstance()->getRow($sql);
}
static public function getPaymentCurrencies($id_module, $id_shop = null)
{
if (is_null($id_shop))
$id_shop = Shop::getCurrentShop(true);
$sql = 'SELECT c.*
FROM `'._DB_PREFIX_.'module_currency` mc
LEFT JOIN `'._DB_PREFIX_.'currency` c ON c.`id_currency` = mc.`id_currency`
WHERE c.`deleted` = 0
AND mc.`id_module` = '.(int)$id_module.'
AND c.`active` = 1
AND mc.id_shop = '.(int)$id_shop.'
ORDER BY c.`name` ASC';
return Db::getInstance()->ExecuteS($sql);
}
static public function checkPaymentCurrencies($id_module, $id_shop = null)
{
if (is_null($id_shop))
$id_shop = Shop::getCurrentShop(true);
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT mc.*
FROM `'._DB_PREFIX_.'module_currency` mc
WHERE mc.`id_module` = '.(int)$id_module.' AND mc.`id_shop`='.(int)$id_shop);
}
static public function getCurrency($id_currency)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT *
FROM `'._DB_PREFIX_.'currency`
WHERE `deleted` = 0
AND `id_currency` = '.(int)($id_currency));
}
static public function getIdByIsoCode($iso_code)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_currency`
FROM `'._DB_PREFIX_.'currency`
WHERE `deleted` = 0
AND `iso_code` = \''.pSQL($iso_code).'\'');
return $result['id_currency'];
}
static public function getIdByIsoCodeNum($iso_code)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_currency`
FROM `'._DB_PREFIX_.'currency`
WHERE `deleted` = 0
AND `iso_code_num` = \''.pSQL($iso_code).'\'');
return (int)$result['id_currency'];
}
/**
* Refresh the currency conversion rate
* The XML file define conversion rate for each from a default currency ($isoCodeSource).
*
* @param $data XML content which contains all the conversion rates
* @param $isoCodeSource The default currency used in the XML file
* @param $defaultCurrency The default currency object
*/
public function refreshCurrency($data, $isoCodeSource, $defaultCurrency)
{
// fetch the conversion rate of the default currency
$conversion_rate = 1;
if ($defaultCurrency->iso_code != $isoCodeSource)
{
foreach ($data->currency AS $currency)
if ($currency['iso_code'] == $defaultCurrency->iso_code)
{
$conversion_rate = round((float)$currency['rate'], 6);
break;
}
}
if ($defaultCurrency->iso_code == $this->iso_code)
$this->conversion_rate = 1;
else
{
if ($this->iso_code == $isoCodeSource)
$rate = 1;
else
{
foreach ($data->currency AS $obj)
if ($this->iso_code == strval($obj['iso_code']))
{
$rate = (float) $obj['rate'];
break;
}
}
$this->conversion_rate = round($rate / $conversion_rate, 6);
}
$this->update();
}
/**
* @deprecated
**/
static public function refreshCurrenciesGetDefault($data, $isoCodeSource, $idCurrency)
{
Tools::displayAsDeprecated();
$defaultCurrency = new Currency($idCurrency);
/* Change defaultCurrency rate if not as currency of feed source */
if ($defaultCurrency->iso_code != $isoCodeSource)
foreach ($data->currency AS $obj)
if ($defaultCurrency->iso_code == strval($obj['iso_code']))
$defaultCurrency->conversion_rate = round((float)($obj['rate']), 6);
return $defaultCurrency;
}
public static function getDefaultCurrency()
{
$id_currency = (int)Configuration::get('PS_CURRENCY_DEFAULT');
if ($id_currency == 0)
return false;
return new Currency($id_currency);
}
static public function refreshCurrencies()
{
// Parse
if (!$feed = @simplexml_load_file('http://www.prestashop.com/xml/currencies.xml'))
return Tools::displayError('Cannot parse feed.');
// Default feed currency (EUR)
$isoCodeSource = strval($feed->source['iso_code']);
if (!$default_currency = self::getDefaultCurrency())
return Tools::displayError('No default currency');
$currencies = self::getCurrencies(true);
foreach ($currencies as $currency)
$currency->refreshCurrency($feed->list, $isoCodeSource, $default_currency);
}
static public function getCurrent()
{
global $cookie;
if (!self::$current)
{
if (isset($cookie->id_currency) AND $cookie->id_currency)
self::$current = new Currency((int)($cookie->id_currency));
else
self::$current = new Currency((int)(Configuration::get('PS_CURRENCY_DEFAULT')));
}
return self::$current;
}
static public function getCurrencyInstance($id)
{
if (!array_key_exists($id, self::$currencies))
self::$currencies[(int)($id)] = new Currency((int)($id));
return self::$currencies[(int)($id)];
}
}
+699
View File
@@ -0,0 +1,699 @@
<?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: 7499 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class CustomerCore extends ObjectModel
{
public $id;
public $id_shop;
public $id_group_shop;
/** @var string Secure key */
public $secure_key;
/** @var string protected note */
public $note;
/** @var integer Gender ID */
public $id_gender = 9;
/** @var integer Default group ID */
public $id_default_group;
/** @var string Lastname */
public $lastname;
/** @var string Firstname */
public $firstname;
/** @var string Birthday (yyyy-mm-dd) */
public $birthday = NULL;
/** @var string e-mail */
public $email;
/** @var boolean Newsletter subscription */
public $newsletter;
/** @var string Newsletter ip registration */
public $ip_registration_newsletter;
/** @var string Newsletter ip registration */
public $newsletter_date_add;
/** @var boolean Opt-in subscription */
public $optin;
/** @var integer Password */
public $passwd;
/** @var datetime Password */
public $last_passwd_gen;
/** @var boolean Status */
public $active = true;
/** @var boolean Status */
public $is_guest = 0;
/** @var boolean True if carrier has been deleted (staying in database as deleted) */
public $deleted = 0;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
public $years;
public $days;
public $months;
protected $tables = array ('customer');
protected $fieldsRequired = array('lastname', 'passwd', 'firstname', 'email');
protected $fieldsSize = array('lastname' => 32, 'passwd' => 32, 'firstname' => 32, 'email' => 128, 'note' => 65000);
protected $fieldsValidate = array('secure_key' => 'isMd5', 'lastname' => 'isName', 'firstname' => 'isName', 'email' => 'isEmail', 'passwd' => 'isPasswd',
'id_gender' => 'isUnsignedId', 'birthday' => 'isBirthDate', 'newsletter' => 'isBool', 'optin' => 'isBool', 'active' => 'isBool', 'note' => 'isCleanHtml', 'is_guest' => 'isBool', 'id_shop' => 'isUnsignedId','id_group_shop' => 'isUnsignedId',);
protected $webserviceParameters = array(
'fields' => array(
'id_default_group' => array('xlink_resource' => 'groups'),
'newsletter_date_add' => array(),
'ip_registration_newsletter' => array(),
'last_passwd_gen' => array('setter' => null),
'secure_key' => array('setter' => null),
'deleted' => array(),
'passwd' => array('setter' => 'setWsPasswd'),
),
);
protected $table = 'customer';
protected $identifier = 'id_customer';
protected static $_defaultGroupId = array();
protected static $_customerHasAddress = array();
public function getFields()
{
parent::validateFields();
if (isset($this->id))
$fields['id_customer'] = (int)($this->id);
$fields['id_shop'] = (int)$this->id_shop;
$fields['id_group_shop'] = (int)$this->id_group_shop;
$fields['secure_key'] = pSQL($this->secure_key);
$fields['note'] = pSQL($this->note, true);
$fields['id_gender'] = (int)($this->id_gender);
$fields['id_default_group'] = (int)($this->id_default_group);
$fields['lastname'] = pSQL($this->lastname);
$fields['firstname'] = pSQL($this->firstname);
$fields['birthday'] = pSQL($this->birthday);
$fields['email'] = pSQL($this->email);
$fields['newsletter'] = (int)($this->newsletter);
$fields['newsletter_date_add'] = pSQL($this->newsletter_date_add);
$fields['ip_registration_newsletter'] = pSQL($this->ip_registration_newsletter);
$fields['optin'] = (int)($this->optin);
$fields['passwd'] = pSQL($this->passwd);
$fields['last_passwd_gen'] = pSQL($this->last_passwd_gen);
$fields['active'] = (int)($this->active);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
$fields['is_guest'] = (int)($this->is_guest);
$fields['deleted'] = (int)($this->deleted);
return $fields;
}
public function add($autodate = true, $nullValues = true)
{
$this->id_shop = ($this->id_shop) ? $this->id_shop : Shop::getCurrentShop();
$this->id_group_shop = ($this->id_group_shop) ? $this->id_group_shop : Shop::getCurrentGroupShop();
$this->birthday = (empty($this->years) ? $this->birthday : (int)($this->years).'-'.(int)($this->months).'-'.(int)($this->days));
$this->secure_key = md5(uniqid(rand(), true));
$this->last_passwd_gen = date('Y-m-d H:i:s', strtotime('-'.Configuration::get('PS_PASSWD_TIME_FRONT').'minutes'));
if (empty($this->id_default_group))
$this->id_default_group = 1;
/* Can't create a guest customer, if this feature is disabled */
if ($this->is_guest AND !Configuration::get('PS_GUEST_CHECKOUT_ENABLED'))
return false;
if (!parent::add($autodate, $nullValues))
return false;
$row = array('id_customer' => (int)($this->id), 'id_group' => (int)$this->id_default_group);
return Db::getInstance()->AutoExecute(_DB_PREFIX_.'customer_group', $row, 'INSERT');
}
public function update($nullValues = false)
{
$this->birthday = (empty($this->years) ? $this->birthday : (int)$this->years.'-'.(int)$this->months.'-'.(int)$this->days);
if ($this->newsletter AND !$this->newsletter_date_add)
$this->newsletter_date_add = date('Y-m-d H:i:s');
return parent::update(true);
}
public function delete()
{
$addresses = $this->getAddresses((int)(Configuration::get('PS_LANG_DEFAULT')));
foreach ($addresses AS $address)
{
$obj = new Address((int)($address['id_address']));
$obj->delete();
}
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'customer_group` WHERE `id_customer` = '.(int)($this->id));
Discount::deleteByIdCustomer((int)($this->id));
return parent::delete();
}
/**
* Return customers list
*
* @return array Customers
*/
static public function getCustomers()
{
$sql = 'SELECT `id_customer`, `email`, `firstname`, `lastname`
FROM `'._DB_PREFIX_.'customer`
WHERE 1
'.Shop::sqlRestriction(true).'
ORDER BY `id_customer` ASC';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
}
/**
* Return customer instance from its e-mail (optionnaly check password)
*
* @param string $email e-mail
* @param string $passwd Password is also checked if specified
* @return Customer instance
*/
public function getByEmail($email, $passwd = NULL, $id_group_shop = null, $id_shop = null)
{
if (!Validate::isEmail($email) OR ($passwd AND !Validate::isPasswd($passwd)))
die (Tools::displayError());
$sql = 'SELECT *
FROM `'._DB_PREFIX_ .'customer`
WHERE `active` = 1
AND `email` = \''.pSQL($email).'\'
'.Shop::sqlRestriction(true, null, $id_shop, $id_group_shop).'
'.(isset($passwd) ? 'AND `passwd` = \''.md5(_COOKIE_KEY_.$passwd).'\'' : '').'
AND `deleted` = 0
AND `is_guest` = 0';
$result = Db::getInstance()->getRow($sql);
if (!$result)
return false;
$this->id = $result['id_customer'];
foreach ($result AS $key => $value)
if (key_exists($key, $this))
$this->{$key} = $value;
return $this;
}
/**
* Check id the customer is active or not
*
* @return boolean customer validity
*/
public static function isBanned($id_customer)
{
if (!Validate::isUnsignedId($id_customer))
return true;
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_customer`
FROM `'._DB_PREFIX_.'customer`
WHERE `id_customer` = \''.(int)($id_customer).'\'
AND active = 1
AND `deleted` = 0');
if (isset($result['id_customer']))
return false;
return true;
}
/**
* Check if e-mail is already registered in database
*
* @param string $email e-mail
* @param $return_id boolean
* @param $ignoreGuest boolean, for exclure guest customer
* @return Customer ID if found, false otherwise
*/
static public function customerExists($email, $return_id = false, $ignoreGuest = true, $id_group_shop = null, $id_shop = null)
{
if (!Validate::isEmail($email))
die (Tools::displayError());
$sql = 'SELECT `id_customer`
FROM `'._DB_PREFIX_.'customer`
WHERE `email` = \''.pSQL($email).'\'
'.Shop::sqlRestriction(true, null, $id_shop, $id_group_shop).
($ignoreGuest ? 'AND `is_guest` = 0' : '');
$result = Db::getInstance()->getRow($sql);
if ($return_id)
return $result['id_customer'];
return isset($result['id_customer']);
}
/**
* Check if, except current customer, someone else registered this e-email
*
* @return integer Number of customers who have also this e-mail
* @deprecated
*/
public function cantChangeemail()
{
Tools::displayAsDeprecated();
if (!Validate::isEmail($this->email))
die (Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(`id_customer`) AS total
FROM `'._DB_PREFIX_.'customer`
WHERE `email` = \''.pSQL($this->email).'\' AND `id_customer` != '.(int)($this->id));
return $result['total'];
}
/**
* Check if an address is owned by a customer
*
* @param integer $id_customer Customer ID
* @param integer $id_address Address ID
* @return boolean result
*/
static public function customerHasAddress($id_customer, $id_address)
{
if (!array_key_exists($id_customer, self::$_customerHasAddress))
{
self::$_customerHasAddress[$id_customer] = (bool)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_address`
FROM `'._DB_PREFIX_.'address`
WHERE `id_customer` = '.(int)($id_customer).'
AND `id_address` = '.(int)($id_address).'
AND `deleted` = 0');
}
return self::$_customerHasAddress[$id_customer];
}
static public function resetAddressCache($id_customer)
{
if (array_key_exists($id_customer, self::$_customerHasAddress))
unset(self::$_customerHasAddress[$id_customer]);
}
/**
* Return customer addresses
*
* @param integer $id_lang Language ID
* @return array Addresses
*/
public function getAddresses($id_lang)
{
$sql = 'SELECT a.*, cl.`name` AS country, s.name AS state, s.iso_code AS state_iso
FROM `'._DB_PREFIX_.'address` a
LEFT JOIN `'._DB_PREFIX_.'country` c ON (a.`id_country` = c.`id_country`)
LEFT JOIN `'._DB_PREFIX_.'country_lang` cl ON (c.`id_country` = cl.`id_country`)
LEFT JOIN `'._DB_PREFIX_.'state` s ON (s.`id_state` = a.`id_state`)
WHERE `id_lang` = '.(int)($id_lang).' AND `id_customer` = '.(int)($this->id).' AND a.`deleted` = 0';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
}
/**
* Returns customer last connections
*
* @param integer $nb Number of connections wanted
* @return array Connections
*/
public function getConnections($nb = 10)
{
Tools::displayAsDeprecated();
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT `ip_address`, `date_add`
FROM `'._DB_PREFIX_.'connections`
WHERE `id_guest` IN (SELECT `id_guest` FROM `'._DB_PREFIX_.'guest` WHERE `id_customer` = '.(int)($this->id).')
ORDER BY `date_add` DESC
LIMIT 0,'.(int)($nb));
}
/**
* Count the number of addresses for a customer
*
* @param integer $id_customer Customer ID
* @return integer Number of addresses
*/
public static function getAddressesTotalById($id_customer)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT COUNT(`id_address`)
FROM `'._DB_PREFIX_.'address`
WHERE `id_customer` = '.(int)($id_customer).'
AND `deleted` = 0');
}
/**
* Check if customer password is the right one
*
* @param string $passwd Password
* @return boolean result
*/
static public function checkPassword($id_customer, $passwd)
{
if (!Validate::isUnsignedId($id_customer) OR !Validate::isMd5($passwd))
die (Tools::displayError());
$sql = 'SELECT `id_customer`
FROM `'._DB_PREFIX_.'customer`
WHERE `id_customer` = '.$id_customer.'
AND `passwd` = \''.$passwd.'\'';
return (bool)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue($sql);
}
/**
* Return customers who have subscribed to the newsletter
*
* @return array Customers
* @deprecated
*/
public static function getNewsletteremails()
{
Tools::displayAsDeprecated();
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT `email`, `firstname`, `lastname`, `newsletter`, `ip_registration_newsletter`, `newsletter_date_add`
FROM `'._DB_PREFIX_.'customer`
WHERE `newsletter` = 1
AND `active` = 1');
}
/**
* Return the number of customers who registered today
*
* @return integer number of customers who registered today
* @deprecated
*/
public static function getTodaysRegistration()
{
Tools::displayAsDeprecated();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(`id_customer`) as nb
FROM `'._DB_PREFIX_.'customer`
WHERE DAYOFYEAR(`date_add`) = DAYOFYEAR(NOW())
AND YEAR(`date_add`) = YEAR(NOW())');
if (!$result['nb'])
return '0';
return $result['nb'];
}
/**
* Light back office search for customers
*
* @param string $query Searched string
* @return array Corresponding customers
*/
public static function searchByName($query)
{
$sql = 'SELECT *
FROM `'._DB_PREFIX_.'customer`
WHERE (
`email` LIKE \'%'.pSQL($query).'%\'
OR `id_customer` LIKE \'%'.pSQL($query).'%\'
OR `lastname` LIKE \'%'.pSQL($query).'%\'
OR `firstname` LIKE \'%'.pSQL($query).'%\'
)'.Shop::sqlRestriction(true);
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
}
/**
* Return several useful statistics about customer
*
* @return array Stats
*/
public function getStats()
{
$result = Db::getInstance()->getRow('
SELECT COUNT(`id_order`) AS nb_orders, SUM(`total_paid` / o.`conversion_rate`) AS total_orders
FROM `'._DB_PREFIX_.'orders` o
WHERE o.`id_customer` = '.(int)($this->id).'
AND o.valid = 1');
$result2 = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT MAX(c.`date_add`) AS last_visit
FROM `'._DB_PREFIX_.'guest` g
LEFT JOIN `'._DB_PREFIX_.'connections` c ON c.id_guest = g.id_guest
WHERE g.`id_customer` = '.(int)($this->id));
$result3 = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT (YEAR(CURRENT_DATE)-YEAR(c.`birthday`)) - (RIGHT(CURRENT_DATE, 5)<RIGHT(c.`birthday`, 5)) AS age
FROM `'._DB_PREFIX_.'customer` c
WHERE c.`id_customer` = '.(int)($this->id));
$result['last_visit'] = $result2['last_visit'];
$result['age'] = ($result3['age'] != date('Y') ? $result3['age'] : '--');
return $result;
}
public function getLastConnections()
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT c.date_add, COUNT(cp.id_page) AS pages, TIMEDIFF(MAX(cp.time_end), c.date_add) as time, http_referer,INET_NTOA(ip_address) as ipaddress
FROM `'._DB_PREFIX_.'guest` g
LEFT JOIN `'._DB_PREFIX_.'connections` c ON c.id_guest = g.id_guest
LEFT JOIN `'._DB_PREFIX_.'connections_page` cp ON c.id_connections = cp.id_connections
WHERE g.`id_customer` = '.(int)($this->id).'
GROUP BY c.`id_connections`
ORDER BY c.date_add DESC
LIMIT 10');
}
/**
* Return last cart ID for this customer
*
* @return integer Cart ID
* @deprecated
*/
public function getLastCart()
{
Tools::displayAsDeprecated();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT MAX(c.`id_cart`) AS id_cart
FROM `'._DB_PREFIX_.'cart` c
WHERE c.`id_customer` = '.(int)($this->id));
if (isset($result['id_cart']))
return $result['id_cart'];
return false;
}
/*
* Specify if a customer already in base
*
* @param $id_customer Customer id
* @return boolean
*/
// DEPRECATED
public function customerIdExists($id_customer)
{
return self::customerIdExistsStatic((int)($id_customer));
}
static public function customerIdExistsStatic($id_customer)
{
$row = Db::getInstance()->getRow('
SELECT `id_customer`
FROM '._DB_PREFIX_.'customer c
WHERE c.`id_customer` = '.(int)($id_customer));
return isset($row['id_customer']);
}
public function cleanGroups()
{
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'customer_group` WHERE `id_customer` = '.(int)($this->id));
}
public function addGroups($groups)
{
foreach ($groups as $group)
{
$row = array('id_customer' => (int)($this->id), 'id_group' => (int)($group));
Db::getInstance()->AutoExecute(_DB_PREFIX_.'customer_group', $row, 'INSERT');
}
}
public static function getGroupsStatic($id_customer)
{
$groups = array();
$result = Db::getInstance()->ExecuteS('
SELECT cg.`id_group`
FROM '._DB_PREFIX_.'customer_group cg
WHERE cg.`id_customer` = '.(int)($id_customer));
foreach ($result AS $group)
$groups[] = (int)($group['id_group']);
return $groups;
}
public function getGroups()
{
return self::getGroupsStatic((int)($this->id));
}
public function isUsed()
{
return false;
}
/**
* @param int $id_group
* @return int
* @deprecated
*/
public function isMemberOfGroup($id_group)
{
Tools::displayAsDeprecated();
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT count(cg.`id_group`) as nb
FROM '._DB_PREFIX_.'customer_group cg
WHERE cg.`id_customer` = '.(int)($this->id).'
AND cg.`id_group` = '.(int)($id_group));
return $result['nb'];
}
public function getBoughtProducts()
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'orders` o
LEFT JOIN `'._DB_PREFIX_.'order_detail` od ON o.id_order = od.id_order
WHERE o.valid = 1 AND o.`id_customer` = '.(int)($this->id));
}
/**
* @deprecated
* @return bool
*/
public function getNeedDNI()
{
Tools::displayAsDeprecated();
return false;
}
static public function getDefaultGroupId($id_customer)
{
if (!isset(self::$_defaultGroupId[(int)($id_customer)]))
self::$_defaultGroupId[(int)($id_customer)] = Db::getInstance()->getValue('SELECT `id_default_group` FROM `'._DB_PREFIX_.'customer` WHERE `id_customer` = '.(int)($id_customer));
return self::$_defaultGroupId[(int)($id_customer)];
}
static public function getCurrentCountry($id_customer)
{
global $cart;
if (!$cart OR !$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})
$id_address = (int)(Db::getInstance()->getValue('SELECT `id_address` FROM `'._DB_PREFIX_.'address` WHERE `id_customer` = '.(int)($id_customer).' AND `deleted` = 0 ORDER BY `id`'));
else
$id_address = $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')};
$ids = Address::getCountryAndState($id_address);
return (int)($ids['id_country'] ? $ids['id_country'] : Configuration::get('PS_COUNTRY_DEFAULT'));
}
public function toggleStatus()
{
parent::toggleStatus();
/* Change status to active/inactive */
return Db::getInstance()->Execute('
UPDATE `'.pSQL(_DB_PREFIX_.$this->table).'`
SET `date_upd` = NOW()
WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
}
public function isGuest()
{
return (bool)$this->is_guest;
}
public function transformToCustomer($id_lang, $password = NULL)
{
if (!$this->isGuest())
return false;
if (empty($password))
$password = Tools::passwdGen();
if (!Validate::isPasswd($password))
return false;
$this->is_guest = 0;
$this->passwd = Tools::encrypt($password);
if ($this->update())
{
$vars = array(
'{firstname}' => $this->firstname,
'{lastname}' => $this->lastname,
'{email}' => $this->email,
'{passwd}' => $password
);
Mail::Send((int)$id_lang, 'guest_to_customer', Mail::l('Your guest account has been transformed to customer account'), $vars, $this->email, $this->firstname.' '.$this->lastname);
return true;
}
return false;
}
static public function printNewsIcon($id_customer, $tr)
{
$customer = new Customer($tr['id_customer']);
if (!Validate::isLoadedObject($customer))
die(Tools::displayError('Invalid objects'));
echo '<a href="index.php?tab=AdminCustomers&id_customer='.(int)($customer->id).'&changeNewsletterVal&token='.Tools::getAdminTokenLite('AdminCustomers').'">'.
($customer->newsletter ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />').
'</a>';
}
static public function printOptinIcon($id_customer, $tr)
{
$customer = new Customer($tr['id_customer']);
if (!Validate::isLoadedObject($customer))
die(Tools::displayError('Invalid objects'));
echo '<a href="index.php?tab=AdminCustomers&id_customer='.(int)($customer->id).'&changeOptinVal&token='.Tools::getAdminTokenLite('AdminCustomers').'">'.
($customer->optin ? '<img src="../img/admin/enabled.gif" />' : '<img src="../img/admin/disabled.gif" />').
'</a>';
}
public function setWsPasswd($passwd)
{
if ($this->id != 0)
{
if ($this->passwd != $passwd)
$this->passwd = Tools::encrypt($passwd);
}
else
$this->passwd = Tools::encrypt($passwd);
return true;
}
}
+59
View File
@@ -0,0 +1,59 @@
<?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 CustomerMessageCore extends ObjectModel
{
public $id;
public $id_customer_thread;
public $id_employee;
public $message;
public $file_name;
public $ip_address;
public $user_agent;
public $date_add;
protected $table = 'customer_message';
protected $identifier = 'id_customer_message';
protected $fieldsRequired = array('message');
protected $fieldsSize = array('message' => 65000);
protected $fieldsValidate = array('message' => 'isCleanHtml', 'id_employee' => 'isUnsignedId', 'ip_address' => 'isIp2Long');
public function getFields()
{
parent::validateFields();
$fields['id_customer_thread'] = (int)($this->id_customer_thread);
$fields['id_employee'] = (int)($this->id_employee);
$fields['message'] = pSQL($this->message);
$fields['file_name'] = pSQL($this->file_name);
$fields['ip_address'] = (int)($this->ip_address);
$fields['user_agent'] = pSQL($this->user_agent);
$fields['date_add'] = pSQL($this->date_add);
return $fields;
}
}
+84
View File
@@ -0,0 +1,84 @@
<?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 CustomerThreadCore extends ObjectModel
{
public $id;
public $id_shop;
public $id_lang;
public $id_contact;
public $id_customer;
public $id_order;
public $id_product;
public $status;
public $email;
public $token;
public $date_add;
public $date_upd;
protected $table = 'customer_thread';
protected $identifier = 'id_customer_thread';
protected $fieldsRequired = array('id_lang', 'id_contact', 'token');
protected $fieldsSize = array('email' => 254);
protected $fieldsValidate = array('id_lang' => 'isUnsignedId', 'id_contact' => 'isUnsignedId', 'id_shop' => 'isUnsignedId', 'id_customer' => 'isUnsignedId',
'id_order' => 'isUnsignedId', 'id_product' => 'isUnsignedId', 'email' => 'isEmail', 'token' => 'isGenericName');
public function getFields()
{
parent::validateFields();
$fields['id_lang'] = (int)($this->id_lang);
$fields['id_shop'] = (int)$this->id_shop;
$fields['id_contact'] = (int)($this->id_contact);
$fields['id_customer'] = (int)($this->id_customer);
$fields['id_order'] = (int)($this->id_order);
$fields['id_product'] = (int)($this->id_product);
$fields['status'] = pSQL($this->status);
$fields['email'] = pSQL($this->email);
$fields['token'] = pSQL($this->token);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
public function delete()
{
if (!Validate::isUnsignedId($this->id))
return false;
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'customer_message` WHERE `id_customer_thread` = '.(int)($this->id));
return (parent::delete());
}
public static function getCustomerMessages($id_customer)
{
return Db::getInstance()->ExecuteS('
SELECT * FROM '._DB_PREFIX_.'customer_thread ct
LEFT JOIN '._DB_PREFIX_.'customer_message cm ON ct.id_customer_thread = cm.id_customer_thread
WHERE id_customer = '.(int)($id_customer));
}
}
+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
*/
class CustomizationCore
{
static public function getReturnedCustomizations($id_order)
{
if (($result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT ore.`id_order_return`, ord.`id_order_detail`, ord.`id_customization`, ord.`product_quantity`
FROM `'._DB_PREFIX_.'order_return` ore
INNER JOIN `'._DB_PREFIX_.'order_return_detail` ord ON (ord.`id_order_return` = ore.`id_order_return`)
WHERE ore.`id_order` = '.(int)($id_order).' AND ord.`id_customization` != 0')) === false)
return false;
$customizations = array();
foreach ($result AS $row)
$customizations[(int)($row['id_customization'])] = $row;
return $customizations;
}
static public function getOrderedCustomizations($id_cart)
{
if (!$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT `id_customization`, `quantity` FROM `'._DB_PREFIX_.'customization` WHERE `id_cart` = '.(int)($id_cart)))
return false;
$customizations = array();
foreach ($result AS $row)
$customizations[(int)($row['id_customization'])] = $row;
return $customizations;
}
static public function countCustomizationQuantityByProduct($customizations)
{
$total = array();
foreach ($customizations AS $customization)
$total[(int)($customization['id_order_detail'])] = !isset($total[(int)($customization['id_order_detail'])]) ? (int)($customization['quantity']) : $total[(int)($customization['id_order_detail'])] + (int)($customization['quantity']);
return $total;
}
static public function getLabel($id_customization, $id_lang)
{
if (!$id_customization || !$id_lang)
return false;
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `name`
FROM `'._DB_PREFIX_.'customization_field_lang`
WHERE `id_customization_field` = '.(int)($id_customization).'
AND `id_lang` = '.(int)($id_lang)
);
return $result['name'];
}
public static function retrieveQuantitiesFromIds($ids_customizations)
{
$quantities = array();
$in_values = '';
foreach($ids_customizations as $key => $id_customization)
{
if ($key > 0) $in_values += ',';
$in_values += (int)($id_customization);
}
if (!empty($in_values))
{
$results = Db::getInstance()->ExecuteS(
'SELECT `id_customization`, `id_product`, `quantity`, `quantity_refunded`, `quantity_returned`
FROM `'._DB_PREFIX_.'customization`
WHERE `id_customization` IN ('.$in_values.')');
foreach($results as $row)
{
$quantities[$row['id_customization']] = $row;
}
}
return $quantities;
}
public static function countQuantityByCart($id_cart)
{
$quantity = array();
$results = Db::getInstance()->executeS('
SELECT `id_product`, `id_product_attribute`, SUM(`quantity`) AS quantity
FROM `'._DB_PREFIX_.'customization`
WHERE `id_cart` = '.(int)($id_cart).'
GROUP BY `id_cart`, `id_product`, `id_product_attribute`'
);
foreach($results as $row)
{
$quantity[$row['id_product']][$row['product_attribute_id']] = $row['quantity'];
}
return $quantity;
}
}
+67
View File
@@ -0,0 +1,67 @@
<?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 DateRangeCore extends ObjectModel
{
public $time_start;
public $time_end;
protected $fieldsRequired = array ('time_start', 'time_end');
protected $fieldsValidate = array ('time_start' => 'isDate', 'time_end' => 'isDate');
protected $table = 'date_range';
protected $identifier = 'id_date_range';
public function getFields()
{
parent::validateFields();
$fields['time_start'] = pSQL($this->time_start);
$fields['time_end'] = pSQL($this->time_end);
return $fields;
}
public static function getCurrentRange()
{
$result = Db::getInstance()->getRow('
SELECT `id_date_range`, `time_end`
FROM `'._DB_PREFIX_.'date_range`
WHERE `time_end` = (SELECT MAX(`time_end`) FROM `'._DB_PREFIX_.'date_range`)');
if (!$result['id_date_range'] OR strtotime($result['time_end']) < strtotime(date('Y-m-d H:i:s')))
{
// The default range is set to 1 day less 1 second (in seconds)
$rangeSize = 86399;
$dateRange = new DateRange();
$dateRange->time_start = date('Y-m-d');
$dateRange->time_end = strftime('%Y-%m-%d %H:%M:%S', strtotime($dateRange->time_start) + $rangeSize);
$dateRange->add();
return $dateRange->id;
}
return $result['id_date_range'];
}
}
+328
View File
@@ -0,0 +1,328 @@
<?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
*/
if (file_exists(dirname(__FILE__).'/../config/settings.inc.php'))
include_once(dirname(__FILE__).'/../config/settings.inc.php');
//include_once(dirname(__FILE__).'/../classes/MySQL.php');
abstract class DbCore
{
/** @var string Server (eg. localhost) */
protected $_server;
/** @var string Database user (eg. root) */
protected $_user;
/** @var string Database password (eg. can be empty !) */
protected $_password;
/** @var string Database type (MySQL, PgSQL) */
protected $_type;
/** @var string Database name */
protected $_database;
/** @var mixed Ressource link */
protected $_link;
/** @var mixed SQL cached result */
protected $_result;
/** @var mixed ? */
protected static $_db;
/** @var mixed Object instance for singleton */
protected static $_instance = array();
protected static $_servers = array(
array('server' => _DB_SERVER_, 'user' => _DB_USER_, 'password' => _DB_PASSWD_, 'database' => _DB_NAME_), /* MySQL Master server */
/* Add here your slave(s) server(s)*/
/*array('server' => '192.168.0.15', 'user' => 'rep', 'password' => '123456', 'database' => 'rep'),
array('server' => '192.168.0.3', 'user' => 'myuser', 'password' => 'mypassword', 'database' => 'mydatabase'),
*/
);
protected $_lastQuery;
protected $_lastCached;
protected static $_idServer;
/**
* Get Db object instance (Singleton)
*
* @param boolean $master Decides wether the connection to be returned by the master server or the slave server
* @return object Db instance
*/
public static function getInstance($master = 1)
{
if ($master OR ($nServers = sizeof(self::$_servers)) == 1)
$idServer = 0;
else
$idServer = ($nServers > 2 AND ($id = ++self::$_idServer % (int)$nServers) !== 0) ? $id : 1;
if(!isset(self::$_instance[$idServer]))
self::$_instance[(int)($idServer)] = new MySQL(self::$_servers[(int)($idServer)]['server'], self::$_servers[(int)($idServer)]['user'], self::$_servers[(int)($idServer)]['password'], self::$_servers[(int)($idServer)]['database']);
return self::$_instance[(int)($idServer)];
}
public function getRessource() { return $this->_link;}
public function __destruct()
{
$this->disconnect();
}
/**
* Build a Db object
*/
public function __construct($server, $user, $password, $database)
{
$this->_server = $server;
$this->_user = $user;
$this->_password = $password;
$this->_type = _DB_TYPE_;
$this->_database = $database;
$this->connect();
}
/**
* Filter SQL query within a blacklist
*
* @param string $table Table where insert/update data
* @param string $values Data to insert/update
* @param string $type INSERT or UPDATE
* @param string $where WHERE clause, only for UPDATE (optional)
* @param string $limit LIMIT clause (optional)
* @return mixed|boolean SQL query result
*/
public function autoExecute($table, $values, $type, $where = false, $limit = false, $use_cache = 1)
{
if (!sizeof($values))
return true;
if (strtoupper($type) == 'INSERT')
{
$query = 'INSERT INTO `'.$table.'` (';
foreach ($values AS $key => $value)
$query .= '`'.$key.'`,';
$query = rtrim($query, ',').') VALUES (';
foreach ($values AS $key => $value)
$query .= '\''.$value.'\',';
$query = rtrim($query, ',').')';
if ($limit)
$query .= ' LIMIT '.(int)($limit);
return $this->q($query, $use_cache);
}
elseif (strtoupper($type) == 'UPDATE')
{
$query = 'UPDATE `'.$table.'` SET ';
foreach ($values AS $key => $value)
$query .= '`'.$key.'` = \''.$value.'\',';
$query = rtrim($query, ',');
if ($where)
$query .= ' WHERE '.$where;
if ($limit)
$query .= ' LIMIT '.(int)($limit);
return $this->q($query, $use_cache);
}
return false;
}
/**
* Filter SQL query within a blacklist
*
* @param string $table Table where insert/update data
* @param string $values Data to insert/update
* @param string $type INSERT or UPDATE
* @param string $where WHERE clause, only for UPDATE (optional)
* @param string $limit LIMIT clause (optional)
* @return mixed|boolean SQL query result
*/
public function autoExecuteWithNullValues($table, $values, $type, $where = false, $limit = false)
{
if (!sizeof($values))
return true;
if (strtoupper($type) == 'INSERT')
{
$query = 'INSERT INTO `'.$table.'` (';
foreach ($values AS $key => $value)
$query .= '`'.$key.'`,';
$query = rtrim($query, ',').') VALUES (';
foreach ($values AS $key => $value)
$query .= (($value === '' OR $value === NULL) ? 'NULL' : '\''.$value.'\'').',';
$query = rtrim($query, ',').')';
if ($limit)
$query .= ' LIMIT '.(int)($limit);
return $this->q($query);
}
elseif (strtoupper($type) == 'UPDATE')
{
$query = 'UPDATE `'.$table.'` SET ';
foreach ($values AS $key => $value)
$query .= '`'.$key.'` = '.(($value === '' OR $value === NULL) ? 'NULL' : '\''.$value.'\'').',';
$query = rtrim($query, ',');
if ($where)
$query .= ' WHERE '.$where;
if ($limit)
$query .= ' LIMIT '.(int)($limit);
return $this->q($query);
}
return false;
}
/*********************************************************
* ABSTRACT METHODS
*********************************************************/
/**
* Open a connection
*/
abstract public function connect();
/**
* Get the ID generated from the previous INSERT operation
*/
abstract public function Insert_ID();
/**
* Get number of affected rows in previous databse operation
*/
abstract public function Affected_Rows();
/**
* Gets the number of rows in a result
*/
abstract public function NumRows();
/**
* Delete
*/
abstract public function delete ($table, $where = false, $limit = false, $use_cache = 1);
/**
* Fetches a row from a result set
*/
abstract public function Execute ($query, $use_cache = 1);
/**
* Fetches an array containing all of the rows from a result set
*/
abstract public function ExecuteS($query, $array = true, $use_cache = 1);
/*
* Get next row for a query which doesn't return an array
*/
abstract public function nextRow($result = false);
/**
* Alias of Db::getInstance()->ExecuteS
*
* @acces string query The query to execute
* @return array Array of line returned by MySQL
*/
static public function s($query, $use_cache = 1)
{
return Db::getInstance()->ExecuteS($query, true, $use_cache);
}
static public function ps($query, $use_cache = 1)
{
$ret = Db::s($query, $use_cache);
p($ret);
return $ret;
}
static public function ds($query, $use_cache = 1)
{
Db::s($query, $use_cache);
die();
}
/**
* getRow return an associative array containing the first row of the query
* This function automatically add "limit 1" to the query
*
* @param mixed $query the select query (without "LIMIT 1")
* @param int $use_cache find it in cache first
* @return array associative array of (field=>value)
*/
abstract public function getRow($query, $use_cache = 1);
/**
* getValue return the first item of a select query.
*
* @param mixed $query
* @param int $use_cache
* @return void
*/
abstract public function getValue($query, $use_cache = 1);
/**
* Returns the text of the error message from previous database operation
*/
abstract public function getMsgError();
}
/**
* Sanitize data which will be injected into SQL query
*
* @param string $string SQL data which will be injected into SQL query
* @param boolean $htmlOK Does data contain HTML code ? (optional)
* @return string Sanitized data
*/
function pSQL($string, $htmlOK = false)
{
if (_PS_MAGIC_QUOTES_GPC_)
$string = stripslashes($string);
if (!is_numeric($string))
{
$link = Db::getInstance()->getRessource();
$string = _PS_MYSQL_REAL_ESCAPE_STRING_ ? mysql_real_escape_string($string, $link) : addslashes($string);
if (!$htmlOK)
$string = strip_tags(nl2br2($string));
}
return $string;
}
/**
* Convert \n and \r\n and \r to <br />
*
* @param string $string String to transform
* @return string New string
*/
function nl2br2($string)
{
return str_replace(array("\r\n", "\r", "\n"), '<br />', $string);
}
+78
View File
@@ -0,0 +1,78 @@
<?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 DeliveryCore extends ObjectModel
{
/** @var integer */
public $id_delivery;
/** @var integer */
public $id_carrier;
/** @var integer */
public $id_range_price;
/** @var integer */
public $id_range_weight;
/** @var integer */
public $id_zone;
/** @var float */
public $price;
protected $fieldsRequired = array ('id_carrier', 'id_range_price', 'id_range_weight', 'id_zone', 'price');
protected $fieldsValidate = array ('id_carrier' => 'isUnsignedId', 'id_range_price' => 'isUnsignedId',
'id_range_weight' => 'isUnsignedId', 'id_zone' => 'isUnsignedId', 'price' => 'isPrice');
protected $table = 'delivery';
protected $identifier = 'id_delivery';
protected $webserviceParameters = array(
'objectsNodeName' => 'deliveries',
'fields' => array(
'id_carrier' => array('xlink_resource' => 'carriers'),
'id_range_price' => array('xlink_resource' => 'price_ranges'),
'id_range_weight' => array('xlink_resource' => 'weight_ranges'),
'id_zone' => array('xlink_resource' => 'zones'),
)
);
public function getFields()
{
parent::validateFields();
$fields['id_carrier'] = (int)($this->id_carrier);
$fields['id_range_price'] = (int)($this->id_range_price);
$fields['id_range_weight'] = (int)($this->id_range_weight);
$fields['id_zone'] = (int)($this->id_zone);
$fields['price'] = (float)($this->price);
return $fields;
}
}
+520
View File
@@ -0,0 +1,520 @@
<?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
*/
class DiscountCore extends ObjectModel
{
public $id;
public $id_group_shop;
public $id_shop;
/** @var integer Customer id only if discount is reserved */
public $id_customer;
/** @var integer Group id only if discount is reserved */
public $id_group;
/** @var integer Currency ID only if the discount type is 2 */
public $id_currency;
/** @var integer Discount type ID */
public $id_discount_type;
/** @var string Name (the one which must be entered) */
public $name;
/** @var string A short description for the discount */
public $description;
/** @var string Value in percent as well as in euros */
public $value;
/** @var integer Totale quantity available */
public $quantity;
/** @var integer User quantity available */
public $quantity_per_user;
/** @var boolean Indicate if discount is cumulable with others */
public $cumulable;
/** @var integer Indicate if discount is cumulable with already bargained products */
public $cumulable_reduction;
/** @var integer Date from wich discount become active */
public $date_from;
/** @var integer Date from wich discount is no more active */
public $date_to;
/** @var integer Minimum cart total amount required to use the discount */
public $minimal;
/** @var integer display the discount in the summary */
public $cart_display;
public $behavior_not_exhausted;
/** @var boolean Status */
public $active = true;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $fieldsRequired = array('id_discount_type', 'name', 'value', 'quantity', 'quantity_per_user', 'date_from', 'date_to');
protected $fieldsSize = array('name' => '32', 'date_from' => '32', 'date_to' => '32');
protected $fieldsValidate = array('id_customer' => 'isUnsignedId', 'id_group' => 'isUnsignedId', 'id_discount_type' => 'isUnsignedId', 'id_currency' => 'isUnsignedId',
'name' => 'isDiscountName', 'value' => 'isPrice', 'quantity' => 'isUnsignedInt', 'quantity_per_user' => 'isUnsignedInt',
'cumulable' => 'isBool', 'cumulable_reduction' => 'isBool', 'date_from' => 'isDate',
'date_to' => 'isDate', 'minimal' => 'isUnsignedFloat', 'active' => 'isBool');
protected $fieldsRequiredLang = array('description');
protected $fieldsSizeLang = array('description' => 128);
protected $fieldsValidateLang = array('description' => 'isVoucherDescription');
protected $table = 'discount';
protected $identifier = 'id_discount';
protected $webserviceParameters = array(
'fields' => array(
'id_discount_type' => array('sqlId' => 'id_discount_type', 'xlink_resource' => 'discount_types'),
'id_customer' => array('sqlId' => 'id_customer', 'xlink_resource' => 'customers'),
'id_group' => array('sqlId' => 'id_group', 'xlink_resource' => 'groups'),
'id_currency' => array('sqlId' => 'id_currency', 'xlink_resource' => 'currencies'),
'name' => array('sqlId' => 'name'),
'value' => array('sqlId' => 'value'),
'quantity' => array('sqlId' => 'quantity'),
'quantity_per_user' => array('sqlId' => 'quantity_per_user'),
'cumulable' => array('sqlId' => 'cumulable'),
'cumulable_reduction' => array('sqlId' => 'cumulable_reduction'),
'behavior_not_exhausted' => array('sqlId' => 'behavior_not_exhausted'),
'date_from' => array('sqlId' => 'date_from'),
'date_to' => array('sqlId' => 'date_to'),
'minimal' => array('sqlId' => 'minimal'),
'active' => array('sqlId' => 'active'),
'cart_display' => array('sqlId' => 'cart_display'),
'date_add' => array('sqlId' => 'date_add'),
'date_upd' => array('sqlId' => 'date_upd')
)
);
public function getFields()
{
parent::validateFields();
$fields['id_group_shop'] = (int)$this->id_group_shop;
$fields['id_shop'] = (int)$this->id_shop;
$fields['id_customer'] = (int)($this->id_customer);
$fields['id_group'] = (int)($this->id_group);
$fields['id_currency'] = (int)($this->id_currency);
$fields['id_discount_type'] = (int)($this->id_discount_type);
$fields['name'] = pSQL($this->name);
$fields['value'] = (float)($this->value);
$fields['quantity'] = (int)($this->quantity);
$fields['quantity_per_user'] = (int)($this->quantity_per_user);
$fields['cumulable'] = (int)($this->cumulable);
$fields['cumulable_reduction'] = (int)($this->cumulable_reduction);
$fields['date_from'] = pSQL($this->date_from);
$fields['date_to'] = pSQL($this->date_to);
$fields['minimal'] = (float)($this->minimal);
$fields['behavior_not_exhausted'] = (int)$this->behavior_not_exhausted;
$fields['active'] = (int)($this->active);
$fields['cart_display'] = (int)($this->cart_display);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
public function add($autodate = true, $nullValues = false, $categories = null)
{
$ret = NULL;
if (parent::add($autodate, $nullValues))
$ret = true;
$this->updateCategories($categories);
return $ret;
}
/* Categories initialization is different between add() and update() because the addition will set all categories if none are selected (compatibility with old modules) and update won't update categories if none are selected */
public function update($autodate = true, $nullValues = false, $categories = false)
{
$ret = NULL;
if (parent::update($autodate, $nullValues))
$ret = true;
$this->updateCategories($categories);
return $ret;
}
public function delete()
{
if (!parent::delete())
return false;
return (Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'cart_discount WHERE id_discount = '.(int)($this->id))
AND Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'discount_category WHERE id_discount = '.(int)($this->id)));
}
public function getTranslationsFieldsChild()
{
if (!parent::validateFieldsLang())
return false;
return parent::getTranslationsFields(array('description'));
}
/**
* Return discount types list
*
* @return array Discount types
*/
static public function getDiscountTypes($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM '._DB_PREFIX_.'discount_type dt
LEFT JOIN `'._DB_PREFIX_.'discount_type_lang` dtl ON (dt.`id_discount_type` = dtl.`id_discount_type` AND dtl.`id_lang` = '.(int)($id_lang).')');
}
/**
* Get discount ID from name
*
* @param string $discountName Discount name
* @return integer Discount ID
*/
public static function getIdByName($discountName)
{
if (!Validate::isDiscountName($discountName))
die(Tools::displayError());
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_discount`
FROM `'._DB_PREFIX_.'discount`
WHERE `name` = \''.pSQL($discountName).'\'');
return isset($result['id_discount']) ? $result['id_discount'] : false;
}
/**
* Return customer discounts
*
* @param integer $id_lang Language ID
* @param boolean $id_customer Customer ID
* @return array Discounts
*/
static public function getCustomerDiscounts($id_lang, $id_customer, $active = false, $includeGenericOnes = true, $stock = false)
{
global $cart;
$res = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT d.*, dtl.`name` AS `type`, dl.`description`
FROM `'._DB_PREFIX_.'discount` d
LEFT JOIN `'._DB_PREFIX_.'discount_lang` dl ON (d.`id_discount` = dl.`id_discount` AND dl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'discount_type` dt ON dt.`id_discount_type` = d.`id_discount_type`
LEFT JOIN `'._DB_PREFIX_.'discount_type_lang` dtl ON (dt.`id_discount_type` = dtl.`id_discount_type` AND dtl.`id_lang` = '.(int)($id_lang).')
WHERE (`id_customer` = '.(int)($id_customer).'
OR `id_group` IN (SELECT `id_group` FROM `'._DB_PREFIX_.'customer_group` WHERE `id_customer` = '.(int)($id_customer).')'.
($includeGenericOnes ? ' OR (`id_customer` = 0 AND `id_group` = 0)' : '').')
'.($active ? ' AND d.`active` = 1' : '').'
'.($stock ? ' AND d.`quantity` != 0' : ''));
foreach ($res as &$discount)
if ($discount['quantity_per_user'])
{
$quantity_used = Order::getDiscountsCustomer((int)($id_customer), (int)($discount['id_discount']));
if (isset($cart) AND isset($cart->id))
$quantity_used += $cart->getDiscountsCustomer((int)($discount['id_discount']));
$discount['quantity_for_user'] = $discount['quantity_per_user'] - $quantity_used;
}
else
$discount['quantity_for_user'] = 0;
return $res;
}
public function usedByCustomer($id_customer)
{
return Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `'._DB_PREFIX_.'order_discount` od
LEFT JOIN `'._DB_PREFIX_.'orders` o ON (od.`id_order` = o.`id_order`)
WHERE od.`id_discount` = '.(int)($this->id).'
AND o.`id_customer` = '.(int)($id_customer)
);
}
/**
* Return discount value
*
* @param integer $nb_discounts Number of discount currently in cart
* @param boolean $order_total_products Total cart products amount
* @return mixed Return a float value or '!' if reduction is 'Shipping free'
*/
public function getValue($nb_discounts = 0, $order_total_products = 0, $shipping_fees = 0, $idCart = false, $useTax = true, $id_group_shop = false, $id_shop = false)
{
$totalAmount = 0;
$cart = new Cart((int)($idCart));
if (!Validate::isLoadedObject($cart))
return 0;
if ((!$this->cumulable AND (int)($nb_discounts) > 1) OR !$this->active OR (!$this->quantity AND !$cart->OrderExists()))
return 0;
if ($this->usedByCustomer((int)($cart->id_customer)) >= $this->quantity_per_user AND !$cart->OrderExists())
return 0;
$date_start = strtotime($this->date_from);
$date_end = strtotime($this->date_to);
if ((time() < $date_start OR time() > $date_end) AND !$cart->OrderExists()) return 0;
if ($id_group_shop AND $id_shop)
if (!$this->availableWithShop($id_group_shop, $id_shop))
return 0;
$products = $cart->getProducts();
$categories = Discount::getCategories((int)($this->id));
$in_category = false;
foreach ($products AS $product)
if (count($categories) AND Product::idIsOnCategoryId($product['id_product'], $categories))
$totalAmount += $useTax ? $product['price_wt'] * $product['quantity']: $product['price'] * $product['quantity'];
if ($this->minimal > 0 AND $totalAmount < $this->minimal)
return 0;
switch ($this->id_discount_type)
{
/* Relative value (% of the order total) */
case 1:
$amount = 0;
$percentage = $this->value / 100;
foreach ($products AS $product)
if (Product::idIsOnCategoryId($product['id_product'], $categories))
if ($this->cumulable_reduction OR (!$product['reduction_applies'] AND !$product['on_sale']))
$amount += ($useTax ? $product['total_wt'] : $product['total']) * $percentage;
return $amount;
/* Absolute value */
case 2:
// An "absolute" voucher is available in one currency only
$currency = ((int)$cart->id_currency ? Currency::getCurrencyInstance($cart->id_currency) : Currency::getCurrent());
if ($this->id_currency != $currency->id)
return 0;
$taxDiscount = Cart::getTaxesAverageUsed((int)($cart->id));
if (!$useTax AND isset($taxDiscount) AND $taxDiscount != 1)
$this->value = abs($this->value / (1 + $taxDiscount * 0.01));
// Main return
$value = 0;
foreach ($products AS $product)
if (Product::idIsOnCategoryId($product['id_product'], $categories))
$value = $this->value;
// Return 0 if there are no applicable categories
return $value;
/* Free shipping (does not return a value but a special code) */
case 3:
return '!';
}
return 0;
}
/**
* @param int $id_category_product
* @param int $id_category_discount
* @return bool
* @deprecated
*/
static public function isParentCategoryProductDiscount($id_category_product, $id_category_discount)
{
Tools::displayAsDeprecated();
$category = new Category((int)($id_category_product));
$parentCategories = $category->getParentsCategories();
foreach($parentCategories AS $parentCategory)
if($id_category_discount == $parentCategory['id_category'])
return true;
return false;
}
static public function getCategories($id_discount)
{
return Db::getInstance()->ExecuteS('
SELECT `id_category`
FROM `'._DB_PREFIX_.'discount_category`
WHERE `id_discount` = '.(int)($id_discount));
}
public function updateCategories($categories)
{
/* false value will avoid category update and null value will force all category to be selected */
if ($categories === false)
return ;
if ($categories === null)
{
// Compatibility for modules which create discount without setting categories (ex. fidelity, sponsorship)
$result = Db::getInstance()->ExecuteS('SELECT id_category FROM '._DB_PREFIX_.'category');
$categories = array();
foreach ($result as $row)
$categories[] = $row['id_category'];
}
elseif (!is_array($categories) OR !sizeof($categories))
return false;
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount_category` WHERE `id_discount`='.(int)($this->id));
foreach($categories AS $category)
{
Db::getInstance()->ExecuteS('
SELECT `id_discount`
FROM `'._DB_PREFIX_.'discount_category`
WHERE `id_discount`='.(int)($this->id).' AND `id_category`='.(int)($category));
if (Db::getInstance()->NumRows() == 0)
Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'discount_category` (`id_discount`, `id_category`) VALUES('.(int)($this->id).','.(int)($category).')');
}
}
static public function discountExists($discountName, $id_discount = 0)
{
return Db::getInstance()->getRow('SELECT `id_discount` FROM '._DB_PREFIX_.'discount WHERE `name` LIKE \''.pSQL($discountName).'\' AND `id_discount` != '.(int)($id_discount));
}
static public function createOrderDiscount($order, $productList, $qtyList, $name, $shipping_cost = false, $id_category = 0, $subcategory = 0)
{
$languages = Language::getLanguages($order);
$products = $order->getProducts(false, $productList, $qtyList);
// Totals are stored in the order currency (or at least should be)
$total = $order->getTotalProductsWithTaxes($products);
$discounts = $order->getDiscounts(true);
$total_tmp = $total;
foreach ($discounts as $discount)
{
if ($discount['id_discount_type'] == 1)
$total -= $total_tmp * ($discount['value'] / 100);
elseif ($discount['id_discount_type'] == 2)
$total -= ($discount['value'] * ($total_tmp / $order->total_products_wt));
}
if ($shipping_cost)
$total += $order->total_shipping;
// create discount
$voucher = new Discount();
$voucher->id_discount_type = 2;
foreach ($languages as $language)
$voucher->description[$language['id_lang']] = strval($name).(int)($order->id);
$voucher->value = (float)($total);
$voucher->name = 'V0C'.(int)($order->id_customer).'O'.(int)($order->id);
$voucher->id_customer = (int)($order->id_customer);
$voucher->id_currency = (int)($order->id_currency);
$voucher->quantity = 1;
$voucher->quantity_per_user = 1;
$voucher->cumulable = 1;
$voucher->cumulable_reduction = 1;
$voucher->minimal = (float)($voucher->value);
$voucher->active = 1;
$voucher->cart_display = 1;
$voucher->id_group_shop = (int)$order->id_group_shop;
$voucher->id_shop = (int)$order->id_shop;
$now = time();
$voucher->date_from = date('Y-m-d H:i:s', $now);
$voucher->date_to = date('Y-m-d H:i:s', $now + (3600 * 24 * 365.25)); /* 1 year */
if (!$voucher->validateFieldsLang(false) OR !$voucher->add())
return false;
// set correct name
$voucher->name = 'V'.(int)($voucher->id).'C'.(int)($order->id_customer).'O'.$order->id;
if (!$voucher->update())
return false;
return $voucher;
}
static public function display($discountValue, $discountType, $currency = false)
{
if ((float)($discountValue) AND (int)($discountType))
{
if ($discountType == 1)
return $discountValue.chr(37); // ASCII #37 --> % (percent)
elseif ($discountType == 2)
return Tools::displayPrice($discountValue, $currency);
}
return ''; // return a string because it's a display method
}
static public function getVouchersToCartDisplay($id_lang, $id_customer)
{
return Db::getInstance()->ExecuteS('
SELECT d.`name`, dl.`description`, d.`id_discount`
FROM `'._DB_PREFIX_.'discount` d
LEFT JOIN `'._DB_PREFIX_.'discount_lang` dl ON (d.`id_discount` = dl.`id_discount`)
WHERE d.`active` = 1
AND d.`date_from` <= \''.pSQL(date('Y-m-d H:i:s')).'\' AND d.`date_to` >= \''.pSQL(date('Y-m-d H:i:s')).'\'
AND dl.`id_lang` = '.(int)($id_lang).'
AND d.`cart_display` = 1 AND d.`quantity` > 0
AND ((d.`id_customer` = 0 AND d.`id_group` = 0) '.($id_customer ? 'OR (d.`id_customer` = '.$id_customer.'
OR d.`id_group` IN (SELECT `id_group` FROM `'._DB_PREFIX_.'customer_group` WHERE `id_customer` = '.(int)($id_customer).')))' : 'OR d.`id_group` = 1)'));
}
static public function deleteByIdCustomer($id_customer)
{
$discounts = Db::getInstance()->ExecuteS('SELECT `id_discount` FROM `'._DB_PREFIX_.'discount` WHERE `id_customer` = '.(int)($id_customer));
foreach ($discounts as $discount)
{
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount` WHERE `id_discount` = '.(int)($discount['id_discount']));
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount_category` WHERE `id_discount` = '.(int)($discount['id_discount']));
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount_lang` WHERE `id_discount` = '.(int)($discount['id_discount']));
}
return true;
}
static public function deleteByIdGroup($id_group)
{
$discounts = Db::getInstance()->ExecuteS('SELECT `id_discount` FROM `'._DB_PREFIX_.'discount` WHERE `id_group` = '.(int)($id_group));
foreach ($discounts as $discount)
{
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount` WHERE `id_discount` = '.(int)($discount['id_discount']));
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount_category` WHERE `id_discount` = '.(int)($discount['id_discount']));
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'discount_lang` WHERE `id_discount` = '.(int)($discount['id_discount']));
}
return true;
}
static public function getDiscount($id_discount)
{
return Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.'discount` WHERE `id_discount` = '.(int)$id_discount);
}
public function availableWithShop($id_group_shop, $id_shop)
{
return Db::getInstance()->getValue('SELECT d.id_discount
FROM '._DB_PREFIX_.'discount d
LEFT JOIN '._DB_PREFIX_.'group_shop gs ON (gs.id_group_shop=d.id_group_shop)
WHERE d.id_discount='.(int)$this->id.' AND (d.id_shop='.(int)$id_shop.' OR (d.id_group_shop='.(int)$id_group_shop.' AND gs.share_datas=1))');
}
}
+51
View File
@@ -0,0 +1,51 @@
<?php
class DispatcherCore
{
public $controllers;
public static $controller;
function __construct()
{
$this->loadControllers();
}
public function dispatch()
{
self::$controller = $this->getController();
self::$controller = str_replace('-', '', strtolower(self::$controller));
if (!isset($this->controllers[self::$controller]))
self::$controller = 'index';
ControllerFactory::getController($this->controllers[self::$controller])->run();
}
protected function loadControllers()
{
$controller_files = scandir(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.'controllers');
foreach($controller_files as $controller_filename)
{
if (substr($controller_filename, -14, 14) == 'Controller.php')
$this->controllers[strtolower(substr($controller_filename, 0, -14))] = basename($controller_filename, '.php');
}
// add default controller
$this->controllers['index'] = 'IndexController';
$this->controllers['authentication'] = $this->controllers['auth'];
$this->controllers['productscomparison'] = $this->controllers['compare'];
}
public function getController()
{
$controller = Tools::getValue('controller');
if (isset($controller) && preg_match('/^([0-9a-z_-]+)\?(.*)=(.*)$/Ui', $controller, $controller_string))
{
$controller = $controller_string[1];
if (isset($_GET['controller']))
$_GET[$controller_string[2]] = $controller_string[3];
elseif (isset($_POST['controller']))
$_POST[$controller_string[2]] = $controller_string[3];
}
return (!empty($controller)) ? $controller : 'index';
}
}
+223
View File
@@ -0,0 +1,223 @@
<?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 EmployeeCore extends ObjectModel
{
public $id;
/** @var string Determine employee profile */
public $id_profile;
/** @var string employee language */
public $id_lang;
/** @var string Lastname */
public $lastname;
/** @var string Firstname */
public $firstname;
/** @var string e-mail */
public $email;
/** @var string Password */
public $passwd;
/** @var datetime Password */
public $last_passwd_gen;
public $stats_date_from;
public $stats_date_to;
/** @var string Display back office background in the specified color */
public $bo_color;
/** @var string employee's chosen theme */
public $bo_theme;
/** @var string / enum hover or click mode */
public $bo_uimode;
/** @var boolean Status */
public $active = 1;
protected $fieldsRequired = array('lastname', 'firstname', 'email', 'passwd', 'id_profile', 'id_lang');
protected $fieldsSize = array('lastname' => 32, 'firstname' => 32, 'email' => 128, 'passwd' => 32, 'bo_color' => 32, 'bo_theme' => 32);
protected $fieldsValidate = array('lastname' => 'isName', 'firstname' => 'isName', 'email' => 'isEmail', 'id_lang' => 'isUnsignedInt',
'passwd' => 'isPasswdAdmin', 'active' => 'isBool', 'id_profile' => 'isInt', 'bo_color' => 'isColor', 'bo_theme' => 'isGenericName', 'bo_uimode' => 'isGenericName');
protected $table = 'employee';
protected $identifier = 'id_employee';
protected $webserviceParameters = array(
'fields' => array(
'id_lang' => array('xlink_resource' => 'languages'),
'last_passwd_gen' => array('setter' => null),
'stats_date_from' => array('setter' => null),
'stats_date_to' => array('setter' => null),
'passwd' => array('setter' => 'setWsPasswd'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_profile'] = (int)$this->id_profile;
$fields['id_lang'] = (int)$this->id_lang;
$fields['lastname'] = pSQL($this->lastname);
$fields['firstname'] = pSQL(Tools::ucfirst($this->firstname));
$fields['email'] = pSQL($this->email);
$fields['passwd'] = pSQL($this->passwd);
$fields['last_passwd_gen'] = pSQL($this->last_passwd_gen);
if (empty($this->stats_date_from))
$this->stats_date_from = date('Y-m-d 00:00:00');
$fields['stats_date_from'] = pSQL($this->stats_date_from);
if (empty($this->stats_date_to))
$this->stats_date_to = date('Y-m-d 23:59:59');
$fields['stats_date_to'] = pSQL($this->stats_date_to);
$fields['bo_color'] = pSQL($this->bo_color);
$fields['bo_theme'] = pSQL($this->bo_theme);
$fields['bo_uimode'] = pSQL($this->bo_uimode);
$fields['active'] = (int)$this->active;
return $fields;
}
/**
* Return all employee id and email
*
* @return array Employees
* @deprecated
*/
static public function getEmployees()
{
Tools::displayAsDeprecated();
return Db::getInstance()->ExecuteS('
SELECT `id_employee`, CONCAT(`firstname`, \' \', `lastname`) AS "name"
FROM `'._DB_PREFIX_.'employee`
WHERE `active` = 1
ORDER BY `email`');
}
public function add($autodate = true, $nullValues = true)
{
$this->last_passwd_gen = date('Y-m-d H:i:s', strtotime('-'.Configuration::get('PS_PASSWD_TIME_BACK').'minutes'));
return parent::add($autodate, $nullValues);
}
/**
* Return employee instance from its e-mail (optionnaly check password)
*
* @param string $email e-mail
* @param string $passwd Password is also checked if specified
* @return Employee instance
*/
public function getByEmail($email, $passwd = NULL)
{
if (!Validate::isEmail($email) OR ($passwd != NULL AND !Validate::isPasswd($passwd)))
die(Tools::displayError());
$result = Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.'employee`
WHERE `active` = 1
AND `email` = \''.pSQL($email).'\'
'.($passwd ? 'AND `passwd` = \''.Tools::encrypt($passwd).'\'' : ''));
if (!$result)
return false;
$this->id = $result['id_employee'];
$this->id_profile = $result['id_profile'];
foreach ($result AS $key => $value)
if (key_exists($key, $this))
$this->{$key} = $value;
return $this;
}
static public function employeeExists($email)
{
if (!Validate::isEmail($email))
die (Tools::displayError());
return (bool)Db::getInstance()->getValue('
SELECT `id_employee`
FROM `'._DB_PREFIX_.'employee`
WHERE `email` = \''.pSQL($email).'\'');
}
/**
* Check if employee password is the right one
*
* @param string $passwd Password
* @return boolean result
*/
static public function checkPassword($id_employee, $passwd)
{
if (!Validate::isUnsignedId($id_employee) OR !Validate::isPasswd($passwd, 8))
die (Tools::displayError());
return Db::getInstance()->getValue('
SELECT `id_employee`
FROM `'._DB_PREFIX_.'employee`
WHERE `id_employee` = '.(int)$id_employee.'
AND `passwd` = \''.pSQL($passwd).'\'
AND active = 1');
}
static public function countProfile($id_profile, $activeOnly = false)
{
return Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `'._DB_PREFIX_.'employee`
WHERE `id_profile` = '.(int)$id_profile.'
'.($activeOnly ? ' AND `active` = 1' : ''));
}
public function isLastAdmin()
{
return ($this->id_profile == _PS_ADMIN_PROFILE_
AND Employee::countProfile($this->id_profile, true) == 1
AND $this->active
);
}
public function setWsPasswd($passwd)
{
if ($this->id != 0)
{
if ($this->passwd != $passwd)
$this->passwd = Tools::encrypt($passwd);
}
else
$this->passwd = Tools::encrypt($passwd);
return true;
}
}
+207
View File
@@ -0,0 +1,207 @@
<?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 FeatureCore extends ObjectModel
{
/** @var string Name */
public $name;
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 128);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $table = 'feature';
protected $identifier = 'id_feature';
protected $webserviceParameters = array(
'objectsNodeName' => 'product_features',
'objectNodeName' => 'product_feature',
'fields' => array(),
);
public function getFields()
{
return array('id_feature' => NULL);
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
/**
* Get a feature data for a given id_feature and id_lang
*
* @param integer $id_lang Language id
* @param integer $id_feature Feature id
* @return array Array with feature's data
* @static
*/
static public function getFeature($id_lang, $id_feature)
{
return Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.'feature` f
LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON ( f.`id_feature` = fl.`id_feature` AND fl.`id_lang` = '.(int)($id_lang).')
WHERE f.`id_feature` = '.(int)($id_feature));
}
/**
* Get all features for a given language
*
* @param integer $id_lang Language id
* @return array Multiple arrays with feature's data
* @static
*/
static public function getFeatures($id_lang)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'feature` f
LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON (f.`id_feature` = fl.`id_feature` AND fl.`id_lang` = '.(int)($id_lang).')
ORDER BY fl.`name` ASC');
}
/**
* Delete several objects from database
*
* @param array $selection Array with items to delete
* @return boolean Deletion result
*/
public function deleteSelection($selection)
{
/* Also delete Attributes */
foreach ($selection AS $value) {
$obj = new Feature($value);
if (!$obj->delete())
return false;
}
return true;
}
public function add($autodate = true, $nullValues = false)
{
return parent::add($autodate, true);
}
public function delete()
{
/* Also delete related attributes */
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'feature_value_lang` WHERE `id_feature_value` IN (SELECT id_feature_value FROM `'._DB_PREFIX_.'feature_value` WHERE `id_feature` = '.(int)($this->id).')');
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'feature_value` WHERE `id_feature` = '.(int)($this->id));
/* Also delete related products */
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'feature_product` WHERE `id_feature` = '.(int)($this->id));
return parent::delete();
}
public function update($nullValues = false)
{
$this->clearCache();
$result = 1;
$fields = $this->getTranslationsFieldsChild();
foreach ($fields as $field)
{
foreach ($field as $key => $value)
if (!Validate::isTableOrIdentifier($key))
die(Tools::displayError());
$mode = Db::getInstance()->getRow('SELECT `id_lang` FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE `'.pSQL($this->identifier).
'` = '.(int)($this->id).' AND `id_lang` = '.(int)($field['id_lang']));
$result *= (!Db::getInstance()->NumRows()) ? Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT') :
Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'UPDATE', '`'.
pSQL($this->identifier).'` = '.(int)($this->id).' AND `id_lang` = '.(int)($field['id_lang']));
}
return $result;
}
/**
* Count number of features for a given language
*
* @param integer $id_lang Language id
* @return int Number of feature
* @static
*/
static public function nbFeatures($id_lang)
{
$result = Db::getInstance()->getRow('
SELECT COUNT(ag.`id_feature`) as nb
FROM `'._DB_PREFIX_.'feature` ag
LEFT JOIN `'._DB_PREFIX_.'feature_lang` agl ON (ag.`id_feature` = agl.`id_feature` AND `id_lang` = '.(int)($id_lang).')
ORDER BY `name` ASC');
return ($result['nb']);
}
/**
* Create a feature from import
*
* @param integer $id_feature Feature id
* @param integer $id_product Product id
* @param array $value Feature Value
*/
static public function addFeatureImport($name)
{
$rq = Db::getInstance()->getRow('SELECT `id_feature` FROM '._DB_PREFIX_.'feature_lang WHERE `name` = \''.pSQL($name).'\' GROUP BY `id_feature`');
if (!empty($rq))
return (int)($rq['id_feature']);
// Feature doesn't exist, create it
$feature = new Feature();
$languages = Language::getLanguages();
foreach ($languages as $language)
$feature->name[$language['id_lang']] = strval($name);
$feature->add();
return $feature->id;
}
public static function getFeaturesForComparison($list_ids_product, $id_lang)
{
$ids = '';
foreach($list_ids_product as $id)
$ids .= (int)($id).',';
$ids = rtrim($ids, ',');
if (empty($ids))
return false;
return Db::getInstance()->ExecuteS('
SELECT * , COUNT(*) as nb
FROM `'._DB_PREFIX_.'feature` f
LEFT JOIN `'._DB_PREFIX_.'feature_product` fp ON f.`id_feature` = fp.`id_feature`
LEFT JOIN `'._DB_PREFIX_.'feature_lang` fl ON f.`id_feature` = fl.`id_feature`
WHERE fp.`id_product` IN ('.$ids.')
AND `id_lang` = '.(int)($id_lang).'
GROUP BY f.`id_feature`
ORDER BY nb DESC');
}
}
+176
View File
@@ -0,0 +1,176 @@
<?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 FeatureValueCore extends ObjectModel
{
/** @var integer Group id which attribute belongs */
public $id_feature;
/** @var string Name */
public $value;
/** @var boolean Custom */
public $custom = 0;
protected $fieldsRequired = array('id_feature');
protected $fieldsValidate = array('id_feature' => 'isUnsignedId', 'custom' => 'isBool');
protected $fieldsRequiredLang = array('value');
protected $fieldsSizeLang = array('value' => 255);
protected $fieldsValidateLang = array('value' => 'isGenericName');
protected $table = 'feature_value';
protected $identifier = 'id_feature_value';
protected $webserviceParameters = array(
'objectsNodeName' => 'product_feature_values',
'objectNodeName' => 'product_feature_value',
'fields' => array(
'id_feature' => array('xlink_resource'=> 'product_features'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_feature'] = (int)$this->id_feature;
$fields['custom'] = (int)$this->custom;
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('value'));
}
/**
* Get all values for a given feature
*
* @param boolean $id_feature Feature id
* @return array Array with feature's values
* @static
*/
static public function getFeatureValues($id_feature)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'feature_value`
WHERE `id_feature` = '.(int)$id_feature);
}
/**
* Get all values for a given feature and language
*
* @param integer $id_lang Language id
* @param boolean $id_feature Feature id
* @return array Array with feature's values
* @static
*/
static public function getFeatureValuesWithLang($id_lang, $id_feature)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'feature_value` v
LEFT JOIN `'._DB_PREFIX_.'feature_value_lang` vl ON (v.`id_feature_value` = vl.`id_feature_value` AND vl.`id_lang` = '.(int)$id_lang.')
WHERE v.`id_feature` = '.(int)$id_feature.' AND (v.`custom` IS NULL OR v.`custom` = 0)
ORDER BY vl.`value` ASC');
}
/**
* Get all language for a given value
*
* @param boolean $id_feature_value Feature value id
* @return array Array with value's languages
* @static
*/
static public function getFeatureValueLang($id_feature_value)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'feature_value_lang`
WHERE `id_feature_value` = '.(int)$id_feature_value.'
ORDER BY `id_lang`');
}
/**
* Select the good lang in tab
*
* @param array $lang Array with all language
* @param integer $id_lang Language id
* @return string String value name selected
* @static
*/
static public function selectLang($lang, $id_lang)
{
foreach ($lang as $tab)
if ($tab['id_lang'] == $id_lang)
return $tab['value'];
}
static public function addFeatureValueImport($id_feature, $name)
{
$rq = Db::getInstance()->ExecuteS('
SELECT fv.`id_feature_value`
FROM '._DB_PREFIX_.'feature_value fv
LEFT JOIN '._DB_PREFIX_.'feature_value_lang fvl ON (fvl.`id_feature_value` = fv.`id_feature_value`)
WHERE `value` = \''.pSQL($name).'\'
AND fv.`id_feature` = '.(int)$id_feature.'
AND fv.`custom` = 0
GROUP BY fv.`id_feature_value` LIMIT 1');
if (!isset($rq[0]['id_feature_value']) OR !$id_feature_value = (int)$rq[0]['id_feature_value'])
{
// Feature doesn't exist, create it
$featureValue = new FeatureValue();
$languages = Language::getLanguages();
foreach ($languages AS $language)
$featureValue->value[$language['id_lang']] = strval($name);
$featureValue->id_feature = (int)$id_feature;
$featureValue->custom = 1;
$featureValue->add();
return (int)$featureValue->id;
}
return (int)$id_feature_value;
}
public function delete()
{
/* Also delete related products */
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'feature_product` WHERE `id_feature_value` = '.(int)$this->id);
return parent::delete();
}
}
+70
View File
@@ -0,0 +1,70 @@
<?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 FileLoggerCore extends AbstractLogger
{
protected $filename = '';
/**
* Write the message in the log file
*
* @param string message
* @param level
*/
protected function logMessage($message, $level)
{
$formatted_message = '*'.$this->level_value[$level].'* '."\t".date('Y/m/d - H:i:s').': '.$message."\r\n";
return file_put_contents($this->getFilename(), $formatted_message, FILE_APPEND);
}
/**
* Check if the specified filename is writable and set the filename
*
* @param string filename
*/
public function setFilename($filename)
{
if (is_writable(dirname($filename)))
$this->filename = $filename;
else
die('Directory '.dirname($filename).' is not writable');
}
/**
* Log the message
*
* @param string message
* @param level
*/
public function getFilename()
{
if (empty($this->filename))
die('Filename is empty.');
return $this->filename;
}
}
+617
View File
@@ -0,0 +1,617 @@
<?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: 7483 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class FrontControllerCore
{
public $errors = array();
protected static $smarty;
protected static $cookie;
protected static $link;
protected static $cart;
public $iso;
public $orderBy;
public $orderWay;
public $p;
public $n;
public $auth = false;
public $guestAllowed = false;
public $authRedirection = false;
public $ssl = false;
protected $restrictedCountry = false;
protected $maintenance = false;
protected $id_current_shop;
protected $id_current_group_shop;
public static $initialized = false;
protected static $currentCustomerGroups;
public function __construct()
{
global $useSSL;
$useSSL = $this->ssl;
}
public function run()
{
$this->init();
$this->preProcess();
$this->displayHeader();
$this->process();
$this->displayContent();
$this->displayFooter();
}
public function init()
{
global $cookie, $smarty, $cart, $iso, $defaultCountry, $protocol_link, $protocol_content, $link, $css_files, $js_files;
if (self::$initialized)
return;
self::$initialized = true;
$this->id_current_shop = (int)Shop::getCurrentShop();
$this->id_current_group_shop = (int)Shop::getCurrentGroupShop();
$css_files = array();
$js_files = array();
if ($this->ssl AND (empty($_SERVER['HTTPS']) OR strtolower($_SERVER['HTTPS']) == 'off') AND Configuration::get('PS_SSL_ENABLED'))
{
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.Tools::getShopDomainSsl(true).$_SERVER['REQUEST_URI']);
exit();
}
ob_start();
/* Loading default country */
$defaultCountry = new Country((int)Configuration::get('PS_COUNTRY_DEFAULT'), Configuration::get('PS_LANG_DEFAULT'));
$cookie = new Cookie('ps');
$link = new Link();
if ($this->auth AND !$cookie->isLogged($this->guestAllowed))
Tools::redirect('index.php?controller=authentication'.($this->authRedirection ? '&back='.$this->authRedirection : ''));
/* Theme is missing or maintenance */
if (!is_dir(_PS_THEME_DIR_))
die(Tools::displayError('Current theme unavailable. Please check your theme directory name and permissions.'));
elseif (basename($_SERVER['PHP_SELF']) != 'disabled.php' AND !(int)(Configuration::get('PS_SHOP_ENABLE')))
$this->maintenance = true;
elseif (Configuration::get('PS_GEOLOCATION_ENABLED'))
$this->geolocationManagement();
// Switch language if needed and init cookie language
if ($iso = Tools::getValue('isolang') AND Validate::isLanguageIsoCode($iso) AND ($id_lang = (int)(Language::getIdByIso($iso))))
$_GET['id_lang'] = $id_lang;
Tools::switchLanguage();
Tools::setCookieLanguage();
/* attribute id_lang is often needed, so we create a constant for performance reasons */
if (!defined('_USER_ID_LANG_'))
define('_USER_ID_LANG_', (int)$cookie->id_lang);
if (isset($_GET['logout']) OR ($cookie->logged AND Customer::isBanned((int)$cookie->id_customer)))
{
$cookie->logout();
Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL);
}
elseif (isset($_GET['mylogout']))
{
$cookie->mylogout();
Tools::redirect(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : NULL);
}
global $currency;
$currency = Tools::setCurrency();
$_MODULES = array();
/* Cart already exists */
if ((int)$cookie->id_cart)
{
$cart = new Cart((int)$cookie->id_cart);
if ($cart->OrderExists())
unset($cookie->id_cart, $cart, $cookie->checkedTOS);
/* Delete product of cart, if user can't make an order from his country */
elseif (intval(Configuration::get('PS_GEOLOCATION_ENABLED')) AND
!in_array(strtoupper($cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) AND
$cart->nbProducts() AND intval(Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR')) != -1 AND
!self::isInWhitelistForGeolocation())
unset($cookie->id_cart, $cart);
elseif ($cookie->id_customer != $cart->id_customer OR $cookie->id_lang != $cart->id_lang OR $cookie->id_currency != $cart->id_currency)
{
if ($cookie->id_customer)
$cart->id_customer = (int)($cookie->id_customer);
$cart->id_lang = (int)($cookie->id_lang);
$cart->id_currency = (int)($cookie->id_currency);
$cart->update();
}
/* Select an address if not set */
if (isset($cart) && (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0 ||
!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0) && $cookie->id_customer)
{
$to_update = false;
if (!isset($cart->id_address_delivery) || $cart->id_address_delivery == 0)
{
$to_update = true;
$cart->id_address_delivery = (int)Address::getFirstCustomerAddressId($cart->id_customer);
}
if (!isset($cart->id_address_invoice) || $cart->id_address_invoice == 0)
{
$to_update = true;
$cart->id_address_invoice = (int)Address::getFirstCustomerAddressId($cart->id_customer);
}
if ($to_update)
$cart->update();
}
}
if (!isset($cart) OR !$cart->id)
{
$cart = new Cart();
$cart->id_lang = (int)($cookie->id_lang);
$cart->id_currency = (int)($cookie->id_currency);
$cart->id_guest = (int)($cookie->id_guest);
$cart->id_group_shop = (int)$this->id_current_group_shop;
$cart->id_shop = (int)$this->id_current_shop;
if ($cookie->id_customer)
{
$cart->id_customer = (int)($cookie->id_customer);
$cart->id_address_delivery = (int)(Address::getFirstCustomerAddressId($cart->id_customer));
$cart->id_address_invoice = $cart->id_address_delivery;
}
else
{
$cart->id_address_delivery = 0;
$cart->id_address_invoice = 0;
}
}
if (!$cart->nbProducts())
$cart->id_carrier = NULL;
$locale = strtolower(Configuration::get('PS_LOCALE_LANGUAGE')).'_'.strtoupper(Configuration::get('PS_LOCALE_COUNTRY').'.UTF-8');
setlocale(LC_COLLATE, $locale);
setlocale(LC_CTYPE, $locale);
setlocale(LC_TIME, $locale);
setlocale(LC_NUMERIC, 'en_US.UTF-8');
if (Validate::isLoadedObject($currency))
$smarty->ps_currency = $currency;
if (Validate::isLoadedObject($ps_language = new Language((int)$cookie->id_lang)))
$smarty->ps_language = $ps_language;
/* get page name to display it in body id */
$pathinfo = pathinfo(__FILE__);
$page_name = Dispatcher::$controller;
$page_name = (preg_match('/^[0-9]/', $page_name)) ? 'page_'.$page_name : $page_name;
$smarty->assign(Tools::getMetaTags($cookie->id_lang, $page_name));
$smarty->assign('request_uri', Tools::safeOutput(urldecode($_SERVER['REQUEST_URI'])));
/* Breadcrumb */
$navigationPipe = (Configuration::get('PS_NAVIGATION_PIPE') ? Configuration::get('PS_NAVIGATION_PIPE') : '>');
$smarty->assign('navigationPipe', $navigationPipe);
$protocol_link = (Configuration::get('PS_SSL_ENABLED') OR (!empty($_SERVER['HTTPS']) AND strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
$protocol_content = ((isset($useSSL) AND $useSSL AND Configuration::get('PS_SSL_ENABLED')) OR (!empty($_SERVER['HTTPS']) AND strtolower($_SERVER['HTTPS']) != 'off')) ? 'https://' : 'http://';
if (!defined('_PS_BASE_URL_'))
define('_PS_BASE_URL_', Tools::getShopDomain(true));
if (!defined('_PS_BASE_URL_SSL_'))
define('_PS_BASE_URL_SSL_', Tools::getShopDomainSsl(true));
$link->preloadPageLinks();
$this->canonicalRedirection();
Product::initPricesComputation();
$display_tax_label = $defaultCountry->display_tax_label;
if ($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')})
{
$infos = Address::getCountryAndState((int)($cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$country = new Country((int)$infos['id_country']);
if (Validate::isLoadedObject($country))
$display_tax_label = $country->display_tax_label;
}
$smarty->assign(array(
'link' => $link,
'cart' => $cart,
'currency' => $currency,
'cookie' => $cookie,
'page_name' => $page_name,
'base_dir' => _PS_BASE_URL_.__PS_BASE_URI__,
'base_dir_ssl' => $protocol_link.Tools::getShopDomainSsl().__PS_BASE_URI__,
'content_dir' => $protocol_content.Tools::getShopDomain().__PS_BASE_URI__,
'tpl_dir' => _PS_THEME_DIR_,
'modules_dir' => _MODULE_DIR_,
'mail_dir' => _MAIL_DIR_,
'lang_iso' => $ps_language->iso_code,
'come_from' => Tools::getHttpHost(true, true).Tools::htmlentitiesUTF8(str_replace('\'', '', urldecode($_SERVER['REQUEST_URI']))),
'cart_qties' => (int)$cart->nbProducts(),
'currencies' => Currency::getCurrencies(),
'languages' => Language::getLanguages(),
'priceDisplay' => Product::getTaxCalculationMethod(),
'add_prod_display' => (int)Configuration::get('PS_ATTRIBUTE_CATEGORY_DISPLAY'),
'shop_name' => Configuration::get('PS_SHOP_NAME'),
'roundMode' => (int)Configuration::get('PS_PRICE_ROUND_MODE'),
'use_taxes' => (int)Configuration::get('PS_TAX'),
'display_tax_label' => (bool)$display_tax_label,
'vat_management' => (int)Configuration::get('VATNUMBER_MANAGEMENT'),
'opc' => (bool)Configuration::get('PS_ORDER_PROCESS_TYPE'),
'PS_CATALOG_MODE' => (bool)Configuration::get('PS_CATALOG_MODE'),
'id_current_shop' => (int)$this->id_current_shop,
'id_current_group_shop' => (int)$this->id_current_group_shop
));
// Deprecated
$smarty->assign(array(
'id_currency_cookie' => (int)$currency->id,
'logged' => $cookie->isLogged(),
'customerName' => ($cookie->logged ? $cookie->customer_firstname.' '.$cookie->customer_lastname : false)
));
// TODO for better performances (cache usage), remove these assign and use a smarty function to get the right media server in relation to the full ressource name
$assignArray = array(
'img_ps_dir' => _PS_IMG_,
'img_cat_dir' => _THEME_CAT_DIR_,
'img_lang_dir' => _THEME_LANG_DIR_,
'img_prod_dir' => _THEME_PROD_DIR_,
'img_manu_dir' => _THEME_MANU_DIR_,
'img_sup_dir' => _THEME_SUP_DIR_,
'img_ship_dir' => _THEME_SHIP_DIR_,
'img_store_dir' => _THEME_STORE_DIR_,
'img_col_dir' => _THEME_COL_DIR_,
'img_dir' => _THEME_IMG_DIR_,
'css_dir' => _THEME_CSS_DIR_,
'js_dir' => _THEME_JS_DIR_,
'pic_dir' => _THEME_PROD_PIC_DIR_
);
foreach ($assignArray as $assignKey => $assignValue)
if (substr($assignValue, 0, 1) == '/' OR $protocol_content == 'https://')
$smarty->assign($assignKey, $protocol_content.Tools::getMediaServer($assignValue).$assignValue);
else
$smarty->assign($assignKey, $assignValue);
// setting properties from global var
self::$cookie = $cookie;
self::$cart = $cart;
self::$smarty = $smarty;
self::$link = $link;
if ($this->maintenance)
$this->displayMaintenancePage();
if ($this->restrictedCountry)
$this->displayRestrictedCountryPage();
//live edit
if (Tools::isSubmit('live_edit') AND $ad = Tools::getValue('ad') AND (Tools::getValue('liveToken') == sha1(Tools::getValue('ad')._COOKIE_KEY_)))
if (!is_dir(_PS_ROOT_DIR_.DIRECTORY_SEPARATOR.$ad))
die(Tools::displayError());
$this->iso = $iso;
$this->setMedia();
}
/* Display a maintenance page if shop is closed */
protected function displayMaintenancePage()
{
if (!in_array(Tools::getRemoteAddr(), explode(',', Configuration::get('PS_MAINTENANCE_IP'))))
{
header('HTTP/1.1 503 temporarily overloaded');
self::$smarty->display(_PS_THEME_DIR_.'maintenance.tpl');
exit;
}
}
/* Display a specific page if the user country is not allowed */
protected function displayRestrictedCountryPage()
{
global $smarty;
header('HTTP/1.1 503 temporarily overloaded');
$smarty->display(_PS_THEME_DIR_.'restricted-country.tpl');
exit;
}
protected function canonicalRedirection()
{
global $link, $cookie;
// Automatically redirect to the canonical URL if needed
if (isset($this->php_self) AND !empty($this->php_self))
{
// $_SERVER['HTTP_HOST'] must be replaced by the real canonical domain
$canonicalURL = $link->getPageLink($this->php_self, $this->ssl, $cookie->id_lang);
if (!preg_match('/^'.Tools::pRegexp($canonicalURL, '/').'([&?].*)?$/i', (($this->ssl AND Configuration::get('PS_SSL_ENABLED')) ? 'https://' : 'http://').$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']))
{
header('HTTP/1.0 301 Moved');
$params = '';
$excludedKey = array('isolang', 'id_lang');
foreach ($_GET as $key => $value)
if (!in_array($key, $excludedKey))
$params .= ($params == '' ? '?' : '&').$key.'='.$value;
if (defined('_PS_MODE_DEV_') AND _PS_MODE_DEV_ AND $_SERVER['REQUEST_URI'] != __PS_BASE_URI__)
die('[Debug] This page has moved<br />Please use the following URL instead: <a href="'.$canonicalURL.$params.'">'.$canonicalURL.$params.'</a>');
Tools::redirectLink($canonicalURL.$params);
}
}
}
protected function geolocationManagement()
{
global $cookie, $smarty;
if (!in_array($_SERVER['SERVER_NAME'], array('localhost', '127.0.0.1')))
{
/* Check if Maxmind Database exists */
if (file_exists(_PS_GEOIP_DIR_.'GeoLiteCity.dat'))
{
if (!isset($cookie->iso_code_country) OR (isset($cookie->iso_code_country) AND !in_array(strtoupper($cookie->iso_code_country), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES')))))
{
include_once(_PS_GEOIP_DIR_.'geoipcity.inc');
include_once(_PS_GEOIP_DIR_.'geoipregionvars.php');
$gi = geoip_open(realpath(_PS_GEOIP_DIR_.'GeoLiteCity.dat'), GEOIP_STANDARD);
$record = geoip_record_by_addr($gi, Tools::getRemoteAddr());
if (is_object($record) AND !in_array(strtoupper($record->country_code), explode(';', Configuration::get('PS_ALLOWED_COUNTRIES'))) AND !self::isInWhitelistForGeolocation())
{
if (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_)
$this->restrictedCountry = true;
elseif (Configuration::get('PS_GEOLOCATION_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_)
$smarty->assign(array(
'restricted_country_mode' => true,
'geolocation_country' => $record->country_name
));
}
elseif (is_object($record))
{
$cookie->iso_code_country = strtoupper($record->country_code);
$hasBeenSet = true;
}
}
if (isset($cookie->iso_code_country) AND (int)($id_country = Country::getByIso(strtoupper($cookie->iso_code_country))))
{
/* Update defaultCountry */
$defaultCountry = new Country($id_country);
if (isset($hasBeenSet) AND $hasBeenSet)
$cookie->id_currency = (int)(Currency::getCurrencyInstance($defaultCountry->id_currency ? (int)$defaultCountry->id_currency : Configuration::get('PS_CURRENCY_DEFAULT'))->id);
}
elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_CATALOG_)
$this->restrictedCountry = true;
elseif (Configuration::get('PS_GEOLOCATION_NA_BEHAVIOR') == _PS_GEOLOCATION_NO_ORDER_)
$smarty->assign(array(
'restricted_country_mode' => true,
'geolocation_country' => 'Undefined'
));
}
/* If not exists we disabled the geolocation feature */
else
Configuration::updateValue('PS_GEOLOCATION_ENABLED', 0);
}
}
public function preProcess()
{
}
public function setMedia()
{
global $cookie;
Tools::addCSS(_THEME_CSS_DIR_.'global.css', 'all');
Tools::addJS(array(_PS_JS_DIR_.'jquery/jquery-1.4.4.min.js', _PS_JS_DIR_.'jquery/jquery.easing.1.3.js', _PS_JS_DIR_.'tools.js'));
if (Tools::isSubmit('live_edit') AND $ad = Tools::getValue('ad') AND (Tools::getValue('liveToken') == sha1(Tools::getValue('ad')._COOKIE_KEY_)))
{
Tools::addJS(array(
_PS_JS_DIR_.'jquery/jquery-ui-1.8.10.custom.min.js',
_PS_JS_DIR_.'jquery/jquery.fancybox-1.3.4.js',
_PS_JS_DIR_.'hookLiveEdit.js')
);
Tools::addCSS(_PS_CSS_DIR_.'jquery.fancybox-1.3.4.css');
}
}
public function process()
{
}
public function displayContent()
{
Tools::safePostVars();
self::$smarty->assign('errors', $this->errors);
}
public function displayHeader()
{
global $css_files, $js_files;
if (!self::$initialized)
$this->init();
// P3P Policies (http://www.w3.org/TR/2002/REC-P3P-20020416/#compact_policies)
header('P3P: CP="IDC DSP COR CURa ADMa OUR IND PHY ONL COM STA"');
/* Hooks are volontary out the initialize array (need those variables already assigned) */
self::$smarty->assign(array(
'time' => time(),
'img_update_time' => Configuration::get('PS_IMG_UPDATE_TIME'),
'static_token' => Tools::getToken(false),
'token' => Tools::getToken(),
'logo_image_width' => Configuration::get('SHOP_LOGO_WIDTH'),
'logo_image_height' => Configuration::get('SHOP_LOGO_HEIGHT'),
'priceDisplayPrecision' => _PS_PRICE_DISPLAY_PRECISION_,
'content_only' => (int)Tools::getValue('content_only')
));
self::$smarty->assign(array(
'HOOK_HEADER' => Module::hookExec('header'),
'HOOK_TOP' => Module::hookExec('top'),
'HOOK_LEFT_COLUMN' => Module::hookExec('leftColumn')
));
if ((Configuration::get('PS_CSS_THEME_CACHE') OR Configuration::get('PS_JS_THEME_CACHE')) AND is_writable(_PS_THEME_DIR_.'cache'))
{
// CSS compressor management
if (Configuration::get('PS_CSS_THEME_CACHE'))
Tools::cccCss();
//JS compressor management
if (Configuration::get('PS_JS_THEME_CACHE'))
Tools::cccJs();
}
self::$smarty->assign('css_files', $css_files);
self::$smarty->assign('js_files', array_unique($js_files));
self::$smarty->display(_PS_THEME_DIR_.'header.tpl');
}
public function displayFooter()
{
global $cookie;
if (!self::$initialized)
$this->init();
self::$smarty->assign(array(
'HOOK_RIGHT_COLUMN' => Module::hookExec('rightColumn', array('cart' => self::$cart)),
'HOOK_FOOTER' => Module::hookExec('footer'),
'content_only' => (int)(Tools::getValue('content_only'))));
self::$smarty->display(_PS_THEME_DIR_.'footer.tpl');
//live edit
if (Tools::isSubmit('live_edit') AND $ad = Tools::getValue('ad') AND (Tools::getValue('liveToken') == sha1(Tools::getValue('ad')._COOKIE_KEY_)))
{
self::$smarty->assign(array('ad' => $ad, 'live_edit' => true));
self::$smarty->display(_PS_ALL_THEMES_DIR_.'live_edit.tpl');
}
else
Tools::displayError();
}
public function productSort()
{
if (!self::$initialized)
$this->init();
// $this->orderBy = Tools::getProductsOrder('by', Tools::getValue('orderby'));
// $this->orderWay = Tools::getProductsOrder('way', Tools::getValue('orderway'));
// 'orderbydefault' => Tools::getProductsOrder('by'),
// 'orderwayposition' => Tools::getProductsOrder('way'), // Deprecated: orderwayposition
// 'orderwaydefault' => Tools::getProductsOrder('way'),
$stock_management = (int)(Configuration::get('PS_STOCK_MANAGEMENT')) ? true : false; // no display quantity order if stock management disabled
$orderByValues = array(0 => 'name', 1 => 'price', 2 => 'date_add', 3 => 'date_upd', 4 => 'position', 5 => 'manufacturer_name', 6 => 'quantity');
$orderWayValues = array(0 => 'asc', 1 => 'desc');
$this->orderBy = Tools::strtolower(Tools::getValue('orderby', $orderByValues[(int)(Configuration::get('PS_PRODUCTS_ORDER_BY'))]));
$this->orderWay = Tools::strtolower(Tools::getValue('orderway', $orderWayValues[(int)(Configuration::get('PS_PRODUCTS_ORDER_WAY'))]));
if (!in_array($this->orderBy, $orderByValues))
$this->orderBy = $orderByValues[0];
if (!in_array($this->orderWay, $orderWayValues))
$this->orderWay = $orderWayValues[0];
self::$smarty->assign(array(
'orderby' => $this->orderBy,
'orderway' => $this->orderWay,
'orderbydefault' => $orderByValues[(int)(Configuration::get('PS_PRODUCTS_ORDER_BY'))],
'orderwayposition' => $orderWayValues[(int)(Configuration::get('PS_PRODUCTS_ORDER_WAY'))], // Deprecated: orderwayposition
'orderwaydefault' => $orderWayValues[(int)(Configuration::get('PS_PRODUCTS_ORDER_WAY'))],
'stock_management' => (int)($stock_management)));
}
public function pagination($nbProducts = 10)
{
if (!self::$initialized)
$this->init();
$nArray = (int)(Configuration::get('PS_PRODUCTS_PER_PAGE')) != 10 ? array((int)(Configuration::get('PS_PRODUCTS_PER_PAGE')), 10, 20, 50) : array(10, 20, 50);
asort($nArray);
$this->n = abs((int)(Tools::getValue('n', ((isset(self::$cookie->nb_item_per_page) AND self::$cookie->nb_item_per_page >= 10) ? self::$cookie->nb_item_per_page : (int)(Configuration::get('PS_PRODUCTS_PER_PAGE'))))));
$this->p = abs((int)(Tools::getValue('p', 1)));
$range = 2; /* how many pages around page selected */
if ($this->p < 0)
$this->p = 0;
if (isset(self::$cookie->nb_item_per_page) AND $this->n != self::$cookie->nb_item_per_page AND in_array($this->n, $nArray))
self::$cookie->nb_item_per_page = $this->n;
if ($this->p > ($nbProducts / $this->n))
$this->p = ceil($nbProducts / $this->n);
$pages_nb = ceil($nbProducts / (int)($this->n));
$start = (int)($this->p - $range);
if ($start < 1)
$start = 1;
$stop = (int)($this->p + $range);
if ($stop > $pages_nb)
$stop = (int)($pages_nb);
self::$smarty->assign('nb_products', $nbProducts);
$pagination_infos = array(
'pages_nb' => (int)($pages_nb),
'p' => (int)($this->p),
'n' => (int)($this->n),
'nArray' => $nArray,
'range' => (int)($range),
'start' => (int)($start),
'stop' => (int)($stop)
);
self::$smarty->assign($pagination_infos);
}
public static function getCurrentCustomerGroups()
{
if (!isset(self::$cookie) || !self::$cookie->id_customer)
return array();
if (!is_array(self::$currentCustomerGroups))
{
self::$currentCustomerGroups = array();
$result = Db::getInstance()->ExecuteS('SELECT id_group FROM '._DB_PREFIX_.'customer_group WHERE id_customer = '.(int)self::$cookie->id_customer);
foreach ($result as $row)
self::$currentCustomerGroups[] = $row['id_group'];
}
return self::$currentCustomerGroups;
}
protected static function isInWhitelistForGeolocation()
{
$allowed = false;
$userIp = Tools::getRemoteAddr();
$ips = explode(';', Configuration::get('PS_GEOLOCATION_WHITELIST'));
if (is_array($ips) AND sizeof($ips))
foreach ($ips AS $ip)
if (!empty($ip) AND strpos($userIp, $ip) === 0)
$allowed = true;
return $allowed;
}
}
+176
View File
@@ -0,0 +1,176 @@
<?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
*/
class GroupCore extends ObjectModel
{
public $id;
/** @var string Lastname */
public $name;
/** @var string Reduction */
public $reduction;
/** @var int Price display method (tax inc/tax exc) */
public $price_display_method;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $tables = array ('group');
protected $fieldsRequired = array('price_display_method');
protected $fieldsSize = array();
protected $fieldsValidate = array('reduction' => 'isFloat', 'price_display_method' => 'isPriceDisplayMethod');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 32);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $table = 'group';
protected $identifier = 'id_group';
protected static $_cacheReduction = array();
protected static $_groupPriceDisplayMethod = array();
protected $webserviceParameters = array();
public function getFields()
{
parent::validateFields();
if (isset($this->id))
$fields['id_group'] = (int)($this->id);
$fields['reduction'] = (float)($this->reduction);
$fields['price_display_method'] = (int)($this->price_display_method);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
public function getTranslationsFieldsChild()
{
if (!parent::validateFieldsLang())
return false;
return parent::getTranslationsFields(array('name'));
}
static public function getGroups($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT g.`id_group`, g.`reduction`, g.`price_display_method`, gl.`name`
FROM `'._DB_PREFIX_.'group` g
LEFT JOIN `'._DB_PREFIX_.'group_lang` AS gl ON (g.`id_group` = gl.`id_group` AND gl.`id_lang` = '.(int)($id_lang).')
ORDER BY g.`id_group` ASC');
}
public function getCustomers($count = false, $start = 0, $limit = 0)
{
if ($count)
return Db::getInstance()->getValue('
SELECT COUNT(*)
FROM `'._DB_PREFIX_.'customer_group` cg
LEFT JOIN `'._DB_PREFIX_.'customer` c ON (cg.`id_customer` = c.`id_customer`)
WHERE cg.`id_group` = '.(int)$this->id.'
AND c.`deleted` != 1');
return Db::getInstance()->ExecuteS('
SELECT cg.`id_customer`, c.*
FROM `'._DB_PREFIX_.'customer_group` cg
LEFT JOIN `'._DB_PREFIX_.'customer` c ON (cg.`id_customer` = c.`id_customer`)
WHERE cg.`id_group` = '.(int)$this->id.'
AND c.`deleted` != 1
ORDER BY cg.`id_customer` ASC
'.($limit > 0 ? 'LIMIT '.(int)$start.', '.(int)$limit : ''));
}
static public function getReduction($id_customer = NULL)
{
if ($id_customer === NULL)
$id_customer = 0;
if (!isset(self::$_cacheReduction['customer'][$id_customer]))
{
if ($id_customer)
$customer = new Customer((int)($id_customer));
self::$_cacheReduction['customer'][$id_customer] = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `reduction`
FROM `'._DB_PREFIX_.'group`
WHERE `id_group` = '.((isset($customer) AND Validate::isLoadedObject($customer)) ? (int)($customer->id_default_group) : 1));
}
return self::$_cacheReduction['customer'][$id_customer];
}
public static function getReductionByIdGroup($id_group)
{
if (!isset(self::$_cacheReduction['group'][$id_group]))
{
self::$_cacheReduction['group'][$id_group] = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `reduction`
FROM `'._DB_PREFIX_.'group`
WHERE `id_group` = '.$id_group);
}
return self::$_cacheReduction['group'][$id_group];
}
static public function getPriceDisplayMethod($id_group)
{
if (!isset(self::$_groupPriceDisplayMethod[$id_group]))
self::$_groupPriceDisplayMethod[$id_group] = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `price_display_method`
FROM `'._DB_PREFIX_.'group`
WHERE `id_group` = '.(int)($id_group));
return self::$_groupPriceDisplayMethod[$id_group];
}
static public function getDefaultPriceDisplayMethod()
{
return self::getPriceDisplayMethod(1);
}
public function add($autodate = true, $nullValues = false)
{
return parent::add() && Category::setNewGroupForHome((int)($this->id));
}
public function delete()
{
if ($this->id == _PS_DEFAULT_CUSTOMER_GROUP_)
return false;
if (parent::delete())
{
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'customer_group` WHERE `id_group` = '.(int)($this->id));
Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'category_group` WHERE `id_group` = '.(int)($this->id));
Discount::deleteByIdGroup((int)($this->id));
return true;
}
return false;
}
}
+108
View File
@@ -0,0 +1,108 @@
<?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 GroupReductionCore extends ObjectModel
{
public $id_group;
public $id_category;
public $reduction;
protected $fieldsRequired = array('id_group', 'id_category', 'reduction');
protected $fieldsValidate = array('id_group' => 'isUnsignedId', 'id_category' => 'isUnsignedId', 'reduction' => 'isPrice');
protected $table = 'group_reduction';
protected $identifier = 'id_group_reduction';
protected static $reductionCache = array();
public function getFields()
{
parent::validateFields();
$fields['id_group'] = (int)($this->id_group);
$fields['id_category'] = (int)($this->id_category);
$fields['reduction'] = (float)($this->reduction);
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
return (parent::add($autodate, $nullValues) AND $this->_setCache());
}
public function update($nullValues = false)
{
return (parent::update($nullValues) AND $this->_clearCache() AND $this->_setCache());
}
public function delete()
{
return $this->_clearCache() AND parent::delete();
}
protected function _clearCache()
{
return Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'product_group_reduction_cache` WHERE `id_group` = '.(int)($this->id_group));
}
protected function _setCache()
{
$resource = Db::getInstance()->ExecuteS('
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_product` cp
INNER JOIN `'._DB_PREFIX_.'product` p ON (p.`id_product` = cp.`id_product`)
WHERE cp.`id_category` = '.(int)($this->id_category)
, false);
$query = 'INSERT INTO `'._DB_PREFIX_.'product_group_reduction_cache` (`id_product`, `id_group`, `reduction`) VALUES ';
while ($row = Db::getInstance()->nextRow($resource))
$query .= '('.(int)($row['id_product']).', '.(int)($this->id_group).', '.(float)($this->reduction).'), ';
return Db::getInstance()->Execute(rtrim($query, ', '));
}
static public function getGroupReductions($id_group, $id_lang)
{
return Db::getInstance()->ExecuteS('
SELECT gr.`id_group_reduction`, gr.`id_group`, gr.`id_category`, gr.`reduction`, cl.`name` AS category_name
FROM `'._DB_PREFIX_.'group_reduction` gr
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (cl.`id_category` = gr.`id_category` AND cl.`id_lang` = '.(int)($id_lang).')
WHERE `id_group` = '.(int)($id_group)
);
}
static public function getValueForProduct($id_product, $id_group)
{
if (!isset(self::$reductionCache[$id_product.'-'.$id_group]))
self::$reductionCache[$id_product.'-'.$id_group] = Db::getInstance()->getValue('SELECT `reduction` FROM `'._DB_PREFIX_.'product_group_reduction_cache` WHERE `id_product` = '.(int)($id_product).' AND `id_group` = '.(int)($id_group));
return self::$reductionCache[$id_product.'-'.$id_group];
}
static public function doesExist($id_group, $id_category)
{
return (bool)Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('SELECT `id_group` FROM `'._DB_PREFIX_.'group_reduction` WHERE `id_group` = '.(int)($id_group).' AND `id_category` = '.(int)($id_category));
}
}
+128
View File
@@ -0,0 +1,128 @@
<?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: 1.4 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
class GroupShopCore extends ObjectModel
{
public $name;
public $active;
public $share_datas;
public $share_stock;
public $deleted;
protected $fieldsSize = array('name' => 64);
protected $fieldsValidate = array(
'active' => 'isBool',
'share_datas' => 'isBool',
'share_stock' => 'isBool',
'name' => 'isGenericName',
);
protected $table = 'group_shop';
protected $identifier = 'id_group_shop';
private static $assoTables = array(
'attribute_group' => array('type' => 'group_shop'),
'attribute' => array('type' => 'group_shop'),
'customer_group' => array('type' => 'group_shop'),
'feature' => array('type' => 'group_shop'),
'group' => array('type' => 'group_shop'),
'manufacturer' => array('type' => 'group_shop'),
'supplier' => array('type' => 'group_shop'),
'zone' => array('type' => 'group_shop'),
'tax_rules_group' => array('type' => 'group_shop'),
);
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
$fields['share_datas'] = (int)$this->share_datas;
$fields['share_stock'] = (int)$this->share_stock;
$fields['active'] = (int)$this->active;
$fields['deleted'] = (int)$this->deleted;
return $fields;
}
public static function getGroupShops($active = true)
{
return Db::getInstance()->ExecuteS('SELECT *
FROM '._DB_PREFIX_.'group_shop
WHERE `deleted`= 0 AND `active`='.(int)$active);
}
public function delete()
{
if (!$res = parent::delete())
return false;
foreach (Shop::getAssoTables() AS $table_name => $row)
{
$id = 'id_'.$row['type'];
if ($row['type'] == 'fk_shop')
$id = 'id_shop';
else
$table_name .= '_'.$row['type'];
$res &= Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.$table_name.'` WHERE `'.$id.'`='.(int)$this->id);
}
return $res;
}
public static function getAssoTables()
{
return self::$assoTables;
}
/**
* @return int Total of groupshops
*/
public static function getTotalGroupShops($active = true)
{
return sizeof(GroupShop::getGroupShops($active));
}
public function copyGroupShopData($old_id)
{
//TODO
}
public function haveShops()
{
return (bool)$this->getNbShops();
}
public function getNbShops()
{
return (int)Db::getInstance()->getValue('SELECT COUNT(*)
FROM '._DB_PREFIX_.'shop s
WHERE id_group_shop='.(int)$this->id);
}
}
+210
View File
@@ -0,0 +1,210 @@
<?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 GuestCore extends ObjectModel
{
public $id_operating_system;
public $id_web_browser;
public $id_customer;
public $javascript;
public $screen_resolution_x;
public $screen_resolution_y;
public $screen_color;
public $sun_java;
public $adobe_flash;
public $adobe_director;
public $apple_quicktime;
public $real_player;
public $windows_media;
public $accept_language;
protected $fieldsSize = array('accept_language' => 8);
protected $fieldsValidate = array(
'id_operating_system' => 'isUnsignedId',
'id_web_browser' => 'isUnsignedId',
'id_customer' => 'isUnsignedId',
'javascript' => 'isBool',
'screen_resolution_x' => 'isInt',
'screen_resolution_y' => 'isInt',
'screen_color' => 'isInt',
'sun_java' => 'isBool',
'adobe_flash' => 'isBool',
'adobe_director' => 'isBool',
'apple_quicktime' => 'isBool',
'real_player' => 'isBool',
'windows_media' => 'isBool',
'accept_language' => 'isGenericName'
);
protected $table = 'guest';
protected $identifier = 'id_guest';
protected $webserviceParameters = array(
'fields' => array(
'id_customer' => array('xlink_resource' => 'customers'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_operating_system'] = (int)($this->id_operating_system);
$fields['id_web_browser'] = (int)($this->id_web_browser);
$fields['id_customer'] = (int)($this->id_customer);
$fields['javascript'] = (int)($this->javascript);
$fields['screen_resolution_x'] = (int)($this->screen_resolution_x);
$fields['screen_resolution_y'] = (int)($this->screen_resolution_y);
$fields['screen_color'] = (int)($this->screen_color);
$fields['sun_java'] = (int)($this->sun_java);
$fields['adobe_flash'] = (int)($this->adobe_flash);
$fields['adobe_director'] = (int)($this->adobe_director);
$fields['apple_quicktime'] = (int)($this->apple_quicktime);
$fields['real_player'] = (int)($this->real_player);
$fields['windows_media'] = (int)($this->windows_media);
$fields['accept_language'] = pSQL($this->accept_language);
return $fields;
}
function userAgent()
{
$userAgent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
$acceptLanguage = isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? $_SERVER['HTTP_ACCEPT_LANGUAGE'] : '';
$this->id_operating_system = $this->getOs($userAgent);
$this->id_web_browser = $this->getBrowser($userAgent);
$this->accept_language = $this->getLanguage($acceptLanguage);
}
protected function getLanguage($acceptLanguage)
{
// $langsArray is filled with all the languages accepted, ordered by priority
$langsArray = array();
preg_match_all('/([a-z]{2}(-[a-z]{2})?)\s*(;\s*q\s*=\s*(1|0\.[0-9]+))?/', $acceptLanguage, $array);
if (count($array[1]))
{
$langsArray = array_combine($array[1], $array[4]);
foreach ($langsArray as $lang => $val)
if ($val === '')
$langsArray[$lang] = 1;
arsort($langsArray, SORT_NUMERIC);
}
// Only the first language is returned
return (sizeof($langsArray) ? key($langsArray) : '');
}
protected function getBrowser($userAgent)
{
$browserArray = array(
'Google Chrome' => 'Chrome/',
'Safari' => 'Safari',
'Firefox 3.x' => 'Firefox/3',
'Firefox 2.x' => 'Firefox/2',
'Opera' => 'Opera',
'IE 8.x' => 'MSIE 8',
'IE 7.x' => 'MSIE 7',
'IE 6.x' => 'MSIE 6'
);
foreach ($browserArray as $k => $value)
if (strstr($userAgent, $value))
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_web_browser`
FROM `'._DB_PREFIX_.'web_browser` wb
WHERE wb.`name` = \''.pSQL($k).'\'');
return $result['id_web_browser'];
}
return NULL;
}
protected function getOs($userAgent)
{
$osArray = array(
'Windows Vista' => 'Windows NT 6',
'Windows XP' => 'Windows NT 5',
'MacOsX' => 'Mac OS X',
'Linux' => 'X11'
);
foreach ($osArray as $k => $value)
if (strstr($userAgent, $value))
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `id_operating_system`
FROM `'._DB_PREFIX_.'operating_system` os
WHERE os.`name` = \''.pSQL($k).'\'');
return $result['id_operating_system'];
}
return NULL;
}
public static function getFromCustomer($id_customer)
{
if (!Validate::isUnsignedId($id_customer))
return false;
$result = Db::getInstance()->getRow('
SELECT `id_guest`
FROM `'._DB_PREFIX_.'guest`
WHERE `id_customer` = '.(int)($id_customer));
return $result['id_guest'];
}
public function mergeWithCustomer($id_guest, $id_customer)
{
// Since the guests are merged, the guest id in the connections table must be changed too
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'connections` c
SET c.`id_guest` = '.(int)($id_guest).'
WHERE c.`id_guest` = '.(int)($this->id));
// The current guest is removed from the database
$this->delete();
// $this is still filled with values, so it's id is changed for the old guest
$this->id = (int)($id_guest);
$this->id_customer = (int)($id_customer);
// $this is now the old guest but filled with the most up to date values
$this->update();
}
public static function setNewGuest($cookie)
{
$guest = new Guest(isset($cookie->id_customer) ? Guest::getFromCustomer((int)($cookie->id_customer)) : NULL);
$guest->userAgent();
if ($guest->id_operating_system OR $guest->id_web_browser)
{
$guest->save();
$cookie->id_guest = (int)($guest->id);
}
}
}
+117
View File
@@ -0,0 +1,117 @@
<?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 HelpAccessCore
{
const URL = 'http://help.prestashop.com';
protected static $_images = array(0 => 'none',
1 => 'help2.png',
2 => 'help-new.png');
public static function trackClick($label, $version)
{
Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'help_access` (`label`, `version`) VALUES (\''.pSQL($label).'\',\''.pSQL($version).'\')
ON DUPLICATE KEY UPDATE `version` = \''.pSQL($version).'\'
');
}
public static function getVersion($label)
{
return Db::getInstance()->getValue('
SELECT `version` FROM `'._DB_PREFIX_.'help_access`
WHERE `label` = \''.pSQL($label).'\'
');
}
public static function retrieveInfos($label, $iso_lang, $country, $version)
{
$image = self::$_images[0];
$tooltip = '';
$url = HelpAccess::URL.'/documentation/renderIcon?label='.$label.'&iso_lang='.$iso_lang.'&country='.$country.'&version='.$version;
$ctx = stream_context_create(array(
'http' => array(
'timeout' => 10
)
));
$res = @file_get_contents($url, 0, $ctx);
$infos = preg_split('/\|/', $res);
if (sizeof($infos) > 0)
{
$version = trim($infos[0]);
if (!empty($version))
{
$image = self::$_images[1];
if (sizeof($infos) > 1)
$tooltip = trim('|'.$infos[1]);
}
}
$last_version = HelpAccess::getVersion($label);
if (!empty($version) && $version != $last_version)
$image = self::$_images[2];
return array('version' => $version, 'image' => $image, 'tooltip' => $tooltip);
}
public static function displayHelp($label, $iso_lang, $country, $ps_version)
{
$infos = HelpAccess::retrieveInfos($label, $iso_lang, $country, $ps_version);
if (array_key_exists('image', $infos) && $infos['image'] != 'none')
{
echo '
<a class="help-button" href="#" onclick="showHelp(\''.HelpAccess::URL.'\',\''.$label.'\',\''.$iso_lang.'\',\''.$ps_version.'\',\''.$infos['version'].'\',\''.$country.'\');" title="'.Tools::htmlentitiesUTF8($infos['tooltip']).'">
<img id="help-'.$label.'" src="../img/admin/'.Tools::htmlentitiesUTF8($infos['image']).'" alt="" class="middle" style="margin-top: -5px"/> '.Tools::displayError('HELP').'
</a>
';
if (!empty($infos['tooltip']))
echo ' <script type="text/javascript">
$(document).ready(function() {
$("a.help-button").cluetip({
splitTitle: "|",
cluetipClass: "help-button",
showTitle: false,
arrows: true,
dropShadow: false,
positionBy: "auto"
});
});
</script>';
}
}
}
+253
View File
@@ -0,0 +1,253 @@
<?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: 7025 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class HookCore extends ObjectModel
{
/** @var string Name */
public $name;
protected $fieldsRequired = array('name');
protected $fieldsSize = array('name' => 32);
protected $fieldsValidate = array('name' => 'isHookName');
protected $table = 'hook';
protected $identifier = 'id_hook';
static $preloadModulesFromHooks = null;
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
return $fields;
}
/**
* Return hook ID from name
*
* @param string $hookName Hook name
* @return integer Hook ID
*/
static public function get($hookName)
{
if (!Validate::isHookName($hookName))
die(Tools::displayError());
$result = Db::getInstance()->getRow('
SELECT `id_hook`, `name`
FROM `'._DB_PREFIX_.'hook`
WHERE `name` = \''.pSQL($hookName).'\'');
return ($result ? $result['id_hook'] : false);
}
static public function getHooks($position = false)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'hook` h
'.($position ? 'WHERE h.`position` = 1' : ''));
}
static public function preloadModulesFromHooks()
{
if (!is_null(self::$preloadModulesFromHooks))
return ;
self::$preloadModulesFromHooks = array();
$sql = 'SELECT h.id_hook, h.name as h_name, title, description, h.position, live_edit, hm.position as hm_position, m.id_module, m.name, active
FROM `'._DB_PREFIX_.'hook` h
INNER JOIN `'._DB_PREFIX_.'hook_module` hm ON (h.id_hook = hm.id_hook)
INNER JOIN `'._DB_PREFIX_.'module` as m ON (m.id_module = hm.id_module)
WHERE hm.id_shop IN('.implode(', ', Shop::getListFromContext()).')
GROUP BY hm.id_hook, hm.id_module
ORDER BY hm.position';
$results = Db::getInstance()->executeS($sql);
foreach ($results as $result)
{
if (!isset(self::$preloadModulesFromHooks[$result['id_hook']]))
self::$preloadModulesFromHooks[$result['id_hook']] = array();
self::$preloadModulesFromHooks[$result['id_hook']][$result['id_module']] = array(
'id_hook' => $result['id_hook'],
'title' => $result['title'],
'description' => $result['description'],
'hm.position' => $result['position'],
'live_edit' => $result['live_edit'],
'm.position' => $result['hm_position'],
'id_module' => $result['id_module'],
'name' => $result['name'],
'active' => $result['active'],
);
}
}
static public function getModulesFromHook($hookID, $moduleID = null)
{
Hook::preloadModulesFromHooks();
$list = (isset(self::$preloadModulesFromHooks[$hookID])) ? self::$preloadModulesFromHooks[$hookID] : array();
if ($moduleID)
return (isset($list[$moduleID])) ? array($list[$moduleID]) : array();
return $list;
}
static public function newOrder($cart, $order, $customer, $currency, $orderStatus)
{
return Module::hookExec('newOrder', array(
'cart' => $cart,
'order' => $order,
'customer' => $customer,
'currency' => $currency,
'orderStatus' => $orderStatus));
}
static public function updateOrderStatus($newOrderStatusId, $id_order)
{
$order = new Order((int)($id_order));
$newOS = new OrderState((int)($newOrderStatusId), $order->id_lang);
$return = ((int)($newOS->id) == _PS_OS_PAYMENT_) ? Module::hookExec('paymentConfirm', array('id_order' => (int)($order->id))) : true;
$return = Module::hookExec('updateOrderStatus', array('newOrderStatus' => $newOS, 'id_order' => (int)($order->id))) AND $return;
return $return;
}
static public function postUpdateOrderStatus($newOrderStatusId, $id_order)
{
$order = new Order((int)($id_order));
$newOS = new OrderState((int)($newOrderStatusId), $order->id_lang);
$return = Module::hookExec('postUpdateOrderStatus', array('newOrderStatus' => $newOS, 'id_order' => (int)($order->id)));
return $return;
}
/**
* Called when quantity of a product is updated.
*
* @param Product
* @param Order
*/
static public function updateQuantity($product, $order = null)
{
return Module::hookExec('updateQuantity', array('product' => $product, 'order' => $order));
}
static public function productFooter($product, $category)
{
return Module::hookExec('productFooter', array('product' => $product, 'category' => $category));
}
static public function productOutOfStock($product)
{
return Module::hookExec('productOutOfStock', array('product' => $product));
}
static public function addProduct($product)
{
return Module::hookExec('addProduct', array('product' => $product));
}
static public function updateProduct($product)
{
return Module::hookExec('updateProduct', array('product' => $product));
}
static public function deleteProduct($product)
{
return Module::hookExec('deleteProduct', array('product' => $product));
}
static public function updateProductAttribute($id_product_attribute)
{
return Module::hookExec('updateProductAttribute', array('id_product_attribute' => $id_product_attribute));
}
static public function orderConfirmation($id_order)
{
if (Validate::isUnsignedId($id_order))
{
$params = array();
$order = new Order((int)$id_order);
$currency = new Currency((int)$order->id_currency);
if (Validate::isLoadedObject($order))
{
$params['total_to_pay'] = $order->total_paid;
$params['currency'] = $currency->sign;
$params['objOrder'] = $order;
$params['currencyObj'] = $currency;
return Module::hookExec('orderConfirmation', $params);
}
}
return false;
}
static public function paymentReturn($id_order, $id_module)
{
if (Validate::isUnsignedId($id_order) AND Validate::isUnsignedId($id_module))
{
$params = array();
$order = new Order((int)($id_order));
$currency = new Currency((int)($order->id_currency));
if (Validate::isLoadedObject($order))
{
$params['total_to_pay'] = $order->total_paid;
$params['currency'] = $currency->sign;
$params['objOrder'] = $order;
$params['currencyObj'] = $currency;
return Module::hookExec('paymentReturn', $params, (int)($id_module));
}
}
return false;
}
static public function PDFInvoice($pdf, $id_order)
{
if (!is_object($pdf) OR !Validate::isUnsignedId($id_order))
return false;
return Module::hookExec('PDFInvoice', array('pdf' => $pdf, 'id_order' => $id_order));
}
static public function backBeforePayment($module)
{
$params['module'] = strval($module);
if (!$params['module'])
return false;
return Module::hookExec('backBeforePayment', $params);
}
static public function updateCarrier($id_carrier, $carrier)
{
if (!Validate::isUnsignedId($id_carrier) OR !is_object($carrier))
return false;
return Module::hookExec('updateCarrier', array('id_carrier' => $id_carrier, 'carrier' => $carrier));
}
}
+516
View File
@@ -0,0 +1,516 @@
<?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: 7310 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ImageCore extends ObjectModel
{
public $id;
/** @var integer Image ID */
public $id_image;
/** @var integer Product ID */
public $id_product;
/** @var string HTML title and alt attributes */
public $legend;
/** @var integer Position used to order images of the same product */
public $position;
/** @var boolean Image is cover */
public $cover;
/** @var string image extension */
public $image_format = 'jpg';
/** @var string image folder */
protected $folder;
/** @var string image path without extension */
protected $existing_path;
protected $tables = array ('image', 'image_lang');
protected $fieldsRequired = array('id_product');
protected $fieldsValidate = array('id_product' => 'isUnsignedId', 'position' => 'isUnsignedInt', 'cover' => 'isBool');
protected $fieldsRequiredLang = array('legend');
protected $fieldsSizeLang = array('legend' => 128);
protected $fieldsValidateLang = array('legend' => 'isGenericName');
protected $table = 'image';
protected $identifier = 'id_image';
protected static $_cacheGetSize = array();
public function __construct($id = NULL, $id_lang = NULL)
{
parent::__construct($id, $id_lang);
$this->image_dir = _PS_PROD_IMG_DIR_;
}
public function getFields()
{
parent::validateFields();
$fields['id_product'] = (int)($this->id_product);
$fields['position'] = (int)($this->position);
$fields['cover'] = (int)($this->cover);
return $fields;
}
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('legend'));
}
public function delete()
{
if (!parent::delete() ||
!$this->deleteProductAttributeImage() ||
!$this->deleteImage())
return false;
// update positions
$result = Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'image`
WHERE `id_product` = '.(int)$this->id_product.'
ORDER BY `position`');
$i = 1;
if ($result)
foreach ($result AS $row)
{
$row['position'] = $i++;
Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table, $row, 'UPDATE', '`id_image` = '.(int)($row['id_image']), 1);
}
return true;
}
/**
* Return available images for a product
*
* @param integer $id_lang Language ID
* @param integer $id_product Product ID
* @return array Images
*/
static public function getImages($id_lang, $id_product)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'image` i
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image`)
WHERE i.`id_product` = '.(int)$id_product.' AND il.`id_lang` = '.(int)$id_lang.'
ORDER BY i.`position` ASC');
}
/**
* Return Images
*
* @return array Images
*/
static public function getAllImages()
{
return Db::getInstance()->ExecuteS('
SELECT `id_image`, `id_product`
FROM `'._DB_PREFIX_.'image`
ORDER BY `id_image` ASC');
}
/**
* Return number of images for a product
*
* @param integer $id_product Product ID
* @return integer number of images
*/
static public function getImagesTotal($id_product)
{
$result = Db::getInstance()->getRow('
SELECT COUNT(`id_image`) AS total
FROM `'._DB_PREFIX_.'image`
WHERE `id_product` = '.(int)($id_product));
return $result['total'];
}
/**
* Return highest position of images for a product
*
* @param integer $id_product Product ID
* @return integer highest position of images
*/
static public function getHighestPosition($id_product)
{
$result = Db::getInstance()->getRow('
SELECT MAX(`position`) AS max
FROM `'._DB_PREFIX_.'image`
WHERE `id_product` = '.(int)($id_product));
return $result['max'];
}
/**
* Delete product cover
*
* @param integer $id_product Product ID
* @return boolean result
*/
static public function deleteCover($id_product)
{
if (!Validate::isUnsignedId($id_product))
die(Tools::displayError());
if (file_exists(_PS_TMP_IMG_DIR_.'product_'.$id_product.'.jpg'))
unlink(_PS_TMP_IMG_DIR_.'product_'.$id_product.'.jpg');
return Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'image`
SET `cover` = 0
WHERE `id_product` = '.(int)($id_product));
}
/**
*Get product cover
*
* @param integer $id_product Product ID
* @return boolean result
*/
static public function getCover($id_product)
{
return Db::getInstance()->getRow('
SELECT * FROM `'._DB_PREFIX_.'image`
WHERE `id_product` = '.(int)($id_product).'
AND `cover`= 1');
}
/**
* Copy images from a product to another
*
* @param integer $id_product_old Source product ID
* @param boolean $id_product_new Destination product ID
*/
static public function duplicateProductImages($id_product_old, $id_product_new, $combinationImages)
{
$imagesTypes = ImageType::getImagesTypes('products');
$result = Db::getInstance()->ExecuteS('
SELECT `id_image`
FROM `'._DB_PREFIX_.'image`
WHERE `id_product` = '.(int)($id_product_old));
foreach ($result as $row)
{
$imageOld = new Image($row['id_image']);
$imageNew = clone $imageOld;
$imageNew->id_product = (int)($id_product_new);
$imageOld->id_product = (int)($id_product_old);
if ($imageNew->add())
{
foreach ($imagesTypes AS $k => $imageType)
{
if (file_exists(_PS_PROD_IMG_DIR_.$imageOld->getExistingImgPath().'-'.$imageType['name'].'.jpg'))
{
$imageNew->createImgFolder();
copy(_PS_PROD_IMG_DIR_.$imageOld->getExistingImgPath().'-'.$imageType['name'].'.jpg', _PS_PROD_IMG_DIR_.
$imageNew->getImgPath().'-'.$imageType['name'].'.jpg');
}
}
if (file_exists(_PS_PROD_IMG_DIR_.$imageOld->getExistingImgPath().'.jpg'))
copy(_PS_PROD_IMG_DIR_.$imageOld->getExistingImgPath().'.jpg',
_PS_PROD_IMG_DIR_.$imageNew->getImgPath().'.jpg');
self::replaceAttributeImageAssociationId($combinationImages, (int)($imageOld->id), (int)($imageNew->id));
}
else
return false;
}
return self::duplicateAttributeImageAssociations($combinationImages);
}
static protected function replaceAttributeImageAssociationId(&$combinationImages, $saved_id, $id_image)
{
if (!isset($combinationImages['new']) OR !is_array($combinationImages['new']))
return ;
foreach ($combinationImages['new'] AS $id_product_attribute => $imageIds)
foreach ($imageIds AS $key => $imageId)
if ((int)($imageId) == (int)($saved_id))
$combinationImages['new'][$id_product_attribute][$key] = (int)($id_image);
}
/**
* Duplicate product attribute image associations
* @param integer $id_product_attribute_old
* @return boolean
*/
static public function duplicateAttributeImageAssociations($combinationImages)
{
if (!isset($combinationImages['new']) OR !is_array($combinationImages['new']))
return true;
$query = 'INSERT INTO `'._DB_PREFIX_.'product_attribute_image` (`id_product_attribute`, `id_image`) VALUES ';
foreach ($combinationImages['new'] AS $id_product_attribute => $imageIds)
foreach ($imageIds AS $imageId)
$query .= '('.(int)($id_product_attribute).', '.(int)($imageId).'), ';
$query = rtrim($query, ', ');
return DB::getInstance()->Execute($query);
}
/**
* Reposition image
*
* @param integer $position Position
* @param boolean $direction Direction
*/
public function positionImage($position, $direction)
{
$position = (int)($position);
$direction = (int)($direction);
// temporary position
$high_position = Image::getHighestPosition($this->id_product) + 1;
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'image`
SET `position` = '.(int)($high_position).'
WHERE `id_product` = '.(int)($this->id_product).'
AND `position` = '.($direction ? $position - 1 : $position + 1));
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'image`
SET `position` = `position`'.($direction ? '-1' : '+1').'
WHERE `id_image` = '.(int)($this->id));
Db::getInstance()->Execute('
UPDATE `'._DB_PREFIX_.'image`
SET `position` = '.$this->position.'
WHERE `id_product` = '.(int)($this->id_product).'
AND `position` = '.(int)($high_position));
}
static public function getSize($type)
{
if (!isset(self::$_cacheGetSize[$type]) OR self::$_cacheGetSize[$type] === NULL)
self::$_cacheGetSize[$type] = Db::getInstance()->getRow('SELECT `width`, `height` FROM '._DB_PREFIX_.'image_type WHERE `name` = \''.pSQL($type).'\'');
return self::$_cacheGetSize[$type];
}
/**
* Clear all images in tmp dir
*/
static public function clearTmpDir()
{
foreach (scandir(_PS_TMP_IMG_DIR_) AS $d)
if (preg_match('/(.*)\.jpg$/', $d))
unlink(_PS_TMP_IMG_DIR_.$d);
}
/**
* Delete Image - Product attribute associations for this image
*/
public function deleteProductAttributeImage()
{
return Db::getInstance()->Execute('
DELETE
FROM `'._DB_PREFIX_.'product_attribute_image`
WHERE `id_image` = '.(int)($this->id)
);
}
/**
* Delete a product image from disk and remove the containing folder if empty
* Handles both legacy and new image filesystems
*/
public function deleteImage()
{
// Delete base image
if (file_exists($this->image_dir.$this->getExistingImgPath().'.'.$this->image_format))
unlink($this->image_dir.$this->getExistingImgPath().'.'.$this->image_format);
else
return false;
// Delete auto-generated images
$imageTypes = ImageType::getImagesTypes();
foreach ($imageTypes AS $imageType)
if (file_exists($this->image_dir.$this->getExistingImgPath().'-'.$imageType['name'].'.'.$this->image_format))
unlink($this->image_dir.$this->getExistingImgPath().'-'.$imageType['name'].'.'.$this->image_format);
// Can we remove the image folder?
if (is_dir($this->image_dir.$this->getImgFolder()))
{
$remove_folder = true;
foreach (scandir($this->image_dir.$this->getImgFolder()) as $file)
if (($file != '.' && $file != '..'))
{
$remove_folder = false;
break;
}
}
if (isset($remove_folder) && $remove_folder)
@rmdir($this->image_dir.$this->getImgFolder());
// Delete tmp images
if (file_exists(_PS_TMP_IMG_DIR_.'product_'.$this->id_product.'.'.$this->image_format)
&& !unlink(_PS_TMP_IMG_DIR_.'product_'.$this->id_product.'.'.$this->image_format))
return false;
if (file_exists(_PS_TMP_IMG_DIR_.'product_mini_'.$this->id_product.'.'.$this->image_format)
&& !unlink(_PS_TMP_IMG_DIR_.'product_mini_'.$this->id_product.'.'.$this->image_format))
return false;
return true;
}
/**
* Recursively deletes all product images in the given folder tree and removes empty folders.
*
* @param string $path folder containing the product images to delete
* @param string $format image format
* @return bool success
*/
public static function deleteAllImages($path, $format='jpg')
{
if (!$path || !$format || !is_dir($path))
return false;
foreach (scandir($path) as $file)
{
if (preg_match('/^[0-9]+(\-(.*))?\.'.$format.'$/', $file))
unlink($path.$file);
else if (is_dir($path.$file) && (preg_match('/^[0-9]$/', $file)))
self::deleteAllImages($path.$file.'/', $format);
}
// Can we remove the image folder?
$remove_folder = true;
foreach (scandir($path) as $file)
if (($file != '.' && $file != '..'))
{
$remove_folder = false;
break;
}
if ($remove_folder)
@rmdir($path);
return true;
}
/**
* Returns image path in the old or in the new filesystem
*
* @ returns string image path
*/
public function getExistingImgPath()
{
if (!$this->existing_path)
{
if (Configuration::get('PS_LEGACY_IMAGES') && file_exists(_PS_PROD_IMG_DIR_.$this->id_product.'-'.$this->id.'.'.$this->image_format))
$this->existing_path = $this->id_product.'-'.$this->id;
else
$this->existing_path = $this->getImgPath();
}
return $this->existing_path;
}
/**
* Returns the path to the folder containing the image in the new filesystem
*
* @return string path to folder
*/
public function getImgFolder()
{
if (!$this->id)
return false;
if (!$this->folder)
$this->folder = self::getImgFolderStatic($this->id);
return $this->folder;
}
/**
* Create parent folders for the image in the new filesystem
*
* @return bool success
*/
public function createImgFolder()
{
if (!file_exists(_PS_PROD_IMG_DIR_.$this->getImgFolder()))
return @mkdir(_PS_PROD_IMG_DIR_.$this->getImgFolder(), 0755, true);
return true;
}
/**
* Returns the path to the image without file extension
*
* @return string path
*/
public function getImgPath()
{
$path = $this->getImgFolder().$this->id;
return $path;
}
/**
* Returns the path to the folder containing the image in the new filesystem
*
* @param mixed $id_image
* @return string path to folder
*/
public static function getImgFolderStatic($id_image)
{
if (!is_numeric($id_image))
return false;
$folders = str_split((string)$id_image);
return implode('/', $folders).'/';
}
/**
* Move all legacy product image files from the image folder root to their subfolder in the new filesystem.
* If max_execution_time is provided, stops before timeout and returns string "timeout".
*
* @return mixed success or timeout
*/
public static function moveToNewFileSystem($max_execution_time = 0)
{
$start_time = time();
$image = null;
$result = true;
foreach (scandir(_PS_PROD_IMG_DIR_) as $file)
{
if (preg_match('/^([0-9]+\-)([0-9]+)(\-(.*))?\.jpg$/', $file, $matches))
{
// don't recreate an image object for each image type
if (!$image || $image->id !== (int)$matches[2])
$image = new Image((int)$matches[2]);
if ($image->createImgFolder())
{
$new_path = _PS_PROD_IMG_DIR_.$image->getImgPath().(isset($matches[3]) ? $matches[3] : '').'.jpg';
$result &= @rename(_PS_PROD_IMG_DIR_.$file, $new_path);
}
}
if ((int)$max_execution_time != 0 && (time() - $start_time > (int)$max_execution_time - 4))
return 'timeout';
}
return $result;
}
}
+149
View File
@@ -0,0 +1,149 @@
<?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 ImageTypeCore extends ObjectModel
{
public $id;
/** @var string Name */
public $name;
/** @var integer Width */
public $width;
/** @var integer Height */
public $height;
/** @var boolean Apply to products */
public $products;
/** @var integer Apply to categories */
public $categories;
/** @var integer Apply to manufacturers */
public $manufacturers;
/** @var integer Apply to suppliers */
public $suppliers;
/** @var integer Apply to scenes */
public $scenes;
/** @var integer Apply to store */
public $stores;
protected $fieldsRequired = array('name', 'width', 'height');
protected $fieldsValidate = array(
'name' => 'isImageTypeName',
'width' => 'isImageSize',
'height' => 'isImageSize',
'categories' => 'isBool',
'products' => 'isBool',
'manufacturers' => 'isBool',
'suppliers' => 'isBool',
'scenes' => 'isBool',
'stores' => 'isBool'
);
protected $fieldsSize = array('name' => 16);
protected $table = 'image_type';
protected $identifier = 'id_image_type';
/**
* @var array Image types cache
*/
protected static $images_types_cache = array();
protected $webserviceParameters = array();
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
$fields['width'] = (int)($this->width);
$fields['height'] = (int)($this->height);
$fields['products'] = (int)($this->products);
$fields['categories'] = (int)($this->categories);
$fields['manufacturers'] = (int)($this->manufacturers);
$fields['suppliers'] = (int)($this->suppliers);
$fields['scenes'] = (int)($this->scenes);
$fields['stores'] = (int)($this->stores);
return $fields;
}
/**
* Returns image type definitions
*
* @param string|null Image type
* @return array Image type definitions
*/
static public function getImagesTypes($type = NULL)
{
if (!isset(self::$images_types_cache[$type]))
{
if (!empty($type))
$where = 'WHERE ' . pSQL($type) . ' = 1 ';
else
$where = '';
$query = 'SELECT * FROM `'._DB_PREFIX_.'image_type`'.$where.'ORDER BY `name` ASC';
self::$images_types_cache[$type] = Db::getInstance()->ExecuteS($query);
}
return self::$images_types_cache[$type];
}
/**
* Check if type already is already registered in database
*
* @param string $typeName Name
* @return integer Number of results found
*/
static public function typeAlreadyExists($typeName)
{
if (!Validate::isImageTypeName($typeName))
die(Tools::displayError());
$result = Db::getInstance()->ExecuteS('
SELECT `id_image_type`
FROM `'._DB_PREFIX_.'image_type`
WHERE `name` = \''.pSQL($typeName).'\'');
return Db::getInstance()->NumRows();
}
/**
* Finds image type definition by name and type
* @param string $name
* @param string $type
*/
static public function getByNameNType($name, $type)
{
return Db::getInstance()->getRow('SELECT `id_image_type`, `name`, `width`, `height`, `products`, `categories`, `manufacturers`, `suppliers`, `scenes` FROM `'._DB_PREFIX_.'image_type` WHERE `name` = \''.pSQL($name).'\' AND `'.pSQL($type).'` = 1');
}
}
+93
View File
@@ -0,0 +1,93 @@
<?php
/**
* ImportModule class, ImportModule.php
* Import module management
* @category classes
*
* @author PrestaShop <support@prestashop.com>
* @copyright PrestaShop
* @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
* @version 1.4
*
*/
abstract class ImportModuleCore extends Module
{
protected $_link = NULL;
public $server;
public $user;
public $passwd;
public $database;
/** @var string Prefix database */
public $prefix;
public function __destruct()
{
if($this->_link)
@mysql_close($this->_link);
}
protected function initDatabaseConnection()
{
if ($this->_link != NULL)
return $this->_link;
if ($this->_link = mysql_connect($this->server, $this->user, $this->passwd, true))
{
if(!mysql_select_db($this->database, $this->_link))
die(Tools::displayError('The database selection cannot be made.'));
if (!mysql_query('SET NAMES \'utf8\'', $this->_link))
die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
}
else
die(Tools::displayError('Link to database cannot be established.'));
return $this->_link;
}
public function ExecuteS($query)
{
$this->initDatabaseConnection();
$result = mysql_query($query, $this->_link);
$resultArray = array();
if ($result !== true)
while ($row = mysql_fetch_assoc($result))
$resultArray[] = $row;
return $resultArray;
}
public function Execute($query)
{
$this->initDatabaseConnection();
return mysql_query($query, $this->_link);
}
public function getValue($query)
{
$this->initDatabaseConnection();
$result = $this->ExecuteS($query);
if (!sizeof($result))
return 0;
else
return array_shift($result[0]);
}
public static function getImportModulesOnDisk ()
{
$modules = Module::getModulesOnDisk(true);
foreach ($modules as $key => $module)
if(get_parent_class($module) != 'ImportModule')
unset($modules[$key]);
return $modules;
}
abstract public function getDefaultIdLang();
}
?>
+655
View File
@@ -0,0 +1,655 @@
<?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
*/
class LanguageCore extends ObjectModel
{
public $id;
/** @var string Name */
public $name;
/** @var string 2-letter iso code */
public $iso_code;
/** @var string 5-letter iso code */
public $language_code;
/** @var boolean Status */
public $active = true;
protected $fieldsRequired = array('name', 'iso_code');
protected $fieldsSize = array('name' => 32, 'iso_code' => 2, 'language_code' => 5);
protected $fieldsValidate = array('name' => 'isGenericName', 'iso_code' => 'isLanguageIsoCode', 'language_code' => 'isLanguageCode', 'active' => 'isBool');
protected $table = 'lang';
protected $identifier = 'id_lang';
/** @var array Languages cache */
protected static $_checkedLangs;
protected static $_LANGUAGES;
protected static $countActiveLanguages;
protected $webserviceParameters = array(
'objectNodeName' => 'language',
'objectsNodeName' => 'languages',
);
public function __construct($id = NULL, $id_lang = NULL)
{
parent::__construct($id);
}
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
$fields['iso_code'] = pSQL(strtolower($this->iso_code));
$fields['language_code'] = pSQL(strtolower($this->language_code));
if (empty($fields['language_code']))
$fields['language_code'] = $fields['iso_code'];
$fields['active'] = (int)($this->active);
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
if (!parent::add($autodate))
return false;
$translationsFiles = array(
'fields' => '_FIELDS',
'errors' => '_ERRORS',
'admin' => '_LANGADM',
'pdf' => '_LANGPDF',
);
if (!file_exists(_PS_TRANSLATIONS_DIR_.$this->iso_code))
mkdir(_PS_TRANSLATIONS_DIR_.$this->iso_code);
foreach ($translationsFiles as $file => $var)
if (!file_exists(_PS_TRANSLATIONS_DIR_.$this->iso_code.'/'.$file.'.php'))
file_put_contents(_PS_TRANSLATIONS_DIR_.$this->iso_code.'/'.$file.'.php', '<?php
global $'.$var.';
$'.$var.' = array();
?>');
$resUpdateSQL = $this->loadUpdateSQL();
// If url_rewrite is not enabled, we don't need to regenerate .htaccess
if(!Configuration::get('PS_REWRITING_SETTINGS'))
return $resUpdateSQL;
return ($resUpdateSQL AND Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
));
}
public function toggleStatus()
{
if (!parent::toggleStatus())
return false;
// If url_rewrite is not enabled, we don't need to regenerate .htaccess
if(!Configuration::get('PS_REWRITING_SETTINGS'))
return true;
return (Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
));
}
public function checkFiles()
{
return self::checkFilesWithIsoCode($this->iso_code);
}
/**
* This functions checks if every files exists for the language $iso_code.
* Concerned files are theses located in translations/$iso_code/
* and translations/mails/$iso_code .
*
* @param mixed $iso_code
* @returntrue if all files exists
*/
public static function checkFilesWithIsoCode($iso_code)
{
if (isset(self::$_checkedLangs[$iso_code]) AND self::$_checkedLangs[$iso_code])
return true;
foreach (self::getFilesList($iso_code, _THEME_NAME_, false, false, false, true) as $key => $file)
if (!file_exists($key))
return false;
self::$_checkedLangs[$iso_code] = true;
return true;
}
public static function getFilesList($iso_from, $theme_from, $iso_to = false, $theme_to = false, $select = false, $check = false, $modules = false)
{
if (empty($iso_from))
die(Tools::displayError());
$copy = ($iso_to AND $theme_to) ? true : false;
$lPath_from = _PS_TRANSLATIONS_DIR_.(string)$iso_from.'/';
$tPath_from = _PS_ROOT_DIR_.'/themes/'.(string)$theme_from.'/';
$mPath_from = _PS_MAIL_DIR_.(string)$iso_from.'/';
if ($copy)
{
$lPath_to = _PS_TRANSLATIONS_DIR_.(string)$iso_to.'/';
$tPath_to = _PS_ROOT_DIR_.'/themes/'.(string)$theme_to.'/';
$mPath_to = _PS_MAIL_DIR_.(string)$iso_to.'/';
}
$lFiles = array('admin'.'.php', 'errors'.'.php', 'fields'.'.php', 'pdf'.'.php');
$mFiles = array(
'account.html', 'account.txt',
'bankwire.html', 'bankwire.txt',
'cheque.html', 'cheque.txt',
'contact.html', 'contact.txt',
'contact_form.html', 'contact_form.txt',
'credit_slip.html', 'credit_slip.txt',
'download_product.html', 'download_product.txt',
'download-product.tpl',
'employee_password.html', 'employee_password.txt',
'forward_msg.html', 'forward_msg.txt',
'guest_to_customer.html', 'guest_to_customer.txt',
'in_transit.html', 'in_transit.txt',
'newsletter.html', 'newsletter.txt',
'order_canceled.html', 'order_canceled.txt',
'order_conf.html', 'order_conf.txt',
'order_customer_comment.html', 'order_customer_comment.txt',
'order_merchant_comment.html', 'order_merchant_comment.txt',
'order_return_state.html', 'order_return_state.txt',
'outofstock.html', 'outofstock.txt',
'password.html', 'password.txt',
'password_query.html', 'password_query.txt',
'payment.html', 'payment.txt',
'payment_error.html', 'payment_error.txt',
'preparation.html', 'preparation.txt',
'refund.html', 'refund.txt',
'reply_msg.html', 'reply_msg.txt',
'shipped.html', 'shipped.txt',
'test.html', 'test.txt',
'voucher.html', 'voucher.txt',
);
$number = -1;
$files = array();
$files_tr = array();
$files_theme = array();
$files_mail = array();
$files_modules = array();
// When a copy is made from a theme in specific language
// to an other theme for the same language,
// it's avoid to copy Translations, Mails files
// and modules files which are not override by theme.
if (!$copy OR $iso_from != $iso_to)
{
// Translations files
if (!$check OR ($check AND (string)$iso_from != 'en'))
foreach ($lFiles as $file)
$files_tr[$lPath_from.$file] = ($copy ? $lPath_to.$file : ++$number);
if ($select == 'tr')
return $files_tr;
$files = array_merge($files, $files_tr);
// Mail files
if (!$check OR ($check AND (string)$iso_from != 'en'))
$files_mail[$mPath_from.'lang.php'] = ($copy ? $mPath_to.'lang.php' : ++$number);
foreach ($mFiles as $file)
$files_mail[$mPath_from.$file] = ($copy ? $mPath_to.$file : ++$number);
if ($select == 'mail')
return $files_mail;
$files = array_merge($files, $files_mail);
// Modules
if ($modules)
{
$modList = Module::getModulesDirOnDisk();
foreach ($modList as $k => $mod)
{
$modDir = _PS_MODULE_DIR_.$mod;
// Lang file
if (file_exists($modDir.'/'.(string)$iso_from.'.php'))
$files_modules[$modDir.'/'.(string)$iso_from.'.php'] = ($copy ? $modDir.'/'.(string)$iso_to.'.php' : ++$number);
// Mails files
$modMailDirFrom = $modDir.'/mails/'.(string)$iso_from;
$modMailDirTo = $modDir.'/mails/'.(string)$iso_to;
if (file_exists($modMailDirFrom))
{
$dirFiles = scandir($modMailDirFrom);
foreach ($dirFiles as $file)
if (file_exists($modMailDirFrom.'/'.$file) AND $file != '.' AND $file != '..' AND $file != '.svn')
$files_modules[$modMailDirFrom.'/'.$file] = ($copy ? $modMailDirTo.'/'.$file : ++$number);
}
}
if ($select == 'modules')
return $files_modules;
$files = array_merge($files, $files_modules);
}
}
else if ($select == 'mail' OR $select == 'tr')
{
return $files;
}
// Theme files
if (!$check OR ($check AND (string)$iso_from != 'en'))
{
$files_theme[$tPath_from.'lang/'.(string)$iso_from.'.php'] = ($copy ? $tPath_to.'lang/'.(string)$iso_to.'.php' : ++$number);
$module_theme_files = (file_exists($tPath_from.'modules/') ? scandir($tPath_from.'modules/') : array());
foreach ($module_theme_files as $module)
if ($module !== '.' AND $module != '..' AND $module !== '.svn' AND file_exists($tPath_from.'modules/'.$module.'/'.(string)$iso_from.'.php'))
$files_theme[$tPath_from.'modules/'.$module.'/'.(string)$iso_from.'.php'] = ($copy ? $tPath_to.'modules/'.$module.'/'.(string)$iso_to.'.php' : ++$number);
}
if ($select == 'theme')
return $files_theme;
$files = array_merge($files, $files_theme);
// Return
return $files;
}
/**
* loadUpdateSQL will create default lang values when you create a new lang, based on default id lang
*
* @return boolean true if succeed
*/
public function loadUpdateSQL()
{
$tables = Db::getInstance()->ExecuteS('SHOW TABLES LIKE \''._DB_PREFIX_.'%_lang\' ');
$langTables = array();
foreach($tables as $table)
foreach($table as $t)
$langTables[] = $t;
Db::getInstance()->Execute('SET @id_lang_default = (SELECT c.`value` FROM `'._DB_PREFIX_.'configuration` c WHERE c.`name` = \'PS_LANG_DEFAULT\' LIMIT 1)');
$return = true;
foreach($langTables as $name)
{
$fields = '';
$columns = Db::getInstance()->ExecuteS('SHOW COLUMNS FROM `'.$name.'`');
foreach($columns as $column)
$fields .= $column['Field'].', ';
$fields = rtrim($fields, ', ');
$identifier = 'id_'.str_replace('_lang', '', str_replace(_DB_PREFIX_, '', $name));
$sql = 'INSERT IGNORE INTO `'.$name.'` ('.$fields.') (SELECT ';
foreach($columns as $column) {
if ($identifier != $column['Field'] and $column['Field'] != 'id_lang')
$sql .= '(SELECT `'.$column['Field'].'` FROM `'.$name.'` tl WHERE tl.`id_lang` = @id_lang_default AND tl.`'.$identifier.'` = `'.str_replace('_lang', '', $name).'`.`'.$identifier.'`), ';
else
$sql.= '`'.$column['Field'].'`, ';
}
$sql = rtrim($sql, ', ');
$sql .= ' FROM `'._DB_PREFIX_.'lang` CROSS JOIN `'.str_replace('_lang', '', $name).'`) ;';
$return &= Db::getInstance()->Execute(pSQL($sql));
}
return $return;
}
public static function recurseDeleteDir($dir)
{
if (!is_dir($dir))
return false;
if ($handle = @opendir($dir))
{
while (false !== ($file = readdir($handle)))
if ($file != '.' && $file != '..')
{
if (is_dir($dir.'/'.$file))
self::recurseDeleteDir($dir.'/'.$file);
elseif (file_exists($dir.'/'.$file))
@unlink($dir.'/'.$file);
}
closedir($handle);
}
rmdir($dir);
}
public function delete()
{
if (empty($this->iso_code))
$this->iso_code = self::getIsoById($this->id);
// Database translations deletion
$result = Db::getInstance()->ExecuteS('SHOW TABLES FROM `'._DB_NAME_.'`');
foreach ($result AS $row)
if (preg_match('/_lang/', $row['Tables_in_'._DB_NAME_]))
if (!Db::getInstance()->Execute('DELETE FROM `'.$row['Tables_in_'._DB_NAME_].'` WHERE `id_lang` = '.(int)($this->id)))
return false;
// Delete tags
Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'tag WHERE id_lang = '.(int)($this->id));
// Delete search words
Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'search_word WHERE id_lang = '.(int)($this->id));
// Files deletion
foreach (self::getFilesList($this->iso_code, _THEME_NAME_, false, false, false, true, true) as $key => $file)
if (file_exists($key))
unlink($key);
$modList = scandir(_PS_MODULE_DIR_);
foreach ($modList as $k => $mod)
{
self::recurseDeleteDir(_PS_MODULE_DIR_.$mod.'/mails/'.$this->iso_code);
$files = @scandir(_PS_MODULE_DIR_.$mod.'/mails/');
if (count($files) <= 2)
self::recurseDeleteDir(_PS_MODULE_DIR_.$mod.'/mails/');
if(file_exists(_PS_MODULE_DIR_.$mod.'/'.$this->iso_code.'.php'))
{
$return = unlink(_PS_MODULE_DIR_.$mod.'/'.$this->iso_code.'.php');
$files = @scandir(_PS_MODULE_DIR_.$mod);
if (count($files) <= 2)
self::recurseDeleteDir(_PS_MODULE_DIR_.$mod);
}
}
if (file_exists(_PS_MAIL_DIR_.$this->iso_code))
self::recurseDeleteDir(_PS_MAIL_DIR_.$this->iso_code);
if (file_exists(_PS_TRANSLATIONS_DIR_.$this->iso_code))
self::recurseDeleteDir(_PS_TRANSLATIONS_DIR_.$this->iso_code);
if (!parent::delete())
return false;
// delete images
$files_copy = array('/en.jpg', '/en-default-thickbox.jpg', '/en-default-home.jpg', '/en-default-large.jpg', '/en-default-medium.jpg', '/en-default-small.jpg', '/en-default-large_scene.jpg');
$tos = array(_PS_CAT_IMG_DIR_, _PS_MANU_IMG_DIR_, _PS_PROD_IMG_DIR_, _PS_SUPP_IMG_DIR_);
foreach($tos AS $to)
foreach($files_copy AS $file)
{
$name = str_replace('/en', ''.$this->iso_code, $file);
if (file_exists($to.$name))
unlink($to.$name);
if (file_exists(dirname(__FILE__).'/../img/l/'.$this->id.'.jpg'))
unlink(dirname(__FILE__).'/../img/l/'.$this->id.'.jpg');
}
// If url_rewrite is not enabled, we don't need to regenerate .htaccess
if(!Configuration::get('PS_REWRITING_SETTINGS'))
return true;
return Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
}
public function deleteSelection($selection)
{
if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$result = true;
foreach ($selection AS $id)
{
$this->id = (int)($id);
$result = $result AND $this->delete();
}
// If url_rewrite is not enabled, we don't need to regenerate .htaccess
if(!Configuration::get('PS_REWRITING_SETTINGS'))
return true;
Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
return $result;
}
/**
* Return available languages
*
* @param boolean $active Select only active languages
* @return array Languages
*/
public static function getLanguages($active = true, $id_shop = false)
{
if (!self::$_LANGUAGES)
self::loadLanguages();
$languages = array();
$languages = array();
foreach (self::$_LANGUAGES AS $language)
{
if ($active AND !$language['active'] OR ($id_shop AND !isset($language['shops'][(int)$id_shop])))
continue;
$languages[] = $language;
}
return $languages;
}
public static function getLanguage($id_lang)
{
if (!array_key_exists((int)($id_lang), self::$_LANGUAGES))
return false;
return self::$_LANGUAGES[(int)($id_lang)];
}
/**
* Return iso code from id
*
* @param integer $id_lang Language ID
* @return string Iso code
*/
public static function getIsoById($id_lang)
{
if (isset(self::$_LANGUAGES[(int)$id_lang]['iso_code']))
return self::$_LANGUAGES[(int)$id_lang]['iso_code'];
return false;
}
/**
* Return id from iso code
*
* @param string $iso_code Iso code
* @return integer Language ID
*/
public static function getIdByIso($iso_code)
{
if (!Validate::isLanguageIsoCode($iso_code))
die(Tools::displayError('Fatal error : iso code is not correct : ').$iso_code);
return Db::getInstance()->getValue('SELECT `id_lang` FROM `'._DB_PREFIX_.'lang` WHERE `iso_code` = \''.pSQL(strtolower($iso_code)).'\'');
}
public static function getLanguageCodeByIso($iso_code)
{
if (!Validate::isLanguageIsoCode($iso_code))
die(Tools::displayError('Fatal error : iso code is not correct : ').$iso_code);
return Db::getInstance()->getValue('SELECT `language_code` FROM `'._DB_PREFIX_.'lang` WHERE `iso_code` = \''.pSQL(strtolower($iso_code)).'\'');
}
/**
* Return array (id_lang, iso_code)
*
* @param string $iso_code Iso code
* @return array Language (id_lang, iso_code)
*/
public static function getIsoIds($active = true)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT `id_lang`, `iso_code` FROM `'._DB_PREFIX_.'lang` '.($active ? 'WHERE active = 1' : ''));
}
public static function copyLanguageData($from, $to)
{
$result = Db::getInstance()->ExecuteS('SHOW TABLES FROM `'._DB_NAME_.'`');
foreach ($result AS $row)
if (preg_match('/_lang/', $row['Tables_in_'._DB_NAME_]) AND $row['Tables_in_'._DB_NAME_] != _DB_PREFIX_.'lang')
{
$result2 = Db::getInstance()->ExecuteS('SELECT * FROM `'.$row['Tables_in_'._DB_NAME_].'` WHERE `id_lang` = '.(int)($from));
if (!sizeof($result2))
continue;
Db::getInstance()->Execute('DELETE FROM `'.$row['Tables_in_'._DB_NAME_].'` WHERE `id_lang` = '.(int)($to));
$query = 'INSERT INTO `'.$row['Tables_in_'._DB_NAME_].'` VALUES ';
foreach ($result2 AS $row2)
{
$query .= '(';
$row2['id_lang'] = $to;
foreach ($row2 AS $field)
$query .= '\''.pSQL($field, true).'\',';
$query = rtrim($query, ',').'),';
}
$query = rtrim($query, ',');
Db::getInstance()->Execute($query);
}
return true;
}
/**
* Load all languages in memory for caching
*/
public static function loadLanguages()
{
self::$_LANGUAGES = array();
$result = Db::getInstance()->ExecuteS('
SELECT l.`id_lang`, l.`name`, l.`iso_code`, l.`active`, ls.`id_shop`
FROM `'._DB_PREFIX_.'lang` l
LEFT JOIN `'._DB_PREFIX_.'lang_shop` ls ON (l.id_lang = ls.id_lang)');
foreach ($result AS $row)
{
if (!isset(self::$_LANGUAGES[(int)$row['id_lang']]))
self::$_LANGUAGES[(int)$row['id_lang']] = array('id_lang' => (int)$row['id_lang'],
'name' => $row['name'],
'iso_code' => $row['iso_code'],
'active' => (int)$row['active'],);
self::$_LANGUAGES[(int)$row['id_lang']]['shops'][(int)$row['id_shop']] = true;
}
}
public function update($nullValues = false)
{
if (!parent::update($nullValues))
return false;
// If url_rewrite is not enabled, we don't need to regenerate .htaccess
if(!Configuration::get('PS_REWRITING_SETTINGS'))
return true;
return Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
}
public static function checkAndAddLanguage($iso_code)
{
if (Language::getIdByIso($iso_code))
return true;
else
{
if(@fsockopen('www.prestashop.com', 80))
{
$lang = new Language();
$lang->iso_code = $iso_code;
$lang->active = true;
if ($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version='._PS_VERSION_.'&iso_lang='.$iso_code)))
{
if (isset($lang_pack->name)
&& isset($lang_pack->version)
&& isset($lang_pack->iso_code))
$lang->name = $lang_pack->name;
}
if (!$lang->name OR !$lang->add())
return false;
$insert_id = (int)($lang->id);
if ($lang_pack)
{
$flag = Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/flags/jpeg/'.$iso_code.'.jpg');
if ($flag != NULL && !preg_match('/<body>/', $flag))
{
$file = fopen(dirname(__FILE__).'/../img/l/'.$insert_id.'.jpg', 'w');
if ($file)
{
fwrite($file, $flag);
fclose($file);
}
else
self::_copyNoneFlag($insert_id);
}
else
self::_copyNoneFlag($insert_id);
}
else
self::_copyNoneFlag($insert_id);
$files_copy = array('/en.jpg', '/en-default-thickbox.jpg', '/en-default-home.jpg', '/en-default-large.jpg', '/en-default-medium.jpg', '/en-default-small.jpg', '/en-default-large_scene.jpg');
$tos = array(_PS_CAT_IMG_DIR_, _PS_MANU_IMG_DIR_, _PS_PROD_IMG_DIR_, _PS_SUPP_IMG_DIR_);
foreach($tos AS $to)
foreach($files_copy AS $file)
{
$name = str_replace('/en', '/'.$iso_code, $file);
copy(dirname(__FILE__).'/../img/l'.$file, $to.$name);
}
return true;
}
else
return false;
}
}
protected static function _copyNoneFlag($id)
{
return copy(dirname(__FILE__).'/../img/l/none.jpg', dirname(__FILE__).'/../img/l/'.$id.'.jpg');
}
private static $_cache_language_installation = null;
public static function isInstalled($iso_code)
{
if (self::$_cache_language_installation === null)
{
self::$_cache_language_installation = array();
$result = Db::getInstance()->ExecuteS('SELECT `id_lang`, `iso_code` FROM `'._DB_PREFIX_.'lang`');
foreach ($result as $row)
self::$_cache_language_installation[$row['iso_code']] = $row['id_lang'];
}
return (isset(self::$_cache_language_installation[$iso_code]) ? self::$_cache_language_installation[$iso_code] : false);
}
public static function countActiveLanguages()
{
if (!self::$countActiveLanguages)
self::$countActiveLanguages = Db::getInstance()->getValue('SELECT COUNT(*) FROM `'._DB_PREFIX_.'lang` WHERE `active` = 1');
return self::$countActiveLanguages;
}
}
+365
View File
@@ -0,0 +1,365 @@
<?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: 7465 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class LinkCore
{
/** @var boolean Rewriting activation */
protected $allow;
protected $url;
public static $cache = array('page' => array());
/**
* Constructor (initialization only)
*/
public function __construct()
{
$this->allow = (int)Configuration::get('PS_REWRITING_SETTINGS');
$this->url = $_SERVER['SCRIPT_NAME'];
}
/**
* This function returns a link to delete a customization picture file
*
* @param mixed $product
* @param mixed $id_picture
* @return void
*/
public function getProductDeletePictureLink($product, $id_picture){
if (is_object($product))
return ($this->allow == 1)?(_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink().((isset($product->category) AND !empty($product->category) AND $product->category != 'home') ? $product->category.'/' : '').(int)$product->id.'-'.$product->link_rewrite.($product->ean13 ? '-'.$product->ean13 : '').'.html?deletePicture='.$id_picture) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=product&id_product='.(int)$product->id).'&amp;deletePicture='.$id_picture;
else
return _PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=product&id_product='.(int)$product.'&amp;deletePicture='.$id_picture;
}
/**
* Return the correct link for product/category/supplier/manufacturer
*
* @param mixed $id_OBJ Can be either the object or the ID only
* @param string $alias Friendly URL (only if $id_OBJ is the object)
* @return string link
*/
public function getProductLink($id_product, $alias = NULL, $category = NULL, $ean13 = NULL, $id_lang = NULL)
{
if (is_object($id_product))
return ($this->allow == 1)?(_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)$id_lang).((isset($id_product->category) AND !empty($id_product->category) AND $id_product->category != 'home') ? $id_product->category.'/' : '').(int)$id_product->id.'-'.$id_product->link_rewrite.($id_product->ean13 ? '-'.$id_product->ean13 : '').'.html') :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=product&id_product='.(int)$id_product->id);
elseif ($alias)
return ($this->allow == 1)?(_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)$id_lang).(($category AND $category != 'home') ? ($category.'/') : '').(int)$id_product.'-'.$alias.($ean13 ? '-'.$ean13 : '').'.html') :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=product&id_product='.(int)$id_product);
else
return _PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=product&id_product='.(int)$id_product;
}
public function getCategoryLink($id_category, $alias = NULL, $id_lang = NULL)
{
if (is_object($id_category))
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).(int)($id_category->id).'-'.$id_category->link_rewrite) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=category&id_category='.(int)($id_category->id));
if ($alias)
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).(int)($id_category).'-'.$alias) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=category&id_category='.(int)($id_category));
return _PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=category&id_category='.(int)($id_category);
}
public function getCMSCategoryLink($id_category, $alias = NULL, $id_lang = NULL)
{
if (is_object($id_category))
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).'content/category/'.(int)($id_category->id).'-'.$id_category->link_rewrite) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=cms&id_cms_category='.(int)($id_category->id));
if ($alias)
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).'content/category/'.(int)($id_category).'-'.$alias) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=cms&id_cms_category='.(int)($id_category));
return _PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=cms&id_cms_category='.(int)($id_category);
}
public function getCMSLink($cms, $alias = null, $ssl = false, $id_lang = NULL)
{
$base = (($ssl AND Configuration::get('PS_SSL_ENABLED')) ? Tools::getShopDomainSsl(true) : Tools::getShopDomain(true));
if (is_object($cms))
{
return ($this->allow == 1) ?
($base.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).'content/'.(int)($cms->id).'-'.$cms->link_rewrite) :
($base.__PS_BASE_URI__.'index.php?controller=cms&id_cms='.(int)($cms->id));
}
if ($alias)
return ($this->allow == 1) ? ($base.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).'content/'.(int)($cms).'-'.$alias) :
($base.__PS_BASE_URI__.'index.php?controller=cms&id_cms='.(int)($cms));
return $base.__PS_BASE_URI__.'index.php?controller=cms&id_cms='.(int)($cms);
}
public function getSupplierLink($id_supplier, $alias = NULL, $id_lang = NULL)
{
if (is_object($id_supplier))
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).(int)($id_supplier->id).'__'.$id_supplier->link_rewrite) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=supplier&id_supplier='.(int)($id_supplier->id));
if ($alias)
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).(int)($id_supplier).'__'.$alias) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=supplier&id_supplier='.(int)($id_supplier));
return _PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=supplier&id_supplier='.(int)($id_supplier);
}
public function getManufacturerLink($id_manufacturer, $alias = NULL, $id_lang = NULL)
{
if (is_object($id_manufacturer))
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).(int)($id_manufacturer->id).'_'.$id_manufacturer->link_rewrite) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=manufacturer&id_manufacturer='.(int)($id_manufacturer->id));
if ($alias)
return ($this->allow == 1) ? (_PS_BASE_URL_.__PS_BASE_URI__.$this->getLangLink((int)($id_lang)).(int)($id_manufacturer).'_'.$alias) :
(_PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=manufacturer&id_manufacturer='.(int)($id_manufacturer));
return _PS_BASE_URL_.__PS_BASE_URI__.'index.php?controller=manufacturer&id_manufacturer='.(int)($id_manufacturer);
}
/**
* Returns a link to a product image for display
* Note: the new image filesystem stores product images in subdirectories of img/p/
*
* @param string $name rewrite link of the image
* @param string $ids id part of the image filename - can be "id_product-id_image" (legacy support, recommended) or "id_image" (new)
* @param string $type
*/
public function getImageLink($name, $ids, $type = NULL)
{
global $protocol_content;
// legacy mode
if (Configuration::get('PS_LEGACY_IMAGES')
&& (file_exists(_PS_PROD_IMG_DIR_.$ids.($type ? '-'.$type : '').'.jpg')))
{
if ($this->allow == 1)
$uri_path = __PS_BASE_URI__.$ids.($type ? '-'.$type : '').'/'.$name.'.jpg';
else
$uri_path = _THEME_PROD_DIR_.$ids.($type ? '-'.$type : '').'.jpg';
}else
{
// if ids if of the form id_product-id_image, we want to extract the id_image part
$split_ids = explode('-', $ids);
$id_image = (isset($split_ids[1]) ? $split_ids[1] : $split_ids[0]);
if ($this->allow == 1)
$uri_path = __PS_BASE_URI__.$id_image.($type ? '-'.$type : '').'/'.$name.'.jpg';
else
$uri_path = _THEME_PROD_DIR_.Image::getImgFolderStatic($id_image).$id_image.($type ? '-'.$type : '').'.jpg';
}
return $protocol_content.Tools::getMediaServer($uri_path).$uri_path;
}
public function getMediaLink($filepath)
{
return Tools::getProtocol().Tools::getMediaServer($filepath).$filepath;
}
public function preloadPageLinks()
{
global $cookie;
if ($this->allow != 1)
return;
$result = Db::getInstance()->ExecuteS('
SELECT page, url_rewrite
FROM `'._DB_PREFIX_.'meta` m
LEFT JOIN `'._DB_PREFIX_.'meta_lang` ml ON (m.id_meta = ml.id_meta)
WHERE id_lang = '.(int)$cookie->id_lang);
foreach ($result as $row)
self::$cache['page'][$row['page'].'.php_'.$cookie->id_lang] = $this->getLangLink((int)$cookie->id_lang).$row['url_rewrite'];
}
public function getPageLink($filename, $ssl = false, $id_lang = NULL, $request = NULL)
{
global $cookie;
if ($id_lang == NULL)
$id_lang = (int)($cookie->id_lang);
if (array_key_exists($filename.'_'.$id_lang, self::$cache['page']) AND !empty(self::$cache['page'][$filename.'_'.$id_lang]))
$uri_path = self::$cache['page'][$filename.'_'.$id_lang];
else
{
if ($this->allow == 1)
{
$url_rewrite = '';
if ($filename != 'index')
{
$pagename = $filename;
$url_rewrite = Db::getInstance()->getValue('
SELECT url_rewrite
FROM `'._DB_PREFIX_.'meta` m
LEFT JOIN `'._DB_PREFIX_.'meta_lang` ml ON (m.id_meta = ml.id_meta)
WHERE id_lang = '.(int)$id_lang.' AND `page` = \''.pSQL($pagename).'\'');
$uri_path = $this->getLangLink((int)$id_lang).($url_rewrite ? $url_rewrite : $filename);
}
else
$uri_path = $this->getLangLink((int)$id_lang);
}
else
{
$uri_path = '';
if ($filename != 'index.php')
$uri_path = 'index.php?controller='.str_replace('.php', '', $filename);
}
self::$cache['page'][$filename.'_'.$id_lang] = $uri_path;
}
return (($ssl AND Configuration::get('PS_SSL_ENABLED')) ? Tools::getShopDomainSsl(true) : Tools::getShopDomain(true)).__PS_BASE_URI__.ltrim($uri_path, '/').($request ? (($this->allow ? '?' : '&').trim($request)) : '');
}
public function getCatImageLink($name, $id_category, $type = null)
{
return ($this->allow == 1) ? (__PS_BASE_URI__.'c/'.$id_category.($type ? '-'.$type : '').'/'.$name.'.jpg') : (_THEME_CAT_DIR_.$id_category.($type ? '-'.$type : '').'.jpg');
}
/**
* Create link after language change, for the change language block
*
* @param integer $id_lang Language ID
* @return string link
*/
public function getLanguageLink($id_lang)
{
global $cookie;
$matches = array();
$request = $_SERVER['REQUEST_URI'];
preg_match('#^/([a-z]{2})/([^\?]*).*$#', $request, $matches);
if ($matches)
{
$current_iso = $matches[1];
$rewrite = $matches[2];
$url_rewrite = Meta::getEquivalentUrlRewrite($id_lang, Language::getIdByIso($current_iso), $rewrite);
$request = str_replace($rewrite, $url_rewrite, $request);
}
$queryTab = array();
parse_str($_SERVER['QUERY_STRING'], $queryTab);
unset($queryTab['isolang']);
$query = http_build_query($queryTab);
if (!empty($query) OR !$this->allow)
$query = '?'.$query;
$switchLangLink = $this->getPageLink(substr($_SERVER['PHP_SELF'], strlen(__PS_BASE_URI__)), false, $id_lang).$query;
if (!$this->allow)
if ($id_lang != $cookie->id_lang)
{
if (strpos($switchLangLink,'id_lang'))
$switchLangLink = preg_replace('`id_lang=[0-9]*`','id_lang='.$id_lang,$switchLangLink);
else
$switchLangLink = $switchLangLink.'&amp;id_lang='.$id_lang;
}
return $switchLangLink;
}
/**
* @deprecated
*/
public function getLanguageLinkAdmin($id_lang)
{
Tools::displayAsDeprecated();
return $this->getUrlWith('id_lang', (int)($id_lang));
}
/**
* This function return the current url with a new parameter key=value
* @param mixed $key
* @param mixed $val
* @return url with &key=val (or ?key=val)
* @deprectated
*/
public function getUrlWith($key, $val)
{
// This function does not use rewrite
Tools::displayAsDeprecated();
$n = 0;
$url = str_replace('index.php', '', htmlentities($this->url, ENT_QUOTES, 'UTF-8'));
foreach ($_GET as $k => $value)
// adminlang is an hand-written param in BO
if ($k != 'adminlang')
if (!is_array($value) AND $k != $key AND Tools::isSubmit($k))
$url .= ((!$n++) ? '?' : '&amp;').urlencode($k).($value ? '='.urlencode($value) : '');
return $url.($n ? '&amp;' : '?').urlencode($key).'='.urlencode($val);
}
public function goPage($url, $p)
{
return $url.($p == 1 ? '' : (!strstr($url, '?') ? '?' : '&amp;').'p='.(int)($p));
}
public function getPaginationLink($type, $id_object, $nb = false, $sort = false, $pagination = false, $array = false)
{
if ($type AND $id_object)
$url = $this->{'get'.$type.'Link'}($id_object, NULL);
else
{
$url = $this->url;
if (Configuration::get('PS_REWRITING_SETTINGS'))
$url = $this->getPageLink(basename($url));
}
$vars = (!$array ? '' : array());
$varsNb = array('n', 'search_query');
$varsSort = array('orderby', 'orderway');
$varsPagination = array('p');
$n = 0;
foreach ($_GET AS $k => $value)
if ($k != 'id_'.$type)
{
if (Configuration::get('PS_REWRITING_SETTINGS') AND ($k == 'isolang' OR $k == 'id_lang'))
continue;
$ifNb = (!$nb OR ($nb AND !in_array($k, $varsNb)));
$ifSort = (!$sort OR ($sort AND !in_array($k, $varsSort)));
$ifPagination = (!$pagination OR ($pagination AND !in_array($k, $varsPagination)));
if ($ifNb AND $ifSort AND $ifPagination AND !is_array($value))
!$array ? ($vars .= ((!$n++ AND ($this->allow == 1 OR $url == $this->url)) ? '?' : '&').urlencode($k).'='.urlencode($value)) : ($vars[urlencode($k)] = urlencode($value));
}
if (!$array)
return $url.$vars;
$vars['requestUrl'] = $url;
if ($type AND $id_object)
$vars['id_'.$type] = (is_object($id_object) ? (int)$id_object->id : (int)$id_object);
return $vars;
}
public function addSortDetails($url, $orderby, $orderway)
{
return $url.(!strstr($url, '?') ? '?' : '&').'orderby='.urlencode($orderby).'&orderway='.urlencode($orderway);
}
protected function getLangLink($id_lang = NULL)
{
if (!$this->allow OR Language::countActiveLanguages() <= 1)
return '';
global $cookie;
if (!$id_lang)
$id_lang = (int)$cookie->id_lang;
return Language::getIsoById((int)$id_lang).'/';
}
}
+490
View File
@@ -0,0 +1,490 @@
<?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
*/
require_once(_PS_TOOL_DIR_.'tar/Archive_Tar.php');
class LocalizationPackCore
{
public $name;
public $version;
protected $iso_code_lang;
protected $iso_currency;
protected $_errors = array();
public function loadLocalisationPack($file, $selection, $install_mode = false)
{
if (!$xml = simplexml_load_string($file))
return false;
$mainAttributes = $xml->attributes();
$this->name = strval($mainAttributes['name']);
$this->version = strval($mainAttributes['version']);
if (empty($selection))
{
$res = true;
$res &= $this->_installStates($xml);
$res &= $this->_installTaxes($xml);
$res &= $this->_installCurrencies($xml, $install_mode);
$res &= $this->_installUnits($xml);
$res &= $this->installConfiguration($xml);
$res &= $this->installModules($xml);
$res &= $this->updateDefaultGroupDisplayMethod($xml);
if (!defined('_PS_MODE_DEV_') OR !_PS_MODE_DEV_)
$res &= $this->_installLanguages($xml, $install_mode);
if ($res AND isset($this->iso_code_lang))
Configuration::updateValue('PS_LANG_DEFAULT', (int)Language::getIdByIso($this->iso_code_lang));
if ($install_mode AND $res AND isset($this->iso_currency))
{
$res &= Configuration::updateValue('PS_CURRENCY_DEFAULT', (int)Currency::getIdByIsoCode($this->iso_currency));
Currency::refreshCurrencies();
}
return $res;
}
foreach ($selection AS $selected)
if (!Validate::isLocalizationPackSelection($selected) OR !$this->{'_install'.ucfirst($selected)}($xml))
return false;
return true;
}
protected function _installStates($xml)
{
if (isset($xml->states->state))
foreach ($xml->states->state AS $data)
{
$attributes = $data->attributes();
if (!$id_state = State::getIdByName($attributes['name']))
{
$state = new State();
$state->name = strval($attributes['name']);
$state->iso_code = strval($attributes['iso_code']);
$state->id_country = Country::getByIso(strval($attributes['country']));
$state->id_zone = (int)(Zone::getIdByName(strval($attributes['zone'])));
if (!$state->validateFields())
{
$this->_errors[] = Tools::displayError('Invalid state properties.');
return false;
}
$country = new Country($state->id_country);
if (!$country->contains_states)
{
$country->contains_states = 1;
if (!$country->update())
$this->_errors[] = Tools::displayError('Cannot update the associated country: ').$country->name;
}
if (!$state->add())
{
$this->_errors[] = Tools::displayError('An error occurred while adding the state.');
return false;
}
} else {
$state = new State($id_state);
if (!Validate::isLoadedObject($state))
{
$this->_errors[] = Tools::displayError('An error occurred while fetching the state.');
return false;
}
}
// Add counties
foreach ($data->county AS $xml_county)
{
$county_attributes = $xml_county->attributes();
if (!$id_county = County::getIdCountyByNameAndIdState($county_attributes['name'], $state->id))
{
$county = new County();
$county->name = $county_attributes['name'];
$county->id_state = (int)$state->id;
$county->active = 1;
if (!$county->validateFields())
{
$this->_errors[] = Tools::displayError('Invalid County properties');
return false;
}
if (!$county->save())
{
$this->_errors[] = Tools::displayError('An error has occurred while adding the county');
return false;
}
} else {
$county = new County((int)$id_county);
if (!Validate::isLoadedObject($county))
{
$this->_errors[] = Tools::displayError('An error occurred while fetching the county.');
return false;
}
}
// add zip codes
foreach ($xml_county->zipcode AS $xml_zipcode)
{
$zipcode_attributes = $xml_zipcode->attributes();
$zipcodes = $zipcode_attributes['from'];
if (isset($zipcode_attributes['to']))
$zipcodes .= '-'.$zipcode_attributes['to'];
if ($county->isZipCodeRangePresent($zipcodes))
continue;
if (!$county->addZipCodes($zipcodes))
{
$this->_errors[] = Tools::displayError('An error has occurred while adding zipcodes');
return false;
}
}
}
}
return true;
}
protected function _installTaxes($xml)
{
if (isset($xml->taxes->tax))
{
$available_behavior = array(PS_PRODUCT_TAX, PS_STATE_TAX, PS_BOTH_TAX);
$assoc_taxes = array();
foreach ($xml->taxes->tax AS $taxData)
{
$attributes = $taxData->attributes();
if (Tax::getTaxIdByName($attributes['name']))
continue;
$tax = new Tax();
$tax->name[(int)(Configuration::get('PS_LANG_DEFAULT'))] = strval($attributes['name']);
$tax->rate = (float)($attributes['rate']);
$tax->active = 1;
if (!$tax->validateFields())
{
$this->_errors[] = Tools::displayError('Invalid tax properties.');
return false;
}
if (!$tax->add())
{
$this->_errors[] = Tools::displayError('An error occurred while importing the tax: ').strval($attributes['name']);
return false;
}
$assoc_taxes[(int)$attributes['id']] = $tax->id;
}
foreach ($xml->taxes->taxRulesGroup AS $group)
{
$group_attributes = $group->attributes();
if (!Validate::isGenericName($group_attributes['name']))
continue;
if (TaxRulesGroup::getIdByName($group['name']))
continue;
$trg = new TaxRulesGroup();
$trg->name = $group['name'];
$trg->active = 1;
if (!$trg->save())
{
$this->_errors = Tools::displayError('This tax rule can\'t be saved.');
return false;
}
foreach($group->taxRule as $rule)
{
$rule_attributes = $rule->attributes();
// Validation
if (!isset($rule_attributes['iso_code_country']))
continue;
$id_country = Country::getByIso(strtoupper($rule_attributes['iso_code_country']));
if (!$id_country)
continue;
if (!isset($rule_attributes['id_tax']) || !array_key_exists(strval($rule_attributes['id_tax']), $assoc_taxes))
continue;
// Default values
$id_state = (int) isset($rule_attributes['iso_code_state']) ? State::getIdByIso(strtoupper($rule_attributes['iso_code_state'])) : 0;
$id_county = 0;
$state_behavior = 0;
$county_behavior = 0;
if ($id_state)
{
if (isset($rule_attributes['state_behavior']) && in_array($rule_attributes['state_behavior'], $available_behavior))
$state_behavior = (int)$rule_attributes['state_behavior'];
if (isset($rule_attributes['county_name']))
{
$id_county = County::getIdCountyByNameAndIdState($rule_attributes['county_name'], (int)$id_state);
if (!$id_county)
continue;
}
if (isset($rule_attributes['county_behavior']) && in_array($rule_attributes['state_behavior'], $available_behavior))
$county_behavior = (int)$rule_attributes['county_behavior'];
}
// Creation
$tr = new TaxRule();
$tr->id_tax_rules_group = $trg->id;
$tr->id_country = $id_country;
$tr->id_state = $id_state;
$tr->id_county = $id_county;
$tr->state_behavior = $state_behavior;
$tr->county_behavior = $county_behavior;
$tr->id_tax = $assoc_taxes[strval($rule_attributes['id_tax'])];
$tr->save();
}
}
}
return true;
}
protected function _installCurrencies($xml, $install_mode = false)
{
if (isset($xml->currencies->currency))
{
if (!$feed = @simplexml_load_file('http://www.prestashop.com/xml/currencies.xml') AND !$feed = @simplexml_load_file(dirname(__FILE__).'/../localization/currencies.xml'))
{
$this->_errors[] = Tools::displayError('Cannot parse the currencies XML feed.');
return false;
}
foreach ($xml->currencies->currency AS $data)
{
$attributes = $data->attributes();
if(Currency::exists($attributes['iso_code']))
continue;
$currency = new Currency();
$currency->name = strval($attributes['name']);
$currency->iso_code = strval($attributes['iso_code']);
$currency->iso_code_num = (int)($attributes['iso_code_num']);
$currency->sign = strval($attributes['sign']);
$currency->blank = (int)($attributes['blank']);
$currency->conversion_rate = 1; // This value will be updated if the store is online
$currency->format = (int)($attributes['format']);
$currency->decimals = (int)($attributes['decimals']);
$currency->active = $install_mode;
if (!$currency->validateFields())
{
$this->_errors[] = Tools::displayError('Invalid currency properties.');
return false;
}
if (!Currency::exists($currency->iso_code))
{
if (!$currency->add())
{
$this->_errors[] = Tools::displayError('An error occurred while importing the currency: ').strval($attributes['name']);
return false;
}
}
}
Currency::refreshCurrencies();
if (!sizeof($this->_errors) AND $install_mode AND isset($attributes['iso_code']) AND sizeof($xml->currencies->currency) == 1)
$this->iso_currency = $attributes['iso_code'];
}
return true;
}
protected function _installLanguages($xml, $install_mode = false)
{
$attributes = array();
if (isset($xml->languages->language))
foreach ($xml->languages->language AS $data)
{
$attributes = $data->attributes();
if (Language::getIdByIso($attributes['iso_code']))
continue;
$native_lang = Language::getLanguages();
$native_iso_code = array();
foreach ($native_lang AS $lang)
$native_iso_code[] = $lang['iso_code'];
if ((in_array((string)$attributes['iso_code'], $native_iso_code) AND !$install_mode) OR !in_array((string)$attributes['iso_code'], $native_iso_code))
if(@fsockopen('www.prestashop.com', 80, $errno = 0, $errstr = '', 10))
{
if ($lang_pack = Tools::jsonDecode(Tools::file_get_contents('http://www.prestashop.com/download/lang_packs/get_language_pack.php?version='._PS_VERSION_.'&iso_lang='.$attributes['iso_code'])))
{
if ($content = file_get_contents('http://www.prestashop.com/download/lang_packs/gzip/'.$lang_pack->version.'/'.$attributes['iso_code'].'.gzip'))
{
$file = _PS_TRANSLATIONS_DIR_.$attributes['iso_code'].'.gzip';
if (file_put_contents($file, $content))
{
$gz = new Archive_Tar($file, true);
if (!$gz->extract(_PS_TRANSLATIONS_DIR_.'../', false))
{
$this->_errors[] = Tools::displayError('Cannot decompress the translation file of the language: ').(string)$attributes['iso_code'];
return false;
}
if (!Language::checkAndAddLanguage((string)$attributes['iso_code']))
{
$this->_errors[] = Tools::displayError('An error occurred while creating the language: ').(string)$attributes['iso_code'];
return false;
}
@unlink($file);
}
else
$this->_errors[] = Tools::displayError('Server does not have permissions for writing.');
}
}
else
$this->_errors[] = Tools::displayError('Error occurred when language was checked according to your Prestashop version.');
}
else
$this->_errors[] = Tools::displayError('Archive cannot be downloaded from prestashop.com.');
}
// change the default language if there is only one language in the localization pack
if (!sizeof($this->_errors) AND $install_mode AND isset($attributes['iso_code']) AND sizeof($xml->languages->language) == 1)
$this->iso_code_lang = $attributes['iso_code'];
return true;
}
protected function _installUnits($xml)
{
$varNames = array('weight' => 'PS_WEIGHT_UNIT', 'volume' => 'PS_VOLUME_UNIT', 'short_distance' => 'PS_DIMENSION_UNIT', 'base_distance' => 'PS_BASE_DISTANCE_UNIT', 'long_distance' => 'PS_DISTANCE_UNIT');
if (isset($xml->units->unit))
foreach ($xml->units->unit AS $data)
{
$attributes = $data->attributes();
if (!isset($varNames[strval($attributes['type'])]))
{
$this->_errors[] = Tools::displayError('Pack corrupted: wrong unit type.');
return false;
}
if (!Configuration::updateValue($varNames[strval($attributes['type'])], strval($attributes['value'])))
{
$this->_errors[] = Tools::displayError('An error occurred while setting the units.');
return false;
}
}
return true;
}
/**
* Install/Uninstall a module from a localization file
* <modules>
* <module name="module_name" [install="0|1"] />
*/
protected function installModules($xml)
{
if (isset($xml->modules))
foreach($xml->modules->module as $data)
{
$attributes = $data->attributes();
$name = (string)$attributes['name'];
if (isset($name) && $module = Module::getInstanceByName($name))
{
$install = ($attributes['install'] == 1) ? true : false;
if ($install)
{
if (!Module::isInstalled($name))
if (!$module->install())
$this->_errors[] = Tools::displayError('An error has occured during the module installation: '). $name;
}
else
if (Module::isInstalled($name))
if (!$module->uninstall())
$this->_errors[] = Tools::displayError('An error has occured during the module uninstall: '). $name;
unset($module);
}
else
$this->_errors[] = Tools::displayError('An error has occured, this module doesnt exists: '). $name;
}
return true;
}
/**
* Update a configuration variable from a localization file
* <configuration>
* <configuration name="variable_name" value="variable_value" />
*/
protected function installConfiguration($xml)
{
if (isset($xml->configurations))
foreach($xml->configurations->configuration as $data)
{
$attributes = $data->attributes();
$name = (string)$attributes['name'];
if (isset($name) && isset($attributes['value']) && Configuration::get($name) !== false)
if (!Configuration::updateValue($name, (string)$attributes['value']))
$this->_errors[] = Tools::displayError('An error has occured during the configuration setup: '. $name);
}
return true;
}
protected function updateDefaultGroupDisplayMethod($xml)
{
if (isset($xml->group_default))
{
$attributes = $xml->group_default->attributes();
if (isset($attributes['price_display_method']) && in_array((int)$attributes['price_display_method'], array(0, 1)))
{
$group = new Group((int)_PS_DEFAULT_CUSTOMER_GROUP_);
$group->price_display_method = (int)$attributes['price_display_method'];
if (!$group->save())
$this->_errors[] = Tools::displayError('An error has occured during the default group update');
}
else
$this->_errors[] = Tools::displayError('An error has occured during the default group update');
}
return true;
}
public function getErrors()
{
return $this->_errors;
}
}
+161
View File
@@ -0,0 +1,161 @@
<?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 LoggerCore extends ObjectModel
{
/** @var integer Log id */
public $id_log;
/** @var integer Log severity */
public $severity;
/** @var integer Error code */
public $error_code;
/** @var string Message */
public $message;
/** @var string Object type (eg. Order, Customer...) */
public $object_type;
/** @var integer Object ID */
public $object_id;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $fieldsRequired = array('severity', 'message');
protected $fieldsSize = array();
protected $fieldsValidate = array('id_log' => 'isUnsignedId', 'severity' => 'isInt', 'error_code' => 'isUnsignedInt',
'message' => 'isMessage', 'object_id' => 'isUnsignedInt', 'object_type' => 'isName');
protected $table = 'log';
protected $identifier = 'id_log';
protected static $_is_present = array();
public function getFields()
{
parent::validateFields();
$fields['severity'] = intval($this->severity);
$fields['error_code'] = intval($this->error_code);
$fields['message'] = pSQL($this->message);
$fields['object_type'] = pSQL($this->object_type);
$fields['object_id'] = intval($this->object_id);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
static public function sendByMail($log)
{
/* Send e-mail to the shop owner only if the minimal severity level has been reached */
if (intval(Configuration::get('PS_LOGS_BY_EMAIL')) <= intval($log->severity))
Mail::Send((int)Configuration::get('PS_LANG_DEFAULT'), 'log_alert', Mail::l('Log: You have a new alert from your shop'), array(), Configuration::get('PS_SHOP_EMAIL'));
}
/**
* add a log item to the database and send a mail if configured for this $severity
*
* @param string $message the log message
* @param int $severity
* @param int $errorCode
* @param string $objectType
* @param int $objectId
* @param boolean $allowDuplicate if set to true, can log several time the same information (not recommended)
* @return boolean true if succeed
*/
static public function addLog($message, $severity = 1, $errorCode = NULL, $objectType = NULL, $objectId = NULL, $allowDuplicate = false)
{
$log = new Logger();
$log->severity = intval($severity);
$log->error_code = intval($errorCode);
$log->message = pSQL($message);
$log->date_add = date('Y-m-d H:i:s');
$log->date_upd = date('Y-m-d H:i:s');
if (!empty($objectType) AND !empty($objectId))
{
$log->object_type = pSQL($objectType);
$log->object_id = intval($objectId);
}
self::sendByMail($log);
if ($allowDuplicate or !$log->_isPresent() )
{
$res = $log->add();
if ($res)
{
self::$_is_present[$log->getHash()] = isset(self::$_is_present[$log->getHash()])?self::$_is_present[$log->getHash()] + 1:1;
return true;
}
}
return false;
}
/**
* this function md5($this->message.$this->severity.$this->error_code.$this->object_type.$this->object_id)
*
* @return string hash
*/
public function getHash(){
if (empty($this->hash))
$this->hash = md5($this->message.$this->severity.$this->error_code.$this->object_type.$this->object_id);
return $this->hash;
}
/**
* check if this log message already exists in database.
*
* @param mixed $message
* @return true if exists
*/
private function _isPresent()
{
if (!isset(self::$_is_present[md5($this->message)]))
self::$_is_present[$this->getHash()] = Db::getInstance()->getValue('SELECT COUNT(*)
FROM `'._DB_PREFIX_.'log`
WHERE
`message` = \''.$this->message.'\'
AND `severity` = \''.$this->severity.'\'
AND `error_code` = \''.$this->error_code.'\'
AND `object_type` = \''.$this->object_type.'\'
AND `object_id` = \''.$this->object_id.'\'
');
return self::$_is_present[$this->getHash()];
}
}
+171
View File
@@ -0,0 +1,171 @@
<?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 MCachedCore extends Cache
{
protected $_memcacheObj;
protected $_isConnected = false;
protected function __construct()
{
parent::__construct();
$this->connect();
}
public function connect()
{
$this->_memcacheObj = new Memcache();
$servers = self::getMemcachedServers();
if (!$servers)
return false;
foreach ($servers AS $server)
$this->_memcacheObj->addServer($server['ip'], $server['port'], $server['weight']);
$this->_isConnected = true;
return $this->_setKeys();
}
public function set($key, $value, $expire = 0)
{
if (!$this->_isConnected)
return false;
if ($this->_memcacheObj->set($key, $value, 0, $expire))
{
$this->_keysCached[$key] = true;
return $key;
}
}
public function setNumRows($key, $value, $expire = 0)
{
return $this->set($key.'_nrows', $value, $expire);
}
public function getNumRows($key)
{
return $this->get($key.'_nrows');
}
public function get($key)
{
if (!isset($this->_keysCached[$key]))
return false;
return $this->_memcacheObj->get($key);
}
protected function _setKeys()
{
if (!$this->_isConnected)
return false;
$this->_keysCached = $this->_memcacheObj->get('keysCached');
$this->_tablesCached = $this->_memcacheObj->get('tablesCached');
return true;
}
public function setQuery($query, $result)
{
if (!$this->_isConnected)
return false;
if ($this->isBlacklist($query))
return true;
$md5_query = md5($query);
if (isset($this->_keysCached[$md5_query]))
return true;
$key = $this->set($md5_query, $result);
if(preg_match_all('/('._DB_PREFIX_.'[a-z_-]*)`?.*/i', $query, $res))
foreach($res[1] AS $table)
if(!isset($this->_tablesCached[$table][$key]))
$this->_tablesCached[$table][$key] = true;
}
public function delete($key, $timeout = 0)
{
if (!$this->_isConnected)
return false;
if (!empty($key) AND $this->_memcacheObj->delete($key, $timeout))
unset($this->_keysCached[$key]);
}
public function deleteQuery($query)
{
if (!$this->_isConnected)
return false;
if (preg_match_all('/('._DB_PREFIX_.'[a-z_-]*)`?.*/i', $query, $res))
foreach ($res[1] AS $table)
if (isset($this->_tablesCached[$table]))
{
foreach ($this->_tablesCached[$table] AS $memcachedKey => $foo)
{
$this->delete($memcachedKey);
$this->delete($memcachedKey.'_nrows');
}
unset($this->_tablesCached[$table]);
}
}
protected function close()
{
if (!$this->_isConnected)
return false;
return $this->_memcacheObj->close();
}
public function flush()
{
if(!$this->_isConnected)
return false;
if ($this->_memcacheObj->flush())
return $this->_setKeys();
return false;
}
public function __destruct()
{
parent::__destruct();
if (!$this->_isConnected)
return false;
$this->_memcacheObj->set('keysCached', $this->_keysCached, 0, 0);
$this->_memcacheObj->set('tablesCached', $this->_tablesCached, 0, 0);
$this->close();
}
public static function addServer($ip, $port, $weight)
{
return Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'memcached_servers (id_memcached_server, ip, port, weight) VALUES(\'\', \''.pSQL($ip).'\', '.(int)$port.', '.(int)$weight.')', false);
}
public static function getMemcachedServers()
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT * FROM '._DB_PREFIX_.'memcached_servers', true, false);
}
public static function deleteServer($id_server)
{
return Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'memcached_servers WHERE id_memcached_server='.(int)$id_server);
}
}
+228
View File
@@ -0,0 +1,228 @@
<?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
*/
include_once(_PS_SWIFT_DIR_.'Swift.php');
include_once(_PS_SWIFT_DIR_.'Swift/Connection/SMTP.php');
include_once(_PS_SWIFT_DIR_.'Swift/Connection/NativeMail.php');
include_once(_PS_SWIFT_DIR_.'Swift/Plugin/Decorator.php');
class MailCore
{
static public function Send($id_lang, $template, $subject, $templateVars, $to, $toName = NULL, $from = NULL, $fromName = NULL, $fileAttachment = NULL, $modeSMTP = NULL, $templatePath = _PS_MAIL_DIR_)
{
$configuration = Configuration::getMultiple(array('PS_SHOP_EMAIL', 'PS_MAIL_METHOD', 'PS_MAIL_SERVER', 'PS_MAIL_USER', 'PS_MAIL_PASSWD', 'PS_SHOP_NAME', 'PS_MAIL_SMTP_ENCRYPTION', 'PS_MAIL_SMTP_PORT', 'PS_MAIL_METHOD', 'PS_MAIL_TYPE'));
if(!isset($configuration['PS_MAIL_SMTP_ENCRYPTION'])) $configuration['PS_MAIL_SMTP_ENCRYPTION'] = 'off';
if(!isset($configuration['PS_MAIL_SMTP_PORT'])) $configuration['PS_MAIL_SMTP_PORT'] = 'default';
if (!isset($from)) $from = $configuration['PS_SHOP_EMAIL'];
if (!isset($fromName)) $fromName = $configuration['PS_SHOP_NAME'];
if (!empty($from) AND !Validate::isEmail($from))
die(Tools::displayError('Error: parameter "from" is corrupted'));
if (!empty($fromName) AND !Validate::isMailName($fromName))
die(Tools::displayError('Error: parameter "fromName" is corrupted'));
if (!is_array($to) AND !Validate::isEmail($to))
die(Tools::displayError('Error: parameter "to" is corrupted'));
if (!is_array($templateVars))
die(Tools::displayError('Error: parameter "templateVars" is not an array'));
// Do not crash for this error, that may be a complicated customer name
if (!empty($toName) AND !Validate::isMailName($toName))
$toName = NULL;
if (!Validate::isTplName($template))
die(Tools::displayError('Error: invalid email template'));
if (!Validate::isMailSubject($subject))
die(Tools::displayError('Error: invalid email subject'));
/* Construct multiple recipients list if needed */
if (is_array($to))
{
$to_list = new Swift_RecipientList();
foreach ($to AS $key => $addr)
{
$to_name = NULL;
$addr = trim($addr);
if (!Validate::isEmail($addr))
die(Tools::displayError('Error: invalid email address'));
if ($toName AND is_array($toName) AND Validate::isGenericName($toName[$key]))
$to_name = $toName[$key];
$to_list->addTo($addr, $to_name);
}
$to_plugin = $to[0];
$to = $to_list;
} else {
/* Simple recipient, one address */
$to_plugin = $to;
$to = new Swift_Address($to, $toName);
}
try {
/* Connect with the appropriate configuration */
if ($configuration['PS_MAIL_METHOD'] == 2)
{
if (empty($configuration['PS_MAIL_SERVER']) OR empty($configuration['PS_MAIL_SMTP_PORT']))
die(Tools::displayError('Error: invalid SMTP server or SMTP port'));
$connection = new Swift_Connection_SMTP($configuration['PS_MAIL_SERVER'], $configuration['PS_MAIL_SMTP_PORT'], ($configuration['PS_MAIL_SMTP_ENCRYPTION'] == "ssl") ? Swift_Connection_SMTP::ENC_SSL : (($configuration['PS_MAIL_SMTP_ENCRYPTION'] == "tls") ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_OFF));
$connection->setTimeout(4);
if (!$connection)
return false;
if (!empty($configuration['PS_MAIL_USER']))
$connection->setUsername($configuration['PS_MAIL_USER']);
if (!empty($configuration['PS_MAIL_PASSWD']))
$connection->setPassword($configuration['PS_MAIL_PASSWD']);
}
else
$connection = new Swift_Connection_NativeMail();
if (!$connection)
return false;
$swift = new Swift($connection, Configuration::get('PS_MAIL_DOMAIN'));
/* Get templates content */
$iso = Language::getIsoById((int)($id_lang));
if (!$iso)
die (Tools::displayError('Error - No ISO code for email'));
$template = $iso.'/'.$template;
$moduleName = false;
$overrideMail = false;
// get templatePath
if (preg_match('#'.__PS_BASE_URI__.'modules/#', $templatePath) AND preg_match('#modules/([a-z0-9_-]+)/#ui' , $templatePath , $res))
$moduleName = $res[1];
if ($moduleName !== false AND (file_exists(_PS_THEME_DIR_.'modules/'.$moduleName.'/mails/'.$template.'.txt') OR
file_exists(_PS_THEME_DIR_.'modules/'.$moduleName.'/mails/'.$template.'.html')))
$templatePath = _PS_THEME_DIR_.'modules/'.$moduleName.'/mails/';
elseif (file_exists(_PS_THEME_DIR_.'mails/'.$template.'.txt') OR file_exists(_PS_THEME_DIR_.'mails/'.$template.'.html'))
{
$templatePath = _PS_THEME_DIR_.'mails/';
$overrideMail = true;
}
elseif (!file_exists($templatePath.$template.'.txt') OR !file_exists($templatePath.$template.'.html'))
die(Tools::displayError('Error - The following email template is missing:').' '.$templatePath.$template.'.txt');
$templateHtml = file_get_contents($templatePath.$template.'.html');
$templateTxt = strip_tags(html_entity_decode(file_get_contents($templatePath.$template.'.txt'), NULL, 'utf-8'));
if ($overrideMail AND file_exists($templatePath.$iso.'/lang.php'))
include_once($templatePath.$iso.'/lang.php');
elseif ($moduleName AND file_exists($templatePath.$iso.'/lang.php'))
include_once(_PS_THEME_DIR_.'mails/'.$iso.'/lang.php');
else
include_once(dirname(__FILE__).'/../mails/'.$iso.'/lang.php');
/* Create mail and attach differents parts */
$message = new Swift_Message('['.Configuration::get('PS_SHOP_NAME').'] '. $subject);
$templateVars['{shop_logo}'] = (file_exists(_PS_IMG_DIR_.'logo_mail.jpg')) ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_.'logo_mail.jpg'))) : ((file_exists(_PS_IMG_DIR_.'logo.jpg')) ? $message->attach(new Swift_Message_Image(new Swift_File(_PS_IMG_DIR_.'logo.jpg'))) : '');
$templateVars['{shop_name}'] = Tools::safeOutput(Configuration::get('PS_SHOP_NAME'));
$templateVars['{shop_url}'] = Tools::getShopDomain(true, true).__PS_BASE_URI__;
$swift->attachPlugin(new Swift_Plugin_Decorator(array($to_plugin => $templateVars)), 'decorator');
if ($configuration['PS_MAIL_TYPE'] == 3 OR $configuration['PS_MAIL_TYPE'] == 2)
$message->attach(new Swift_Message_Part($templateTxt, 'text/plain', '8bit', 'utf-8'));
if ($configuration['PS_MAIL_TYPE'] == 3 OR $configuration['PS_MAIL_TYPE'] == 1)
$message->attach(new Swift_Message_Part($templateHtml, 'text/html', '8bit', 'utf-8'));
if ($fileAttachment AND isset($fileAttachment['content']) AND isset($fileAttachment['name']) AND isset($fileAttachment['mime']))
$message->attach(new Swift_Message_Attachment($fileAttachment['content'], $fileAttachment['name'], $fileAttachment['mime']));
/* Send mail */
$send = $swift->send($message, $to, new Swift_Address($from, $fromName));
$swift->disconnect();
return $send;
}
catch (Swift_ConnectionException $e) { return false; }
}
static public function sendMailTest($smtpChecked, $smtpServer, $content, $subject, $type, $to, $from, $smtpLogin, $smtpPassword, $smtpPort = 25, $smtpEncryption)
{
$swift = NULL;
$result = NULL;
try
{
if($smtpChecked)
{
$smtp = new Swift_Connection_SMTP($smtpServer, $smtpPort, ($smtpEncryption == "off") ? Swift_Connection_SMTP::ENC_OFF : (($smtpEncryption == "tls") ? Swift_Connection_SMTP::ENC_TLS : Swift_Connection_SMTP::ENC_SSL));
$smtp->setUsername($smtpLogin);
$smtp->setpassword($smtpPassword);
$smtp->setTimeout(5);
$swift = new Swift($smtp, Configuration::get('PS_MAIL_DOMAIN'));
}
else
$swift = new Swift(new Swift_Connection_NativeMail(), Configuration::get('PS_MAIL_DOMAIN'));
$message = new Swift_Message($subject, $content, $type);
if ($swift->send($message, $to, $from))
$result = true;
else
$result = 999;
$swift->disconnect();
}
catch (Swift_Connection_Exception $e) { $result = $e->getCode(); }
catch (Swift_Message_MimeException $e) { $result = $e->getCode(); }
return $result;
}
/**
* This method is used to get the translation for email Object.
* For an object is forbidden to use htmlentities,
* we have to return a sentence with accents.
*
* @param string $string raw sentence (write directly in file)
*/
static public function l($string)
{
global $_LANGMAIL, $cookie;
$key = str_replace('\'', '\\\'', $string);
$id_lang = (!isset($cookie) OR !is_object($cookie)) ? (int)Configuration::get('PS_LANG_DEFAULT') : (int)$cookie->id_lang;
$file_core = _PS_ROOT_DIR_.'/mails/'.Language::getIsoById((int)$id_lang).'/lang.php';
if (Tools::file_exists_cache($file_core) && empty($_LANGMAIL))
include_once($file_core);
$file_theme = _PS_THEME_DIR_.'mails/'.Language::getIsoById((int)$id_lang).'/lang.php';
if (Tools::file_exists_cache($file_theme))
include_once($file_theme);
if (!is_array($_LANGMAIL))
return (str_replace('"', '&quot;', $string));
if (key_exists($key, $_LANGMAIL))
$str = $_LANGMAIL[$key];
else
$str = $string;
return str_replace('"', '&quot;', addslashes($str));
}
}
+397
View File
@@ -0,0 +1,397 @@
<?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: 7310 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ManufacturerCore extends ObjectModel
{
public $id;
/** @var integer manufacturer ID */
public $id_manufacturer;//FIXME is it really usefull...?
/** @var string Name */
public $name;
/** @var string A description */
public $description;
/** @var string A short description */
public $short_description;
/** @var int Address */
public $id_address;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
/** @var string Friendly URL */
public $link_rewrite;
/** @var string Meta title */
public $meta_title;
/** @var string Meta keywords */
public $meta_keywords;
/** @var string Meta description */
public $meta_description;
/** @var boolean active */
public $active;
protected $fieldsRequired = array('name');
protected $fieldsSize = array('name' => 64);
protected $fieldsValidate = array('name' => 'isCatalogName');
protected $fieldsSizeLang = array('short_description' => 254, 'meta_title' => 128, 'meta_description' => 255, 'meta_description' => 255);
protected $fieldsValidateLang = array('description' => 'isString', 'short_description' => 'isString', 'meta_title' => 'isGenericName', 'meta_description' => 'isGenericName', 'meta_keywords' => 'isGenericName');
protected $table = 'manufacturer';
protected $identifier = 'id_manufacturer';
protected $webserviceParameters = array(
'fields' => array(
'link_rewrite' => array('getter' => 'getLink', 'setter' => false),
),
'associations' => array(
'addresses' => array('resource' => 'address', 'setter' => false, 'fields' => array(
'id' => array('xlink_resource' => 'addresses'),
)),
),
);
public function __construct($id = NULL, $id_lang = NULL)
{
parent::__construct($id, $id_lang);
/* Get the manufacturer's id_address */
$this->id_address = $this->getManufacturerAddress();
$this->link_rewrite = $this->getLink();
$this->image_dir = _PS_MANU_IMG_DIR_;
}
public function getFields()
{
parent::validateFields();
if (isset($this->id))
$fields['id_manufacturer'] = (int)($this->id);
$fields['name'] = pSQL($this->name);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
$fields['active'] = (int)($this->active);
return $fields;
}
public function getTranslationsFieldsChild()
{
$fieldsArray = array('description', 'short_description', 'meta_title', 'meta_keywords', 'meta_description');
$fields = array();
$languages = Language::getLanguages(false);
$defaultLanguage = Configuration::get('PS_LANG_DEFAULT');
foreach ($languages as $language)
{
$fields[$language['id_lang']]['id_lang'] = $language['id_lang'];
$fields[$language['id_lang']][$this->identifier] = (int)($this->id);
$fields[$language['id_lang']]['description'] = (isset($this->description[$language['id_lang']])) ? pSQL($this->description[$language['id_lang']], true) : '';
$fields[$language['id_lang']]['short_description'] = (isset($this->short_description[$language['id_lang']])) ? pSQL($this->short_description[$language['id_lang']], true) : '';
foreach ($fieldsArray as $field)
{
if (!Validate::isTableOrIdentifier($field))
die(Tools::displayError());
/* Check fields validity */
if (isset($this->{$field}[$language['id_lang']]) AND !empty($this->{$field}[$language['id_lang']]))
$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$language['id_lang']], true);
elseif (in_array($field, $this->fieldsRequiredLang))
$fields[$language['id_lang']][$field] = pSQL($this->{$field}[$defaultLanguage]);
else
$fields[$language['id_lang']][$field] = '';
}
}
return $fields;
}
public function delete()
{
$address = new Address($this->id_address);
if (!$address->delete())
return false;
if (parent::delete())
return $this->deleteImage();
}
/**
* Delete several objects from database
*
* return boolean Deletion result
*/
public function deleteSelection($selection)
{
if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$result = true;
foreach ($selection AS $id)
{
$this->id = (int)($id);
$this->id_address = self::getManufacturerAddress();
$result = $result AND $this->delete();
}
return $result;
}
protected function getManufacturerAddress()
{
if (!(int)($this->id))
return false;
$result = Db::GetInstance(_PS_USE_SQL_SLAVE_)->getRow('SELECT `id_address` FROM '._DB_PREFIX_.'address WHERE `id_manufacturer` = '.(int)($this->id));
if (!$result)
return false;
return $result['id_address'];
}
/**
* Return manufacturers
*
* @param boolean $getNbProducts [optional] return products numbers for each
* @return array Manufacturers
*/
static public function getManufacturers($getNbProducts = false, $id_lang = 0, $active = true, $p = false, $n = false, $all_group = false, $id_group_shop = false)
{
if (!$id_lang)
$id_lang = (int)Configuration::get('PS_LANG_DEFAULT');
if (!$id_group_shop)
$id_group_shop = Configuration::get('PS_GROUP_SHOP_DEFAULT');
$sql = 'SELECT m.*, ml.`description`';
$sql.= 'FROM `'._DB_PREFIX_.'manufacturer_group_shop` mgs
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.id_manufacturer = mgs.id_manufacturer)
LEFT JOIN `'._DB_PREFIX_.'manufacturer_lang` ml ON (m.`id_manufacturer` = ml.`id_manufacturer` AND ml.`id_lang` = '.(int)($id_lang).')
WHERE mgs.id_group_shop='.(int)$id_group_shop.($active ? ' AND m.`active` = 1' : '');
$sql.= ' ORDER BY m.`name` ASC'.($p ? ' LIMIT '.(((int)($p) - 1) * (int)($n)).','.(int)($n) : '');
$manufacturers = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
if ($manufacturers === false)
return false;
if ($getNbProducts)
{
$sqlGroups = '';
if (!$all_group)
{
$groups = FrontController::getCurrentCustomerGroups();
$sqlGroups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');
}
foreach ($manufacturers as $key => $manufacturer)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT p.`id_product`
FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'manufacturer` as m ON (m.`id_manufacturer`= p.`id_manufacturer`)
WHERE m.`id_manufacturer` = '.(int)($manufacturer['id_manufacturer']).
($active ? ' AND p.`active` = 1 ' : '').
($all_group ? '' : ' AND p.`id_product` IN (
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_group` cg
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
WHERE cg.`id_group` '.$sqlGroups.')'));
$manufacturers[$key]['nb_products'] = sizeof($result);
}
}
for ($i = 0; $i < sizeof($manufacturers); $i++)
if ((int)(Configuration::get('PS_REWRITING_SETTINGS')))
$manufacturers[$i]['link_rewrite'] = Tools::link_rewrite($manufacturers[$i]['name'], false);
else
$manufacturers[$i]['link_rewrite'] = 0;
return $manufacturers;
}
/**
* @deprecated
*/
static public function getManufacturersWithoutAddress()
{
Tools::displayAsDeprecated();
$sql = 'SELECT m.* FROM `'._DB_PREFIX_.'manufacturer` m
LEFT JOIN `'._DB_PREFIX_.'address` a ON (a.`id_manufacturer` = m.`id_manufacturer` AND a.`deleted` = 0)
WHERE a.`id_manufacturer` IS NULL';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
}
/**
* Return name from id
*
* @param integer $id_manufacturer Manufacturer ID
* @return string name
*/
static protected $cacheName = array();
static public function getNameById($id_manufacturer)
{
if (!isset(self::$cacheName[$id_manufacturer]))
self::$cacheName[$id_manufacturer] = Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `name` FROM `'._DB_PREFIX_.'manufacturer` WHERE `id_manufacturer` = '.(int)($id_manufacturer).' AND `active` = 1');
return self::$cacheName[$id_manufacturer];
}
static public function getIdByName($name)
{
$result = Db::getInstance()->getRow('
SELECT `id_manufacturer`
FROM `'._DB_PREFIX_.'manufacturer`
WHERE `name` = \''.pSQL($name).'\'');
if (isset($result['id_manufacturer']))
return (int)($result['id_manufacturer']);
return false;
}
public function getLink()
{
return Tools::link_rewrite($this->name, false);
}
static public function getProducts($id_manufacturer, $id_lang, $p, $n, $orderBy = NULL, $orderWay = NULL, $getTotal = false, $active = true)
{
if ($p < 1) $p = 1;
if (empty($orderBy) ||$orderBy == 'position') $orderBy = 'name';
if (empty($orderWay)) $orderWay = 'ASC';
if (!Validate::isOrderBy($orderBy) OR !Validate::isOrderWay($orderWay))
die (Tools::displayError());
$groups = FrontController::getCurrentCustomerGroups();
$sqlGroups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');
/* Return only the number of products */
if ($getTotal)
{
$sql = '
SELECT p.`id_product`
FROM `'._DB_PREFIX_.'product` p
WHERE p.id_manufacturer = '.(int)($id_manufacturer)
.($active ? ' AND p.`active` = 1' : '').'
AND p.`id_product` IN (
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_group` cg
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
WHERE cg.`id_group` '.$sqlGroups.'
)';
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
return (int)(sizeof($result));
}
$sql = '
SELECT p.*, pa.`id_product_attribute`, pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, i.`id_image`, il.`legend`, m.`name` AS manufacturer_name, tl.`name` AS tax_name, t.`rate`, DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new,
(p.`price` * ((100 + (t.`rate`))/100)) AS orderprice
FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_attribute` pa ON (p.`id_product` = pa.`id_product` AND default_on = 1)
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
WHERE p.`id_manufacturer` = '.(int)($id_manufacturer).($active ? ' AND p.`active` = 1' : '').'
AND p.`id_product` IN (
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_group` cg
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
WHERE cg.`id_group` '.$sqlGroups.'
)
ORDER BY '.(($orderBy == 'id_product') ? 'p.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).'
LIMIT '.(((int)($p) - 1) * (int)($n)).','.(int)($n);
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
if (!$result)
return false;
if ($orderBy == 'price')
Tools::orderbyPrice($result, $orderWay);
return Product::getProductsProperties($id_lang, $result);
}
public function getProductsLite($id_lang)
{
return Db::getInstance()->ExecuteS('
SELECT p.`id_product`, pl.`name`
FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).')
WHERE p.`id_manufacturer` = '.(int)($this->id));
}
/*
* Specify if a manufacturer already in base
*
* @param $id_manufacturer Manufacturer id
* @return boolean
*/
static public function manufacturerExists($id_manufacturer)
{
$row = Db::getInstance()->getRow('
SELECT `id_manufacturer`
FROM '._DB_PREFIX_.'manufacturer m
WHERE m.`id_manufacturer` = '.(int)($id_manufacturer));
return isset($row['id_manufacturer']);
}
public function getAddresses($id_lang)
{
return Db::getInstance()->ExecuteS('
SELECT a.*, cl.name AS `country`, s.name AS `state`
FROM `'._DB_PREFIX_.'address` AS a
LEFT JOIN `'._DB_PREFIX_.'country_lang` AS cl ON (cl.`id_country` = a.`id_country` AND cl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'state` AS s ON (s.`id_state` = a.`id_state`)
WHERE `id_manufacturer` = '.(int)($this->id).'
AND a.`deleted` = 0');
}
public function getWsAddresses()
{
return Db::getInstance()->ExecuteS('
SELECT a.id_address as id
FROM `'._DB_PREFIX_.'address` AS a
WHERE `id_manufacturer` = '.(int)($this->id).'
AND a.`deleted` = 0');
}
public function setWsAddresses($id_addresses)
{
$ids = array();
foreach ($id_addresses as $id)
$ids[] = (int)$id['id'];
Db::getInstance()->ExecuteS('
UPDATE `'._DB_PREFIX_.'address`
SET id_manufacturer = 0
WHERE id_manufacturer = '.(int)$this->id.'
AND deleted = 0');
return (Db::getInstance()->ExecuteS('
UPDATE `'._DB_PREFIX_.'address`
SET id_customer = 0, id_supplier = 0, id_manufacturer = '.(int)$this->id.'
WHERE id_address IN('.implode(',', $ids).')
AND deleted = 0') !== false);
}
}
+165
View File
@@ -0,0 +1,165 @@
<?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 MessageCore extends ObjectModel
{
public $id;
/** @var string message content */
public $message;
/** @var integer Cart ID (if applicable) */
public $id_cart;
/** @var integer Order ID (if applicable) */
public $id_order;
/** @var integer Customer ID (if applicable) */
public $id_customer;
/** @var integer Employee ID (if applicable) */
public $id_employee;
/** @var boolean Message is not displayed to the customer */
public $private;
/** @var string Object creation date */
public $date_add;
protected $fieldsRequired = array('message');
protected $fieldsSize = array('message' => 1600);
protected $fieldsValidate = array(
'message' => 'isCleanHtml', 'id_cart' => 'isUnsignedId', 'id_order' => 'isUnsignedId',
'id_customer' => 'isUnsignedId', 'id_employee' => 'isUnsignedId', 'private' => 'isBool');
protected $table = 'message';
protected $identifier = 'id_message';
public function getFields()
{
parent::validateFields();
$fields['message'] = pSQL($this->message, true);
$fields['id_cart'] = (int)($this->id_cart);
$fields['id_order'] = (int)($this->id_order);
$fields['id_customer'] = (int)($this->id_customer);
$fields['id_employee'] = (int)($this->id_employee);
$fields['private'] = (int)($this->private);
$fields['date_add'] = pSQL($this->date_add);
return $fields;
}
/**
* Return the last message from cart
*
* @param integer $id_cart Cart ID
* @return array Message
*/
static public function getMessageByCartId($id_cart)
{
$db = Db::getInstance();
$result = $db->getRow('
SELECT *
FROM `'._DB_PREFIX_.'message`
WHERE `id_cart` = '.(int)($id_cart));
return $result;
}
/**
* Return messages from Order ID
*
* @param integer $id_order Order ID
* @param boolean $private return WITH private messages
* @return array Messages
*/
static public function getMessagesByOrderId($id_order, $private = false)
{
if (!Validate::isBool($private))
die(Tools::displayError());
global $cookie;
return Db::getInstance()->ExecuteS('
SELECT m.*, c.`firstname` AS cfirstname, c.`lastname` AS clastname, e.`firstname` AS efirstname, e.`lastname` AS elastname, (COUNT(mr.id_message) = 0 AND m.id_customer != 0) AS is_new_for_me
FROM `'._DB_PREFIX_.'message` m
LEFT JOIN `'._DB_PREFIX_.'customer` c ON m.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'message_readed` mr ON (mr.id_message = m.id_message AND mr.id_employee = '.(int)$cookie->id_employee.')
LEFT OUTER JOIN `'._DB_PREFIX_.'employee` e ON e.`id_employee` = m.`id_employee`
WHERE id_order = '.(int)$id_order.'
'.(!$private ? ' AND m.`private` = 0' : '').'
GROUP BY m.id_message
ORDER BY m.date_add DESC');
}
/**
* Return messages from Cart ID
*
* @param integer $id_order Order ID
* @param boolean $private return WITH private messages
* @return array Messages
*/
static public function getMessagesByCartId($id_cart, $private = false)
{
if (!Validate::isBool($private))
die(Tools::displayError());
global $cookie;
return Db::getInstance()->ExecuteS('
SELECT m.*, c.`firstname` AS cfirstname, c.`lastname` AS clastname, e.`firstname` AS efirstname, e.`lastname` AS elastname, (COUNT(mr.id_message) = 0 AND m.id_customer != 0) AS is_new_for_me
FROM `'._DB_PREFIX_.'message` m
LEFT JOIN `'._DB_PREFIX_.'customer` c ON m.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'message_readed` mr ON (mr.id_message = m.id_message AND mr.id_employee = '.(int)$cookie->id_employee.')
LEFT OUTER JOIN `'._DB_PREFIX_.'employee` e ON e.`id_employee` = m.`id_employee`
WHERE id_cart = '.(int)$id_cart.'
'.(!$private ? ' AND m.`private` = 0' : '').'
GROUP BY m.id_message
ORDER BY m.date_add DESC');
}
/**
* Registered a message 'readed'
*
* @param integer $id_message Message ID
* @param integer $id_emplyee Employee ID
*/
static public function markAsReaded($id_message, $id_employee)
{
if (!Validate::isUnsignedId($id_message) OR !Validate::isUnsignedId($id_employee))
die(Tools::displayError());
$result = Db::getInstance()->Execute('
INSERT INTO '._DB_PREFIX_.'message_readed (id_message , id_employee , date_add) VALUES
('.(int)($id_message).', '.(int)($id_employee).', NOW());
');
return $result;
}
}
+189
View File
@@ -0,0 +1,189 @@
<?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: 7445 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class MetaCore extends ObjectModel
{
/** @var string Name */
public $page;
public $title;
public $description;
public $keywords;
public $url_rewrite;
protected $fieldsRequired = array('page');
protected $fieldsSize = array('page' => 64);
protected $fieldsValidate = array('page' => 'isFileName');
protected $fieldsRequiredLang = array();
protected $fieldsSizeLang = array('title' => 128, 'description' => 255, 'keywords' => 255, 'url_rewrite' => 255);
protected $fieldsValidateLang = array('title' => 'isGenericName', 'description' => 'isGenericName', 'keywords' => 'isGenericName', 'url_rewrite' => 'isLinkRewrite');
protected $langMultiShop = true;
protected $table = 'meta';
protected $identifier = 'id_meta';
public function getFields()
{
parent::validateFields();
return array('page' => pSQL($this->page));
}
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('title', 'description', 'keywords', 'url_rewrite'));
}
static public function getPages($excludeFilled = false, $addPage = false)
{
$selectedPages = array();
if (!$files = scandir(_PS_ROOT_DIR_.'/controllers'))
die(Tools::displayError('Cannot scan root directory'));
// Exclude pages forbidden
$exludePages = array('category', 'changecurrency', 'cms', 'footer', 'header',
'pagination', 'product', 'product-sort', 'statistics');
foreach ($files as $file)
if (preg_match('/^[a-z0-9_.-]*\.php$/i', $file) AND !in_array(strtolower(str_replace('Controller.php', '', $file)), $exludePages))
$selectedPages[] = strtolower(str_replace('Controller.php', '', $file));
// Exclude page already filled
if ($excludeFilled)
{
$metas = self::getMetas();
foreach ($metas as $k => $meta)
if (in_array($meta['page'], $selectedPages))
unset($selectedPages[array_search($meta['page'], $selectedPages)]);
}
// Add selected page
if ($addPage)
{
$selectedPages[] = $addPage;
sort($selectedPages);
}
return $selectedPages;
}
static public function getMetas()
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM '._DB_PREFIX_.'meta
ORDER BY page ASC');
}
static public function getMetasByIdLang($id_lang, $id_shop = false)
{
if (!$id_shop)
$id_shop = (int)Configuration::get('PS_SHOP_DEFAULT');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'meta` m
LEFT JOIN `'._DB_PREFIX_.'meta_lang` ml ON m.`id_meta` = ml.`id_meta`
WHERE ml.`id_lang` = '.(int)($id_lang).
($id_shop ? ' AND ml.id_shop='.(int)$id_shop : '').'
ORDER BY page ASC');
}
static public function getMetaByPage($page, $id_lang, $id_shop = false)
{
if (!$id_shop)
$id_shop = (int)Configuration::get('PS_SHOP_DEFAULT');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT *
FROM '._DB_PREFIX_.'meta m
LEFT JOIN '._DB_PREFIX_.'meta_lang ml on (m.id_meta = ml.id_meta)
WHERE m.page = \''.pSQL($page).'\' AND ml.id_lang = '.(int)($id_lang));
}
public function update($nullValues = false)
{
if (!parent::update($nullValues))
return false;
return Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
}
public function add($autodate = true, $nullValues = false)
{
if (!parent::add($autodate, $nullValues));
return Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
}
public function delete()
{
if (!parent::delete())
return false;
return Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
}
public function deleteSelection($selection)
{
if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$result = true;
foreach ($selection AS $id)
{
$this->id = (int)($id);
$result = $result AND $this->delete();
}
return Tools::generateHtaccess(dirname(__FILE__).'/../.htaccess',
(int)(Configuration::get('PS_REWRITING_SETTINGS')),
(int)(Configuration::get('PS_HTACCESS_CACHE_CONTROL')),
Configuration::get('PS_HTACCESS_SPECIFIC')
);
}
static public function getEquivalentUrlRewrite($new_id_lang, $id_lang, $url_rewrite)
{
return Db::getInstance()->getValue('
SELECT url_rewrite
FROM `'._DB_PREFIX_.'meta_lang`
WHERE id_meta = (
SELECT id_meta
FROM `'._DB_PREFIX_.'meta_lang`
WHERE url_rewrite = \''.pSQL($url_rewrite).'\' AND id_lang = '.(int)($id_lang).'
)
AND id_lang = '.(int)($new_id_lang));
}
}
+1168
View File
File diff suppressed because it is too large Load Diff
+327
View File
@@ -0,0 +1,327 @@
<?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: 7329 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class ModuleGraphCore extends Module
{
protected $_employee;
/** @var integer array graph data */
protected $_values = array();
/** @var string array graph legends (X axis) */
protected $_legend = array();
/**@var string graph titles */
protected $_titles = array('main' => NULL, 'x' => NULL, 'y' => NULL);
/** @var ModuleGraphEngine graph engine */
protected $_render;
abstract protected function getData($layers);
public function setEmployee($id_employee)
{
$this->_employee = new Employee((int)($id_employee));
}
public function setLang($id_lang)
{
$this->_id_lang = $id_lang;
}
protected function setDateGraph($layers, $legend = false)
{
// Get dates in a manageable format
$fromArray = getdate(strtotime($this->_employee->stats_date_from));
$toArray = getdate(strtotime($this->_employee->stats_date_to));
// If the granularity is inferior to 1 day
if ($this->_employee->stats_date_from == $this->_employee->stats_date_to)
{
if ($legend)
for ($i = 0; $i < 24; $i++)
{
if ($layers == 1)
$this->_values[$i] = 0;
else
for ($j = 0; $j < $layers; $j++)
$this->_values[$j][$i] = 0;
$this->_legend[$i] = ($i % 2) ? '' : sprintf('%02dh', $i);
}
if (is_callable(array($this, 'setDayValues')))
$this->setDayValues($layers);
}
// If the granularity is inferior to 1 month TODO : change to manage 28 to 31 days
elseif (strtotime($this->_employee->stats_date_to) - strtotime($this->_employee->stats_date_from) <= 2678400)
{
if ($legend)
{
$days = array();
if ($fromArray['mon'] == $toArray['mon'])
for ($i = $fromArray['mday']; $i <= $toArray['mday']; ++$i)
$days[] = $i;
else
{
$imax = date('t', mktime(0, 0, 0, $fromArray['mon'], 1, $fromArray['year']));
for ($i = $fromArray['mday']; $i <= $imax; ++$i)
$days[] = $i;
for ($i = 1; $i <= $toArray['mday']; ++$i)
$days[] = $i;
}
foreach ($days as $i)
{
if ($layers == 1)
$this->_values[$i] = 0;
else
for ($j = 0; $j < $layers; $j++)
$this->_values[$j][$i] = 0;
$this->_legend[$i] = ($i % 2) ? '' : sprintf('%02d', $i);
}
}
if (is_callable(array($this, 'setMonthValues')))
$this->setMonthValues($layers);
}
// If the granularity is less than 1 year
elseif (strtotime('-1 year', strtotime($this->_employee->stats_date_to)) < strtotime($this->_employee->stats_date_from))
{
if ($legend)
{
$months = array();
if ($fromArray['year'] == $toArray['year'])
for ($i = $fromArray['mon']; $i <= $toArray['mon']; ++$i)
$months[] = $i;
else
{
for ($i = $fromArray['mon']; $i <= 12; ++$i)
$months[] = $i;
for ($i = 1; $i <= $toArray['mon']; ++$i)
$months[] = $i;
}
foreach ($months as $i)
{
if ($layers == 1)
$this->_values[$i] = 0;
else
for ($j = 0; $j < $layers; $j++)
$this->_values[$j][$i] = 0;
$this->_legend[$i] = sprintf('%02d', $i);
}
}
if (is_callable(array($this, 'setYearValues')))
$this->setYearValues($layers);
}
// If the granularity is greater than 1 year
else
{
if ($legend)
{
$years = array();
for ($i = $fromArray['year']; $i <= $toArray['year']; ++$i)
$years[] = $i;
foreach ($years as $i)
{
if ($layers == 1)
$this->_values[$i] = 0;
else
for ($j = 0; $j < $layers; $j++)
$this->_values[$j][$i] = 0;
$this->_legend[$i] = sprintf('%04d', $i);
}
}
if (is_callable(array($this, 'setAllTimeValues')))
$this->setAllTimeValues($layers);
}
}
protected function csvExport($datas)
{
global $cookie;
$this->setEmployee(intval($cookie->id_employee));
$this->setLang(intval($cookie->id_lang));
$layers = isset($datas['layers']) ? $datas['layers'] : 1;
if (isset($datas['option']))
$this->setOption($datas['option'], $layers);
$this->getData($layers);
// @todo use native CSV PHP functions ?
// Generate first line (column titles)
if (is_array($this->_titles['main']))
for ($i = 0; $i <= sizeof($this->_titles['main']); $i++)
{
if($i > 0)
$this->_csv .= ';';
if (isset($this->_titles['main'][$i]))
$this->_csv .= $this->_titles['main'][$i];
}
else // If there is only one column title, there is in fast two column (the first without title)
$this->_csv .= ';'.$this->_titles['main'];
$this->_csv .= "\n";
if (sizeof($this->_legend))
{
$total = 0;
if ($datas['type'] == 'pie')
foreach ($this->_legend AS $key => $legend)
for ($i = 0; $i < (is_array($this->_titles['main']) ? sizeof($this->_values) : 1); ++$i)
$total += (is_array($this->_values[$i]) ? $this->_values[$i][$key] : $this->_values[$key]);
foreach ($this->_legend AS $key => $legend)
{
$this->_csv .= $legend.';';
for ($i = 0; $i < (is_array($this->_titles['main']) ? sizeof($this->_values) : 1); ++$i)
{
if (!isset($this->_values[$i]) || !is_array($this->_values[$i]))
if (isset($this->_values[$key]))
{
// We don't want strings to be divided. Example: product name
if (is_numeric($this->_values[$key]))
$this->_csv .= $this->_values[$key] / (($datas['type'] == 'pie') ? $total : 1);
else
$this->_csv .= $this->_values[$key];
}else
$this->_csv .= '0';
else
{
// We don't want strings to be divided. Example: product name
if (is_numeric($this->_values[$i][$key]))
$this->_csv .= $this->_values[$i][$key] / (($datas['type'] == 'pie') ? $total : 1);
else
$this->_csv .= $this->_values[$i][$key];
}
$this->_csv .= ';';
}
$this->_csv .= "\n";
}
}
$this->_displayCsv();
}
protected function _displayCsv()
{
ob_end_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$this->displayName.' - '.time().'.csv"');
echo $this->_csv;
exit;
}
public function create($render, $type, $width, $height, $layers)
{
if (!Tools::file_exists_cache($file = dirname(__FILE__).'/../modules/'.$render.'/'.$render.'.php'))
die(Tools::displayError());
require_once($file);
$this->_render = new $render($type);
$this->getData($layers);
$this->_render->createValues($this->_values);
$this->_render->setSize($width, $height);
$this->_render->setLegend($this->_legend);
$this->_render->setTitles($this->_titles);
}
public function draw()
{
$this->_render->draw();
}
/**
* @todo Set this method as abstracted ? Quid of module compatibility.
*/
public function setOption($option, $layers = 1)
{
}
public function engine($params)
{
global $cookie;
if (!($render = Configuration::get('PS_STATS_RENDER')))
return Tools::displayError('No graph engine selected');
if (!file_exists(dirname(__FILE__).'/../modules/'.$render.'/'.$render.'.php'))
return Tools::displayError('Graph engine selected is unavailable.');
global $cookie;
$id_employee = (int)($cookie->id_employee);
$id_lang = (int)($cookie->id_lang);
if (!isset($params['layers']))
$params['layers'] = 1;
if (!isset($params['type']))
$params['type'] = 'column';
if (!isset($params['width']))
$params['width'] = 550;
if (!isset($params['height']))
$params['height'] = 270;
$urlParams = $params;
$urlParams['render'] = $render;
$urlParams['module'] = Tools::getValue('module');
$urlParams['id_employee'] = $id_employee;
$urlParams['id_lang'] = $id_lang;
$drawer = 'drawer.php?' . http_build_query($urlParams);
require_once(dirname(__FILE__).'/../modules/'.$render.'/'.$render.'.php');
return call_user_func(array($render, 'hookGraphEngine'), $params, $drawer);
}
protected static function getEmployee($employee = null)
{
if (!$employee)
{
global $cookie;
$employee = new Employee((int)($cookie->id_employee));
}
if (empty($employee->stats_date_from) OR empty($employee->stats_date_to) OR $employee->stats_date_from == '0000-00-00' OR $employee->stats_date_to == '0000-00-00')
{
if (empty($employee->stats_date_from) OR $employee->stats_date_from == '0000-00-00')
$employee->stats_date_from = date('Y').'-01-01';
if (empty($employee->stats_date_to) OR $employee->stats_date_to == '0000-00-00')
$employee->stats_date_to = date('Y').'-12-31';
$employee->update();
}
return $employee;
}
public function getDate()
{
return self::getDateBetween($this->_employee);
}
public static function getDateBetween($employee = null)
{
$employee = self::getEmployee($employee);
return ' \''.$employee->stats_date_from.' 00:00:00\' AND \''.$employee->stats_date_to.' 23:59:59\' ';
}
public function getLang()
{
return $this->_id_lang;
}
}
+72
View File
@@ -0,0 +1,72 @@
<?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
*/
abstract class ModuleGraphEngineCore extends Module
{
protected $_type;
public function __construct($type)
{
$this->_type = $type;
}
public function install()
{
if (!parent::install())
return false;
return Configuration::updateValue('PS_STATS_RENDER', $this->name);
}
public static function getGraphEngines()
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT m.`name`
FROM `'._DB_PREFIX_.'module` m
LEFT JOIN `'._DB_PREFIX_.'hook_module` hm ON hm.`id_module` = m.`id_module`
LEFT JOIN `'._DB_PREFIX_.'hook` h ON hm.`id_hook` = h.`id_hook`
WHERE h.`name` = \'GraphEngine\'');
$arrayEngines = array();
foreach ($result AS $module)
{
$instance = Module::getInstanceByName($module['name']);
if (!$instance)
continue;
$arrayEngines[$module['name']] = array($instance->displayName, $instance->description);
}
return $arrayEngines;
}
abstract public function createValues($values);
abstract public function setSize($width, $height);
abstract public function setLegend($legend);
abstract public function setTitles($titles);
abstract public function draw();
}
+185
View File
@@ -0,0 +1,185 @@
<?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: 7048 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class ModuleGridCore extends Module
{
protected $_employee;
/** @var string array graph data */
protected $_values = array();
/** @var integer total number of values **/
protected $_totalCount = 0;
/**@var string graph titles */
protected $_title;
/**@var integer start */
protected $_start;
/**@var integer limit */
protected $_limit;
/**@var string column name on which to sort */
protected $_sort = null;
/**@var string sort direction DESC/ASC */
protected $_direction = null;
/** @var ModuleGridEngine grid engine */
protected $_render;
public function install()
{
return (parent::install());
}
public function setEmployee($id_employee)
{
$this->_employee = new Employee((int)($id_employee));
}
public function setLang($id_lang)
{
$this->_id_lang = $id_lang;
}
public function create($render, $type, $width, $height, $start, $limit, $sort, $dir)
{
if (!Tools::file_exists_cache($file = dirname(__FILE__).'/../modules/'.$render.'/'.$render.'.php'))
die(Tools::displayError());
require_once($file);
$this->_render = new $render($type);
$this->_start = $start;
$this->_limit = $limit;
$this->_sort = $sort;
$this->_direction = $dir;
$this->getData();
$this->_render->setTitle($this->_title);
$this->_render->setSize($width, $height);
$this->_render->setValues($this->_values);
$this->_render->setTotalCount($this->_totalCount);
$this->_render->setLimit($this->_start, $this->_limit);
}
public function render()
{
$this->_render->render();
}
public function engine($params)
{
if (!($render = Configuration::get('PS_STATS_GRID_RENDER')))
return Tools::displayError('No grid engine selected');
if (!file_exists(dirname(__FILE__).'/../modules/'.$render.'/'.$render.'.php'))
return Tools::displayError('Grid engine selected is unavailable.');
$grider = 'grider.php?render='.$render.'&module='.Tools::getValue('module');
global $cookie;
$grider .= '&id_employee='.(int)($cookie->id_employee);
$grider .= '&id_lang='.(int)($cookie->id_lang);
if (!isset($params['width']) OR !Validate::IsUnsignedInt($params['width']))
$params['width'] = 600;
if (!isset($params['height']) OR !Validate::IsUnsignedInt($params['height']))
$params['height'] = 920;
if (!isset($params['start']) OR !Validate::IsUnsignedInt($params['start']))
$params['start'] = 0;
if (!isset($params['limit']) OR !Validate::IsUnsignedInt($params['height']))
$params['limit'] = 40;
$grider .= '&width='.$params['width'];
$grider .= '&height='.$params['height'];
if (isset($params['start']) AND Validate::IsUnsignedInt($params['start']))
$grider .= '&start='.$params['start'];
if (isset($params['limit']) AND Validate::IsUnsignedInt($params['limit']))
$grider .= '&limit='.$params['limit'];
if (isset($params['type']) AND Validate::IsName($params['type']))
$grider .= '&type='.$params['type'];
if (isset($params['option']) AND Validate::IsGenericName($params['option']))
$grider .= '&option='.$params['option'];
if (isset($params['sort']) AND Validate::IsName($params['sort']))
$grider .= '&sort='.$params['sort'];
if (isset($params['dir']) AND Validate::IsSortDirection($params['dir']))
$grider .= '&dir='.$params['dir'];
require_once(dirname(__FILE__).'/../modules/'.$render.'/'.$render.'.php');
return call_user_func(array($render, 'hookGridEngine'), $params, $grider);
}
protected function csvExport($datas)
{
global $cookie;
$this->_sort = $datas['defaultSortColumn'];
$this->setLang($cookie->id_lang);
$this->getData();
$layers = isset($datas['layers']) ? $datas['layers'] : 1;
if (isset($datas['option']))
$this->setOption($datas['option'], $layers);
if (sizeof($datas['columns']))
{
foreach ($datas['columns'] AS $column)
$this->_csv .= $column['header'].';';
$this->_csv = rtrim($this->_csv, ';')."\n";
foreach ($this->_values AS $value)
{
foreach ($datas['columns'] AS $column)
$this->_csv .= $value[$column['dataIndex']].';';
$this->_csv = rtrim($this->_csv, ';')."\n";
}
}
$this->_displayCsv();
}
protected function _displayCsv()
{
ob_end_clean();
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.$this->displayName.' - '.time().'.csv"');
echo $this->_csv;
exit;
}
abstract protected function getData();
public function getDate()
{
return ModuleGraph::getDateBetween($this->_employee);
}
public function getLang()
{
return $this->_id_lang;
}
}
+71
View File
@@ -0,0 +1,71 @@
<?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
*/
abstract class ModuleGridEngineCore extends Module
{
protected $_type;
public function __construct($type)
{
$this->_type = $type;
}
public function install()
{
if (!parent::install())
return false;
return Configuration::updateValue('PS_STATS_GRID_RENDER', $this->name);
}
public static function getGridEngines()
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT m.`name`
FROM `'._DB_PREFIX_.'module` m
LEFT JOIN `'._DB_PREFIX_.'hook_module` hm ON hm.`id_module` = m.`id_module`
LEFT JOIN `'._DB_PREFIX_.'hook` h ON hm.`id_hook` = h.`id_hook`
WHERE h.`name` = \'GridEngine\'');
$arrayEngines = array();
foreach ($result AS $module)
{
$instance = Module::getInstanceByName($module['name']);
if (!$instance)
continue;
$arrayEngines[$module['name']] = array($instance->displayName, $instance->description);
}
return $arrayEngines;
}
abstract public function setValues($values);
abstract public function setTitle($title);
abstract public function setSize($width, $height);
abstract public function setTotalCount($totalCount);
abstract public function setLimit($start, $limit);
abstract public function render();
}
+285
View File
@@ -0,0 +1,285 @@
<?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: 6856 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class MySQLCore extends Db
{
public function connect()
{
if (!defined('_PS_DEBUG_SQL_'))
define('_PS_DEBUG_SQL_', false);
if ($this->_link = mysql_connect($this->_server, $this->_user, $this->_password))
{
if(!$this->set_db($this->_database))
die(Tools::displayError('The database selection cannot be made.'));
}
else
die(Tools::displayError('Link to database cannot be established.'));
/* UTF-8 support */
if (!mysql_query('SET NAMES \'utf8\'', $this->_link))
die(Tools::displayError('PrestaShop Fatal error: no utf-8 support. Please check your server configuration.'));
// removed SET GLOBAL SQL_MODE : we can't do that (see PSCFI-1548)
return $this->_link;
}
/* do not remove, useful for some modules */
public function set_db($db_name) {
return mysql_select_db($db_name, $this->_link);
}
public function disconnect()
{
if ($this->_link)
@mysql_close($this->_link);
$this->_link = false;
}
public function getRow($query, $use_cache = 1)
{
$query .= ' LIMIT 1';
$this->_result = false;
$this->_lastQuery = $query;
if($use_cache AND _PS_CACHE_ENABLED_)
if ($result = Cache::getInstance()->get(md5($query)))
{
$this->_lastCached = true;
return $result;
}
if ($this->_link)
if ($this->_result = mysql_query($query, $this->_link))
{
$this->_lastCached = false;
if (_PS_DEBUG_SQL_)
$this->displayMySQLError($query);
$result = mysql_fetch_assoc($this->_result);
if ($use_cache = 1 AND _PS_CACHE_ENABLED_)
Cache::getInstance()->setQuery($query, $result);
return $result;
}
if (_PS_DEBUG_SQL_)
$this->displayMySQLError($query);
return false;
}
public function getValue($query, $use_cache = 1)
{
$query .= ' LIMIT 1';
$this->_result = false;
$this->_lastQuery = $query;
if ($use_cache AND _PS_CACHE_ENABLED_)
if ($result = Cache::getInstance()->get(md5($query)))
{
$this->_lastCached = true;
return $result;
}
if ($this->_link AND $this->_result = mysql_query($query, $this->_link) AND is_array($tmpArray = mysql_fetch_assoc($this->_result)))
{
$this->_lastCached = false;
$result = array_shift($tmpArray);
if($use_cache AND _PS_CACHE_ENABLED_)
Cache::getInstance()->setQuery($query, $result);
return $result;
}
return false;
}
public function Execute($query, $use_cache = 1)
{
$this->_result = false;
if ($this->_link)
{
$this->_result = mysql_query($query, $this->_link);
if (_PS_DEBUG_SQL_)
$this->displayMySQLError($query);
if ($use_cache AND _PS_CACHE_ENABLED_)
Cache::getInstance()->deleteQuery($query);
return $this->_result;
}
if (_PS_DEBUG_SQL_)
$this->displayMySQLError($query);
return false;
}
/**
* ExecuteS return the result of $query as array,
* or as mysqli_result if $array set to false
*
* @param string $query query to execute
* @param boolean $array return an array instead of a mysql_result object
* @param int $use_cache if query has been already executed, use its result
* @return array or result object
*/
public function ExecuteS($query, $array = true, $use_cache = 1)
{
$this->_result = false;
$this->_lastQuery = $query;
if ($use_cache AND _PS_CACHE_ENABLED_)
if ($array AND ($result = Cache::getInstance()->get(md5($query))))
{
$this->_lastCached = true;
return $result;
}
if ($this->_link && $this->_result = mysql_query($query, $this->_link))
{
$this->_lastCached = false;
if (_PS_DEBUG_SQL_)
$this->displayMySQLError($query);
if (!$array)
return $this->_result;
$resultArray = array();
// Only SELECT queries and a few others return a valid resource usable with mysql_fetch_assoc
if ($this->_result !== true)
while ($row = mysql_fetch_assoc($this->_result))
$resultArray[] = $row;
if ($use_cache AND _PS_CACHE_ENABLED_)
Cache::getInstance()->setQuery($query, $resultArray);
return $resultArray;
}
if (_PS_DEBUG_SQL_)
$this->displayMySQLError($query);
return false;
}
public function nextRow($result = false)
{
return mysql_fetch_assoc($result ? $result : $this->_result);
}
public function delete($table, $where = false, $limit = false, $use_cache = 1)
{
$this->_result = false;
if ($this->_link)
{
$query = 'DELETE FROM `'.pSQL($table).'`'.($where ? ' WHERE '.$where : '').($limit ? ' LIMIT '.(int)($limit) : '');
$res = mysql_query($query, $this->_link);
if ($use_cache AND _PS_CACHE_ENABLED_)
Cache::getInstance()->deleteQuery($query);
return $res;
}
return false;
}
public function NumRows()
{
if (!$this->_lastCached AND $this->_link AND $this->_result)
{
$nrows = mysql_num_rows($this->_result);
if (_PS_CACHE_ENABLED_)
Cache::getInstance()->setNumRows(md5($this->_lastQuery), $nrows);
return $nrows;
}
elseif (_PS_CACHE_ENABLED_ AND $this->_lastCached)
{
return Cache::getInstance()->getNumRows(md5($this->_lastQuery));
}
}
public function Insert_ID()
{
if ($this->_link)
return mysql_insert_id($this->_link);
return false;
}
public function Affected_Rows()
{
if ($this->_link)
return mysql_affected_rows($this->_link);
return false;
}
protected function q($query, $use_cache = 1)
{
global $webservice_call;
$this->_result = false;
if ($this->_link)
{
$result = mysql_query($query, $this->_link);
$this->_lastQuery = $query;
if ($webservice_call)
$this->displayMySQLError($query);
if ($use_cache AND _PS_CACHE_ENABLED_)
Cache::getInstance()->deleteQuery($query);
return $result;
}
return false;
}
/**
* Returns the text of the error message from previous MySQL operation
*
* @acces public
* @return string error
*/
public function getMsgError($query = false)
{
return mysql_error();
}
public function getNumberError()
{
return mysql_errno();
}
public function displayMySQLError($query = false)
{
global $webservice_call;
if ($webservice_call && mysql_errno())
{
WebserviceRequest::getInstance()->setError(500, '[SQL Error] '.mysql_error().'. Query was : '.$query, 97);
}
elseif (_PS_DEBUG_SQL_ AND mysql_errno() AND !defined('PS_INSTALLATION_IN_PROGRESS'))
{
if ($query)
{
die(Tools::displayError(mysql_error().'<br /><br /><pre>'.$query.'</pre>'));
}
die(Tools::displayError((mysql_error())));
}
}
static public function tryToConnect($server, $user, $pwd, $db)
{
if (!$link = @mysql_connect($server, $user, $pwd))
return 1;
if (!@mysql_select_db($db, $link))
return 2;
@mysql_close($link);
return 0;
}
static public function tryUTF8($server, $user, $pwd)
{
$link = @mysql_connect($server, $user, $pwd);
if (!mysql_query('SET NAMES \'utf8\'', $link))
$ret = false;
else
$ret = true;
@mysql_close($link);
return $ret;
}
}
+831
View File
@@ -0,0 +1,831 @@
<?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: 7499 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
abstract class ObjectModelCore
{
/** @var integer Object id */
public $id;
/** @var integer lang id */
protected $id_lang = NULL;
protected $id_shop = NULL;
/** @var string SQL Table name */
protected $table = NULL;
/** @var string SQL Table identifier */
protected $identifier = NULL;
/** @var array Required fields for admin panel forms */
protected $fieldsRequired = array();
/** @var fieldsRequiredDatabase */
protected static $fieldsRequiredDatabase = NULL;
/** @var array Maximum fields size for admin panel forms */
protected $fieldsSize = array();
/** @var array Fields validity functions for admin panel forms */
protected $fieldsValidate = array();
/** @var array Multilingual required fields for admin panel forms */
protected $fieldsRequiredLang = array();
/** @var array Multilingual maximum fields size for admin panel forms */
protected $fieldsSizeLang = array();
/** @var array Multilingual fields validity functions for admin panel forms */
protected $fieldsValidateLang = array();
protected $langMultiShop = false;
/** @var array tables */
protected $tables = array();
/** @var array tables */
protected $webserviceParameters = array();
protected static $_cache = array();
/** @var string path to image directory. Used for image deletion. */
protected $image_dir = NULL;
/** @var string file type of image files. Used for image deletion. */
protected $image_format = 'jpg';
/**
* Returns object validation rules (fields validity)
*
* @param string $className Child class name for static use (optional)
* @return array Validation rules (fields validity)
*/
static public function getValidationRules($className = __CLASS__)
{
$object = new $className();
return array(
'required' => $object->fieldsRequired,
'size' => $object->fieldsSize,
'validate' => $object->fieldsValidate,
'requiredLang' => $object->fieldsRequiredLang,
'sizeLang' => $object->fieldsSizeLang,
'validateLang' => $object->fieldsValidateLang);
}
/**
* Prepare fields for ObjectModel class (add, update)
* All fields are verified (pSQL, intval...)
*
* @return array All object fields
*/
public function getFields() { return array(); }
/**
* Build object
*
* @param integer $id Existing object id in order to load object (optional)
* @param integer $id_lang Required if object is multilingual (optional)
*/
public function __construct($id = NULL, $id_lang = NULL, $id_shop = NULL)
{
if ($id_lang != NULL && Validate::isLoadedObject(new Language($id_lang)))
$this->id_lang = $id_lang;
elseif ($id_lang != NULL)
die(Tools::displayError());
if ($this->langMultiShop AND $id_shop == NULL)
$id_shop = (int)Shop::getCurrentShop(true);
if ($id_shop AND $this->langMultiShop)
$this->id_shop = $id_shop;
/* Connect to database and check SQL table/identifier */
if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$this->identifier = pSQL($this->identifier);
/* Load object from database if object id is present */
if ($id)
{
if (!isset(self::$_cache[$this->table][(int)$id][(int)$id_shop][(int)$id_lang]))
self::$_cache[$this->table][(int)($id)][(int)$id_shop][(int)$id_lang] = Db::getInstance()->getRow('
SELECT *
FROM `'._DB_PREFIX_.$this->table.'` a '.
($id_lang ? ('LEFT JOIN `'.pSQL(_DB_PREFIX_.$this->table).'_lang` b ON (a.`'.$this->identifier.'` = b.`'.$this->identifier).'` AND `id_lang` = '.(int)($id_lang).')' : '')
.' WHERE 1 AND a.`'.$this->identifier.'` = '.(int)$id.
(($this->langMultiShop AND $id_shop AND $id_lang) ? ' AND b.id_shop='.(int)$id_shop : ''));
$result = self::$_cache[$this->table][(int)$id][(int)$id_shop][(int)$id_lang];
if ($result)
{
$this->id = (int)($id);
foreach ($result AS $key => $value)
if (key_exists($key, $this))
$this->{$key} = stripslashes($value);
if (!$id_lang AND method_exists($this, 'getTranslationsFieldsChild'))
{
$result = Db::getInstance()->ExecuteS('SELECT * FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang`
WHERE `'.$this->identifier.'` = '.(int)$id
.(($this->langMultiShop AND $id_shop) ? ' AND `id_shop`='.(int)$id_shop : ''));
if ($result)
foreach ($result as $row)
foreach ($row AS $key => $value)
{
if (key_exists($key, $this) AND $key != $this->identifier)
{
if (!is_array($this->{$key}))
$this->{$key} = array();
if ($this->langMultiShop AND $id_shop)
$this->{$key}[$row['id_shop']][$row['id_lang']] = stripslashes($value);
else
$this->{$key}[$row['id_lang']] = stripslashes($value);
}
}
}
}
}
if (!is_array(self::$fieldsRequiredDatabase))
{
$fields = $this->getfieldsRequiredDatabase(true);
if ($fields)
foreach ($fields AS $row)
self::$fieldsRequiredDatabase[$row['object_name']][(int)$row['id_required_field']] = pSQL($row['field_name']);
else
self::$fieldsRequiredDatabase = array();
}
}
/**
* Save current object to database (add or update)
*
* return boolean Insertion result
*/
public function save($nullValues = false, $autodate = true)
{
return (int)($this->id) > 0 ? $this->update($nullValues) : $this->add($autodate, $nullValues);
}
/**
* Add current object to database
*
* return boolean Insertion result
*/
public function add($autodate = true, $nullValues = false)
{
if (!Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
/* Automatically fill dates */
if ($autodate AND key_exists('date_add', $this))
$this->date_add = date('Y-m-d H:i:s');
if ($autodate AND key_exists('date_upd', $this))
$this->date_upd = date('Y-m-d H:i:s');
/* Database insertion */
if ($nullValues)
$result = Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_.$this->table, $this->getFields(), 'INSERT');
else
$result = Db::getInstance()->autoExecute(_DB_PREFIX_.$this->table, $this->getFields(), 'INSERT');
if (!$result)
return false;
/* Get object id in database */
$this->id = Db::getInstance()->Insert_ID();
$assos = Shop::getAssoTables();
/* Database insertion for multilingual fields related to the object */
if (method_exists($this, 'getTranslationsFieldsChild'))
{
$fields = $this->getTranslationsFieldsChild();
$shops = Shop::getShops(true, null, true);
if ($fields AND is_array($fields))
foreach ($fields AS &$field)
{
foreach ($field AS $key => $value)
if (!Validate::isTableOrIdentifier($key))
die(Tools::displayError());
$field[$this->identifier] = (int)$this->id;
$result = Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT') && $result;
if (isset($assos[$this->table.'_lang']) && $assos[$this->table.'_lang']['type'] == 'fk_shop')
{
foreach ($shops as $id_shop)
{
if ($this->id_shop == (int)$id_shop)
continue;
$field['id_shop'] = (int)$id_shop;
$result = Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT') && $result;
}
}
}
}
if(!Tools::isMultishopActivated())
{
if (isset($assos[$this->table]) && $assos[$this->table]['type'] == 'shop')
$result &= $this->associateTo(array((int)Shop::getCurrentShop(true)), 'shop');
$assos = GroupShop::getAssoTables();
if (isset($assos[$this->table]) && $assos[$this->table]['type'] == 'group_shop')
$result &= $this->associateTo(array((int)Shop::getCurrentGroupShop()), 'group_shop');
}
return $result;
}
/**
* Update current object to database
*
* return boolean Update result
*/
public function update($nullValues = false)
{
if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$this->clearCache();
/* Automatically fill dates */
if (key_exists('date_upd', $this))
$this->date_upd = date('Y-m-d H:i:s');
/* Database update */
if ($nullValues)
$result = Db::getInstance()->autoExecuteWithNullValues(_DB_PREFIX_.$this->table, $this->getFields(), 'UPDATE', '`'.pSQL($this->identifier).'` = '.(int)($this->id));
else
$result = Db::getInstance()->autoExecute(_DB_PREFIX_.$this->table, $this->getFields(), 'UPDATE', '`'.pSQL($this->identifier).'` = '.(int)($this->id));
if (!$result)
return false;
// Database update for multilingual fields related to the object
if (method_exists($this, 'getTranslationsFieldsChild'))
{
$fields = $this->getTranslationsFieldsChild();
if (is_array($fields))
{
foreach ($fields as $field)
{
foreach ($field as $key => $value)
if (!Validate::isTableOrIdentifier($key))
die(Tools::displayError());
if ($this->langMultiShop)
$field['id_shop'] = ($this->id_shop ? $this->id_shop : Shop::getCurrentShop(true));
// used to insert missing lang entries
$where_lang = '`'.pSQL($this->identifier).'` = '.(int)$this->id.
' AND `id_lang` = '.(int)$field['id_lang'].
(($this->langMultiShop AND $this->id_shop) ? ' AND `id_shop`='.$this->id_shop : '');
$lang_found = Db::getInstance()->getValue('SELECT COUNT(*) FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE '. $where_lang);
if (!$lang_found)
$result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'INSERT');
else
$result &= Db::getInstance()->AutoExecute(_DB_PREFIX_.$this->table.'_lang', $field, 'UPDATE', $where_lang);
}
}
}
return $result;
}
/**
* Delete current object from database
*
* return boolean Deletion result
*/
public function delete()
{
if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$this->clearCache();
/* Database deletion */
$result = Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
if (!$result)
return false;
/* Database deletion for multilingual fields related to the object */
if (method_exists($this, 'getTranslationsFieldsChild'))
Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
return $result;
}
/**
* Delete several objects from database
*
* return boolean Deletion result
*/
public function deleteSelection($selection)
{
if (!is_array($selection) OR !Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
$result = true;
foreach ($selection AS $id)
{
$this->id = (int)($id);
$result = $result AND $this->delete();
}
return $result;
}
/**
* Toggle object status in database
*
* return boolean Update result
*/
public function toggleStatus()
{
if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
/* Object must have a variable called 'active' */
elseif (!key_exists('active', $this))
die(Tools::displayError());
/* Update active status on object */
$this->active = (int)(!$this->active);
/* Change status to active/inactive */
return Db::getInstance()->Execute('
UPDATE `'.pSQL(_DB_PREFIX_.$this->table).'`
SET `active` = !`active`
WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
}
/**
* Prepare multilingual fields for database insertion
*
* @param array $fieldsArray Multilingual fields to prepare
* return array Prepared fields for database insertion
*/
protected function getTranslationsFields($fieldsArray)
{
/* WARNING : Product do not use this function, so do not forget to report any modification if necessary */
if (!Validate::isTableOrIdentifier($this->identifier))
die(Tools::displayError());
$fields = array();
if($this->id_lang == NULL)
foreach (Language::getLanguages() as $language)
$this->makeTranslationFields($fields, $fieldsArray, $language['id_lang']);
else
$this->makeTranslationFields($fields, $fieldsArray, $this->id_lang);
return $fields;
}
protected function makeTranslationFields(&$fields, &$fieldsArray, $id_language)
{
$fields[$id_language]['id_lang'] = $id_language;
$fields[$id_language][$this->identifier] = (int)($this->id);
if ($this->id_shop AND $this->langMultiShop)
$fields[$id_language]['id_shop'] = (int)$this->id_shop;
foreach ($fieldsArray as $field)
{
/* Check fields validity */
if (!Validate::isTableOrIdentifier($field))
die(Tools::displayError());
/* Copy the field, or the default language field if it's both required and empty */
if ((!$this->id_lang AND isset($this->{$field}[$id_language]) AND !empty($this->{$field}[$id_language]))
OR ($this->id_lang AND isset($this->$field) AND !empty($this->$field)))
$fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field) : pSQL($this->{$field}[$id_language]);
elseif (in_array($field, $this->fieldsRequiredLang))
$fields[$id_language][$field] = $this->id_lang ? pSQL($this->$field) : pSQL($this->{$field}[Configuration::get('PS_LANG_DEFAULT')]);
else
$fields[$id_language][$field] = '';
}
}
/**
* Check for fields validity before database interaction
*/
public function validateFields($die = true, $errorReturn = false)
{
$fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
foreach ($fieldsRequired as $field)
if (Tools::isEmpty($this->{$field}) AND (!is_numeric($this->{$field})))
{
if ($die) die (Tools::displayError().' ('.get_class($this).' -> '.$field.' is empty)');
return $errorReturn ? get_class($this).' -> '.$field.' is empty' : false;
}
foreach ($this->fieldsSize as $field => $size)
if (isset($this->{$field}) AND Tools::strlen($this->{$field}) > $size)
{
if ($die) die (Tools::displayError().' ('.get_class($this).' -> '.$field.' Length '.$size.')');
return $errorReturn ? get_class($this).' -> '.$field.' Length '.$size : false;
}
$validate = new Validate();
foreach ($this->fieldsValidate as $field => $method)
if (!method_exists($validate, $method))
die (Tools::displayError('Validation function not found.').' '.$method);
elseif (!empty($this->{$field}) AND !call_user_func(array('Validate', $method), $this->{$field}))
{
if ($die) die (Tools::displayError().' ('.get_class($this).' -> '.$field.' = '.$this->{$field}.')');
return $errorReturn ? get_class($this).' -> '.$field.' = '.$this->{$field} : false;
}
return true;
}
/**
* Check for multilingual fields validity before database interaction
*/
public function validateFieldsLang($die = true, $errorReturn = false)
{
$defaultLanguage = (int)(Configuration::get('PS_LANG_DEFAULT'));
foreach ($this->fieldsRequiredLang as $fieldArray)
{
if (!is_array($this->{$fieldArray}))
continue ;
if (!$this->{$fieldArray} OR !sizeof($this->{$fieldArray}) OR ($this->{$fieldArray}[$defaultLanguage] !== '0' AND empty($this->{$fieldArray}[$defaultLanguage])))
{
if ($die) die (Tools::displayError().' ('.get_class($this).'->'.$fieldArray.' '.Tools::displayError('is empty for default language.').')');
return $errorReturn ? get_class($this).'->'.$fieldArray.' '.Tools::displayError('is empty for default language.') : false;
}
}
foreach ($this->fieldsSizeLang as $fieldArray => $size)
{
if (!is_array($this->{$fieldArray}))
continue ;
foreach ($this->{$fieldArray} as $k => $value)
if (Tools::strlen($value) > $size)
{
if ($die) die (Tools::displayError().' ('.get_class($this).'->'.$fieldArray.' '.Tools::displayError('Length').' '.$size.' '.Tools::displayError('for language').')');
return $errorReturn ? get_class($this).'->'.$fieldArray.' '.Tools::displayError('Length').' '.$size.' '.Tools::displayError('for language') : false;
}
}
$validate = new Validate();
foreach ($this->fieldsValidateLang as $fieldArray => $method)
{
if (!is_array($this->{$fieldArray}))
continue ;
foreach ($this->{$fieldArray} as $k => $value)
if (!method_exists($validate, $method))
die (Tools::displayError('Validation function not found.').' '.$method);
elseif (!empty($value) AND !call_user_func(array('Validate', $method), $value))
{
if ($die) die (Tools::displayError('The following field is invalid according to the validate method ').'<b>'.$method.'</b>:<br/> ('.get_class($this).'->'.$fieldArray.' = '.$value.' '.Tools::displayError('for language').' '.$k.')');
return $errorReturn ? Tools::displayError('The following field is invalid according to the validate method ').'<b>'.$method.'</b>:<br/> ('. get_class($this).'->'.$fieldArray.' = '.$value.' '.Tools::displayError('for language').' '.$k : false;
}
}
return true;
}
static public function displayFieldName($field, $className = __CLASS__, $htmlentities = true)
{
global $_FIELDS, $cookie;
$iso = strtolower(Language::getIsoById($cookie->id_lang ? (int)$cookie->id_lang : Configuration::get('PS_LANG_DEFAULT')));
@include(_PS_TRANSLATIONS_DIR_.$iso.'/fields.php');
$key = $className.'_'.md5($field);
return ((is_array($_FIELDS) AND array_key_exists($key, $_FIELDS)) ? ($htmlentities ? htmlentities($_FIELDS[$key], ENT_QUOTES, 'utf-8') : $_FIELDS[$key]) : $field);
}
/**
* TODO: refactor rename all calls to this to validateController
*/
public function validateControler($htmlentities = true)
{
return $this->validateController($htmlentities);
}
public function validateController($htmlentities = true)
{
$errors = array();
/* Checking for required fields */
$fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
foreach ($fieldsRequired AS $field)
if (($value = Tools::getValue($field, $this->{$field})) == false AND (string)$value != '0')
if (!$this->id OR $field != 'passwd')
$errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is required.');
/* Checking for maximum fields sizes */
foreach ($this->fieldsSize AS $field => $maxLength)
if (($value = Tools::getValue($field, $this->{$field})) AND Tools::strlen($value) > $maxLength)
$errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is too long.').' ('.Tools::displayError('Maximum length:').' '.$maxLength.')';
/* Checking for fields validity */
foreach ($this->fieldsValidate AS $field => $function)
{
// Hack for postcode required for country which does not have postcodes
if ($value = Tools::getValue($field, $this->{$field}) OR ($field == 'postcode' AND $value == '0'))
{
if (!Validate::$function($value))
$errors[] = '<b>'.self::displayFieldName($field, get_class($this), $htmlentities).'</b> '.Tools::displayError('is invalid.');
else
{
if ($field == 'passwd')
{
if ($value = Tools::getValue($field))
$this->{$field} = Tools::encrypt($value);
}
else
$this->{$field} = $value;
}
}
}
return $errors;
}
public function getWebserviceParameters($wsParamsAttributeName = NULL)
{
$defaultResourceParameters = array(
'objectSqlId' => $this->identifier,
'retrieveData' => array(
'className' => get_class($this),
'retrieveMethod' => 'getWebserviceObjectList',
'params' => array(),
'table' => $this->table,
),
'fields' => array(
'id' => array('sqlId' => $this->identifier, 'i18n' => false),
),
);
if (is_null($wsParamsAttributeName))
$wsParamsAttributeName = 'webserviceParameters';
if (!isset($this->{$wsParamsAttributeName}['objectNodeName']))
$defaultResourceParameters['objectNodeName'] = $this->table;
if (!isset($this->{$wsParamsAttributeName}['objectsNodeName']))
$defaultResourceParameters['objectsNodeName'] = $this->table.'s';
if (isset($this->{$wsParamsAttributeName}['associations']))
foreach ($this->{$wsParamsAttributeName}['associations'] as $assocName => &$association)
{
if (!array_key_exists('setter', $association) || (isset($association['setter']) && !$association['setter']))
$association['setter'] = Tools::toCamelCase('set_ws_'.$assocName);
if (!array_key_exists('getter', $association))
$association['getter'] = Tools::toCamelCase('get_ws_'.$assocName);
}
if (isset($this->{$wsParamsAttributeName}['retrieveData']) && isset($this->{$wsParamsAttributeName}['retrieveData']['retrieveMethod']))
unset($defaultResourceParameters['retrieveData']['retrieveMethod']);
$resourceParameters = array_merge_recursive($defaultResourceParameters, $this->{$wsParamsAttributeName});
if (isset($this->fieldsSize))
foreach ($this->fieldsSize as $fieldName => $maxSize)
{
if (!isset($resourceParameters['fields'][$fieldName]))
$resourceParameters['fields'][$fieldName] = array('required' => false);
$resourceParameters['fields'][$fieldName] = array_merge(
$resourceParameters['fields'][$fieldName],
$resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => false)
);
}
if (isset($this->fieldsValidate))
foreach ($this->fieldsValidate as $fieldName => $validateMethod)
{
if (!isset($resourceParameters['fields'][$fieldName]))
$resourceParameters['fields'][$fieldName] = array('required' => false);
$resourceParameters['fields'][$fieldName] = array_merge(
$resourceParameters['fields'][$fieldName],
$resourceParameters['fields'][$fieldName] = array(
'sqlId' => $fieldName,
'validateMethod' => (
array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ?
array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) :
array($validateMethod)
),
'i18n' => false
)
);
}
if (isset($this->fieldsRequired))
{
$fieldsRequired = array_merge($this->fieldsRequired, (isset(self::$fieldsRequiredDatabase[get_class($this)]) ? self::$fieldsRequiredDatabase[get_class($this)] : array()));
foreach ($fieldsRequired as $fieldRequired)
{
if (!isset($resourceParameters['fields'][$fieldRequired]))
$resourceParameters['fields'][$fieldRequired] = array();
$resourceParameters['fields'][$fieldRequired] = array_merge(
$resourceParameters['fields'][$fieldRequired],
$resourceParameters['fields'][$fieldRequired] = array('sqlId' => $fieldRequired, 'required' => true, 'i18n' => false)
);
}
}
if (isset($this->fieldsSizeLang))
foreach ($this->fieldsSizeLang as $fieldName => $maxSize)
{
if (!isset($resourceParameters['fields'][$fieldName]))
$resourceParameters['fields'][$fieldName] = array('required' => false);
$resourceParameters['fields'][$fieldName] = array_merge(
$resourceParameters['fields'][$fieldName],
$resourceParameters['fields'][$fieldName] = array('sqlId' => $fieldName, 'maxSize' => $maxSize, 'i18n' => true)
);
}
if (isset($this->fieldsValidateLang))
foreach ($this->fieldsValidateLang as $fieldName => $validateMethod)
{
if (!isset($resourceParameters['fields'][$fieldName]))
$resourceParameters['fields'][$fieldName] = array('required' => false);
$resourceParameters['fields'][$fieldName] = array_merge(
$resourceParameters['fields'][$fieldName],
$resourceParameters['fields'][$fieldName] = array(
'sqlId' => $fieldName,
'validateMethod' => (
array_key_exists('validateMethod', $resourceParameters['fields'][$fieldName]) ?
array_merge($resourceParameters['fields'][$fieldName]['validateMethod'], array($validateMethod)) :
array($validateMethod)
),
'i18n' => true
)
);
}
if (isset($this->fieldsRequiredLang))
foreach ($this->fieldsRequiredLang as $field)
{
if (!isset($resourceParameters['fields'][$field]))
$resourceParameters['fields'][$field] = array();
$resourceParameters['fields'][$field] = array_merge(
$resourceParameters['fields'][$field],
$resourceParameters['fields'][$field] = array('sqlId' => $field, 'required' => true, 'i18n' => true)
);
}
if (isset($this->date_add))
$resourceParameters['fields']['date_add']['setter'] = false;
if (isset($this->date_upd))
$resourceParameters['fields']['date_upd']['setter'] = false;
foreach ($resourceParameters['fields'] as $key => &$resourceParametersField)
if (!isset($resourceParametersField['sqlId']))
$resourceParametersField['sqlId'] = $key;
return $resourceParameters;
}
public function getWebserviceObjectList($sql_join, $sql_filter, $sql_sort, $sql_limit)
{
$assoc = Shop::getAssoTables();
if (array_key_exists($this->table ,$assoc))
{
$multi_shop_join = ' LEFT JOIN `'._DB_PREFIX_.$this->table.'_'.$assoc[$this->table]['type'].'` AS multi_shop_'.$this->table.' ON (main.'.$this->identifier.' = '.'multi_shop_'.$this->table.'.'.$this->identifier.')';
$class_name = WebserviceRequest::$ws_current_classname;
foreach ($class_name::$shopIDs as $id_shop)
$OR[] = ' multi_shop_'.$this->table.'.id_shop = '.$id_shop.' ';
$multi_shop_filter = ' AND ('.implode('OR', $OR).') ';
$sql_filter = $multi_shop_filter.' '.$sql_filter;
$sql_join = $multi_shop_join .' '. $sql_join;
}
$query = '
SELECT DISTINCT main.`'.$this->identifier.'` FROM `'._DB_PREFIX_.$this->table.'` AS main
'.$sql_join.'
WHERE 1 '.$sql_filter.'
'.($sql_sort != '' ? $sql_sort : '').'
'.($sql_limit != '' ? $sql_limit : '').'
';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($query);
}
public function getFieldsRequiredDatabase($all = false)
{
return Db::getInstance()->ExecuteS('
SELECT id_required_field, object_name, field_name
FROM '._DB_PREFIX_.'required_field
'.(!$all ? 'WHERE object_name = \''.pSQL(get_class($this)).'\'' : ''));
}
public function addFieldsRequiredDatabase($fields)
{
if (!is_array($fields))
return false;
if (!Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'required_field WHERE object_name = \''.pSQL(get_class($this)).'\''))
return false;
foreach ($fields AS $field)
if (!Db::getInstance()->AutoExecute(_DB_PREFIX_.'required_field', array('object_name' => pSQL(get_class($this)), 'field_name' => pSQL($field)), 'INSERT'))
return false;
return true;
}
public function clearCache($all = false)
{
if ($all AND isset(self::$_cache[$this->table]))
unset(self::$_cache[$this->table]);
elseif ($this->id AND isset(self::$_cache[$this->table][(int)$this->id]))
unset(self::$_cache[$this->table][(int)$this->id]);
}
/**
* Check if current object is associated to a shop
*
* @since 1.5.0
* @param int $id_shop
* @return bool
*/
public function isAssociatedToShop($id_shop = null)
{
if (is_null($id_shop))
$id_shop = Shop::getCurrentShop();
$sql = 'SELECT id_shop
FROM `'.pSQL(_DB_PREFIX_.$this->table).'_shop`
WHERE `'.$this->identifier.'`='.(int)$this->id.' AND id_shop='.(int)$id_shop;
return (bool)Db::getInstance()->getValue($sql);
}
/**
* This function associate an item to its context
*
* @param int|array $id_shops
* @param string $context
* @return boolean
*/
public function associateTo($id_shops, $context = 'shop')
{
if (!$this->id)
return;
$sql = '';
if (!is_array($id_shops))
$id_shops = array($id_shops);
foreach ($id_shops as $id_shop)
{
if (!$this->isAssociatedToShop((int)$id_shop))
$sql .= '('.(int)$this->id.','.(int)$id_shop.'),';
}
if (!empty($sql))
return Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.$this->table.'_'.$context.'` (`'.$this->identifier.'`, `id_'.$context.'`) VALUES '.rtrim($sql,','));
return true;
}
/**
* Check if current object is associated to a group shop
*
* @since 1.5.0
* @param int $id_group_shop
* @return bool
*/
public function isAssociatedToGroupShop($id_group_shop = null)
{
if (is_null($id_group_shop))
$id_shop = Shop::getCurrentGroupShop();
$sql = 'SELECT id_group_shop
FROM `'.pSQL(_DB_PREFIX_.$this->table).'_group_shop`
WHERE `'.$this->identifier.'`='.(int)$this->id.' AND id_group_shop='.(int)$id_group_shop;
return (bool)Db::getInstance()->getValue($sql);
}
public function isLangMultishop()
{
return (int)$this->langMultiShop;
}
/**
* Delete images associated with the object
*
* @return bool success
*/
public function deleteImage()
{
if (!$this->id)
return false;
/* Deleting object images and thumbnails (cache) */
if ($this->image_dir)
{
if (file_exists($this->image_dir.$this->id.'.'.$this->image_format)
&& !unlink($this->image_dir.$this->id.'.'.$this->image_format))
return false;
}
if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_'.$this->id.'.'.$this->image_format)
&& !unlink(_PS_TMP_IMG_DIR_.$this->table.'_'.$this->id.'.'.$this->image_format))
return false;
if (file_exists(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$this->id.'.'.$this->image_format)
&& !unlink(_PS_TMP_IMG_DIR_.$this->table.'_mini_'.$this->id.'.'.$this->image_format))
return false;
$types = ImageType::getImagesTypes();
foreach ($types AS $image_type)
if (file_exists($this->image_dir.$this->id.'-'.stripslashes($image_type['name']).'.'.$this->image_format)
&& !unlink($this->image_dir.$this->id.'-'.stripslashes($image_type['name']).'.'.$this->image_format))
return false;
return true;
}
}
+1057
View File
File diff suppressed because it is too large Load Diff
+218
View File
@@ -0,0 +1,218 @@
<?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 OrderDetailCore extends ObjectModel
{
/** @var integer */
public $id_order_detail;
/** @var integer */
public $id_order;
/** @var integer */
public $product_id;
/** @var integer */
public $product_attribute_id;
/** @var string */
public $product_name;
/** @var integer */
public $product_quantity;
/** @var integer */
public $product_quantity_in_stock;
/** @var integer */
public $product_quantity_return;
/** @var integer */
public $product_quantity_refunded;
/** @var integer */
public $product_quantity_reinjected;
/** @var float */
public $product_price;
/** @var float */
public $reduction_percent;
/** @var float */
public $reduction_amount;
/** @var float */
public $group_reduction;
/** @var float */
public $product_quantity_discount;
/** @var string */
public $product_ean13;
/** @var string */
public $product_upc;
/** @var string */
public $product_reference;
/** @var string */
public $product_supplier_reference;
/** @var float */
public $product_weight;
/** @var string */
public $tax_name;
/** @var float */
public $tax_rate;
/** @var float */
public $ecotax;
/** @var float */
public $ecotax_tax_rate;
/** @var integer */
public $discount_quantity_applied;
/** @var string */
public $download_hash;
/** @var integer */
public $download_nb;
/** @var date */
public $download_deadline;
protected $tables = array ('order_detail');
protected $fieldsRequired = array ('id_order', 'product_name', 'product_quantity', 'product_price', 'tax_rate');
protected $fieldsValidate = array (
'id_order' => 'isUnsignedId',
'product_id' => 'isUnsignedId',
'product_attribute_id' => 'isUnsignedId',
'product_name' => 'isGenericName',
'product_quantity' => 'isInt',
'product_quantity_in_stock' => 'isInt',
'product_quantity_return' => 'isUnsignedInt',
'product_quantity_refunded' => 'isUnsignedInt',
'product_quantity_reinjected' => 'isUnsignedInt',
'product_price' => 'isPrice',
'reduction_percent' => 'isFloat',
'reduction_amount' => 'isPrice',
'group_reduction' => 'isFloat',
'product_quantity_discount' => 'isFloat',
'product_ean13' => 'isEan13',
'product_upc' => 'isUpc',
'product_reference' => 'isReference',
'product_supplier_reference' => 'isReference',
'product_weight' => 'isFloat',
'tax_name' => 'isGenericName',
'tax_rate' => 'isFloat',
'ecotax' => 'isFloat',
'ecotax_tax_rate' => 'isFloat',
'download_nb' => 'isInt',
);
protected $table = 'order_detail';
protected $identifier = 'id_order_detail';
protected $webserviceParameters = array(
'fields' => array (
'id_order' => array('xlink_resource' => 'orders'),
'product_id' => array('xlink_resource' => 'products'),
'product_attribute_id' => array('xlink_resource' => 'combinations'),
'product_quantity_reinjected' => array(),
'group_reduction' => array(),
'discount_quantity_applied' => array(),
'download_hash' => array(),
'download_deadline' => array()
)
);
public function getFields()
{
parent::validateFields();
$fields['id_order'] = (int)($this->id_order);
$fields['product_id'] = (int)($this->product_id);
$fields['product_attribute_id'] = (int)($this->product_attribute_id);
$fields['product_name'] = pSQL($this->product_name);
$fields['product_quantity'] = (int)($this->product_quantity);
$fields['product_quantity_in_stock'] = (int)($this->product_quantity_in_stock);
$fields['product_quantity_return'] = (int)($this->product_quantity_return);
$fields['product_quantity_refunded'] = (int)($this->product_quantity_refunded);
$fields['product_quantity_reinjected'] = (int)($this->product_quantity_reinjected);
$fields['product_price'] = (float)($this->product_price);
$fields['reduction_percent'] = (float)($this->reduction_percent);
$fields['reduction_amount'] = (float)($this->reduction_amount);
$fields['group_reduction'] = (float)($this->group_reduction);
$fields['product_quantity_discount'] = (float)($this->product_quantity_discount);
$fields['product_ean13'] = pSQL($this->product_ean13);
$fields['product_upc'] = pSQL($this->product_upc);
$fields['product_reference'] = pSQL($this->product_reference);
$fields['product_supplier_reference'] = pSQL($this->product_reference);
$fields['product_weight'] = (float)($this->product_weight);
$fields['tax_name'] = pSQL($this->tax_name);
$fields['tax_rate'] = (float)($this->tax_rate);
$fields['ecotax'] = (float)($this->ecotax);
$fields['ecotax_tax_rate'] = (float)($this->ecotax_tax_rate);
$fields['download_hash'] = pSQL($this->download_hash);
$fields['download_nb'] = (int)($this->download_nb);
$fields['download_deadline'] = pSQL($this->download_deadline);
return $fields;
}
static public function getDownloadFromHash($hash)
{
if ($hash == '') return false;
$sql = 'SELECT *
FROM `'._DB_PREFIX_.'order_detail` od
LEFT JOIN `'._DB_PREFIX_.'product_download` pd ON (od.`product_id`=pd.`id_product`)
WHERE od.`download_hash` = \''.pSQL(strval($hash)).'\'
AND pd.`active` = 1';
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow($sql);
}
static public function incrementDownload($id_order_detail, $increment=1)
{
$sql = 'UPDATE `'._DB_PREFIX_.'order_detail`
SET `download_nb` = `download_nb` + '.(int)($increment).'
WHERE `id_order_detail`= '.(int)($id_order_detail).'
LIMIT 1';
return Db::getInstance()->Execute($sql);
}
}
+71
View File
@@ -0,0 +1,71 @@
<?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 OrderDiscountCore extends ObjectModel
{
/** @var integer */
public $id_order_discount;
/** @var integer */
public $id_order;
/** @var integer */
public $id_discount;
/** @var string */
public $name;
/** @var integer */
public $value;
protected $tables = array ('order_discount');
protected $fieldsRequired = array ('id_order', 'name', 'value');
protected $fieldsValidate = array ('id_order' => 'isUnsignedId', 'name' => 'isGenericName', 'value' => 'isInt');
/* MySQL does not allow 'order detail' for a table name */
protected $table = 'order_discount';
protected $identifier = 'id_order_discount';
protected $webserviceParameters = array(
'fields' => array(
'id_order' => array('xlink_resource' => 'orders'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_order'] = (int)($this->id_order);
$fields['name'] = pSQL($this->name);
$fields['value'] = (int)($this->value);
return $fields;
}
}
+203
View File
@@ -0,0 +1,203 @@
<?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 OrderHistoryCore extends ObjectModel
{
/** @var integer Order id */
public $id_order;
/** @var integer Order state id */
public $id_order_state;
/** @var integer Employee id for this history entry */
public $id_employee;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $tables = array ('order_history');
protected $fieldsRequired = array('id_order', 'id_order_state');
protected $fieldsValidate = array('id_order' => 'isUnsignedId', 'id_order_state' => 'isUnsignedId', 'id_employee' => 'isUnsignedId');
protected $table = 'order_history';
protected $identifier = 'id_order_history';
protected $webserviceParameters = array(
'objectsNodeName' => 'order_histories',
'fields' => array(
'id_order_state' => array('required' => true, 'xlink_resource'=> 'order_states'),
'id_order' => array('xlink_resource' => 'orders'),
),
);
public function getFields()
{
parent::validateFields();
$fields['id_order'] = (int)($this->id_order);
$fields['id_order_state'] = (int)($this->id_order_state);
$fields['id_employee'] = (int)($this->id_employee);
$fields['date_add'] = pSQL($this->date_add);
return $fields;
}
public function changeIdOrderState($new_order_state = NULL, $id_order)
{
if ($new_order_state != NULL)
{
Hook::updateOrderStatus((int)($new_order_state), (int)($id_order));
$order = new Order((int)($id_order));
/* Best sellers */
$newOS = new OrderState((int)($new_order_state), $order->id_lang);
$oldOrderStatus = OrderHistory::getLastOrderState((int)($id_order));
$cart = Cart::getCartByOrderId($id_order);
$isValidated = $this->isValidated();
if (Validate::isLoadedObject($cart))
foreach ($cart->getProducts() as $product)
{
/* If becoming logable => adding sale */
if ($newOS->logable AND (!$oldOrderStatus OR !$oldOrderStatus->logable))
ProductSale::addProductSale($product['id_product'], $product['cart_quantity']);
/* If becoming unlogable => removing sale */
elseif (!$newOS->logable AND ($oldOrderStatus AND $oldOrderStatus->logable))
ProductSale::removeProductSale($product['id_product'], $product['cart_quantity']);
if (!$isValidated AND $newOS->logable AND isset($oldOrderStatus) AND $oldOrderStatus AND $oldOrderStatus->id == _PS_OS_ERROR_)
{
Product::updateQuantity($product);
}
}
$this->id_order_state = (int)($new_order_state);
/* Change invoice number of order ? */
if (!Validate::isLoadedObject($newOS) OR !Validate::isLoadedObject($order))
die(Tools::displayError('Invalid new order state'));
/* The order is valid only if the invoice is available and the order is not cancelled */
$order->valid = $newOS->logable;
$order->update();
if ($newOS->invoice AND !$order->invoice_number)
$order->setInvoice();
if ($newOS->delivery AND !$order->delivery_number)
$order->setDelivery();
Hook::postUpdateOrderStatus((int)($new_order_state), (int)($id_order));
}
}
static public function getLastOrderState($id_order)
{
$id_order_state = Db::getInstance()->getValue('
SELECT `id_order_state`
FROM `'._DB_PREFIX_.'order_history`
WHERE `id_order` = '.(int)($id_order).'
ORDER BY `date_add` DESC, `id_order_history` DESC');
if (!$id_order_state)
return false;
return new OrderState($id_order_state, Configuration::get('PS_LANG_DEFAULT'));
}
public function addWithemail($autodate = true, $templateVars = false)
{
$lastOrderState = $this->getLastOrderState($this->id_order);
if (!parent::add($autodate))
return false;
$result = Db::getInstance()->getRow('
SELECT osl.`template`, c.`lastname`, c.`firstname`, osl.`name` AS osname, c.`email`
FROM `'._DB_PREFIX_.'order_history` oh
LEFT JOIN `'._DB_PREFIX_.'orders` o ON oh.`id_order` = o.`id_order`
LEFT JOIN `'._DB_PREFIX_.'customer` c ON o.`id_customer` = c.`id_customer`
LEFT JOIN `'._DB_PREFIX_.'order_state` os ON oh.`id_order_state` = os.`id_order_state`
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = o.`id_lang`)
WHERE oh.`id_order_history` = '.(int)($this->id).'
AND os.`send_email` = 1');
if (isset($result['template']) AND Validate::isEmail($result['email']))
{
$topic = $result['osname'];
$data = array('{lastname}' => $result['lastname'], '{firstname}' => $result['firstname'], '{id_order}' => (int)($this->id_order));
if ($templateVars)
$data = array_merge($data, $templateVars);
$order = new Order((int)($this->id_order));
$data['{total_paid}'] = Tools::displayPrice((float)($order->total_paid), new Currency((int)($order->id_currency)), false);
$data['{order_name}'] = sprintf("#%06d", (int)($order->id));
// An additional email is sent the first time a virtual item is validated
if ($virtualProducts = $order->getVirtualProducts() AND (!$lastOrderState OR !$lastOrderState->logable) AND $newOrderState = new OrderState($this->id_order_state, Configuration::get('PS_LANG_DEFAULT')) AND $newOrderState->logable)
{
global $smarty;
$assign = array();
foreach ($virtualProducts AS $key => $virtualProduct)
{
$id_product_download = ProductDownload::getIdFromIdProduct($virtualProduct['product_id']);
$product_download = new ProductDownload($id_product_download);
$assign[$key]['name'] = $product_download->display_filename;
$dl_link = $product_download->getTextLink(false, $virtualProduct['download_hash'])
.'&id_order='.$order->id
.'&secure_key='.$order->secure_key;
$assign[$key]['link'] = $dl_link;
if ($virtualProduct['download_deadline'] != '0000-00-00 00:00:00')
$assign[$key]['deadline'] = Tools::displayDate($virtualProduct['download_deadline'], $order->id_lang);
if ($product_download->nb_downloadable != 0)
$assign[$key]['downloadable'] = $product_download->nb_downloadable;
}
$smarty->assign('virtualProducts', $assign);
$smarty->assign('id_order', $order->id);
$iso = Language::getIsoById((int)($order->id_lang));
$links = $smarty->fetch(_PS_MAIL_DIR_.$iso.'/download-product.tpl');
$tmpArray = array('{nbProducts}' => count($virtualProducts), '{virtualProducts}' => $links);
$data = array_merge ($data, $tmpArray);
global $_LANGMAIL;
Mail::Send((int)($order->id_lang), 'download_product', Mail::l('Virtual product to download'), $data, $result['email'], $result['firstname'].' '.$result['lastname']);
}
if (Validate::isLoadedObject($order))
Mail::Send((int)($order->id_lang), $result['template'], $topic, $data, $result['email'], $result['firstname'].' '.$result['lastname']);
}
return true;
}
public function isValidated()
{
return Db::getInstance()->getValue('
SELECT COUNT(oh.`id_order_history`) AS nb
FROM `'._DB_PREFIX_.'order_state` os
LEFT JOIN `'._DB_PREFIX_.'order_history` oh ON (os.`id_order_state` = oh.`id_order_state`)
WHERE oh.`id_order` = '.(int)$this->id_order.'
AND os.`logable` = 1');
}
}
+79
View File
@@ -0,0 +1,79 @@
<?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 OrderMessageCore extends ObjectModel
{
/** @var string name name */
public $name;
/** @var string message content */
public $message;
/** @var string Object creation date */
public $date_add;
protected $fieldsRequired = array();
protected $fieldsValidate = array();
protected $fieldsSize = array();
protected $fieldsRequiredLang = array('name', 'message');
protected $fieldsSizeLang = array('name' => 128, 'message' => 1200);
protected $fieldsValidateLang = array('name' => 'isGenericName', 'message' => 'isMessage');
protected $table = 'order_message';
protected $identifier = 'id_order_message';
protected $webserviceParameters = array(
'fields' => array(
'id' => array('sqlId' => 'id_discount_type', 'xlink_resource' => 'order_message_lang'),
'date_add' => array('sqlId' => 'date_add')
)
);
public function getFields()
{
parent::validateFields();
return array('date_add' => pSQL($this->date_add));
}
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name', 'message'));
}
static public function getOrderMessages($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT om.id_order_message, oml.name, oml.message
FROM '._DB_PREFIX_.'order_message om
LEFT JOIN '._DB_PREFIX_.'order_message_lang oml ON (oml.id_order_message = om.id_order_message)
WHERE oml.id_lang = '.(int)($id_lang).'
ORDER BY name ASC');
}
}
+205
View File
@@ -0,0 +1,205 @@
<?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 OrderReturnCore extends ObjectModel
{
/** @var integer */
public $id;
/** @var integer */
public $id_customer;
/** @var integer */
public $id_order;
/** @var integer */
public $state;
/** @var string message content */
public $question;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $tables = array ('order_return');
protected $fieldsRequired = array ('id_customer', 'id_order');
protected $fieldsValidate = array('id_customer' => 'isUnsignedId', 'id_order' => 'isUnsignedId', 'question' => 'isMessage');
protected $table = 'order_return';
protected $identifier = 'id_order_return';
public function getFields()
{
parent::validateFields();
$fields['id_customer'] = pSQL($this->id_customer);
$fields['id_order'] = pSQL($this->id_order);
$fields['state'] = pSQL($this->state);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
$fields['question'] = pSQL(nl2br2($this->question), true);
return $fields;
}
public function addReturnDetail($orderDetailList, $productQtyList, $customizationIds, $customizationQtyInput)
{
/* Classic product return */
if ($orderDetailList)
foreach ($orderDetailList AS $key => $orderDetail)
if ($qty = (int)($productQtyList[$key]))
Db::getInstance()->AutoExecute(_DB_PREFIX_.'order_return_detail', array('id_order_return' => (int)($this->id), 'id_order_detail' => (int)($orderDetail), 'product_quantity' => $qty, 'id_customization' => 0), 'INSERT');
/* Customized product return */
if ($customizationIds)
foreach ($customizationIds AS $orderDetailId => $customizations)
foreach ($customizations AS $customizationId)
if ($quantity = (int)($customizationQtyInput[(int)($customizationId)]))
Db::getInstance()->AutoExecute(_DB_PREFIX_.'order_return_detail', array('id_order_return' => (int)($this->id), 'id_order_detail' => (int)($orderDetailId), 'product_quantity' => $quantity, 'id_customization' => (int)($customizationId)), 'INSERT');
}
public function checkEnoughProduct($orderDetailList, $productQtyList, $customizationIds, $customizationQtyInput)
{
$order = new Order((int)($this->id_order));
if (!Validate::isLoadedObject($order))
die(Tools::displayError());
$products = $order->getProducts();
/* Products already returned */
$order_return = self::getOrdersReturn($order->id_customer, $order->id, true);
foreach ($order_return AS $or)
{
$order_return_products = self::getOrdersReturnProducts($or['id_order_return'], $order);
foreach ($order_return_products AS $key => $orp)
$products[$key]['product_quantity'] -= (int)($orp['product_quantity']);
}
/* Quantity check */
if ($orderDetailList)
foreach ($orderDetailList AS $key => $orderDetail)
if ($qty = (int)($productQtyList[$key]))
if ($products[$key]['product_quantity'] - $qty < 0)
return false;
/* Customization quantity check */
if ($customizationIds)
{
$orderedCustomizations = Customization::getOrderedCustomizations((int)($order->id_cart));
foreach ($customizationIds AS $productId => $customizations)
foreach ($customizations AS $customizationId)
{
$customizationId = (int)($customizationId);
if (!isset($orderedCustomizations[$customizationId]))
return false;
$quantity = (isset($customizationQtyInput[$customizationId]) ? (int)($customizationQtyInput[$customizationId]) : 0);
if ((int)($orderedCustomizations[$customizationId]['quantity']) - $quantity < 0)
return false;
}
}
return true;
}
public function countProduct()
{
if (!$data = Db::getInstance()->getRow('
SELECT COUNT(`id_order_return`) AS total
FROM `'._DB_PREFIX_.'order_return_detail`
WHERE `id_order_return` = '.(int)($this->id)))
return false;
return (int)($data['total']);
}
static public function getOrdersReturn($customer_id, $order_id = false, $no_denied = false)
{
global $cookie;
$data = Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'order_return`
WHERE `id_customer` = '.(int)($customer_id).
($order_id ? ' AND `id_order` = '.(int)($order_id) : '').
($no_denied ? ' AND `state` != 4' : '').'
ORDER BY `date_add` DESC');
foreach ($data AS $k => $or)
{
$state = new OrderReturnState($or['state']);
$data[$k]['state_name'] = $state->name[$cookie->id_lang];
}
return $data;
}
static public function getOrdersReturnDetail($id_order_return)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'order_return_detail`
WHERE `id_order_return` = '.(int)($id_order_return));
}
static public function getOrdersReturnProducts($orderReturnId, $order)
{
$productsRet = self::getOrdersReturnDetail($orderReturnId);
$products = $order->getProducts();
$tmp = array();
foreach ($productsRet AS $return_detail)
{
$tmp[$return_detail['id_order_detail']]['quantity'] = isset($tmp[$return_detail['id_order_detail']]['quantity']) ? $tmp[$return_detail['id_order_detail']]['quantity'] + (int)($return_detail['product_quantity']) : (int)($return_detail['product_quantity']);
$tmp[$return_detail['id_order_detail']]['customizations'] = (int)($return_detail['id_customization']);
}
$resTab = array();
foreach ($products AS $key => $product)
if (isset($tmp[$product['id_order_detail']]))
{
$resTab[$key] = $product;
$resTab[$key]['product_quantity'] = $tmp[$product['id_order_detail']]['quantity'];
$resTab[$key]['customizations'] = $tmp[$product['id_order_detail']]['customizations'];
}
return $resTab;
}
static public function getReturnedCustomizedProducts($id_order)
{
$returns = Customization::getReturnedCustomizations($id_order);
$order = new Order((int)($id_order));
if (!Validate::isLoadedObject($order))
die(Tools::displayError());
$products = $order->getProducts();
foreach ($returns AS &$return)
{
$return['product_id'] = (int)($products[(int)($return['id_order_detail'])]['product_id']);
$return['product_attribute_id'] = (int)($products[(int)($return['id_order_detail'])]['product_attribute_id']);
$return['name'] = $products[(int)($return['id_order_detail'])]['product_name'];
$return['reference'] = $products[(int)($return['id_order_detail'])]['product_reference'];
}
return $returns;
}
static public function deleteOrderReturnDetail($id_order_return, $id_order_detail, $id_customization = 0)
{
return Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'order_return_detail` WHERE `id_order_detail` = '.(int)($id_order_detail).' AND `id_order_return` = '.(int)($id_order_return).' AND `id_customization` = '.(int)($id_customization));
}
}
+80
View File
@@ -0,0 +1,80 @@
<?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 OrderReturnStateCore extends ObjectModel
{
/** @var string Name */
public $name;
/** @var string Display state in the specified color */
public $color;
protected $fieldsValidate = array('color' => 'isColor');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 64);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $table = 'order_return_state';
protected $identifier = 'id_order_return_state';
public function getFields()
{
parent::validateFields();
$fields['color'] = pSQL($this->color);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
/**
* Get all available order states
*
* @param integer $id_lang Language id for state name
* @return array Order states
*/
static public function getOrderReturnStates($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'order_return_state` ors
LEFT JOIN `'._DB_PREFIX_.'order_return_state_lang` orsl ON (ors.`id_order_return_state` = orsl.`id_order_return_state` AND orsl.`id_lang` = '.(int)($id_lang).')
ORDER BY ors.`id_order_return_state` ASC');
}
}
+179
View File
@@ -0,0 +1,179 @@
<?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 OrderSlipCore extends ObjectModel
{
/** @var integer */
public $id;
/** @var integer */
public $id_customer;
/** @var integer */
public $id_order;
/** @var float */
public $conversion_rate;
/** @var integer */
public $shipping_cost;
/** @var string Object creation date */
public $date_add;
/** @var string Object last modification date */
public $date_upd;
protected $tables = array ('order_slip');
protected $fieldsRequired = array ('id_customer', 'id_order', 'conversion_rate');
protected $fieldsValidate = array('id_customer' => 'isUnsignedId', 'id_order' => 'isUnsignedId', 'conversion_rate' => 'isFloat');
protected $table = 'order_slip';
protected $identifier = 'id_order_slip';
public function getFields()
{
parent::validateFields();
$fields['id_customer'] = (int)($this->id_customer);
$fields['id_order'] = (int)($this->id_order);
$fields['conversion_rate'] = (float)($this->conversion_rate);
$fields['shipping_cost'] = (int)($this->shipping_cost);
$fields['date_add'] = pSQL($this->date_add);
$fields['date_upd'] = pSQL($this->date_upd);
return $fields;
}
public function addSlipDetail($orderDetailList, $productQtyList)
{
foreach ($orderDetailList as $key => $orderDetail)
{
if ($qty = (int)($productQtyList[$key]))
Db::getInstance()->AutoExecute(_DB_PREFIX_.'order_slip_detail', array('id_order_slip' => (int)($this->id), 'id_order_detail' => (int)($orderDetail), 'product_quantity' => $qty), 'INSERT');
}
}
static public function getOrdersSlip($customer_id, $order_id = false)
{
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'order_slip`
WHERE `id_customer` = '.(int)($customer_id).
($order_id ? ' AND `id_order` = '.(int)($order_id) : '').'
ORDER BY `date_add` DESC');
}
static public function getOrdersSlipDetail($id_order_slip = true, $id_order_detail = false)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS(
($id_order_detail ? 'SELECT SUM(`product_quantity`) AS `total`' : 'SELECT *').
'FROM `'._DB_PREFIX_.'order_slip_detail`'
.($id_order_slip ? ' WHERE `id_order_slip` = '.(int)($id_order_slip) : '')
.($id_order_detail ? ' WHERE `id_order_detail` = '.(int)($id_order_detail) : ''));
}
static public function getOrdersSlipProducts($orderSlipId, $order)
{
$discounts = $order->getDiscounts(true);
$productsRet = self::getOrdersSlipDetail($orderSlipId);
$products = $order->getProductsDetail();
$tmp = array();
foreach ($productsRet as $slip_detail)
$tmp[$slip_detail['id_order_detail']] = $slip_detail['product_quantity'];
$resTab = array();
foreach ($products as $key => $product)
if (isset($tmp[$product['id_order_detail']]))
{
$resTab[$key] = $product;
$resTab[$key]['product_quantity'] = $tmp[$product['id_order_detail']];
if (sizeof($discounts))
{
$order->setProductPrices($product);
$realProductPrice = $resTab[$key]['product_price'];
foreach ($discounts as $discount)
{
if ($discount['id_discount_type'] == 1)
$resTab[$key]['product_price'] -= $realProductPrice * ($discount['value'] / 100);
elseif ($discount['id_discount_type'] == 2)
$resTab[$key]['product_price'] -= (($discount['value'] * ($product['product_price_wt'] / $order->total_products_wt)) / (1.00 + ($product['tax_rate'] / 100)));
}
}
}
return $order->getProducts($resTab);
}
public function getProducts()
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *, osd.product_quantity
FROM `'._DB_PREFIX_.'order_slip_detail` osd
INNER JOIN `'._DB_PREFIX_.'order_detail` od ON osd.id_order_detail = od.id_order_detail
WHERE osd.`id_order_slip` = '.(int)$this->id);
$order = new Order($this->id_order);
$products = array();
foreach ($result AS $row)
{
$order->setProductPrices($row);
$products[] = $row;
}
return $products;
}
static public function getSlipsIdByDate($dateFrom, $dateTo)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT `id_order_slip`
FROM `'._DB_PREFIX_.'order_slip`
WHERE `date_add` BETWEEN \''.pSQL($dateFrom).' 00:00:00\' AND \''.pSQL($dateTo).' 23:59:59\'
ORDER BY `date_add` ASC');
$slips = array();
foreach ($result AS $slip)
$slips[] = (int)$slip['id_order_slip'];
return $slips;
}
static public function createOrderSlip($order, $productList, $qtyList, $shipping_cost = false)
{
$currency = new Currency($order->id_currency);
$orderSlip = new OrderSlip();
$orderSlip->id_customer = (int)($order->id_customer);
$orderSlip->id_order = (int)($order->id);
$orderSlip->shipping_cost = (int)($shipping_cost);
$orderSlip->conversion_rate = $currency->conversion_rate;
if (!$orderSlip->add())
return false;
$orderSlip->addSlipDetail($productList, $qtyList);
return true;
}
}
+132
View File
@@ -0,0 +1,132 @@
<?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 OrderStateCore extends ObjectModel
{
/** @var string Name */
public $name;
/** @var string Template name if there is any e-mail to send */
public $template;
/** @var boolean Send an e-mail to customer ? */
public $send_email;
/** @var boolean Allow customer to view and download invoice when order is at this state */
public $invoice;
/** @var string Display state in the specified color */
public $color;
public $unremovable;
/** @var boolean Log authorization */
public $logable;
/** @var boolean Delivery */
public $delivery;
/** @var boolean Hidden */
public $hidden;
protected $fieldsValidate = array('send_email' => 'isBool', 'invoice' => 'isBool', 'color' => 'isColor', 'logable' => 'isBool');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 64, 'template' => 64);
protected $fieldsValidateLang = array('name' => 'isGenericName', 'template' => 'isTplName');
protected $table = 'order_state';
protected $identifier = 'id_order_state';
protected $webserviceParameters = array(
'fields' => array(
'unremovable' => array(),
'delivery' => array(),
'hidden' => array(),
),
);
public function getFields()
{
parent::validateFields();
$fields['send_email'] = (int)($this->send_email);
$fields['invoice'] = (int)($this->invoice);
$fields['color'] = pSQL($this->color);
$fields['unremovable'] = (int)($this->unremovable);
$fields['logable'] = (int)($this->logable);
$fields['delivery'] = (int)($this->delivery);
$fields['hidden'] = (int)($this->hidden);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name', 'template'));
}
/**
* Get all available order states
*
* @param integer $id_lang Language id for state name
* @return array Order states
*/
static public function getOrderStates($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'order_state` os
LEFT JOIN `'._DB_PREFIX_.'order_state_lang` osl ON (os.`id_order_state` = osl.`id_order_state` AND osl.`id_lang` = '.(int)($id_lang).')
ORDER BY `name` ASC');
}
/**
* Check if we can make a facture when order is in this state
*
* @param integer $id_order_state State ID
* @return boolean availability
*/
static public function invoiceAvailable($id_order_state)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `invoice` AS ok
FROM `'._DB_PREFIX_.'order_state`
WHERE `id_order_state` = '.(int)($id_order_state));
return $result['ok'];
}
public function isRemovable()
{
return !($this->unremovable);
}
}
+1128
View File
File diff suppressed because it is too large Load Diff
+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: 6844 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class PackCore extends Product
{
protected static $cachePackItems = array();
protected static $cacheIsPack = array();
protected static $cacheIsPacked = array();
public static function isPack($id_product)
{
if (!array_key_exists($id_product, self::$cacheIsPack))
{
$result = Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_.'pack WHERE id_product_pack = '.(int)($id_product));
self::$cacheIsPack[$id_product] = ($result > 0);
}
return self::$cacheIsPack[$id_product];
}
public static function isPacked($id_product)
{
if (!array_key_exists($id_product, self::$cacheIsPacked))
{
$result = Db::getInstance()->getValue('SELECT COUNT(*) FROM '._DB_PREFIX_.'pack WHERE id_product_item = '.(int)($id_product));
self::$cacheIsPacked[$id_product] = ($result > 0);
}
return self::$cacheIsPacked[$id_product];
}
public static function noPackPrice($id_product)
{
global $cookie;
$sum = 0;
$price_display_method = !self::$_taxCalculationMethod;
$items = self::getItems($id_product, Configuration::get('PS_LANG_DEFAULT'));
foreach ($items as $item)
$sum += $item->getPrice($price_display_method) * $item->pack_quantity;
return $sum;
}
public static function getItems($id_product, $id_lang)
{
if (array_key_exists($id_product, self::$cachePackItems))
return self::$cachePackItems[$id_product];
$result = Db::getInstance()->ExecuteS('SELECT id_product_item, quantity FROM '._DB_PREFIX_.'pack where id_product_pack = '.(int)($id_product));
$arrayResult = array();
foreach ($result AS $row)
{
$p = new Product($row['id_product_item'], false, (int)($id_lang));
$p->pack_quantity = $row['quantity'];
$arrayResult[] = $p;
}
self::$cachePackItems[$id_product] = $arrayResult;
return self::$cachePackItems[$id_product];
}
public static function isInStock($id_product)
{
$items = self::getItems((int)($id_product), Configuration::get('PS_LANG_DEFAULT'));
foreach ($items AS $item)
if ($item->quantity < $item->pack_quantity AND !$item->isAvailableWhenOutOfStock((int)($item->out_of_stock)))
return false;
return true;
}
public static function getItemTable($id_product, $id_lang, $full = false)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.*, pl.*, i.`id_image`, il.`legend`, t.`rate`, cl.`name` AS category_default, a.quantity AS pack_quantity
FROM `'._DB_PREFIX_.'pack` a
LEFT JOIN `'._DB_PREFIX_.'product` p ON p.id_product = a.id_product_item
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.id_product = pl.id_product AND pl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)($id_lang).')
WHERE a.`id_product_pack` = '.(int)($id_product)
);
if (!$full)
return $result;
$arrayResult = array();
foreach ($result as $row)
if (!Pack::isPack($row['id_product']))
$arrayResult[] = Product::getProductProperties($id_lang, $row);
return $arrayResult;
}
public static function getPacksTable($id_product, $id_lang, $full = false, $limit = NULL)
{
$packs = Db::getInstance()->getValue('
SELECT GROUP_CONCAT(a.`id_product_pack`)
FROM `'._DB_PREFIX_.'pack` a
WHERE a.`id_product_item` = '.(int)$id_product);
if (!(int)$packs)
return array();
$sql = '
SELECT p.*, pl.*, i.`id_image`, il.`legend`, t.`rate`
FROM `'._DB_PREFIX_.'product` p
NATURAL LEFT JOIN `'._DB_PREFIX_.'product_lang` pl
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'tax_lang` tl ON (t.`id_tax` = tl.`id_tax` AND tl.`id_lang` = '.(int)$id_lang.')
WHERE pl.`id_lang` = '.(int)$id_lang.'
AND p.`id_product` IN ('.$packs.')';
if ($limit)
$sql .= ' LIMIT '.(int)$limit;
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql);
if (!$full)
return $result;
$arrayResult = array();
foreach ($result as $row)
if (!Pack::isPacked($row['id_product']))
$arrayResult[] = Product::getProductProperties($id_lang, $row);
return $arrayResult;
}
public static function deleteItems($id_product)
{
Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'product SET cache_is_pack = 0 WHERE id_product = '.(int)($id_product).' LIMIT 1');
return Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'pack` WHERE `id_product_pack` = '.(int)($id_product));
}
/**
* @deprecated
*/
public static function addItems($id_product, $ids)
{
Tools::displayAsDeprecated();
array_pop($ids);
foreach ($ids as $id_product_item)
{
$idQty = explode('x', $id_product_item);
if (!self::addItem($id_product, $idQty[1], $idQty[0]))
return false;
}
return true;
}
/**
* Add an item to the pack
*
* @param integer $id_product
* @param integer $id_item
* @param integer $qty
* @return boolean true if everything was fine
*/
public static function addItem($id_product, $id_item, $qty)
{
Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'product SET cache_is_pack = 1 WHERE id_product = '.(int)($id_product).' LIMIT 1');
return Db::getInstance()->AutoExecute(_DB_PREFIX_.'pack', array('id_product_pack' => (int)($id_product), 'id_product_item' => (int)($id_item), 'quantity' => (int)($qty)), 'INSERT');
}
public static function duplicate($id_product_old, $id_product_new)
{
Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'pack (id_product_pack, id_product_item, quantity)
(SELECT '.(int)($id_product_new).', id_product_item, quantity FROM '._DB_PREFIX_.'pack WHERE id_product_pack = '.(int)($id_product_old).')');
// If return query result, a non-pack product will return false
return true;
}
}
+129
View File
@@ -0,0 +1,129 @@
<?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: 6946 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class PageCore extends ObjectModel
{
public $id_page_type;
public $id_object;
public $name;
protected $fieldsRequired = array ('id_page_type');
protected $fieldsValidate = array ('id_page_type' => 'isUnsignedId', 'id_object' => 'isUnsignedId');
protected $table = 'page';
protected $identifier = 'id_page';
public function getFields()
{
parent::validateFields();
$fields['id_page_type'] = (int)($this->id_page_type);
$fields['id_object'] = (int)($this->id_object);
return $fields;
}
/**
* @return int Current page ID
*/
public static function getCurrentId()
{
$phpSelf = isset($_SERVER['PHP_SELF']) ? substr($_SERVER['PHP_SELF'], strlen(__PS_BASE_URI__)) : '';
$pageTypeID = Page::getPageTypeByName($phpSelf);
// Some pages must be distinguished in order to record exactly what is being seen
$specialArray = array(
'product.php' => 'id_product',
'category.php' => 'id_category',
'order.php' => 'step',
'manufacturer.php' => 'id_manufacturer',
);
$where = '';
$insertData = array(
'id_page_type' => $pageTypeID,
);
if (array_key_exists($phpSelf, $specialArray))
{
$objectID = Tools::getValue($specialArray[$phpSelf]);
$where = ' AND `id_object` = '.(int)$objectID;
$insertData['id_object'] = $objectID;
}
$sql = 'SELECT `id_page`
FROM `'._DB_PREFIX_.'page`
WHERE `id_page_type` = '.(int)$pageTypeID.$where;
$result = Db::getInstance()->getRow($sql);
if ($result['id_page'])
return $result['id_page'];
Db::getInstance()->autoExecute(_DB_PREFIX_.'page', $insertData, 'INSERT');
return Db::getInstance()->Insert_ID();
}
/**
* Return page type ID from page name
*
* @param string $name Page name (E.g. product.php)
*/
public static function getPageTypeByName($name)
{
$sql = 'SELECT id_page_type
FROM '._DB_PREFIX_.'page_type
WHERE name = \''.pSQL($name).'\'';
if ($value = Db::getInstance()->getValue($sql))
return $value;
Db::getInstance()->autoExecute(_DB_PREFIX_.'page_type', array(
'name' => $name,
), 'INSERT');
return Db::getInstance()->Insert_ID();
}
public static function setPageViewed($id_page)
{
$id_date_range = DateRange::getCurrentRange();
// Try to increment the visits counter
$sql = 'UPDATE `'._DB_PREFIX_.'page_viewed`
SET `counter` = `counter` + 1
WHERE `id_date_range` = '.(int)$id_date_range.'
AND `id_page` = '.(int)$id_page.'
AND `id_shop` = ' . Shop::getCurrentShop();
Db::getInstance()->Execute($sql);
// If no one has seen the page in this date range, it is added
if (Db::getInstance()->Affected_Rows() == 0)
Db::getInstance()->autoExecute(_DB_PREFIX_.'page_viewed', array(
'id_date_range' => (int)$id_date_range,
'id_page' => (int)$id_page,
'counter' => 1,
'id_shop' => Shop::getCurrentShop(),
'id_group_shop' => Shop::getCurrentGroupShop(),
), 'INSERT');
}
}
+74
View File
@@ -0,0 +1,74 @@
<?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 PaymentCCCore extends ObjectModel
{
public $id_order;
public $id_currency;
public $amount;
public $transaction_id;
public $card_number;
public $card_brand;
public $card_expiration;
public $card_holder;
public $date_add;
protected $fieldsRequired = array('id_currency', 'amount');
protected $fieldsSize = array('transaction_id' => 254, 'card_number' => 254, 'card_brand' => 254, 'card_expiration' => 254, 'card_holder' => 254);
protected $fieldsValidate = array(
'id_order' => 'isUnsignedId', 'id_currency' => 'isUnsignedId', 'amount' => 'isPrice',
'transaction_id' => 'isAnything', 'card_number' => 'isAnything', 'card_brand' => 'isAnything', 'card_expiration' => 'isAnything', 'card_holder' => 'isAnything');
protected $table = 'payment_cc';
protected $identifier = 'id_payment_cc';
public function getFields()
{
parent::validateFields();
$fields['id_order'] = (int)($this->id_order);
$fields['id_currency'] = (int)($this->id_currency);
$fields['amount'] = (float)($this->amount);
$fields['transaction_id'] = pSQL($this->transaction_id);
$fields['card_number'] = pSQL($this->card_number);
$fields['card_brand'] = pSQL($this->card_brand);
$fields['card_expiration'] = pSQL($this->card_expiration);
$fields['card_holder'] = pSQL($this->card_holder);
$fields['date_add'] = pSQL($this->date_add);
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
if (parent::add($autodate, $nullValues))
{
Module::hookExec('paymentCCAdded', array('paymentCC' => $this));
return true;
}
return false;
}
}
+535
View File
@@ -0,0 +1,535 @@
<?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
*/
include_once(dirname(__FILE__).'/../config/config.inc.php');
abstract class PaymentModuleCore extends Module
{
/** @var integer Current order's id */
public $currentOrder;
public $currencies = true;
public $currencies_mode = 'checkbox';
public function install()
{
if (!parent::install())
return false;
// Insert currencies availability
if ($this->currencies_mode == 'checkbox')
{
if (!Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'module_currency` (id_module, id_currency)
SELECT '.(int)($this->id).', id_currency FROM `'._DB_PREFIX_.'currency` WHERE deleted = 0'))
return false;
}
elseif ($this->currencies_mode == 'radio')
{
if (!Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'module_currency` (id_module, id_currency)
VALUES ('.(int)($this->id).', -2)'))
return false;
}
else
Tools::displayError('No currency mode for payment module');
// Insert countries availability
$return = Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'module_country` (id_module, id_country)
SELECT '.(int)($this->id).', id_country FROM `'._DB_PREFIX_.'country` WHERE active = 1');
// Insert group availability
$return &= Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'module_group` (id_module, id_group)
SELECT '.(int)($this->id).', id_group FROM `'._DB_PREFIX_.'group`');
return $return;
}
public function uninstall()
{
if (!Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'module_country` WHERE id_module = '.(int)($this->id))
OR !Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'module_currency` WHERE id_module = '.(int)($this->id))
OR !Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'module_group` WHERE id_module = '.(int)($this->id)))
return false;
return parent::uninstall();
}
/**
* Validate an order in database
* Function called from a payment module
*
* @param integer $id_cart Value
* @param integer $id_order_state Value
* @param float $amountPaid Amount really paid by customer (in the default currency)
* @param string $paymentMethod Payment method (eg. 'Credit card')
* @param string $message Message to attach to order
*/
public function validateOrder($id_cart, $id_order_state, $amountPaid, $paymentMethod = 'Unknown', $message = NULL, $extraVars = array(), $currency_special = NULL, $dont_touch_amount = false, $secure_key = false, $id_group_shop = false, $id_shop = false)
{
global $cart;
$cart = new Cart((int)($id_cart));
// Does order already exists ?
if (Validate::isLoadedObject($cart) AND $cart->OrderExists() == false)
{
if ($secure_key !== false AND $secure_key != $cart->secure_key)
die(Tools::displayError());
// Copying data from cart
$order = new Order();
$order->id_carrier = (int)($cart->id_carrier);
$order->id_customer = (int)($cart->id_customer);
$order->id_address_invoice = (int)($cart->id_address_invoice);
$order->id_address_delivery = (int)($cart->id_address_delivery);
$vat_address = new Address((int)($order->id_address_delivery));
$order->id_currency = ($currency_special ? (int)($currency_special) : (int)($cart->id_currency));
$order->id_lang = (int)($cart->id_lang);
$order->id_cart = (int)($cart->id);
$order->id_group_shop = (int)($id_group_shop ? $id_group_shop : $cart->id_group_shop);
$order->id_shop = (int)($id_shop ? $id_shop : $cart->id_shop);
$customer = new Customer((int)($order->id_customer));
$order->secure_key = ($secure_key ? pSQL($secure_key) : pSQL($customer->secure_key));
$order->payment = $paymentMethod;
if (isset($this->name))
$order->module = $this->name;
$order->recyclable = $cart->recyclable;
$order->gift = (int)($cart->gift);
$order->gift_message = $cart->gift_message;
$currency = new Currency($order->id_currency);
$order->conversion_rate = $currency->conversion_rate;
$amountPaid = !$dont_touch_amount ? Tools::ps_round((float)($amountPaid), 2) : $amountPaid;
$order->total_paid_real = $amountPaid;
$order->total_products = (float)($cart->getOrderTotal(false, Cart::ONLY_PRODUCTS));
$order->total_products_wt = (float)($cart->getOrderTotal(true, Cart::ONLY_PRODUCTS));
$order->total_discounts = (float)(abs($cart->getOrderTotal(true, Cart::ONLY_DISCOUNTS)));
$order->total_shipping = (float)($cart->getOrderShippingCost());
$order->carrier_tax_rate = (float)Tax::getCarrierTaxRate($cart->id_carrier, (int)$cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$order->total_wrapping = (float)(abs($cart->getOrderTotal(true, Cart::ONLY_WRAPPING)));
$order->total_paid = (float)(Tools::ps_round((float)($cart->getOrderTotal(true, Cart::BOTH)), 2));
$order->invoice_date = '0000-00-00 00:00:00';
$order->delivery_date = '0000-00-00 00:00:00';
// Amount paid by customer is not the right one -> Status = payment error
// We don't use the following condition to avoid the float precision issues : http://www.php.net/manual/en/language.types.float.php
// if ($order->total_paid != $order->total_paid_real)
// We use number_format in order to compare two string
if (number_format($order->total_paid, 2) != number_format($order->total_paid_real, 2))
$id_order_state = _PS_OS_ERROR_;
// Creating order
if ($cart->OrderExists() == false)
$result = $order->add();
else
{
$errorMessage = Tools::displayError('An order has already been placed using this cart.');
Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($order->id_cart));
die($errorMessage);
}
// Next !
if ($result AND isset($order->id))
{
if (!$secure_key)
$message .= $this->l('Warning : the secure key is empty, check your payment account before validation');
// Optional message to attach to this order
if (isset($message) AND !empty($message))
{
$msg = new Message();
$message = strip_tags($message, '<br>');
if (Validate::isCleanHtml($message))
{
$msg->message = $message;
$msg->id_order = intval($order->id);
$msg->private = 1;
$msg->add();
}
}
// Insert products from cart into order_detail table
$products = $cart->getProducts();
$productsList = '';
$db = Db::getInstance();
$query = 'INSERT INTO `'._DB_PREFIX_.'order_detail`
(`id_order`, `product_id`, `product_attribute_id`, `product_name`, `product_quantity`, `product_quantity_in_stock`, `product_price`, `reduction_percent`, `reduction_amount`, `group_reduction`, `product_quantity_discount`, `product_ean13`, `product_upc`, `product_reference`, `product_supplier_reference`, `product_weight`, `tax_name`, `tax_rate`, `ecotax`, `ecotax_tax_rate`, `discount_quantity_applied`, `download_deadline`, `download_hash`)
VALUES ';
$customizedDatas = Product::getAllCustomizedDatas((int)($order->id_cart));
Product::addCustomizationPrice($products, $customizedDatas);
$outOfStock = false;
foreach ($products AS $key => $product)
{
$productQuantity = (int)(Product::getQuantity((int)($product['id_product']), ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL)));
$quantityInStock = ($productQuantity - (int)($product['cart_quantity']) < 0) ? $productQuantity : (int)($product['cart_quantity']);
if ($id_order_state != _PS_OS_CANCELED_ AND $id_order_state != _PS_OS_ERROR_)
{
if (Product::updateQuantity($product, (int)$order->id))
$product['stock_quantity'] -= $product['cart_quantity'];
if ($product['stock_quantity'] < 0 && Configuration::get('PS_STOCK_MANAGEMENT'))
$outOfStock = true;
Product::updateDefaultAttribute($product['id_product']);
}
$price = Product::getPriceStatic((int)($product['id_product']), false, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), 6, NULL, false, true, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
$price_wt = Product::getPriceStatic((int)($product['id_product']), true, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), 2, NULL, false, true, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}));
// Add some informations for virtual products
$deadline = '0000-00-00 00:00:00';
$download_hash = NULL;
if ($id_product_download = ProductDownload::getIdFromIdProduct((int)($product['id_product'])))
{
$productDownload = new ProductDownload((int)($id_product_download));
$deadline = $productDownload->getDeadLine();
$download_hash = $productDownload->getHash();
}
// Exclude VAT
if (Tax::excludeTaxeOption())
{
$product['tax'] = 0;
$product['rate'] = 0;
$tax_rate = 0;
}
else
$tax_rate = Tax::getProductTaxRate((int)($product['id_product']), $cart->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$ecotaxTaxRate = 0;
if (!empty($product['ecotax']))
$ecotaxTaxRate = Tax::getProductEcotaxRate($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$quantityDiscount = SpecificPrice::getQuantityDiscount((int)$product['id_product'], Shop::getCurrentShop(), (int)$cart->id_currency, (int)$vat_address->id_country, (int)$customer->id_default_group, (int)$product['cart_quantity']);
$unitPrice = Product::getPriceStatic((int)$product['id_product'], true, ($product['id_product_attribute'] ? intval($product['id_product_attribute']) : NULL), 2, NULL, false, true, 1, false, (int)$order->id_customer, NULL, (int)$order->{Configuration::get('PS_TAX_ADDRESS_TYPE')});
$quantityDiscountValue = $quantityDiscount ? ((Product::getTaxCalculationMethod((int)$order->id_customer) == PS_TAX_EXC ? Tools::ps_round($unitPrice, 2) : $unitPrice) - $quantityDiscount['price'] * (1 + $tax_rate / 100)) : 0.00;
$query .= '('.(int)($order->id).',
'.(int)($product['id_product']).',
'.(isset($product['id_product_attribute']) ? (int)($product['id_product_attribute']) : 'NULL').',
\''.pSQL($product['name'].((isset($product['attributes']) AND $product['attributes'] != NULL) ? ' - '.$product['attributes'] : '')).'\',
'.(int)($product['cart_quantity']).',
'.$quantityInStock.',
'.(float)(Product::getPriceStatic((int)($product['id_product']), false, ($product['id_product_attribute'] ? (int)($product['id_product_attribute']) : NULL), (Product::getTaxCalculationMethod((int)($order->id_customer)) == PS_TAX_EXC ? 2 : 6), NULL, false, false, $product['cart_quantity'], false, (int)($order->id_customer), (int)($order->id_cart), (int)($order->{Configuration::get('PS_TAX_ADDRESS_TYPE')}), $specificPrice, FALSE)).',
'.(float)(($specificPrice AND $specificPrice['reduction_type'] == 'percentage') ? $specificPrice['reduction'] * 100 : 0.00).',
'.(float)(($specificPrice AND $specificPrice['reduction_type'] == 'amount') ? (!$specificPrice['id_currency'] ? Tools::convertPrice($specificPrice['reduction'], $order->id_currency) : $specificPrice['reduction']) : 0.00).',
'.(float)(Group::getReduction((int)($order->id_customer))).',
'.$quantityDiscountValue.',
'.(empty($product['ean13']) ? 'NULL' : '\''.pSQL($product['ean13']).'\'').',
'.(empty($product['upc']) ? 'NULL' : '\''.pSQL($product['upc']).'\'').',
'.(empty($product['reference']) ? 'NULL' : '\''.pSQL($product['reference']).'\'').',
'.(empty($product['supplier_reference']) ? 'NULL' : '\''.pSQL($product['supplier_reference']).'\'').',
'.(float)($product['id_product_attribute'] ? $product['weight_attribute'] : $product['weight']).',
\''.(empty($tax_rate) ? '' : pSQL($product['tax'])).'\',
'.(float)($tax_rate).',
'.(float)Tools::convertPrice(floatval($product['ecotax']), intval($order->id_currency)).',
'.(float)$ecotaxTaxRate.',
'.(($specificPrice AND $specificPrice['from_quantity'] > 1) ? 1 : 0).',
\''.pSQL($deadline).'\',
\''.pSQL($download_hash).'\'),';
$customizationQuantity = 0;
if (isset($customizedDatas[$product['id_product']][$product['id_product_attribute']]))
{
$customizationText = '';
foreach ($customizedDatas[$product['id_product']][$product['id_product_attribute']] AS $customization)
{
if (isset($customization['datas'][_CUSTOMIZE_TEXTFIELD_]))
foreach ($customization['datas'][_CUSTOMIZE_TEXTFIELD_] AS $text)
$customizationText .= $text['name'].':'.' '.$text['value'].'<br />';
if (isset($customization['datas'][_CUSTOMIZE_FILE_]))
$customizationText .= sizeof($customization['datas'][_CUSTOMIZE_FILE_]) .' '. Tools::displayError('image(s)').'<br />';
$customizationText .= '---<br />';
}
$customizationText = rtrim($customizationText, '---<br />');
$customizationQuantity = (int)($product['customizationQuantityTotal']);
$productsList .=
'<tr style="background-color: '.($key % 2 ? '#DDE2E6' : '#EBECEE').';">
<td style="padding: 0.6em 0.4em;">'.$product['reference'].'</td>
<td style="padding: 0.6em 0.4em;"><strong>'.$product['name'].(isset($product['attributes_small']) ? ' '.$product['attributes_small'] : '').' - '.$this->l('Customized').(!empty($customizationText) ? ' - '.$customizationText : '').'</strong></td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false).'</td>
<td style="padding: 0.6em 0.4em; text-align: center;">'.$customizationQuantity.'</td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.Tools::displayPrice($customizationQuantity * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false).'</td>
</tr>';
}
if (!$customizationQuantity OR (int)$product['cart_quantity'] > $customizationQuantity)
$productsList .=
'<tr style="background-color: '.($key % 2 ? '#DDE2E6' : '#EBECEE').';">
<td style="padding: 0.6em 0.4em;">'.$product['reference'].'</td>
<td style="padding: 0.6em 0.4em;"><strong>'.$product['name'].(isset($product['attributes_small']) ? ' '.$product['attributes_small'] : '').'</strong></td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.Tools::displayPrice(Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt, $currency, false).'</td>
<td style="padding: 0.6em 0.4em; text-align: center;">'.((int)($product['cart_quantity']) - $customizationQuantity).'</td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.Tools::displayPrice(((int)($product['cart_quantity']) - $customizationQuantity) * (Product::getTaxCalculationMethod() == PS_TAX_EXC ? $price : $price_wt), $currency, false).'</td>
</tr>';
} // end foreach ($products)
$query = rtrim($query, ',');
$result = $db->Execute($query);
// Insert discounts from cart into order_discount table
$discounts = $cart->getDiscounts();
$discountsList = '';
$total_discount_value = 0;
$shrunk = false;
foreach ($discounts AS $discount)
{
$objDiscount = new Discount((int)$discount['id_discount'], $order->id_lang);
$value = $objDiscount->getValue(sizeof($discounts), $cart->getOrderTotal(true, Cart::ONLY_PRODUCTS), $order->total_shipping, $cart->id);
if ($objDiscount->id_discount_type == 2 AND in_array($objDiscount->behavior_not_exhausted, array(1,2)))
$shrunk = true;
if ($shrunk AND ($total_discount_value + $value) > ($order->total_products + $order->total_shipping + $order->total_wrapping))
{
$amount_to_add = ($order->total_products + $order->total_shipping + $order->total_wrapping) - $total_discount_value;
if ($objDiscount->id_discount_type == 2 AND $objDiscount->behavior_not_exhausted == 2)
{
$voucher = new Discount();
foreach ($objDiscount AS $key => $discountValue)
$voucher->$key = $discountValue;
$voucher->name = 'VSRK'.(int)$order->id_customer.'O'.(int)$order->id;
$voucher->value = (float)$value - $amount_to_add;
$voucher->add();
$params['{voucher_amount}'] = Tools::displayPrice($voucher->value, $currency, false);
$params['{voucher_num}'] = $voucher->name;
@Mail::Send((int)$order->id_lang, 'voucher', Mail::l('New voucher regarding your order #').$order->id, $params, $customer->email, $customer->firstname.' '.$customer->lastname);
}
}
else
$amount_to_add = $value;
$order->addDiscount($objDiscount->id, $objDiscount->name, $amount_to_add);
$total_discount_value += $amount_to_add;
if ($id_order_state != _PS_OS_ERROR_ AND $id_order_state != _PS_OS_CANCELED_)
$objDiscount->quantity = $objDiscount->quantity - 1;
$objDiscount->update();
$discountsList .=
'<tr style="background-color:#EBECEE;">
<td colspan="4" style="padding: 0.6em 0.4em; text-align: right;">'.$this->l('Voucher code:').' '.$objDiscount->name.'</td>
<td style="padding: 0.6em 0.4em; text-align: right;">'.($value != 0.00 ? '-' : '').Tools::displayPrice($value, $currency, false).'</td>
</tr>';
}
// Specify order id for message
$oldMessage = Message::getMessageByCartId((int)($cart->id));
if ($oldMessage)
{
$message = new Message((int)$oldMessage['id_message']);
$message->id_order = (int)$order->id;
$message->update();
}
// Hook new order
$orderStatus = new OrderState((int)$id_order_state, (int)$order->id_lang);
if (Validate::isLoadedObject($orderStatus))
{
Hook::newOrder($cart, $order, $customer, $currency, $orderStatus);
foreach ($cart->getProducts() AS $product)
if ($orderStatus->logable)
ProductSale::addProductSale((int)$product['id_product'], (int)$product['cart_quantity']);
}
if (isset($outOfStock) AND $outOfStock)
{
$history = new OrderHistory();
$history->id_order = (int)$order->id;
$history->changeIdOrderState(_PS_OS_OUTOFSTOCK_, (int)$order->id);
$history->addWithemail();
}
// Set order state in order history ONLY even if the "out of stock" status has not been yet reached
// So you migth have two order states
$new_history = new OrderHistory();
$new_history->id_order = (int)$order->id;
$new_history->changeIdOrderState((int)$id_order_state, (int)$order->id);
$new_history->addWithemail(true, $extraVars);
// Order is reloaded because the status just changed
$order = new Order($order->id);
// Send an e-mail to customer
if ($id_order_state != _PS_OS_ERROR_ AND $id_order_state != _PS_OS_CANCELED_ AND $customer->id)
{
$invoice = new Address((int)($order->id_address_invoice));
$delivery = new Address((int)($order->id_address_delivery));
$carrier = new Carrier((int)($order->id_carrier), $order->id_lang);
$delivery_state = $delivery->id_state ? new State((int)($delivery->id_state)) : false;
$invoice_state = $invoice->id_state ? new State((int)($invoice->id_state)) : false;
$data = array(
'{firstname}' => $customer->firstname,
'{lastname}' => $customer->lastname,
'{email}' => $customer->email,
'{delivery_block_txt}' => $this->_getFormatedAddress($delivery, "\n"),
'{invoice_block_txt}' => $this->_getFormatedAddress($invoice, "\n"),
'{delivery_block_html}' => $this->_getFormatedAddress($delivery, "<br />",
array(
'firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>',
'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')),
'{invoice_block_html}' => $this->_getFormatedAddress($invoice, "<br />",
array(
'firstname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>',
'lastname' => '<span style="color:#DB3484; font-weight:bold;">%s</span>')),
'{delivery_company}' => $delivery->company,
'{delivery_firstname}' => $delivery->firstname,
'{delivery_lastname}' => $delivery->lastname,
'{delivery_address1}' => $delivery->address1,
'{delivery_address2}' => $delivery->address2,
'{delivery_city}' => $delivery->city,
'{delivery_postal_code}' => $delivery->postcode,
'{delivery_country}' => $delivery->country,
'{delivery_state}' => $delivery->id_state ? $delivery_state->name : '',
'{delivery_phone}' => ($delivery->phone) ? $delivery->phone : $delivery->phone_mobile,
'{delivery_other}' => $delivery->other,
'{invoice_company}' => $invoice->company,
'{invoice_vat_number}' => $invoice->vat_number,
'{invoice_firstname}' => $invoice->firstname,
'{invoice_lastname}' => $invoice->lastname,
'{invoice_address2}' => $invoice->address2,
'{invoice_address1}' => $invoice->address1,
'{invoice_city}' => $invoice->city,
'{invoice_postal_code}' => $invoice->postcode,
'{invoice_country}' => $invoice->country,
'{invoice_state}' => $invoice->id_state ? $invoice_state->name : '',
'{invoice_phone}' => ($invoice->phone) ? $invoice->phone : $invoice->phone_mobile,
'{invoice_other}' => $invoice->other,
'{order_name}' => sprintf("#%06d", (int)($order->id)),
'{date}' => Tools::displayDate(date('Y-m-d H:i:s'), (int)($order->id_lang), 1),
'{carrier}' => $carrier->name,
'{payment}' => Tools::substr($order->payment, 0, 32),
'{products}' => $productsList,
'{discounts}' => $discountsList,
'{total_paid}' => Tools::displayPrice($order->total_paid, $currency, false),
'{total_products}' => Tools::displayPrice($order->total_paid - $order->total_shipping - $order->total_wrapping + $order->total_discounts, $currency, false),
'{total_discounts}' => Tools::displayPrice($order->total_discounts, $currency, false),
'{total_shipping}' => Tools::displayPrice($order->total_shipping, $currency, false),
'{total_wrapping}' => Tools::displayPrice($order->total_wrapping, $currency, false));
if (is_array($extraVars))
$data = array_merge($data, $extraVars);
// Join PDF invoice
if ((int)(Configuration::get('PS_INVOICE')) AND Validate::isLoadedObject($orderStatus) AND $orderStatus->invoice AND $order->invoice_number)
{
$fileAttachment['content'] = PDF::invoice($order, 'S');
$fileAttachment['name'] = Configuration::get('PS_INVOICE_PREFIX', (int)($order->id_lang)).sprintf('%06d', $order->invoice_number).'.pdf';
$fileAttachment['mime'] = 'application/pdf';
}
else
$fileAttachment = NULL;
if (Validate::isEmail($customer->email))
Mail::Send((int)($order->id_lang), 'order_conf', Mail::l('Order confirmation'), $data, $customer->email, $customer->firstname.' '.$customer->lastname, NULL, NULL, $fileAttachment);
}
$this->currentOrder = (int)($order->id);
return true;
}
else
{
$errorMessage = Tools::displayError('Order creation failed');
Logger::addLog($errorMessage, 4, '0000002', 'Cart', intval($order->id_cart));
die($errorMessage);
}
}
else
{
$errorMessage = Tools::displayError('Cart can\'t be loaded or an order has already been placed using this cart');
Logger::addLog($errorMessage, 4, '0000001', 'Cart', intval($cart->id));
die($errorMessage);
}
}
/**
* @param Object Address $the_address that needs to be txt formated
* @return String the txt formated address block
*/
private function _getTxtFormatedAddress($the_address)
{
$out = '';
$adr_fields = AddressFormat::getOrderedAddressFields($the_address->id_country);
$r_values = array();
foreach($adr_fields as $fields_line)
{
$tmp_values = array();
foreach (explode(' ', $fields_line) as $field_item)
{
$field_item = trim($field_item);
$tmp_values[] = $the_address->{$field_item};
}
$r_values[] = implode(' ', $tmp_values);
}
$out = implode("\n", $r_values);
return $out;
}
/**
* @param Object Address $the_address that needs to be txt formated
* @return String the txt formated address block
*/
private function _getFormatedAddress(Address $the_address, $line_sep, $fields_style = array())
{
return AddressFormat::generateAddress($the_address, array('avoid' => array()), $line_sep, ' ', $fields_style);
}
/**
* @param int $id_currency : this parameter is optionnal but on 1.5 version of Prestashop, it will be REQUIRED
* @return Currency
*/
public function getCurrency($current_id_currency = NULL)
{
if (!(int)$current_id_currency)
global $cookie;
if (!$this->currencies)
return false;
if ($this->currencies_mode == 'checkbox')
{
$currencies = Currency::getPaymentCurrencies($this->id);
return $currencies;
}
elseif ($this->currencies_mode == 'radio')
{
$currencies = Currency::getPaymentCurrenciesSpecial($this->id);
$currency = $currencies['id_currency'];
if ($currency == -1)
{
// not use $cookie if $current_id_currency is set
if ((int)$current_id_currency)
$id_currency = (int)$current_id_currency;
else
$id_currency = (int)($cookie->id_currency);
}
elseif ($currency == -2)
$id_currency = (int)(Configuration::get('PS_CURRENCY_DEFAULT'));
else
$id_currency = $currency;
}
if (!isset($id_currency) OR empty($id_currency))
return false;
return (new Currency($id_currency));
}
}
+3486
View File
File diff suppressed because it is too large Load Diff
+272
View File
@@ -0,0 +1,272 @@
<?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: 7099 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ProductDownloadCore extends ObjectModel
{
/** @var integer Product id which download belongs */
public $id_product;
/** @var string DisplayFilename the name which appear */
public $display_filename;
/** @var string PhysicallyFilename the name of the file on hard disk */
public $physically_filename;
/** @var string DateDeposit when the file is upload */
public $date_deposit;
/** @var string DateExpiration deadline of the file */
public $date_expiration;
/** @var string NbDaysAccessible how many days the customer can access to file */
public $nb_days_accessible;
/** @var string NbDownloadable how many time the customer can download the file */
public $nb_downloadable;
/** @var boolean Active if file is accessible or not */
public $active = 1;
protected static $_productIds = array();
protected $fieldsRequired = array(
'id_product',
'display_filename'
);
protected $fieldsSize = array(
'display_filename' => 255,
'physically_filename' => 255,
'date_deposit' => 20,
'date_expiration' => 20,
'nb_days_accessible' => 10,
'nb_downloadable' => 10,
'active' => 1
);
protected $fieldsValidate = array(
'id_product' => 'isUnsignedId',
'display_filename' => 'isGenericName',
'physically_filename' => 'isSha1',
'date_deposit' => 'isDate',
'date_expiration' => 'isDate',
'nb_days_accessible' => 'isUnsignedInt',
'nb_downloadable' => 'isUnsignedInt',
'active' => 'isUnsignedInt'
);
protected $table = 'product_download';
protected $identifier = 'id_product_download';
/**
* Build a virtual product
*
* @param integer $id_product_download Existing productDownload id in order to load object (optional)
*/
public function __construct($id_product_download = NULL)
{
parent::__construct($id_product_download);
// TODO check if the file is present on hard drive
}
public function delete($deleteFile=false)
{
if ($deleteFile)
$this->deleteFile();
}
public function getFields()
{
parent::validateFields();
$fields['id_product'] = (int)($this->id_product);
$fields['display_filename'] = pSQL($this->display_filename);
$fields['physically_filename'] = pSQL($this->physically_filename);
$fields['date_deposit'] = pSQL($this->date_deposit);
$fields['date_expiration'] = pSQL($this->date_expiration);
$fields['nb_days_accessible'] = (int)($this->nb_days_accessible);
$fields['nb_downloadable'] = (int)($this->nb_downloadable);
$fields['active'] = (int)($this->active);
return $fields;
}
/**
* Delete the file
*
* @return boolean
*/
public function deleteFile()
{
if (!$this->checkFile())
return false;
return unlink(_PS_DOWNLOAD_DIR_.$this->physically_filename);
}
/**
* Check if file exists
*
* @return boolean
*/
public function checkFile()
{
if (!$this->physically_filename) return false;
return file_exists(_PS_DOWNLOAD_DIR_.$this->physically_filename);
}
/**
* Check if download repository is writable
*
* @return boolean
*/
static public function checkWritableDir()
{
return is_writable(_PS_DOWNLOAD_DIR_);
}
/**
* Return the id_product_download from an id_product
*
* @param int $id_product Product the id
* @return integer Product the id for this virtual product
*/
public static function getIdFromIdProduct($id_product)
{
if (array_key_exists($id_product, self::$_productIds))
return self::$_productIds[$id_product];
$data = Db::getInstance()->getRow('
SELECT `id_product_download`
FROM `'._DB_PREFIX_.'product_download`
WHERE `id_product` = '.(int)($id_product).' AND `active` = 1');
self::$_productIds[$id_product] = isset($data['id_product_download']) ? (int)($data['id_product_download']) : false;
return self::$_productIds[$id_product];
}
/**
* Return the filename from an id_product
*
* @param int $id_product Product the id
* @return string Filename the filename for this virtual product
*/
public static function getFilenameFromIdProduct($id_product)
{
$data = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `physically_filename`
FROM `'._DB_PREFIX_.'product_download`
WHERE `id_product` = '.(int)($id_product).'
AND `active` = 1');
return $data['physically_filename'];
}
/**
* Return the display filename from a physical filename
*
* @param string $physically_filename Filename physically
* @return string Filename the display filename for this virtual product
*/
public static function getFilenameFromFilename($physically_filename)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `display_filename`
FROM `'._DB_PREFIX_.'product_download`
WHERE `physically_filename` = \''.pSQL($physically_filename).'\'');
}
/**
* Return html link
*
* @param string $class CSS selector (optionnal)
* @param bool $admin specific to backend (optionnal)
* @param string $hash hash code in table order detail (optionnal)
* @return string Html all the code for print a link to the file
*/
public function getTextLink($admin=true, $hash=false)
{
$key = $this->physically_filename . '-' . ($hash ? $hash : 'orderdetail');
$link = ($admin) ? './index.php?controller=get-file-admin' : Tools::getHttpHost(true, true).'index.php?controller=get-file';
$link .= ($admin) ? 'file='.$this->physically_filename : 'key='.$key;
return $link;
}
/**
* Return html link
*
* @param string $class CSS selector (optionnal)
* @param bool $admin specific to backend (optionnal)
* @param string $hash hash code in table order detail (optionnal)
* @return string Html all the code for print a link to the file
*/
public function getHtmlLink($class=false, $admin=true, $hash=false)
{
$link = $this->getTextLink($admin, $hash);
$html = '<a href="'.$link.'" title=""';
if ($class) $html.= ' class="'.$class.'"';
$html.= '>'.$this->display_filename.'</a>';
return $html;
}
/**
* Return a deadline
*
* @return string Datetime in SQL format
*/
public function getDeadline()
{
if (!(int)($this->nb_days_accessible))
return '0000-00-00 00:00:00';
$timestamp = strtotime('+'.(int)($this->nb_days_accessible).' day');
return date('Y-m-d H:i:s', $timestamp);
}
/**
* Return a hash for control download access
*
* @return string Hash ready to insert in database
*/
public function getHash()
{
// TODO check if this hash not already in database
return sha1(microtime().$this->id);
}
/**
* Return a sha1 filename
*
* @return string Sha1 unique filename
*/
static public function getNewFilename()
{
$ret = sha1(microtime());
if (file_exists(_PS_DOWNLOAD_DIR_.$ret))
$ret = ProductDownload::getNewFilename();
return $ret;
}
}
+186
View File
@@ -0,0 +1,186 @@
<?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: 7484 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ProductSaleCore
{
/*
** Fill the `product_sale` SQL table with data from `order_detail`
** @return bool True on success
*/
static public function fillProductSales()
{
return Db::getInstance()->Execute('
REPLACE INTO '._DB_PREFIX_.'product_sale
(`id_product`, `quantity`, `sale_nbr`, `date_upd`)
SELECT od.product_id, COUNT(od.product_id), SUM(od.product_quantity), NOW()
FROM '._DB_PREFIX_.'order_detail od GROUP BY od.product_id');
}
/*
** Get number of actives products sold
** @return int number of actives products listed in product_sales
*/
static public function getNbSales($id_shop = false)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(ps.`id_product`) AS nb
FROM `'._DB_PREFIX_.'product_sale` ps
'.($id_shop ? 'LEFT JOIN '._DB_PREFIX_.'product_shop pss ON (pss.id_product = ps.id_product)' : '').'
LEFT JOIN `'._DB_PREFIX_.'product` p ON p.`id_product` = ps.`id_product`
WHERE p.`active` = 1'.($id_shop ? ' AND pss.id_shop='.(int)$id_shop : ''));
return (int)($result['nb']);
}
/*
** Get required informations on best sales products
**
** @param integer $id_lang Language id
** @param integer $pageNumber Start from (optional)
** @param integer $nbProducts Number of products to return (optional)
** @return array from Product::getProductProperties
*/
static public function getBestSales($id_lang, $pageNumber = 0, $nbProducts = 10, $orderBy=NULL, $orderWay=NULL, $id_shop = false)
{
if ($pageNumber < 0) $pageNumber = 0;
if ($nbProducts < 1) $nbProducts = 10;
if (empty($orderBy) || $orderBy == 'position') $orderBy = 'sales';
if (empty($orderWay)) $orderWay = 'DESC';
$groups = FrontController::getCurrentCustomerGroups();
$sqlGroups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.*,
pl.`description`, pl.`description_short`, pl.`link_rewrite`, pl.`meta_description`, pl.`meta_keywords`, pl.`meta_title`, pl.`name`, m.`name` AS manufacturer_name, p.`id_manufacturer` as id_manufacturer,
i.`id_image`, il.`legend`,
ps.`quantity` AS sales, t.`rate`, pl.`meta_keywords`, pl.`meta_title`, pl.`meta_description`,
DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 AS new
FROM `'._DB_PREFIX_.'product_sale` ps
LEFT JOIN `'._DB_PREFIX_.'product` p ON ps.`id_product` = p.`id_product`
'.($id_shop ? 'LEFT JOIN `'._DB_PREFIX_.'product_shop` pss ON (pss.`id_product` = p.`id_product`)' : '').'
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)($id_lang).')
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` t ON (t.`id_tax` = tr.`id_tax`)
WHERE p.`active` = 1
'.($id_shop ? ' AND pss.id_shop='.(int)$id_shop : '').'
AND p.`id_product` IN (
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_group` cg
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
WHERE cg.`id_group` '.$sqlGroups.'
)
ORDER BY '.(isset($orderByPrefix) ? $orderByPrefix.'.' : '').'`'.pSQL($orderBy).'` '.pSQL($orderWay).'
LIMIT '.(int)($pageNumber * $nbProducts).', '.(int)($nbProducts));
if ($orderBy == 'price')
Tools::orderbyPrice($result,$orderWay);
if (!$result)
return false;
return Product::getProductsProperties($id_lang, $result);
}
/*
** Get required informations on best sales products
**
** @param integer $id_lang Language id
** @param integer $pageNumber Start from (optional)
** @param integer $nbProducts Number of products to return (optional)
** @return array keys : id_product, link_rewrite, name, id_image, legend, sales, ean13, upc, link
*/
static public function getBestSalesLight($id_lang, $pageNumber = 0, $nbProducts = 10, $id_shop = null)
{
global $link;
if ($pageNumber < 0) $pageNumber = 0;
if ($nbProducts < 1) $nbProducts = 10;
if (is_null($id_shop)) $id_shop = Shop::getCurrentShop();
$groups = FrontController::getCurrentCustomerGroups();
$sqlGroups = (count($groups) ? 'IN ('.implode(',', $groups).')' : '= 1');
$sql = 'SELECT p.id_product, pl.`link_rewrite`, pl.`name`, pl.`description_short`, i.`id_image`, il.`legend`, ps.`quantity` AS sales, p.`ean13`, p.`upc`, cl.`link_rewrite` AS category
FROM `'._DB_PREFIX_.'product_sale` ps
LEFT JOIN `'._DB_PREFIX_.'product` p ON ps.`id_product` = p.`id_product`
'.($id_shop ? 'LEFT JOIN `'._DB_PREFIX_.'product_shop` pss ON (pss.`id_product` = p.`id_product`)' : '').'
LEFT JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.(($id_shop) ? ' AND pl.id_shop = '.(int)$id_shop : '').')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'category_lang` cl ON (cl.`id_category` = p.`id_category_default` AND cl.`id_lang` = '.(int)$id_lang.(($id_shop) ? ' AND cl.id_shop = '.(int)$id_shop : '').')
WHERE p.`active` = 1
'.($id_shop ? ' AND pss.id_shop='.(int)$id_shop : '').'
AND p.`id_product` IN (
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_group` cg
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_category` = cg.`id_category`)
WHERE cg.`id_group` '.$sqlGroups.'
)
ORDER BY sales DESC
LIMIT '.(int)($pageNumber * $nbProducts).', '.(int)($nbProducts);
if (!$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS($sql))
return $result;
foreach ($result AS &$row)
{
$row['link'] = $link->getProductLink($row['id_product'], $row['link_rewrite'], $row['category'], $row['ean13']);
$row['id_image'] = Product::defineProductImage($row, $id_lang);
}
return $result;
}
static public function addProductSale($product_id, $qty = 1)
{
return Db::getInstance()->Execute('
INSERT INTO '._DB_PREFIX_.'product_sale
(`id_product`, `quantity`, `sale_nbr`, `date_upd`)
VALUES ('.(int)($product_id).', '.(int)($qty).', 1, NOW())
ON DUPLICATE KEY UPDATE `quantity` = `quantity` + '.(int)($qty).', `sale_nbr` = `sale_nbr` + 1, `date_upd` = NOW()');
}
static public function getNbrSales($id_product)
{
$result = Db::getInstance()->getRow('SELECT `sale_nbr` FROM '._DB_PREFIX_.'product_sale WHERE `id_product` = '.(int)($id_product));
if (!$result OR empty($result) OR !key_exists('sale_nbr', $result))
return -1;
return (int)($result['sale_nbr']);
}
static public function removeProductSale($id_product, $qty = 1)
{
$nbrSales = self::getNbrSales($id_product);
if ($nbrSales > 1)
return Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'product_sale SET `quantity` = `quantity` - '.(int)($qty).', `sale_nbr` = `sale_nbr` - 1, `date_upd` = NOW() WHERE `id_product` = '.(int)($id_product));
elseif ($nbrSales == 1)
return Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'product_sale WHERE `id_product` = '.(int)($id_product));
return true;
}
}
+131
View File
@@ -0,0 +1,131 @@
<?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 ProfileCore extends ObjectModel
{
/** @var string Name */
public $name;
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 32);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $table = 'profile';
protected $identifier = 'id_profile';
public function getFields()
{
return array('id_profile' => $this->id);
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
/**
* Get all available profiles
*
* @return array Profiles
*/
static public function getProfiles($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT p.`id_profile`, `name`
FROM `'._DB_PREFIX_.'profile` p
LEFT JOIN `'._DB_PREFIX_.'profile_lang` pl ON (p.`id_profile` = pl.`id_profile` AND `id_lang` = '.(int)($id_lang).')
ORDER BY `name` ASC');
}
/**
* Get the current profile name
*
* @return string Profile
*/
static public function getProfile($id_profile, $id_lang = NULL)
{
if ($id_lang == NULL)
$id_lang = Configuration::get('PS_LANG_DEFAULT');
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `name`
FROM `'._DB_PREFIX_.'profile` p
LEFT JOIN `'._DB_PREFIX_.'profile_lang` pl ON (p.`id_profile` = pl.`id_profile`)
WHERE p.`id_profile` = '.(int)($id_profile).'
AND pl.`id_lang` = '.(int)($id_lang));
}
public function add($autodate = true, $nullValues = false)
{
if (parent::add($autodate, true))
return Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'access (SELECT '.(int)($this->id).', id_tab, 0, 0, 0, 0 FROM '._DB_PREFIX_.'tab)');
return false;
}
public function delete()
{
if (parent::delete())
return Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'access` WHERE `id_profile` = '.(int)($this->id));
return false;
}
public static function getProfileAccess($id_profile, $id_tab)
{
// getProfileAccesses is cached so there is no performance leak
$accesses = self::getProfileAccesses($id_profile);
return (isset($accesses[$id_tab]) ? $accesses[$id_tab] : false);
}
private static $_cache_accesses = array();
public static function getProfileAccesses($id_profile)
{
if (!isset(self::$_cache_accesses[$id_profile]))
{
$result = Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'access`
WHERE `id_profile` = '.(int)$id_profile);
self::$_cache_accesses[$id_profile] = array();
foreach($result AS $row)
{
if (!isset(self::$_cache_accesses[$id_profile][$row['id_tab']]))
self::$_cache_accesses[$id_profile][$row['id_tab']] = array();
self::$_cache_accesses[$id_profile][$row['id_tab']] = $row;
}
}
return self::$_cache_accesses[$id_profile];
}
}
+82
View File
@@ -0,0 +1,82 @@
<?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 QuickAccessCore extends ObjectModel
{
/** @var string Name */
public $name;
/** @var string Link */
public $link;
/** @var boolean New windows or not */
public $new_window;
protected $fieldsRequired = array('link', 'new_window');
protected $fieldsSize = array('link' => 128);
protected $fieldsValidate = array('link' => 'isUrl', 'new_window' => 'isBool');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 32);
protected $fieldsValidateLang = array('name' => 'isGenericName');
protected $table = 'quick_access';
protected $identifier = 'id_quick_access';
public function getFields()
{
parent::validateFields();
$fields['link'] = pSQL($this->link);
$fields['new_window'] = (int)($this->new_window);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
/**
* Get all available quick_accesses
*
* @return array QuickAccesses
*/
static public function getQuickAccesses($id_lang)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'quick_access` qa
LEFT JOIN `'._DB_PREFIX_.'quick_access_lang` qal ON (qa.`id_quick_access` = qal.`id_quick_access` AND qal.`id_lang` = '.(int)($id_lang).')
ORDER BY `name` ASC');
}
}
+71
View File
@@ -0,0 +1,71 @@
<?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 RangePriceCore extends ObjectModel
{
public $id_carrier;
public $delimiter1;
public $delimiter2;
protected $fieldsRequired = array('id_carrier', 'delimiter1', 'delimiter2');
protected $fieldsValidate = array('id_carrier' => 'isInt', 'delimiter1' => 'isUnsignedFloat', 'delimiter2' => 'isUnsignedFloat');
protected $table = 'range_price';
protected $identifier = 'id_range_price';
protected $webserviceParameters = array(
'objectsNodeName' => 'price_ranges',
'objectNodeName' => 'price_range',
'fields' => array(
'id_carrier' => array('xlink_resource' => 'carriers'),
)
);
public function getFields()
{
parent::validateFields();
$fields['id_carrier'] = (int)($this->id_carrier);
$fields['delimiter1'] = (float)($this->delimiter1);
$fields['delimiter2'] = (float)($this->delimiter2);
return $fields;
}
/**
* Get all available price ranges
*
* @return array Ranges
*/
public static function getRanges($id_carrier)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'range_price`
WHERE `id_carrier` = '.(int)($id_carrier).'
ORDER BY `delimiter1` ASC');
}
}
+71
View File
@@ -0,0 +1,71 @@
<?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 RangeWeightCore extends ObjectModel
{
public $id_carrier;
public $delimiter1;
public $delimiter2;
protected $fieldsRequired = array('id_carrier', 'delimiter1', 'delimiter2');
protected $fieldsValidate = array('id_carrier' => 'isInt', 'delimiter1' => 'isUnsignedFloat', 'delimiter2' => 'isUnsignedFloat');
protected $table = 'range_weight';
protected $identifier = 'id_range_weight';
protected $webserviceParameters = array(
'objectNodeName' => 'weight_range',
'objectsNodeName' => 'weight_ranges',
'fields' => array(
'id_carrier' => array('xlink_resource' => 'carriers'),
)
);
public function getFields()
{
parent::validateFields();
$fields['id_carrier'] = (int)($this->id_carrier);
$fields['delimiter1'] = (float)($this->delimiter1);
$fields['delimiter2'] = (float)($this->delimiter2);
return $fields;
}
/**
* Get all available weight ranges
*
* @return array Ranges
*/
public static function getRanges($id_carrier)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'range_weight`
WHERE `id_carrier` = '.(int)($id_carrier).'
ORDER BY `delimiter1` ASC');
}
}
+315
View File
@@ -0,0 +1,315 @@
<?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 ReferrerCore extends ObjectModel
{
public $name;
public $passwd;
public $http_referer_regexp;
public $http_referer_like;
public $request_uri_regexp;
public $request_uri_like;
public $http_referer_regexp_not;
public $http_referer_like_not;
public $request_uri_regexp_not;
public $request_uri_like_not;
public $base_fee;
public $percent_fee;
public $click_fee;
public $cache_visitors;
public $cache_visits;
public $cache_pages;
public $cache_registrations;
public $cache_orders;
public $cache_sales;
public $cache_reg_rate;
public $cache_order_rate;
public $date_add;
protected $fieldsRequired = array('name');
protected $fieldsSize = array('name' => 64, 'http_referer_regexp' => 64, 'request_uri_regexp' => 64, 'http_referer_like' => 64, 'request_uri_like' => 64, 'passwd' => 32);
protected $fieldsValidate = array(
'name' => 'isGenericName', 'passwd' => 'isPasswd',
'http_referer_regexp' => 'isCleanHtml', 'request_uri_regexp' => 'isCleanHtml', 'http_referer_like' => 'isCleanHtml', 'request_uri_like' => 'isCleanHtml',
'http_referer_regexp_not' => 'isCleanHtml', 'request_uri_regexp_not' => 'isCleanHtml', 'http_referer_like_not' => 'isCleanHtml', 'request_uri_like_not' => 'isCleanHtml',
'base_fee' => 'isFloat', 'percent_fee' => 'isFloat', 'click_fee' => 'isFloat',
'cache_visitors' => 'isUnsignedInt', 'cache_visits' => 'isUnsignedInt', 'cache_pages' => 'isUnsignedInt', 'cache_registrations' => 'isUnsignedInt',
'cache_orders' => 'isUnsignedInt', 'cache_sales' => 'isOptFloat', 'cache_reg_rate' => 'isOptFloat', 'cache_order_rate' => 'isOptFloat');
protected $table = 'referrer';
protected $identifier = 'id_referrer';
protected static $_join = '(r.http_referer_like IS NULL OR r.http_referer_like = \'\' OR cs.http_referer LIKE r.http_referer_like)
AND (r.request_uri_like IS NULL OR r.request_uri_like = \'\' OR cs.request_uri LIKE r.request_uri_like)
AND (r.http_referer_like_not IS NULL OR r.http_referer_like_not = \'\' OR cs.http_referer NOT LIKE r.http_referer_like_not)
AND (r.request_uri_like_not IS NULL OR r.request_uri_like_not = \'\' OR cs.request_uri NOT LIKE r.request_uri_like_not)
AND (r.http_referer_regexp IS NULL OR r.http_referer_regexp = \'\' OR cs.http_referer REGEXP r.http_referer_regexp)
AND (r.request_uri_regexp IS NULL OR r.request_uri_regexp = \'\' OR cs.request_uri REGEXP r.request_uri_regexp)
AND (r.http_referer_regexp_not IS NULL OR r.http_referer_regexp_not = \'\' OR cs.http_referer NOT REGEXP r.http_referer_regexp_not)
AND (r.request_uri_regexp_not IS NULL OR r.request_uri_regexp_not = \'\' OR cs.request_uri NOT REGEXP r.request_uri_regexp_not)';
public function getFields()
{
parent::validateFields();
$fields['name'] = pSQL($this->name);
$fields['passwd'] = pSQL($this->passwd);
$fields['http_referer_regexp'] = pSQL($this->http_referer_regexp, true);
$fields['request_uri_regexp'] = pSQL($this->request_uri_regexp, true);
$fields['http_referer_like'] = pSQL($this->http_referer_like, true);
$fields['request_uri_like'] = pSQL($this->request_uri_like, true);
$fields['http_referer_regexp_not'] = pSQL($this->http_referer_regexp_not, true);
$fields['request_uri_regexp_not'] = pSQL($this->request_uri_regexp_not, true);
$fields['http_referer_like_not'] = pSQL($this->http_referer_like_not, true);
$fields['request_uri_like_not'] = pSQL($this->request_uri_like_not, true);
$fields['base_fee'] = number_format($this->base_fee, 2, '.', '');
$fields['percent_fee'] = number_format($this->percent_fee, 2, '.', '');
$fields['click_fee'] = number_format($this->click_fee, 2, '.', '');
$fields['cache_visitors'] = (int)($this->cache_visitors);
$fields['cache_visits'] = (int)($this->cache_visits);
$fields['cache_pages'] = (int)($this->cache_pages);
$fields['cache_registrations'] = (int)($this->cache_registrations);
$fields['cache_orders'] = (int)($this->cache_orders);
$fields['cache_sales'] = number_format($this->cache_sales, 2, '.', '');
$fields['cache_reg_rate'] = $this->cache_reg_rate > 1 ? 1 : number_format((float)($this->cache_reg_rate), 4, '.', '');
$fields['cache_order_rate'] = $this->cache_order_rate > 1 ? 1 : number_format((float)($this->cache_order_rate), 4, '.', '');
$fields['date_add'] = pSQL($this->date_add);
return $fields;
}
public function add($autodate = true, $nullValues = false)
{
if (!($result = parent::add($autodate, $nullValues)))
return false;
$this->refreshCache(array(array('id_referrer' => $this->id)));
$this->refreshIndex(array(array('id_referrer' => $this->id)));
return $result;
}
public static function cacheNewSource($id_connections_source)
{
Db::getInstance()->Execute('
INSERT INTO '._DB_PREFIX_.'referrer_cache (id_referrer, id_connections_source) (
SELECT id_referrer, id_connections_source
FROM '._DB_PREFIX_.'referrer r
LEFT JOIN '._DB_PREFIX_.'connections_source cs ON ('.self::$_join.')
WHERE id_connections_source = '.(int)($id_connections_source).'
)');
}
public static function getReferrers($id_customer)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT DISTINCT c.date_add, r.name
FROM '._DB_PREFIX_.'guest g
LEFT JOIN '._DB_PREFIX_.'connections c ON c.id_guest = g.id_guest
LEFT JOIN '._DB_PREFIX_.'connections_source cs ON c.id_connections = cs.id_connections
LEFT JOIN '._DB_PREFIX_.'referrer r ON ('.self::$_join.')
WHERE g.id_customer = '.(int)($id_customer).'
AND r.name IS NOT NULL');
}
public function getStatsVisits($id_product = null, $employee = null)
{
list($join, $where) = array('','');
if ((int)($id_product))
{
$join = 'LEFT JOIN `'._DB_PREFIX_.'page` p ON cp.`id_page` = p.`id_page`
LEFT JOIN `'._DB_PREFIX_.'page_type` pt ON pt.`id_page_type` = p.`id_page_type`';
$where = 'AND pt.`name` = \'product.php\'
AND p.`id_object` = '.(int)($id_product);
}
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(DISTINCT cs.id_connections_source) AS visits,
COUNT(DISTINCT cs.id_connections) as visitors,
COUNT(DISTINCT c.id_guest) as uniqs,
COUNT(DISTINCT cp.time_start) as pages
FROM '._DB_PREFIX_.'referrer_cache rc
LEFT JOIN '._DB_PREFIX_.'connections_source cs ON rc.id_connections_source = cs.id_connections_source
LEFT JOIN '._DB_PREFIX_.'connections c ON cs.id_connections = c.id_connections
LEFT JOIN '._DB_PREFIX_.'connections_page cp ON cp.id_connections = c.id_connections
'.$join.'
WHERE cs.date_add BETWEEN '.ModuleGraph::getDateBetween($employee).'
AND rc.id_referrer = '.(int)($this->id).'
'.$where);
}
public function getRegistrations($id_product = null, $employee = null)
{
list($join, $where) = array('','');
if ((int)($id_product))
{
$join = 'LEFT JOIN '._DB_PREFIX_.'connections_page cp ON cp.id_connections = c.id_connections
LEFT JOIN `'._DB_PREFIX_.'page` p ON cp.`id_page` = p.`id_page`
LEFT JOIN `'._DB_PREFIX_.'page_type` pt ON pt.`id_page_type` = p.`id_page_type`';
$where = 'AND pt.`name` = \'product.php\'
AND p.`id_object` = '.(int)($id_product);
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(DISTINCT cu.id_customer) AS registrations
FROM '._DB_PREFIX_.'referrer_cache rc
LEFT JOIN '._DB_PREFIX_.'connections_source cs ON rc.id_connections_source = cs.id_connections_source
LEFT JOIN '._DB_PREFIX_.'connections c ON cs.id_connections = c.id_connections
LEFT JOIN '._DB_PREFIX_.'guest g ON g.id_guest = c.id_guest
LEFT JOIN '._DB_PREFIX_.'customer cu ON cu.id_customer = g.id_customer
'.$join.'
WHERE cu.date_add BETWEEN '.ModuleGraph::getDateBetween($employee).'
AND cu.date_add > cs.date_add
AND rc.id_referrer = '.(int)($this->id).'
'.$where);
return $result['registrations'];
}
public function getStatsSales($id_product = null, $employee = null)
{
list($join, $where) = array('','');
if ((int)($id_product))
{
$join = 'LEFT JOIN '._DB_PREFIX_.'order_detail od ON oo.id_order = od.id_order';
$where = 'AND od.product_id = '.(int)($id_product);
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
SELECT oo.id_order
FROM '._DB_PREFIX_.'referrer_cache rc
INNER JOIN '._DB_PREFIX_.'connections_source cs ON rc.id_connections_source = cs.id_connections_source
INNER JOIN '._DB_PREFIX_.'connections c ON cs.id_connections = c.id_connections
INNER JOIN '._DB_PREFIX_.'guest g ON g.id_guest = c.id_guest
LEFT JOIN '._DB_PREFIX_.'orders oo ON oo.id_customer = g.id_customer
'.$join.'
WHERE oo.invoice_date BETWEEN '.ModuleGraph::getDateBetween($employee).'
AND oo.date_add > cs.date_add
AND rc.id_referrer = '.(int)($this->id).'
AND oo.valid = 1
'.$where);
$implode = array();
foreach ($result as $row)
if ((int)$row['id_order'])
$implode[] = (int)$row['id_order'];
if ($implode)
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(o.id_order) AS orders, SUM(o.total_paid_real / o.conversion_rate) AS sales
FROM '._DB_PREFIX_.'orders o
WHERE o.id_order IN ('.implode($implode, ',').')
AND o.valid = 1');
else
return array('orders' => 0, 'sales' => 0);
}
public static function refreshCache($referrers = null, $employee = null)
{
if (!$referrers OR !is_array($referrers))
$referrers = Db::getInstance()->ExecuteS('SELECT id_referrer FROM '._DB_PREFIX_.'referrer');
foreach ($referrers as $row)
{
$referrer = new Referrer((int)($row['id_referrer']));
$statsVisits = $referrer->getStatsVisits(null, $employee);
$referrer->cache_visitors = $statsVisits['uniqs'];
$referrer->cache_visits = $statsVisits['visits'];
$referrer->cache_pages = $statsVisits['pages'];
$registrations = $referrer->getRegistrations(null, $employee);
$referrer->cache_registrations = (int)($registrations);
$statsSales = $referrer->getStatsSales(null, $employee);
$referrer->cache_orders = (int)($statsSales['orders']);
$referrer->cache_sales = number_format($statsSales['sales'], 2, '.', '');
$referrer->cache_reg_rate = $statsVisits['uniqs'] ? (int)($registrations) / $statsVisits['uniqs'] : 0;
$referrer->cache_order_rate = $statsVisits['uniqs'] ? (int)($statsSales['orders']) / $statsVisits['uniqs'] : 0;
if (!$referrer->update())
Tools::dieObject(mysql_error());
Configuration::updateValue('PS_REFERRERS_CACHE_LIKE', ModuleGraph::getDateBetween($employee));
Configuration::updateValue('PS_REFERRERS_CACHE_DATE', date('Y-m-d H:i:s'));
}
return true;
}
public static function refreshIndex($referrers = null)
{
if (!$referrers OR !is_array($referrers))
{
Db::getInstance()->Execute('TRUNCATE '._DB_PREFIX_.'referrer_cache');
Db::getInstance()->Execute('
INSERT INTO '._DB_PREFIX_.'referrer_cache (id_referrer, id_connections_source) (
SELECT id_referrer, id_connections_source
FROM '._DB_PREFIX_.'referrer r
LEFT JOIN '._DB_PREFIX_.'connections_source cs ON ('.self::$_join.')
)');
}
else
foreach ($referrers as $row)
{
Db::getInstance()->Execute('DELETE FROM '._DB_PREFIX_.'referrer_cache WHERE id_referrer = '.(int)($row['id_referrer']));
Db::getInstance()->Execute('
INSERT INTO '._DB_PREFIX_.'referrer_cache (id_referrer, id_connections_source) (
SELECT id_referrer, id_connections_source
FROM '._DB_PREFIX_.'referrer r
LEFT JOIN '._DB_PREFIX_.'connections_source cs ON ('.self::$_join.')
WHERE id_referrer = '.(int)($row['id_referrer']).'
)');
}
}
public static function getAjaxProduct($id_referrer, $id_product, $employee = null)
{
$product = new Product($id_product, false, Configuration::get('PS_LANG_DEFAULT'));
$currency = Currency::getCurrencyInstance(Configuration::get('PS_CURRENCY_DEFAULT'));
$referrer = new Referrer($id_referrer);
$statsVisits = $referrer->getStatsVisits($id_product, $employee);
$registrations = $referrer->getRegistrations($id_product, $employee);
$statsSales = $referrer->getStatsSales($id_product, $employee);
// If it's a product and it has no visits nor orders
if ((int)($id_product) AND !$statsVisits['visits'] AND !$statsSales['orders'])
exit;
$jsonArray = array();
$jsonArray[] = '"id_product":"'.(int)($product->id).'"';
$jsonArray[] = '"product_name":"'.addslashes($product->name).'"';
$jsonArray[] = '"uniqs":"'.(int)($statsVisits['uniqs']).'"';
$jsonArray[] = '"visitors":"'.(int)($statsVisits['visitors']).'"';
$jsonArray[] = '"visits":"'.(int)($statsVisits['visits']).'"';
$jsonArray[] = '"pages":"'.(int)($statsVisits['pages']).'"';
$jsonArray[] = '"registrations":"'.(int)($registrations).'"';
$jsonArray[] = '"orders":"'.(int)($statsSales['orders']).'"';
$jsonArray[] = '"sales":"'.Tools::displayPrice($statsSales['sales'], $currency).'"';
$jsonArray[] = '"cart":"'.Tools::displayPrice(((int)($statsSales['orders']) ? $statsSales['sales'] / (int)($statsSales['orders']) : 0), $currency).'"';
$jsonArray[] = '"reg_rate":"'.number_format((int)($statsVisits['uniqs']) ? (int)($registrations) / (int)($statsVisits['uniqs']) : 0, 4, '.', '').'"';
$jsonArray[] = '"order_rate":"'.number_format((int)($statsVisits['uniqs']) ? (int)($statsSales['orders']) / (int)($statsVisits['uniqs']) : 0, 4, '.', '').'"';
$jsonArray[] = '"click_fee":"'.Tools::displayPrice((int)($statsVisits['visits']) * $referrer->click_fee, $currency).'"';
$jsonArray[] = '"base_fee":"'.Tools::displayPrice($statsSales['orders'] * $referrer->base_fee, $currency).'"';
$jsonArray[] = '"percent_fee":"'.Tools::displayPrice($statsSales['sales'] * $referrer->percent_fee / 100, $currency).'"';
die ('[{'.implode(',', $jsonArray).'}]');
}
}
+54
View File
@@ -0,0 +1,54 @@
<?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 RijndaelCore
{
protected $_key;
protected $_iv;
public function __construct($key, $iv)
{
$this->_key = $key;
$this->_iv = base64_decode($iv);
}
// Base64 is not required, but it is be more compact than urlencode
public function encrypt($plaintext)
{
if (($length = strlen($plaintext)) >= 1048576)
return false;
return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->_key, $plaintext, MCRYPT_MODE_ECB, $this->_iv)).sprintf('%06d', $length);
}
public function decrypt($ciphertext)
{
$plainTextLength = intval(substr($ciphertext, -6));
$ciphertext = substr($ciphertext, 0, -6);
return substr(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $this->_key, base64_decode($ciphertext), MCRYPT_MODE_ECB, $this->_iv), 0, $plainTextLength);
}
}
+258
View File
@@ -0,0 +1,258 @@
<?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: 7310 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class SceneCore extends ObjectModel
{
/** @var string Name */
public $name;
/** @var boolean Active Scene */
public $active = true;
/** @var array Zone for image map */
public $zones = array();
/** @var array list of category where this scene is available */
public $categories = array();
/** @var array Products */
public $products;
protected $table = 'scene';
protected $identifier = 'id_scene';
protected $fieldsRequired = array('active');
protected $fieldsValidate = array('active' => 'isBool', 'zones' => 'isSceneZones', 'categories' => 'isArrayWithIds');
protected $fieldsRequiredLang = array('name');
protected $fieldsSizeLang = array('name' => 100);
protected $fieldsValidateLang = array('name' => 'isGenericName');
public function __construct($id = NULL, $id_lang = NULL, $liteResult = true, $hideScenePosition = false)
{
parent::__construct((int)($id), (int)($id_lang));
if (!$liteResult)
$this->products = $this->getProducts(true, (int)($id_lang), false);
if ($hideScenePosition)
$this->name = Scene::hideScenePosition($this->name);
$this->image_dir = _PS_SCENE_IMG_DIR_;
}
public function getFields()
{
parent::validateFields();
$fields['active'] = (int)($this->active);
return $fields;
}
/**
* Check then return multilingual fields for database interaction
*
* @return array Multilingual fields
*/
public function getTranslationsFieldsChild()
{
parent::validateFieldsLang();
return parent::getTranslationsFields(array('name'));
}
public function update($nullValues = false)
{
if (!$this->updateZoneProducts())
return false;
if (!$this->updateCategories())
return false;
return parent::update($nullValues);
}
public function add($autodate = true, $nullValues = false)
{
if (!empty($this->zones))
$this->addZoneProducts($this->zones);
if (!empty($this->categories))
$this->addCategories($this->categories);
return parent::add($autodate, $nullValues);
}
public function delete()
{
$this->deleteZoneProducts();
$this->deleteCategories();
if (parent::delete())
return $this->deleteImage();
}
public function deleteImage()
{
if (parent::deleteImage())
{
if (file_exists($this->image_dir.'thumbs/'.$this->id.'-thumb_scene.'.$this->image_format)
&& !unlink($this->image_dir.'thumbs/'.$this->id.'-thumb_scene.'.$this->image_format))
return false;
}
else
return false;
return true;
}
public function addCategories($categories)
{
$result = true;
foreach ($categories AS $category)
{
if (!Db::getInstance()->Execute('INSERT INTO `'._DB_PREFIX_.'scene_category` ( `id_scene` , `id_category`) VALUES ('.(int)($this->id).', '.(int)($category).')'))
$result = false;
}
return $result;
}
public function deleteCategories()
{
return Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'scene_category`
WHERE `id_scene` = '.(int)($this->id));
}
public function updateCategories()
{
if (!$this->deleteCategories())
return false;
if (!empty($this->categories) AND !$this->addCategories($this->categories))
return false;
return true;
}
public function addZoneProducts($zones)
{
$result = true;
foreach ($zones AS $zone)
{
$sql = 'INSERT INTO `'._DB_PREFIX_.'scene_products` ( `id_scene` , `id_product` , `x_axis` , `y_axis` , `zone_width` , `zone_height`) VALUES
('.(int)($this->id).', '.(int)($zone['id_product']).', '.(int)($zone['x1']).', '.(int)($zone['y1']).', '.(int)($zone['width']).', '.(int)($zone['height']).')';
if (!Db::getInstance()->Execute($sql))
$result = false;
}
return $result;
}
public function deleteZoneProducts()
{
return Db::getInstance()->Execute('
DELETE FROM `'._DB_PREFIX_.'scene_products`
WHERE `id_scene` = '.(int)($this->id));
}
public function updateZoneProducts()
{
if (!$this->deleteZoneProducts())
return false;
if ($this->zones AND !$this->addZoneProducts($this->zones))
return false;
return true;
}
/**
* Get all scenes of a category
*
* @return array Products
*/
static public function getScenes($id_category, $id_lang = NULL, $onlyActive = true, $liteResult = true, $hideScenePosition = true)
{
$id_lang = is_null($id_lang) ? _USER_ID_LANG_ : (int)($id_lang);
$scenes = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT s.*
FROM `'._DB_PREFIX_.'scene_category` sc
LEFT JOIN `'._DB_PREFIX_.'scene` s ON (sc.id_scene = s.id_scene)
LEFT JOIN `'._DB_PREFIX_.'scene_lang` sl ON (sl.id_scene = s.id_scene)
WHERE sc.id_category = '.(int)($id_category).' AND sl.id_lang = '.(int)($id_lang).($onlyActive ? ' AND s.active = 1' : '').'
ORDER BY sl.name ASC');
if (!$liteResult AND $scenes)
foreach($scenes AS &$scene)
$scene = new Scene((int)($scene['id_scene']), (int)($id_lang), false, $hideScenePosition);
return $scenes;
}
/**
* Get all products of this scene
*
* @return array Products
*/
public function getProducts($onlyActive = true, $id_lang = NULL, $liteResult = true)
{
global $link;
$id_lang = is_null($id_lang) ? _USER_ID_LANG_ : (int)($id_lang);
$products = Db::getInstance()->ExecuteS('
SELECT s.*
FROM `'._DB_PREFIX_.'scene_products` s
LEFT JOIN `'._DB_PREFIX_.'product` p ON (p.id_product = s.id_product)
WHERE s.id_scene = '.(int)($this->id).($onlyActive ? ' AND p.active = 1' : ''));
if (!$liteResult AND $products)
foreach ($products AS &$product)
{
$product['details'] = new Product((int)($product['id_product']), !$liteResult, (int)($id_lang));
$product['link'] = $link->getProductLink((int)($product['details']->id), $product['details']->link_rewrite, $product['details']->category, $product['details']->ean13);
$cover = Product::getCover((int)($product['details']->id));
if(is_array($cover))
$product = array_merge($cover, $product);
}
return $products;
}
/**
* Get categories where scene is indexed
*
* @param integer $id_scene Scene id
* @return array Categories where scene is indexed
*/
static public function getIndexedCategories($id_scene)
{
return Db::getInstance()->ExecuteS('
SELECT `id_category`
FROM `'._DB_PREFIX_.'scene_category`
WHERE `id_scene` = '.(int)($id_scene));
}
/**
* Hide scene prefix used for position
*
* @param string $name Scene name
* @return string Name without position
*/
static public function hideScenePosition($name)
{
return preg_replace('/^[0-9]+\./', '', $name);
}
}
+595
View File
@@ -0,0 +1,595 @@
<?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: 7489 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
define('PS_SEARCH_MAX_WORD_LENGTH', 15);
/* Copied from Drupal search module, except for \x{0}-\x{2f} that has been replaced by \x{0}-\x{2c}\x{2e}-\x{2f} in order to keep the char '-' */
define('PREG_CLASS_SEARCH_EXCLUDE',
'\x{0}-\x{2c}\x{2e}-\x{2f}\x{3a}-\x{40}\x{5b}-\x{60}\x{7b}-\x{bf}\x{d7}\x{f7}\x{2b0}-'.
'\x{385}\x{387}\x{3f6}\x{482}-\x{489}\x{559}-\x{55f}\x{589}-\x{5c7}\x{5f3}-'.
'\x{61f}\x{640}\x{64b}-\x{65e}\x{66a}-\x{66d}\x{670}\x{6d4}\x{6d6}-\x{6ed}'.
'\x{6fd}\x{6fe}\x{700}-\x{70f}\x{711}\x{730}-\x{74a}\x{7a6}-\x{7b0}\x{901}-'.
'\x{903}\x{93c}\x{93e}-\x{94d}\x{951}-\x{954}\x{962}-\x{965}\x{970}\x{981}-'.
'\x{983}\x{9bc}\x{9be}-\x{9cd}\x{9d7}\x{9e2}\x{9e3}\x{9f2}-\x{a03}\x{a3c}-'.
'\x{a4d}\x{a70}\x{a71}\x{a81}-\x{a83}\x{abc}\x{abe}-\x{acd}\x{ae2}\x{ae3}'.
'\x{af1}-\x{b03}\x{b3c}\x{b3e}-\x{b57}\x{b70}\x{b82}\x{bbe}-\x{bd7}\x{bf0}-'.
'\x{c03}\x{c3e}-\x{c56}\x{c82}\x{c83}\x{cbc}\x{cbe}-\x{cd6}\x{d02}\x{d03}'.
'\x{d3e}-\x{d57}\x{d82}\x{d83}\x{dca}-\x{df4}\x{e31}\x{e34}-\x{e3f}\x{e46}-'.
'\x{e4f}\x{e5a}\x{e5b}\x{eb1}\x{eb4}-\x{ebc}\x{ec6}-\x{ecd}\x{f01}-\x{f1f}'.
'\x{f2a}-\x{f3f}\x{f71}-\x{f87}\x{f90}-\x{fd1}\x{102c}-\x{1039}\x{104a}-'.
'\x{104f}\x{1056}-\x{1059}\x{10fb}\x{10fc}\x{135f}-\x{137c}\x{1390}-\x{1399}'.
'\x{166d}\x{166e}\x{1680}\x{169b}\x{169c}\x{16eb}-\x{16f0}\x{1712}-\x{1714}'.
'\x{1732}-\x{1736}\x{1752}\x{1753}\x{1772}\x{1773}\x{17b4}-\x{17db}\x{17dd}'.
'\x{17f0}-\x{180e}\x{1843}\x{18a9}\x{1920}-\x{1945}\x{19b0}-\x{19c0}\x{19c8}'.
'\x{19c9}\x{19de}-\x{19ff}\x{1a17}-\x{1a1f}\x{1d2c}-\x{1d61}\x{1d78}\x{1d9b}-'.
'\x{1dc3}\x{1fbd}\x{1fbf}-\x{1fc1}\x{1fcd}-\x{1fcf}\x{1fdd}-\x{1fdf}\x{1fed}-'.
'\x{1fef}\x{1ffd}-\x{2070}\x{2074}-\x{207e}\x{2080}-\x{2101}\x{2103}-\x{2106}'.
'\x{2108}\x{2109}\x{2114}\x{2116}-\x{2118}\x{211e}-\x{2123}\x{2125}\x{2127}'.
'\x{2129}\x{212e}\x{2132}\x{213a}\x{213b}\x{2140}-\x{2144}\x{214a}-\x{2b13}'.
'\x{2ce5}-\x{2cff}\x{2d6f}\x{2e00}-\x{3005}\x{3007}-\x{303b}\x{303d}-\x{303f}'.
'\x{3099}-\x{309e}\x{30a0}\x{30fb}\x{30fd}\x{30fe}\x{3190}-\x{319f}\x{31c0}-'.
'\x{31cf}\x{3200}-\x{33ff}\x{4dc0}-\x{4dff}\x{a015}\x{a490}-\x{a716}\x{a802}'.
'\x{a806}\x{a80b}\x{a823}-\x{a82b}\x{d800}-\x{f8ff}\x{fb1e}\x{fb29}\x{fd3e}'.
'\x{fd3f}\x{fdfc}-\x{fe6b}\x{feff}-\x{ff0f}\x{ff1a}-\x{ff20}\x{ff3b}-\x{ff40}'.
'\x{ff5b}-\x{ff65}\x{ff70}\x{ff9e}\x{ff9f}\x{ffe0}-\x{fffd}');
define('PREG_CLASS_NUMBERS',
'\x{30}-\x{39}\x{b2}\x{b3}\x{b9}\x{bc}-\x{be}\x{660}-\x{669}\x{6f0}-\x{6f9}'.
'\x{966}-\x{96f}\x{9e6}-\x{9ef}\x{9f4}-\x{9f9}\x{a66}-\x{a6f}\x{ae6}-\x{aef}'.
'\x{b66}-\x{b6f}\x{be7}-\x{bf2}\x{c66}-\x{c6f}\x{ce6}-\x{cef}\x{d66}-\x{d6f}'.
'\x{e50}-\x{e59}\x{ed0}-\x{ed9}\x{f20}-\x{f33}\x{1040}-\x{1049}\x{1369}-'.
'\x{137c}\x{16ee}-\x{16f0}\x{17e0}-\x{17e9}\x{17f0}-\x{17f9}\x{1810}-\x{1819}'.
'\x{1946}-\x{194f}\x{2070}\x{2074}-\x{2079}\x{2080}-\x{2089}\x{2153}-\x{2183}'.
'\x{2460}-\x{249b}\x{24ea}-\x{24ff}\x{2776}-\x{2793}\x{3007}\x{3021}-\x{3029}'.
'\x{3038}-\x{303a}\x{3192}-\x{3195}\x{3220}-\x{3229}\x{3251}-\x{325f}\x{3280}-'.
'\x{3289}\x{32b1}-\x{32bf}\x{ff10}-\x{ff19}');
define('PREG_CLASS_PUNCTUATION',
'\x{21}-\x{23}\x{25}-\x{2a}\x{2c}-\x{2f}\x{3a}\x{3b}\x{3f}\x{40}\x{5b}-\x{5d}'.
'\x{5f}\x{7b}\x{7d}\x{a1}\x{ab}\x{b7}\x{bb}\x{bf}\x{37e}\x{387}\x{55a}-\x{55f}'.
'\x{589}\x{58a}\x{5be}\x{5c0}\x{5c3}\x{5f3}\x{5f4}\x{60c}\x{60d}\x{61b}\x{61f}'.
'\x{66a}-\x{66d}\x{6d4}\x{700}-\x{70d}\x{964}\x{965}\x{970}\x{df4}\x{e4f}'.
'\x{e5a}\x{e5b}\x{f04}-\x{f12}\x{f3a}-\x{f3d}\x{f85}\x{104a}-\x{104f}\x{10fb}'.
'\x{1361}-\x{1368}\x{166d}\x{166e}\x{169b}\x{169c}\x{16eb}-\x{16ed}\x{1735}'.
'\x{1736}\x{17d4}-\x{17d6}\x{17d8}-\x{17da}\x{1800}-\x{180a}\x{1944}\x{1945}'.
'\x{2010}-\x{2027}\x{2030}-\x{2043}\x{2045}-\x{2051}\x{2053}\x{2054}\x{2057}'.
'\x{207d}\x{207e}\x{208d}\x{208e}\x{2329}\x{232a}\x{23b4}-\x{23b6}\x{2768}-'.
'\x{2775}\x{27e6}-\x{27eb}\x{2983}-\x{2998}\x{29d8}-\x{29db}\x{29fc}\x{29fd}'.
'\x{3001}-\x{3003}\x{3008}-\x{3011}\x{3014}-\x{301f}\x{3030}\x{303d}\x{30a0}'.
'\x{30fb}\x{fd3e}\x{fd3f}\x{fe30}-\x{fe52}\x{fe54}-\x{fe61}\x{fe63}\x{fe68}'.
'\x{fe6a}\x{fe6b}\x{ff01}-\x{ff03}\x{ff05}-\x{ff0a}\x{ff0c}-\x{ff0f}\x{ff1a}'.
'\x{ff1b}\x{ff1f}\x{ff20}\x{ff3b}-\x{ff3d}\x{ff3f}\x{ff5b}\x{ff5d}\x{ff5f}-'.
'\x{ff65}');
/**
* Matches all CJK characters that are candidates for auto-splitting
* (Chinese, Japanese, Korean).
* Contains kana and BMP ideographs.
*/
define('PREG_CLASS_CJK', '\x{3041}-\x{30ff}\x{31f0}-\x{31ff}\x{3400}-\x{4db5}\x{4e00}-\x{9fbb}\x{f900}-\x{fad9}');
class SearchCore
{
public static function sanitize($string, $id_lang, $indexation = false)
{
$string = Tools::strtolower(strip_tags($string));
$string = html_entity_decode($string, ENT_NOQUOTES, 'utf-8');
$string = preg_replace('/(['.PREG_CLASS_NUMBERS.']+)['.PREG_CLASS_PUNCTUATION.']+(?=['.PREG_CLASS_NUMBERS.'])/u', '\1', $string);
$string = preg_replace('/['.PREG_CLASS_SEARCH_EXCLUDE.']+/u', ' ', $string);
if ($indexation)
$string = preg_replace('/[._-]+/', '', $string);
else
{
$string = preg_replace('/[._]+/', '', $string);
$string = ltrim(preg_replace('/([^ ])-/', '$1', ' '.$string));
$string = preg_replace('/[._]+/', '', $string);
$string = preg_replace('/[^\s]-+/', '', $string);
}
$blacklist = Configuration::get('PS_SEARCH_BLACKLIST', $id_lang);
if (!empty($blacklist))
{
$string = preg_replace('/(?<=\s)('.$blacklist.')(?=\s)/Su', '', $string);
$string = preg_replace('/^('.$blacklist.')(?=\s)/Su', '', $string);
$string = preg_replace('/(?<=\s)('.$blacklist.')$/Su', '', $string);
$string = preg_replace('/^('.$blacklist.')$/Su', '', $string);
}
if (!$indexation)
{
$alias = new Alias(NULL, $string);
if (Validate::isLoadedObject($alias))
$string = $alias->search;
}
if ($indexation)
{
$minWordLen = (int)Configuration::get('PS_SEARCH_MINWORDLEN');
if ($minWordLen > 1)
{
$minWordLen -= 1;
$string = preg_replace('/(?<=\s)[^\s]{1,'.$minWordLen.'}(?=\s)/Su', ' ', $string);
$string = preg_replace('/^[^\s]{1,'.$minWordLen.'}(?=\s)/Su', '', $string);
$string = preg_replace('/(?<=\s)[^\s]{1,'.$minWordLen.'}$/Su', '', $string);
$string = preg_replace('/^[^\s]{1,'.$minWordLen.'}$/Su', '', $string);
}
}
$string = trim(preg_replace('/\s+/', ' ', $string));
return $string;
}
public static function find($id_lang, $expr, $pageNumber = 1, $pageSize = 1, $orderBy = 'position', $orderWay = 'desc', $ajax = false, $useCookie = true, $id_shop = false)
{
global $cookie;
$db = Db::getInstance(_PS_USE_SQL_SLAVE_);
// Only use cookie if id_customer is not present
if ($useCookie)
$id_customer = $cookie->id_customer;
else
$id_customer = 0;
if (!$id_shop)
$id_shop = Shop::getCurrentShop();
// TODO : smart page management
if ($pageNumber < 1) $pageNumber = 1;
if ($pageSize < 1) $pageSize = 1;
if (!Validate::isOrderBy($orderBy) OR !Validate::isOrderWay($orderWay))
return false;
$intersectArray = array();
$scoreArray = array();
$words = explode(' ', Search::sanitize($expr, $id_lang));
foreach ($words AS $key => $word)
if (!empty($word) AND strlen($word) >= (int)Configuration::get('PS_SEARCH_MINWORDLEN'))
{
$word = str_replace('%', '\\%', $word);
$word = str_replace('_', '\\_', $word);
$intersectArray[] = 'SELECT si.id_product
FROM '._DB_PREFIX_.'search_word sw
LEFT JOIN '._DB_PREFIX_.'search_index si ON sw.id_word = si.id_word
WHERE sw.id_lang = '.(int)$id_lang.'
AND sw.id_shop = '.(int)$id_shop.'
AND sw.word LIKE
'.($word[0] == '-'
? ' \''.pSQL(Tools::substr($word, 1, PS_SEARCH_MAX_WORD_LENGTH)).'%\''
: '\''.pSQL(Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH)).'%\''
);
if ($word[0] != '-')
$scoreArray[] = 'sw.word LIKE \''.pSQL(Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH)).'%\'';
}
else
unset($words[$key]);
if (!sizeof($words))
return ($ajax ? array() : array('total' => 0, 'result' => array()));
$score = '';
if (sizeof($scoreArray))
$score = ',(
SELECT SUM(weight)
FROM '._DB_PREFIX_.'search_word sw
LEFT JOIN '._DB_PREFIX_.'search_index si ON sw.id_word = si.id_word
WHERE sw.id_lang = '.(int)$id_lang.'
AND sw.id_shop = '.(int)$id_shop.'
AND si.id_product = p.id_product
AND ('.implode(' OR ', $scoreArray).')
) position';
$result = $db->ExecuteS('
SELECT cp.`id_product`
FROM `'._DB_PREFIX_.'category_group` cg
INNER JOIN `'._DB_PREFIX_.'category_product` cp ON cp.`id_category` = cg.`id_category`
INNER JOIN `'._DB_PREFIX_.'category` c ON cp.`id_category` = c.`id_category`
INNER JOIN `'._DB_PREFIX_.'product` p ON cp.`id_product` = p.`id_product`
INNER JOIN `'._DB_PREFIX_.'product_shop` ps ON (p.id_product = ps.id_product)
WHERE c.`active` = 1 AND p.`active` = 1 AND indexed = 1 AND ps.id_shop='.(int)$id_shop.'
AND cg.`id_group` '.(!$id_customer ? '= 1' : 'IN (
SELECT id_group FROM '._DB_PREFIX_.'customer_group
WHERE id_customer = '.(int)$id_customer.'
)'), false);
$eligibleProducts = array();
while ($row = $db->nextRow($result))
$eligibleProducts[] = $row['id_product'];
foreach ($intersectArray as $query)
{
$result = $db->ExecuteS($query, false);
$eligibleProducts2 = array();
while ($row = $db->nextRow($result))
$eligibleProducts2[] = $row['id_product'];
$eligibleProducts = array_intersect($eligibleProducts, $eligibleProducts2);
if (!count($eligibleProducts))
return ($ajax ? array() : array('total' => 0, 'result' => array()));
}
array_unique($eligibleProducts);
$productPool = '';
foreach ($eligibleProducts AS $id_product)
if ($id_product)
$productPool .= (int)$id_product.',';
if (empty($productPool))
return ($ajax ? array() : array('total' => 0, 'result' => array()));
$productPool = ((strpos($productPool, ',') === false) ? (' = '.(int)$productPool.' ') : (' IN ('.rtrim($productPool, ',').') '));
if ($ajax)
{
return $db->ExecuteS('
SELECT DISTINCT p.id_product, pl.name pname, cl.name cname,
cl.link_rewrite crewrite, pl.link_rewrite prewrite '.$score.'
FROM '._DB_PREFIX_.'product p
INNER JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.' AND pl.id_shop='.(int)$id_shop.')
INNER JOIN `'._DB_PREFIX_.'category_lang` cl ON (p.`id_category_default` = cl.`id_category` AND cl.`id_lang` = '.(int)$id_lang.' AND cl.id_shop='.(int)$id_shop.')
WHERE p.`id_product` '.$productPool.'
ORDER BY position DESC LIMIT 10');
}
$queryResults = '
SELECT p.*, pl.`description_short`, pl.`available_now`, pl.`available_later`, pl.`link_rewrite`, pl.`name`,
tax.`rate`, i.`id_image`, il.`legend`, m.`name` manufacturer_name '.$score.', DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 new
FROM '._DB_PREFIX_.'product p
INNER JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.' AND pl.id_shop='.(int)$id_shop.')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` tax ON (tax.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.')
WHERE p.`id_product` '.$productPool.'
'.($orderBy ? 'ORDER BY '.$orderBy : '').($orderWay ? ' '.$orderWay : '').'
LIMIT '.(int)(($pageNumber - 1) * $pageSize).','.(int)$pageSize;
$result = $db->ExecuteS($queryResults);
$total = $db->getValue('SELECT COUNT(*)
FROM '._DB_PREFIX_.'product p
INNER JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.' AND pl.id_shop='.(int)$id_shop.')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` tax ON (tax.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON m.`id_manufacturer` = p.`id_manufacturer`
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.')
WHERE p.`id_product` '.$productPool);
if (!$result)
$resultProperties = false;
else
$resultProperties = Product::getProductsProperties((int)$id_lang, $result);
return array('total' => $total,'result' => $resultProperties);
}
public static function getTags($db, $id_product, $id_lang)
{
$tags = '';
$tagsArray = $db->ExecuteS('
SELECT t.name FROM '._DB_PREFIX_.'product_tag pt
LEFT JOIN '._DB_PREFIX_.'tag t ON (pt.id_tag = t.id_tag AND t.id_lang = '.(int)$id_lang.')
WHERE pt.id_product = '.(int)$id_product);
foreach ($tagsArray AS $tag)
$tags .= $tag['name'].' ';
return $tags;
}
public static function getAttributes($db, $id_product, $id_lang)
{
$attributes = '';
$attributesArray = $db->ExecuteS('
SELECT al.name FROM '._DB_PREFIX_.'product_attribute pa
INNER JOIN '._DB_PREFIX_.'product_attribute_combination pac ON pa.id_product_attribute = pac.id_product_attribute
INNER JOIN '._DB_PREFIX_.'attribute_lang al ON (pac.id_attribute = al.id_attribute AND al.id_lang = '.(int)$id_lang.')
WHERE pa.id_product = '.(int)$id_product);
foreach ($attributesArray AS $attribute)
$attributes .= $attribute['name'].' ';
return $attributes;
}
public static function getFeatures($db, $id_product, $id_lang)
{
$features = '';
$featuresArray = $db->ExecuteS('
SELECT fvl.value FROM '._DB_PREFIX_.'feature_product fp
LEFT JOIN '._DB_PREFIX_.'feature_value_lang fvl ON (fp.id_feature_value = fvl.id_feature_value AND fvl.id_lang = '.(int)$id_lang.')
WHERE fp.id_product = '.(int)$id_product);
foreach ($featuresArray AS $feature)
$features .= $feature['value'].' ';
return $features;
}
public static function indexation($full = false)
{
$db = Db::getInstance();
$dropIndex = false;
if ($full)
{
$db->Execute('TRUNCATE '._DB_PREFIX_.'search_index');
$db->Execute('TRUNCATE '._DB_PREFIX_.'search_word');
$db->Execute('UPDATE '._DB_PREFIX_.'product SET indexed = 0');
$dropIndex = true;
}
else
{
$products = $db->ExecuteS('SELECT id_product FROM '._DB_PREFIX_.'product WHERE indexed = 0');
$ids = array();
if ($products)
foreach($products AS $product)
$ids[] = (int)$product['id_product'];
if (sizeof($ids))
$db->Execute('DELETE FROM '._DB_PREFIX_.'search_index WHERE id_product IN ('.implode(',', $ids).')');
if (count($products) > 2000)
$dropIndex = true;
}
if ($dropIndex)
{
$dropIndex = false;
$result = $db->ExecuteS('SHOW INDEX FROM `'._DB_PREFIX_.'search_index`');
foreach ($result as $row)
if (strtolower($row['Key_name']) == 'primary')
$dropIndex = true;
if ($dropIndex)
$db->Execute('ALTER TABLE '._DB_PREFIX_.'search_index DROP PRIMARY KEY');
$dropIndex = true;
}
// Every fields are weighted according to the configuration in the backend
$weightArray = array(
'pname' => Configuration::get('PS_SEARCH_WEIGHT_PNAME'),
'reference' => Configuration::get('PS_SEARCH_WEIGHT_REF'),
'ean13' => Configuration::get('PS_SEARCH_WEIGHT_REF'),
'upc' => Configuration::get('PS_SEARCH_WEIGHT_REF'),
'description_short' => Configuration::get('PS_SEARCH_WEIGHT_SHORTDESC'),
'description' => Configuration::get('PS_SEARCH_WEIGHT_DESC'),
'cname' => Configuration::get('PS_SEARCH_WEIGHT_CNAME'),
'mname' => Configuration::get('PS_SEARCH_WEIGHT_MNAME'),
'tags' => Configuration::get('PS_SEARCH_WEIGHT_TAG'),
'attributes' => Configuration::get('PS_SEARCH_WEIGHT_ATTRIBUTE'),
'features' => Configuration::get('PS_SEARCH_WEIGHT_FEATURE')
);
// All the product not yet indexed are retrieved
$products = $db->ExecuteS('
SELECT p.id_product, pl.id_lang, pl.name pname, p.reference, p.ean13, p.upc, pl.description_short, pl.description, cl.name cname, m.name mname, pl.id_shop
FROM '._DB_PREFIX_.'product p
LEFT JOIN '._DB_PREFIX_.'product_lang pl ON p.id_product = pl.id_product
LEFT JOIN '._DB_PREFIX_.'category_lang cl ON (cl.id_category = p.id_category_default AND pl.id_lang = cl.id_lang AND pl.id_shop = cl.id_shop)
LEFT JOIN '._DB_PREFIX_.'manufacturer m ON m.id_manufacturer = p.id_manufacturer
WHERE p.indexed = 0', false);
// Those are kind of global variables required to save the processed data in the database every X occurences, in order to avoid overloading MySQL
$countWords = 0;
$countProducts = 0;
$queryArray3 = array();
$productsArray = array();
// Every indexed words are cached into a PHP array
$wordIdsByWord = array();
$wordIds = Db::getInstance()->ExecuteS('
SELECT sw.id_word, sw.word, id_lang, id_shop
FROM '._DB_PREFIX_.'search_word sw', false);
$wordIdsByWord = array();
while ($wordId = $db->nextRow($wordIds))
{
if (!isset($wordIdsByWord[$wordId['id_shop']][$wordId['id_lang']]))
$wordIdsByWord[$wordId['id_shop']][$wordId['id_lang']] = array();
$wordIdsByWord[$wordId['id_shop']][$wordId['id_lang']]['_'.$wordId['word']] = (int)$wordId['id_word'];
}
// Now each non-indexed product is processed one by one, langage by langage
while ($product = $db->nextRow($products))
{
$product['tags'] = Search::getTags($db, (int)$product['id_product'], (int)$product['id_lang']);
$product['attributes'] = Search::getAttributes($db, (int)$product['id_product'], (int)$product['id_lang']);
$product['features'] = Search::getFeatures($db, (int)$product['id_product'], (int)$product['id_lang']);
// Data must be cleaned of html, bad characters, spaces and anything, then if the resulting words are long enough, they're added to the array
$pArray = array();
foreach ($product AS $key => $value)
if (strncmp($key, 'id_', 3))
{
$words = explode(' ', Search::sanitize($value, (int)$product['id_lang'], true));
foreach ($words AS $word)
if (!empty($word))
{
$word = Tools::substr($word, 0, PS_SEARCH_MAX_WORD_LENGTH);
if (!isset($pArray[$word]))
$pArray[$word] = 0;
$pArray[$word] += $weightArray[$key];
}
}
// If we find words that need to be indexed, they're added to the word table in the database
if (sizeof($pArray))
{
$list = '';
foreach ($pArray AS $word => $weight)
$list .= '\''.$word.'\',';
$list = rtrim($list, ',');
$queryArray = array();
$queryArray2 = array();
foreach ($pArray AS $word => $weight)
if ($weight AND !isset($wordIdsByWord['_'.$word]))
{
$queryArray[] = '('.(int)$product['id_lang'].', '.(int)$product['id_shop'].', \''.pSQL($word).'\')';
$queryArray2[] = '\''.pSQL($word).'\'';
$wordIdsByWord[$product['id_shop']][$product['id_lang']]['_'.$word] = 0;
}
if (count($queryArray))
{
// The words are inserted...
$db->Execute('
INSERT IGNORE INTO '._DB_PREFIX_.'search_word (id_lang, id_shop, word)
VALUES '.implode(',',$queryArray));
// ...then their IDs are retrieved and added to the cache
$addedWords = $db->ExecuteS('
SELECT sw.id_word, sw.word
FROM '._DB_PREFIX_.'search_word sw
WHERE sw.word IN ('.implode(',', $queryArray2).')
AND sw.id_lang = '.(int)$product['id_lang'].'
AND sw.id_shop = '.(int)$product['id_shop'].'
LIMIT '.count($queryArray2));
foreach ($addedWords AS $wordId)
$wordIdsByWord[$product['id_shop']][$product['id_lang']]['_'.$wordId['word']] = (int)$wordId['id_word'];
}
}
foreach ($pArray AS $word => $weight)
{
if (!$weight)
continue;
if (!isset($wordIdsByWord[$product['id_shop']][$product['id_lang']]['_'.$word]))
continue;
if (!$wordIdsByWord[$product['id_shop']][$product['id_lang']]['_'.$word])
continue;
$queryArray3[] = '('.(int)$product['id_product'].','.(int)$wordIdsByWord[$product['id_shop']][$product['id_lang']]['_'.$word].','.(int)$weight.')';
// Force save every 200 words in order to avoid overloading MySQL
if (++$countWords % 200 == 0)
Search::saveIndex($queryArray3);
}
if (!in_array($product['id_product'], $productsArray))
$productsArray[] = (int)$product['id_product'];
// Force save every 50 products in order to avoid overloading MySQL
if (++$countProducts % 50 == 0)
Search::setProductsAsIndexed($productsArray);
}
// One last save is done at the end in order to save what's left
Search::saveIndex($queryArray3);
Search::setProductsAsIndexed($productsArray);
// If it has been deleted, the index is created again once the indexation is done
if (!$dropIndex)
{
$dropIndex = true;
$result = $db->ExecuteS('SHOW INDEX FROM `'._DB_PREFIX_.'search_index`');
foreach ($result as $row)
if (strtolower($row['Key_name']) == 'primary')
$dropIndex = false;
}
if ($dropIndex)
$db->Execute('ALTER TABLE `'._DB_PREFIX_.'search_index` ADD PRIMARY KEY (`id_word`, `id_product`)');
Configuration::updateValue('PS_NEED_REBUILD_INDEX', 0);
return true;
}
protected static function setProductsAsIndexed(&$products)
{
if (count($products))
Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'product SET indexed = 1 WHERE id_product IN ('.implode(',', $products).') LIMIT '.(int)count($products));
$productsArray = array();
}
// $queryArray3 is automatically emptied in order to be reused immediatly
protected static function saveIndex(&$queryArray3)
{
if (count($queryArray3))
Db::getInstance()->Execute('INSERT INTO '._DB_PREFIX_.'search_index (id_product, id_word, weight) VALUES '.implode(',', $queryArray3).' ON DUPLICATE KEY UPDATE weight = weight + VALUES(weight)');
$queryArray3 = array();
}
public static function searchTag($id_lang, $tag, $count = false, $pageNumber = 0, $pageSize = 10, $orderBy = false, $orderWay = false, $useCookie = true)
{
global $link, $cookie;
// Only use cookie if id_customer is not present
if ($useCookie)
$id_customer = (int)$cookie->id_customer;
else
$id_customer = 0;
if (!is_numeric($pageNumber) OR !is_numeric($pageSize) OR !Validate::isBool($count) OR !Validate::isValidSearch($tag)
OR $orderBy AND !$orderWay OR ($orderBy AND !Validate::isOrderBy($orderBy)) OR ($orderWay AND !Validate::isOrderBy($orderWay)))
return false;
if ($pageNumber < 1) $pageNumber = 1;
if ($pageSize < 1) $pageSize = 10;
if ($count)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(DISTINCT pt.`id_product`) nb
FROM `'._DB_PREFIX_.'product` p
LEFT JOIN `'._DB_PREFIX_.'product_tag` pt ON (p.`id_product` = pt.`id_product`)
LEFT JOIN `'._DB_PREFIX_.'tag` t ON (pt.`id_tag` = t.`id_tag` AND t.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_product` = p.`id_product`)
LEFT JOIN `'._DB_PREFIX_.'category_group` cg ON (cg.`id_category` = cp.`id_category`)
WHERE p.`active` = 1
AND cg.`id_group` '.(!$id_customer ? '= 1' : 'IN (
SELECT id_group FROM '._DB_PREFIX_.'customer_group
WHERE id_customer = '.(int)$id_customer.')').'
AND t.`name` LIKE \'%'.pSQL($tag).'%\'');
return isset($result['nb']) ? $result['nb'] : 0;
}
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT DISTINCT p.*, pl.`description_short`, pl.`link_rewrite`, pl.`name`, tax.`rate`, i.`id_image`, il.`legend`, m.`name` manufacturer_name, 1 position,
DATEDIFF(p.`date_add`, DATE_SUB(NOW(), INTERVAL '.(Validate::isUnsignedInt(Configuration::get('PS_NB_DAYS_NEW_PRODUCT')) ? Configuration::get('PS_NB_DAYS_NEW_PRODUCT') : 20).' DAY)) > 0 new
FROM `'._DB_PREFIX_.'product` p
INNER JOIN `'._DB_PREFIX_.'product_lang` pl ON (p.`id_product` = pl.`id_product` AND pl.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'image` i ON (i.`id_product` = p.`id_product` AND i.`cover` = 1)
LEFT JOIN `'._DB_PREFIX_.'image_lang` il ON (i.`id_image` = il.`id_image` AND il.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'tax_rule` tr ON (p.`id_tax_rules_group` = tr.`id_tax_rules_group`
AND tr.`id_country` = '.(int)Country::getDefaultCountryId().'
AND tr.`id_state` = 0)
LEFT JOIN `'._DB_PREFIX_.'tax` tax ON (tax.`id_tax` = tr.`id_tax`)
LEFT JOIN `'._DB_PREFIX_.'manufacturer` m ON (m.`id_manufacturer` = p.`id_manufacturer`)
LEFT JOIN `'._DB_PREFIX_.'product_tag` pt ON (p.`id_product` = pt.`id_product`)
LEFT JOIN `'._DB_PREFIX_.'tag` t ON (pt.`id_tag` = t.`id_tag` AND t.`id_lang` = '.(int)$id_lang.')
LEFT JOIN `'._DB_PREFIX_.'category_product` cp ON (cp.`id_product` = p.`id_product`)
LEFT JOIN `'._DB_PREFIX_.'category_group` cg ON (cg.`id_category` = cp.`id_category`)
WHERE p.`active` = 1
AND cg.`id_group` '.(!$id_customer ? '= 1' : 'IN (
SELECT id_group FROM '._DB_PREFIX_.'customer_group
WHERE id_customer = '.(int)$id_customer.')').'
AND t.`name` LIKE \'%'.pSQL($tag).'%\'
ORDER BY position DESC'.($orderBy ? ', '.$orderBy : '').($orderWay ? ' '.$orderWay : '').'
LIMIT '.(int)(($pageNumber - 1) * $pageSize).','.(int)$pageSize);
if (!$result) return false;
return Product::getProductsProperties((int)$id_lang, $result);
}
}
+72
View File
@@ -0,0 +1,72 @@
<?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 SearchEngineCore extends ObjectModel
{
public $server;
public $getvar;
protected $fieldsRequired = array ('server', 'getvar');
protected $fieldsValidate = array ('server' => 'isUrl', 'getvar' => 'isModuleName');
protected $table = 'search_engine';
protected $identifier = 'id_search_engine';
public function getFields()
{
parent::validateFields();
$fields['server'] = pSQL($this->server);
$fields['getvar'] = pSQL($this->getvar);
return $fields;
}
public static function getKeywords($url)
{
$parsedUrl = @parse_url($url);
if (!isset($parsedUrl['host']) OR !isset($parsedUrl['query']))
return false;
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('SELECT `server`, `getvar` FROM `'._DB_PREFIX_.'search_engine`');
foreach ($result as $index => $row)
{
$host =& $row['server'];
$varname =& $row['getvar'];
if (strstr($parsedUrl['host'], $host))
{
$kArray = array();
preg_match('/[^a-z]'.$varname.'=.+\&'.'/U', $parsedUrl['query'], $kArray);
if (empty($kArray[0]))
preg_match('/[^a-z]'.$varname.'=.+$'.'/', $parsedUrl['query'], $kArray);
if (empty($kArray[0]))
return false;
$kString = urldecode(str_replace('+', ' ', ltrim(substr(rtrim($kArray[0], '&'), strlen($varname) + 1), '=')));
return $kString;
}
}
}
}
+588
View File
@@ -0,0 +1,588 @@
<?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: 7521 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
class ShopCore extends ObjectModel
{
public $id_group_shop;
public $id_theme;
public $name;
public $active;
public $id_category;
public $deleted;
private static $current_base_uri;
private static $current_theme_name;
private static $id_current_shop;
private static $id_current_group_shop;
private static $id_current_root_category;
protected $fieldsSize = array('name' => 64);
protected $fieldsValidate = array('active' => 'isBool',
'name' => 'isGenericName');
protected $table = 'shop';
protected $identifier = 'id_shop';
/** @var array List of shops cached */
protected static $shops = array();
private static $assoTables = array(
'carrier' => array('type' => 'shop'),
'category_lang' => array('type' => 'fk_shop'),
'cms' => array('type' => 'shop'),
'contact' => array('type' => 'shop'),
'country' => array('type' => 'shop'),
'currency' => array('type' => 'shop'),
'hook_module' => array('type' => 'fk_shop'),
'hook_module_exceptions' => array('type' => 'fk_shop', 'primary' => 'id_hook_module_exceptions'),
'image' => array('type' => 'shop'),
'lang' => array('type' => 'shop'),
'meta_lang' => array('type' => 'fk_shop'),
'module' => array('type' => 'shop'),
'module_currency' => array('type' => 'fk_shop'),
'module_country' => array('type' => 'fk_shop'),
'module_group' => array('type' => 'fk_shop'),
'stock' => array('type' => 'fk_shop', 'primary' => 'id_stock'),
'product' => array('type' => 'shop'),
'product_lang' => array('type' => 'fk_shop'),
'store' => array('type' => 'shop'),
'webservice_account' => array('type' => 'shop'),
);
protected $webserviceParameters = array(
'fields' => array(
'id_group_shop' => array('xlink_resource' => 'shop_groups'),
'id_category' => array(),
'id_theme' => array(),
),
);
/**
* There are 3 kinds of shop context : shop, group shop and general
*/
const CONTEXT_SHOP = 1;
const CONTEXT_GROUP = 2;
const CONTEXT_ALL = 3;
public function getFields()
{
parent::validateFields();
$fields['id_group_shop'] = (int)$this->id_group_shop;
$fields['id_category'] = (int)$this->id_category;
$fields['id_theme'] = (int)$this->id_theme;
$fields['name'] = pSQL($this->name);
$fields['active'] = (int)$this->active;
$fields['deleted'] = (int)$this->deleted;
return $fields;
}
public static function getAssoTables()
{
return self::$assoTables;
}
public function add($autodate = true, $nullValues = false)
{
$res = parent::add();
Shop::loadShops(true);
return $res;
}
public function delete()
{
if (!$res = parent::delete())
return false;
foreach (Shop::getAssoTables() AS $table_name => $row)
{
// Special case for stock if current shop is in a share stock group
if ($table_name == 'stock')
{
$group = new GroupShop($this->id_group_shop);
if ($group->share_stock && $group->getNbShops() > 1)
continue;
}
$id = 'id_'.$row['type'];
if ($row['type'] == 'fk_shop')
$id = 'id_shop';
else
$table_name .= '_'.$row['type'];
$res &= Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.$table_name.'` WHERE `'.$id.'`='.(int)$this->id);
}
Shop::loadShops(true);
return $res;
}
/**
* Check if shop is the same as default shop in configuration
*
* @param int $shopID
* @return bool
*/
public static function isDefaultShop($shopID)
{
return ($shopID == Configuration::get('PS_SHOP_DEFAULT'));
}
/**
* Load list of groups and shops, and cache it
*
* @param bool $refresh
*/
public static function loadShops($refresh = false)
{
if (self::$shops && !$refresh)
return;
$sql = 'SELECT gs.id_group_shop, gs.name AS group_name, gs.share_datas, gs.share_stock, s.id_shop, s.name AS shop_name, s.id_theme, s.id_category, s.active
FROM '._DB_PREFIX_.'group_shop gs
LEFT JOIN '._DB_PREFIX_.'shop s
ON (s.id_group_shop = gs.id_group_shop)
WHERE s.active = 1
AND s.deleted = 0
AND gs.deleted = 0
ORDER BY gs.name, s.name';
if ($results = Db::getInstance()->ExecuteS($sql))
{
foreach ($results as $row)
{
if (!isset(self::$shops[$row['id_group_shop']]))
self::$shops[$row['id_group_shop']] = array(
'id' => $row['id_group_shop'],
'name' => $row['group_name'],
'share_datas' => $row['share_datas'],
'share_stock' => $row['share_stock'],
'shops' => array(),
);
self::$shops[$row['id_group_shop']]['shops'][$row['id_shop']] = array(
'id_shop' => $row['id_shop'],
'id_group_shop' => $row['id_group_shop'],
'name' => $row['shop_name'],
'id_theme' => $row['id_theme'],
'id_category' => $row['id_category'],
'active' => $row['active'],
);
}
}
}
public function getUrls()
{
return Db::getInstance()->ExecuteS('SELECT *
FROM '._DB_PREFIX.'shop_url
WHERE active=1 AND id_shop='.(int)$this->id);
}
/**
* Get shops list
*
* @param bool $active
* @param int $id_group_shop
* @param bool $getAsListID
*/
public static function getShops($active = true, $id_group_shop = null, $getAsListID = false)
{
Shop::loadShops();
$results = array();
foreach (self::$shops as $groupID => $groupData)
foreach ($groupData['shops'] as $id => $shopData)
if ((!$active || $shopData['active']) && (!$id_group_shop || $id_group_shop == $groupID))
{
if ($getAsListID)
$results[] = $id;
else
$results[] = $shopData;
}
return $results;
}
/**
* @return int Total of shops
*/
public static function getTotalShops($active = true)
{
return count(Shop::getShops($active));
}
public static function setCurrentShop()
{
$excluded_uris = self::getExcludedUris();
preg_match('/^'.Tools::pRegexp(_PS_DIRECTORY_, '/').'([a-z0-9]+)\/.*$/Ui', $_SERVER['REQUEST_URI'], $res);
if (isset($res[1]) AND !in_array($res[1], $excluded_uris))
$uri = $res[1];
else
$uri = '';
if (!$id_shop = (int)Tools::getValue('id_shop'))
{
$id_shop = Db::getInstance()->getValue('SELECT s.id_shop
FROM '._DB_PREFIX_.'shop_url su
LEFT JOIN '._DB_PREFIX_.'shop s ON (s.id_shop = su.id_shop)
WHERE su.domain=\''.pSQL(Tools::getHttpHost()).'\' AND uri=\''.pSQL($uri).'\' AND s.active=1 AND s.deleted=0');
if (!$id_shop)
$id_shop = Configuration::get('PS_SHOP_DEFAULT');
}
$res = Db::getInstance()->getRow('SELECT s.id_shop, s.id_group_shop, s.id_category, su.uri, t.name
FROM '._DB_PREFIX_.'shop s
LEFT JOIN '._DB_PREFIX_.'shop_url su ON (s.id_shop = su.id_shop)
LEFT JOIN '._DB_PREFIX_.'theme t ON (t.id_theme = s.id_theme)
WHERE s.id_shop='.(int)$id_shop.' AND s.active=1 AND s.deleted=0 AND su.main=1');
$id_shop = (int)$res['id_shop'];
$id_group_shop = (int)$res['id_group_shop'];
self::$id_current_shop = (int)$id_shop;
self::$id_current_group_shop = (int)$id_group_shop;
self::$id_current_root_category = (int)$res['id_category'];
self::$current_base_uri = (!empty($res['uri']) ? $res['uri'].'/' : '' );
self::$current_theme_name = $res['name'];
}
public static function getExcludedUris()
{
$directories = scandir(dirname(__FILE__).'/../');
$not_uri = array();
foreach ($directories AS $directory)
if (is_dir(dirname(__FILE__).'/../'.$directory) AND (!preg_match ('/^\./', $directory)))
$not_uri[] = '/'.$directory.'/';
return $not_uri;
}
public static function getCurrentTheme()
{
return self::$current_theme_name;
}
public static function getCurrentBaseURI($with_base = true)
{
return ($with_base ? _PS_DIRECTORY_ : '').self::$current_base_uri;
}
public static function getCurrentGroupShop()
{
return Shop::retrieveContext('group');
}
/**
* Get current shop ID.
*
* @param bool $forceContext If true and if no shop is selected in context, get default shop ID
* @return int
*/
public static function getCurrentShop($forceContext = false)
{
$shopID = Shop::retrieveContext('shop');
if (!$shopID && $forceContext)
$shopID = (int)Configuration::get('PS_SHOP_DEFAULT');
return $shopID;
}
public function getTheme($entity = false, $id = false)
{
return Db::getInstance()->getValue('SELECT t.name
FROM '._DB_PREFIX_.'shop s
LEFT JOIN '._DB_PREFIX_.'theme t ON (s.id_theme = t.id_theme)
WHERE id_shop='.(int)$this->id);
}
public static function getCurrentRootCategory()
{
return self::$id_current_root_category;
}
public function getRootCategory()
{
return $this->id_category;
}
/**
* Retrieve group ID of a shop
*
* @param int $shopID Shop ID
* @return int Group ID
*/
public static function getGroupFromShop($shopID, $asID = true)
{
Shop::loadShops();
foreach (self::$shops as $groupID => $groupData)
if (array_key_exists($shopID, $groupData['shops']))
return ($asID) ? $groupID : $groupData;
return false;
}
/**
* If the shop group has a the option "share_datas" activated, get all shops ID of this group, else get current shop ID
*
* @param int $shopID
* @return array
*/
public static function getSharedShops($shopID)
{
Shop::loadShops();
foreach (self::$shops as $groupData)
if (array_key_exists($shopID, $groupData['shops']) && $groupData['share_datas'])
return array_keys($groupData['shops']);
return array($shopID);
}
/**
* Retrieve the current shop context in FO or BO
*
* @param string null|shop|group
* @return array(id_shop, id_group_shop)|int
*/
public static function retrieveContext($type = null)
{
static $executed = false, $shopID = 0, $shopGroupID = 0;
if (!$executed)
{
if (defined('PS_ADMIN_DIR'))
{
global $cookie;
// While cookie is not instancied in admin, we wait ...
if (!$cookie)
return ($type == 'shop' || $type == 'group') ? '' : array('', '');
// Parse shopContext cookie value (E.g. s-2, g-4)
$split = explode('-', $cookie->shopContext);
$shopID = $shopGroupID = '';
if (count($split) == 2)
{
if ($split[0] == 's')
$shopID = (int)$split[1];
else if ($split[0] == 'g')
$shopGroupID = (int)$split[1];
if ($shopID && !$shopGroupID)
$shopGroupID = Shop::getGroupFromShop($shopID);
}
}
else
{
$shopID = (int)self::$id_current_shop;
$shopGroupID = (int)self::$id_current_group_shop;
}
$executed = true;
}
if ($type == 'shop')
return $shopID;
else if ($type == 'group')
return $shopGroupID;
return array($shopID, $shopGroupID);
}
/**
* Get a list of ID concerned by the shop context (E.g. if context is shop group, get list of children shop ID)
*
* @param int $shopID
* @param int $shopGroupID
* @param bool $share If true and if $shopID is set, list shops with share data too
* @return array
*/
public static function getListOfID($shopID, $shopGroupID, $share = false)
{
if ($shopID)
$list = (!$share) ? array($shopID) : Shop::getSharedShops($shopID);
else if ($shopGroupID)
$list = Shop::getShops(true, $shopGroupID, true);
else
$list = Shop::getShops(true, null, true);
return $list;
}
/**
* Get a list of ID concerned by the shop context (E.g. if context is shop group, get list of children shop ID)
*
* @return array
*/
public static function getListFromContext()
{
list($shopID, $shopGroupID) = Shop::retrieveContext();
return Shop::getListOfID($shopID, $shopGroupID);
}
/**
* Check in which type of shop context we are
*
* @return int
*/
public static function getContextType()
{
list($shopID, $shopGroupID) = Shop::retrieveContext();
if ($shopID)
return Shop::CONTEXT_SHOP;
else if ($shopGroupID)
return Shop::CONTEXT_GROUP;
return Shop::CONTEXT_ALL;
}
public static function sqlRestriction($share = false, $alias = null, $shopID = null, $shopGroupID = null, $type = 'shop')
{
if ($type != 'shop' && $type != 'group_shop')
$type = 'shop';
if ($alias)
$alias .= '.';
$restriction = '';
if (is_null($shopID))
$shopID = Shop::retrieveContext('shop');
if (is_null($shopGroupID))
$shopGroupID = Shop::retrieveContext('group');
if ($type == 'group_shop')
{
if ($shopID)
$restriction = ' AND '.$alias.'id_group_shop = '.Shop::getGroupFromShop($shopID);
else if ($shopGroupID)
$restriction = ' AND '.$alias.'id_group_shop = '.$shopGroupID;
}
else
{
if ($shopID || $shopGroupID)
$restriction = ' AND '.$alias.'id_shop IN ('.implode(', ', Shop::getListOfID($shopID, $shopGroupID, $share)).')';
}
return $restriction;
}
public static function sqlSharedStock($alias = null, $shopID = null, $shopGroupID = null)
{
if ($alias)
$alias .= '.';
if (is_null($shopID))
$shopID = Shop::getCurrentShop(true);
if (!$shopID)
return ($shopGroupID) ? ' AND '.$alias.'id_group_shop = '.(int)$shopGroupID : '';
Shop::loadShops();
foreach (self::$shops as $groupID => $groupData)
if (array_key_exists($shopID, $groupData['shops']) && $groupData['share_stock'])
return ' AND '.$alias.'id_group_shop = '.$groupID;
return ' AND '.$alias.'id_shop = '.$shopID;
}
/**
* Get all groups and associated shops as subarrays
*
* @return array
*/
public static function getTree()
{
Shop::loadShops();
return self::$shops;
}
/**
* Generate a sweet HTML list for shop selection
*
* @return string
*/
public static function generateHtmlList()
{
$tree = Shop::getTree();
// Get default value
list($shopID, $shopGroupID) = Shop::retrieveContext();
if ($shopID)
$value = 's-'.$shopID;
else if ($shopGroupID)
$value = 'g-'.$shopGroupID;
else
$value = '';
// Generate HTML
$url = $_SERVER['REQUEST_URI'] . (($_SERVER['QUERY_STRING']) ? '&' : '?') . 'setShopContext=';
$html = '<select class="shopList" onchange="location.href = \''.$url.'\'+$(this).val();">';
$html .= '<option value="" class="first">' . translate('All shops') . '</option>';
foreach ($tree as $gID => $groupData)
{
$html .= '<option class="group" value="g-'.$gID.'" '.(($value == 'g-'.$gID) ? 'selected="selected"' : '').'>'.htmlspecialchars($groupData['name']).'</option>';
foreach ($groupData['shops'] as $sID => $shopData)
$html .= '<option value="s-'.$sID.'" class="shop" '.(($value == 's-'.$sID) ? 'selected="selected"' : '').'>&raquo; '.$shopData['name'].'</option>';
}
$html .= '</select>';
return $html;
}
public function copyShopData($old_id, $tables_import = false, $deleted = false)
{
foreach (Shop::getAssoTables() AS $table_name => $row)
{
if ($tables_import && !isset($tables_import[$table_name]))
continue;
// Special case for stock if current shop is in a share stock group
if ($table_name == 'stock')
{
$group = new GroupShop($this->id_group_shop);
if ($group->share_stock && $group->haveShops())
continue;
}
$id = 'id_'.$row['type'];
if ($row['type'] == 'fk_shop')
$id = 'id_shop';
else
$table_name .= '_'.$row['type'];
if (!$deleted)
{
$res = Db::getInstance()->getRow('SELECT * FROM `'._DB_PREFIX_.$table_name.'` WHERE `'.$id.'` = '.(int)$old_id);
if ($res)
{
unset($res[$id]);
if (isset($row['primary']))
unset($res[$row['primary']]);
$keys = implode(', ', array_keys($res));
$sql = 'INSERT INTO `'._DB_PREFIX_.$table_name.'` ('.$keys.', '.$id.')
(SELECT '.$keys.', '.(int)$this->id.' FROM '._DB_PREFIX_.$table_name.'
WHERE `'.$id.'` = '.(int)$old_id.')';
Db::getInstance()->Execute($sql);
}
}
else
{
Db::getInstance()->Execute('UPDATE `'._DB_PREFIX_.$table_name.'` SET WHERE `'.$id.'`='.(int)$old_id);
}
}
}
}
+103
View File
@@ -0,0 +1,103 @@
<?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: 1.4 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class ShopUrlCore extends ObjectModel
{
public $id_shop;
public $domain;
public $domain_ssl;
public $uri;
public $main;
public $active;
private static $main_domain = NULL;
private static $main_domain_ssl = NULL;
protected $fieldsRequired = array('domain', 'id_shop');
protected $fieldsSize = array('domain' => 255, 'uri' => 64);
protected $fieldsValidate = array('active' => 'isBool');
protected $table = 'shop_url';
protected $identifier = 'id_shop_url';
public function getFields()
{
parent::validateFields();
$fields['domain'] = pSQL($this->domain);
$fields['domain_ssl'] = pSQL($this->domain_ssl);
$fields['uri'] = pSQL($this->uri);
$fields['id_shop'] = (int)$this->id_shop;
$fields['main'] = (int)$this->main;
$fields['active'] = (int)$this->active;
return $fields;
}
public static function getShopUrls($id_shop = false)
{
return Db::getInstance()->ExecuteS('SELECT *
FROM '._DB_PREFIX_.'shop_url
WHERE 1
'.($id_shop ? ' AND id_shop='.(int)$id_shop : ''));
}
public function setMain()
{
$res = Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'shop_url SET main=0 WHERE id_shop='.(int)$this->id_shop);
$res &= Db::getInstance()->Execute('UPDATE '._DB_PREFIX_.'shop_url SET main=1 WHERE id_shop_url='.(int)$this->id);
return $res;
}
public function canAddThisUrl($domain, $domain_ssl, $uri)
{
$sql = 'SELECT id_shop_url
FROM '._DB_PREFIX_.'shop_url
WHERE uri=\''.pSQL($uri).'\'
AND (domain=\''.pSQL($domain).'\' '.(($domain_ssl) ? 'OR domain_ssl=\''.pSQL($domain_ssl).'\'' : '').')'
.($this->id ? ' AND id_shop_url !='.(int)$this->id : '');
return Db::getInstance()->getValue($sql);
}
public static function getMainShopDomain()
{
if (!self::$main_domain)
self::$main_domain = Db::getInstance()->getValue('SELECT domain
FROM '._DB_PREFIX_.'shop_url
WHERE main=1 AND id_shop='.(int)Shop::getCurrentShop());
return self::$main_domain;
}
public static function getMainShopDomainSSL()
{
if (!self::$main_domain)
self::$main_domain = Db::getInstance()->getValue('SELECT domain
FROM '._DB_PREFIX_.'shop_url
WHERE main=1 AND id_shop='.(int)Shop::getCurrentShop());
return self::$main_domain_ssl;
}
}
+255
View File
@@ -0,0 +1,255 @@
<?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: 7158 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
class SpecificPriceCore extends ObjectModel
{
public $id_product;
public $id_shop;
public $id_currency;
public $id_country;
public $id_group;
public $price;
public $from_quantity;
public $reduction;
public $reduction_type;
public $from;
public $to;
protected $fieldsRequired = array('id_product', 'id_shop', 'id_currency', 'id_country', 'id_group', 'price', 'from_quantity', 'reduction', 'reduction_type', 'from', 'to');
protected $fieldsValidate = array('id_group_shop' => 'isUnsignedId', 'id_product' => 'isUnsignedId', 'id_shop' => 'isUnsignedId', 'id_country' => 'isUnsignedId', 'id_group' => 'isUnsignedId', 'price' => 'isPrice', 'from_quantity' => 'isUnsignedInt', 'reduction' => 'isPrice', 'reduction_type' => 'isReductionType', 'from' => 'isDateFormat', 'to' => 'isDateFormat');
protected $table = 'specific_price';
protected $identifier = 'id_specific_price';
protected static $_specificPriceCache = array();
protected static $_cache_priorities = array();
public function getFields()
{
parent::validateFields();
$fields['id_product'] = (int)($this->id_product);
$fields['id_shop'] = (int)($this->id_shop);
$fields['id_currency'] = (int)($this->id_currency);
$fields['id_country'] = (int)($this->id_country);
$fields['id_group'] = (int)($this->id_group);
$fields['price'] = (float)($this->price);
$fields['from_quantity'] = (int)($this->from_quantity);
$fields['reduction'] = (float)($this->reduction);
$fields['reduction_type'] = pSQL($this->reduction_type);
$fields['from'] = pSQL($this->from);
$fields['to'] = pSQL($this->to);
return $fields;
}
static public function getByProductId($id_product)
{
return Db::getInstance()->ExecuteS('
SELECT * FROM `'._DB_PREFIX_.'specific_price` WHERE `id_product` = '.(int)($id_product)
);
}
static public function getIdsByProductId($id_product)
{
return Db::getInstance()->ExecuteS('
SELECT `id_specific_price` FROM `'._DB_PREFIX_.'specific_price` WHERE `id_product` = '.(int)$id_product.'
');
}
// score generation for quantity discount
protected static function _getScoreQuery($id_product, $id_shop, $id_currency, $id_country, $id_group)
{
$select = '(';
$now = date('Y-m-d H:i:s');
$select .= ' IF (\''.$now.'\' >= `from` AND \''.$now.'\' <= `to`, '.pow(2, 0).', 0) + ';
$priority = SpecificPrice::getPriority($id_product);
foreach (array_reverse($priority) AS $k => $field)
$select .= ' IF (`'.$field.'` = '.(int)(${$field}).', '.pow(2, $k + 1).', 0) + ';
return rtrim($select, ' +').') AS `score`';
}
public static function getPriority($id_product)
{
if (!isset(self::$_cache_priorities[(int)$id_product]))
{
self::$_cache_priorities[(int)$id_product] = Db::getInstance()->getValue('
SELECT `priority`
FROM `'._DB_PREFIX_.'specific_price_priority`
WHERE `id_product` = '.(int)$id_product);
}
$priority = self::$_cache_priorities[(int)$id_product];
if (!$priority)
$priority = Configuration::get('PS_SPECIFIC_PRICE_PRIORITIES');
return preg_split('/;/', $priority);
}
static public function getSpecificPrice($id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity)
{
/*
** The date is not taken into account for the cache, but this is for the better because it keeps the consistency for the whole script.
** The price must not change between the top and the bottom of the page
*/
$key = ((int)$id_product.'-'.(int)$id_shop.'-'.(int)$id_currency.'-'.(int)$id_country.'-'.(int)$id_group.'-'.(int)$quantity);
if (!array_key_exists($key, self::$_specificPriceCache))
{
$now = date('Y-m-d H:i:s');
self::$_specificPriceCache[$key] = Db::getInstance()->getRow('
SELECT *, '.self::_getScoreQuery($id_product, $id_shop, $id_currency, $id_country, $id_group).'
FROM `'._DB_PREFIX_.'specific_price`
WHERE `id_product` IN (0, '.(int)$id_product.')
AND `id_shop` IN (0, '.(int)$id_shop.')
AND `id_currency` IN (0, '.(int)$id_currency.')
AND `id_country` IN (0, '.(int)$id_country.')
AND `id_group` IN (0, '.(int)$id_group.')
AND `from_quantity` <= '.(int)$quantity.'
AND (`from` = \'0000-00-00 00:00:00\' OR (\''.$now.'\' >= `from` AND \''.$now.'\' <= `to`))
ORDER BY `score` DESC, `from_quantity` DESC');
}
return self::$_specificPriceCache[$key];
}
static public function setPriorities($priorities)
{
$value = '';
foreach ($priorities as $priority)
$value .= pSQL($priority).';';
SpecificPrice::deletePriorities();
return Configuration::updateValue('PS_SPECIFIC_PRICE_PRIORITIES', rtrim($value, ';'));
}
public static function deletePriorities()
{
return Db::getInstance()->Execute('
TRUNCATE `'._DB_PREFIX_.'specific_price_priority`
');
}
static public function setSpecificPriority($id_product, $priorities)
{
$fields = '';
$value = '';
foreach ($priorities as $priority)
$value .= pSQL($priority).';';
return Db::getInstance()->Execute('
INSERT INTO `'._DB_PREFIX_.'specific_price_priority` (`id_product`, `priority`)
VALUES ('.(int)$id_product.',\''.rtrim($value, ';').'\')
ON DUPLICATE KEY UPDATE `priority` = \''.rtrim($value, ';').'\'
');
}
static public function getQuantityDiscounts($id_product, $id_shop, $id_currency, $id_country, $id_group)
{
$now = date('Y-m-d H:i:s');
$res = Db::getInstance()->ExecuteS('
SELECT *,
'.self::_getScoreQuery($id_product, $id_shop, $id_currency, $id_country, $id_group).'
FROM `'._DB_PREFIX_.'specific_price`
WHERE `id_product` IN(0, '.(int)($id_product).') AND
`id_shop` IN(0, '.(int)($id_shop).') AND
`id_currency` IN(0, '.(int)($id_currency).') AND
`id_country` IN(0, '.(int)($id_country).') AND
`id_group` IN(0, '.(int)($id_group).') AND
(`from` = \'0000-00-00 00:00:00\' OR (\''.$now.'\' >= `from` AND \''.$now.'\' <= `to`))
ORDER BY `score` DESC, `from_quantity` DESC
');
$targeted_prices = array();
$max_score = NULL;
foreach($res as $specific_price)
{
if (!isset($max_score))
$max_score = $specific_price['score'];
else if ($max_score != $specific_price['score'])
break;
if ($specific_price['from_quantity'] > 1)
$targeted_prices[] = $specific_price;
}
return $targeted_prices;
}
static public function getQuantityDiscount($id_product, $id_shop, $id_currency, $id_country, $id_group, $quantity)
{
$now = date('Y-m-d H:i:s');
return Db::getInstance()->getRow('
SELECT *,
'.self::_getScoreQuery($id_product, $id_shop, $id_currency, $id_country, $id_group).'
FROM `'._DB_PREFIX_.'specific_price`
WHERE `id_product` IN(0, '.(int)($id_product).') AND
`id_shop` IN(0, '.(int)($id_shop).') AND
`id_currency` IN(0, '.(int)($id_currency).') AND
`id_country` IN(0, '.(int)($id_country).') AND
`id_group` IN(0, '.(int)($id_group).') AND
`from_quantity` >= '.(int)($quantity).' AND
(`from` = \'0000-00-00 00:00:00\' OR (\''.$now.'\' >= `from` AND \''.$now.'\' <= `to`))
ORDER BY `score` DESC, `from_quantity` DESC
');
}
static public function getProductIdByDate($id_shop, $id_currency, $id_country, $id_group, $beginning, $ending)
{
$resource = Db::getInstance()->ExecuteS('
SELECT `id_product`
FROM `'._DB_PREFIX_.'specific_price`
WHERE `id_shop` IN(0, '.(int)($id_shop).') AND
`id_currency` IN(0, '.(int)($id_currency).') AND
`id_country` IN(0, '.(int)($id_country).') AND
`id_group` IN(0, '.(int)($id_group).') AND
`from_quantity` = 1 AND
(`from` = \'0000-00-00 00:00:00\' OR (\''.$beginning.'\' >= `from` AND \''.$ending.'\' <= `to`)) AND
`reduction` > 0
', false);
$ids_product = array();
while ($row = DB::getInstance()->nextRow($resource))
$ids_product[] = (int)($row['id_product']);
return $ids_product;
}
static public function deleteByProductId($id_product)
{
return Db::getInstance()->Execute('DELETE FROM `'._DB_PREFIX_.'specific_price` WHERE `id_product` = '.(int)($id_product));
}
public function duplicate($id_product = false)
{
if ($id_product)
$this->id_product = (int)($id_product);
return $this->add();
}
}
+204
View File
@@ -0,0 +1,204 @@
<?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 StateCore extends ObjectModel
{
/** @var integer Country id which state belongs */
public $id_country;
/** @var integer Zone id which state belongs */
public $id_zone;
/** @var string 2 letters iso code */
public $iso_code;
/** @var string Name */
public $name;
/** @var boolean Status for delivery */
public $active = true;
protected $fieldsRequired = array('id_country', 'id_zone', 'iso_code', 'name');
protected $fieldsSize = array('iso_code' => 4, 'name' => 32);
protected $fieldsValidate = array('id_country' => 'isUnsignedId', 'id_zone' => 'isUnsignedId', 'iso_code' => 'isStateIsoCode', 'name' => 'isGenericName', 'active' => 'isBool');
protected $table = 'state';
protected $identifier = 'id_state';
protected $webserviceParameters = array(
'fields' => array(
'id_zone' => array('xlink_resource'=> 'zones'),
'id_country' => array('xlink_resource'=> 'countries')
),
);
public function getFields()
{
parent::validateFields();
$fields['id_country'] = (int)($this->id_country);
$fields['id_zone'] = (int)($this->id_zone);
$fields['iso_code'] = pSQL(strtoupper($this->iso_code));
$fields['name'] = pSQL($this->name);
$fields['active'] = (int)($this->active);
return $fields;
}
public static function getStates($id_lang = false, $active = false)
{
return Db::getInstance(_PS_USE_SQL_SLAVE_)->ExecuteS('
SELECT `id_state`, `id_country`, `id_zone`, `iso_code`, `name`, `active`
FROM `'._DB_PREFIX_.'state`
'.($active ? 'WHERE active = 1' : '').'
ORDER BY `name` ASC');
}
/**
* Get a state name with its ID
*
* @param integer $id_state Country ID
* @return string State name
*/
static public function getNameById($id_state)
{
$result = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT `name`
FROM `'._DB_PREFIX_.'state`
WHERE `id_state` = '.(int)($id_state));
return $result['name'];
}
/**
* Get a state id with its name
*
* @param string $id_state Country ID
* @return integer state id
*/
static public function getIdByName($state)
{
$result = Db::getInstance()->getRow('
SELECT `id_state`
FROM `'._DB_PREFIX_.'state`
WHERE `name` LIKE \''.pSQL($state).'\'');
return ((int)($result['id_state']));
}
/**
* Get a state id with its iso code
*
* @param string $iso_code Iso code
* @return integer state id
*/
static public function getIdByIso($iso_code)
{
return Db::getInstance()->getValue('
SELECT `id_state`
FROM `'._DB_PREFIX_.'state`
WHERE `iso_code` = \''.pSQL($iso_code).'\''
);
}
/**
* Delete a state only if is not in use
*
* @return boolean
*/
public function delete()
{
if (!Validate::isTableOrIdentifier($this->identifier) OR !Validate::isTableOrIdentifier($this->table))
die(Tools::displayError());
if (!$this->isUsed())
{
/* Database deletion */
$result = Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
if (!$result)
return false;
/* Database deletion for multilingual fields related to the object */
if (method_exists($this, 'getTranslationsFieldsChild'))
Db::getInstance()->Execute('DELETE FROM `'.pSQL(_DB_PREFIX_.$this->table).'_lang` WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
return $result;
}
else
return false;
}
/**
* Check if a state is used
*
* @return boolean
*/
public function isUsed()
{
return ($this->countUsed() > 0);
}
/**
* Returns the number of utilisation of a state
*
* @return integer count for this state
*/
public function countUsed()
{
$row = Db::getInstance(_PS_USE_SQL_SLAVE_)->getRow('
SELECT COUNT(*) AS nb_used
FROM `'._DB_PREFIX_.'address`
WHERE `'.pSQL($this->identifier).'` = '.(int)($this->id));
return $row['nb_used'];
}
public static function getStatesByIdCountry($id_country)
{
if (empty($id_country))
die(Tools::displayError());
return Db::getInstance()->ExecuteS('
SELECT *
FROM `'._DB_PREFIX_.'state` s
WHERE s.`id_country` = '.(int)$id_country
);
}
public static function hasCounties($id_state)
{
return sizeof(County::getCounties((int)$id_state));
}
public static function getIdZone($id_state)
{
if (!Validate::isUnsignedId($id_state))
die(Tools::displayError());
return Db::getInstance(_PS_USE_SQL_SLAVE_)->getValue('
SELECT `id_zone`
FROM `'._DB_PREFIX_.'state`
WHERE `id_state` = '.(int)($id_state));
}
}
+66
View File
@@ -0,0 +1,66 @@
<?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: 1.4 $
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
* International Registered Trademark & Property of PrestaShop SA
*/
/**
* @since 1.5.0
*/
class Stock extends ObjectModel
{
public $id_product;
public $id_product_attribute;
public $id_group_shop;
public $id_shop;
public $quantity;
protected $fieldsRequired = array('id_shop', 'id_group_shop', 'id_product', 'id_product_attribute');
protected $fieldsSize = array();
protected $fieldsValidate = array();
protected $table = 'stock';
protected $identifier = 'id_stock';
public function getFields()
{
parent::validateFields();
$fields['id_product'] = (int)$this->id_product;
$fields['id_product_attribute'] = (int)$this->id_product_attribute;
$fields['id_group_shop'] = (int)$this->id_group_shop;
$fields['id_shop'] = (int)$this->id_shop;
$fields['quantity'] = (int)$this->quantity;
return $fields;
}
public static function getStockId($id_product, $id_product_attribute, $shopID = null)
{
$sql = 'SELECT id_stock
FROM '._DB_PREFIX_.'stock
WHERE id_product = '.(int)$id_product.'
AND id_product_attribute = '.(int)$id_product_attribute
.Shop::sqlSharedStock('', $shopID);
return (int)Db::getInstance()->getValue($sql);
}
}

Some files were not shown because too many files have changed in this diff Show More