PageRenderTime 57ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/modules/trustedshops/lib/TSBuyerProtection.php

http://marocmall.googlecode.com/
PHP | 1393 lines | 1012 code | 82 blank | 299 comment | 90 complexity | 6d98944b5653cd777445a7d4626b6c33 MD5 | raw file
Possible License(s): LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /*
  3. * 2007-2011 PrestaShop
  4. *
  5. * NOTICE OF LICENSE
  6. *
  7. * This source file is subject to the Academic Free License (AFL 3.0)
  8. * that is bundled with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://opensource.org/licenses/afl-3.0.php
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@prestashop.com so we can send you a copy immediately.
  14. *
  15. * DISCLAIMER
  16. *
  17. * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
  18. * versions in the future. If you wish to customize PrestaShop for your
  19. * needs please refer to http://www.prestashop.com for more information.
  20. *
  21. * @author PrestaShop SA <contact@prestashop.com>
  22. * @copyright 2007-2011 PrestaShop SA
  23. * @version Release: $Revision: 7001 $
  24. * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
  25. * International Registered Trademark & Property of PrestaShop SA
  26. */
  27. include(_PS_MODULE_DIR_.'trustedshops/lib/TSBPException.php');
  28. /**
  29. * @see the technical doc for entire description.
  30. * too long to set it here.
  31. * @author Prestashop - Nans Pellicari
  32. * @since prestashop 1.4
  33. * @version 0.1
  34. */
  35. class TSBuyerProtection extends AbsTrustedShops
  36. {
  37. const PREFIX_TABLE = 'TS_TAB1_';
  38. const ENV_TEST = 'test';
  39. const ENV_PROD = 'production';
  40. const DB_ITEMS = 'ts_buyerprotection_items';
  41. const DB_APPLI = 'ts_application_id';
  42. const WEBSERVICE_BO = 'administration';
  43. const WEBSERVICE_FO = 'front-end';
  44. /**
  45. * List of registration link, need to add parameters
  46. * @see TSBuyerProtection::_getRegistrationLink()
  47. * @var array
  48. */
  49. private $registration_link = array(
  50. 'DE' => 'http://www.trustedshops.de/shopbetreiber/mitgliedschaft.html',
  51. 'EN' => 'http://www.trustedshops.com/merchants/membership.html',
  52. 'FR' => 'http://www.trustedshops.com/marchands/affiliation.html',
  53. 'PL' => 'http://www.trustedshops.pl/handlowcy/cennik.html',
  54. );
  55. /**
  56. * Link to obtain the certificate about the shop.
  57. * Use by seal of approval.
  58. * @see TSBuyerProtection::hookRightColumn()
  59. * @var array
  60. */
  61. private static $certificate_link = array(
  62. 'DE' => 'http://www.trustedshops.de/profil/#shop_name#_#shop_id#.html',
  63. 'EN' => 'http://www.trustedshops.com/profile/#shop_name#_#shop_id#.html',
  64. 'FR' => 'http://www.trustedshops.fr',
  65. 'PL' => 'http://www.trustedshops.de/profil/#shop_name#_#shop_id#.html',
  66. );
  67. /**
  68. * Available language for used TrustedShops Buyer Protection
  69. * @see TSBuyerProtection::__construct()
  70. * @var array
  71. */
  72. private $available_languages = array('EN'=>'', 'FR'=>'', 'DE'=>'', 'PL'=>'', );
  73. /**
  74. * @todo : be sure : see TrustedShopsRating::__construct()
  75. * @var array
  76. */
  77. public $limited_countries = array('PL', 'GB', 'US', 'FR', 'DE');
  78. /**
  79. * Differents urls to call for Trusted Shops API
  80. * @var array
  81. */
  82. private static $webservice_urls = array(
  83. 'administration' => array(
  84. 'test' => 'https://qa.trustedshops.de/ts/services/TsProtection?wsdl',
  85. 'production' => 'https://www.trustedshops.de/ts/services/TsProtection?wsdl',
  86. ),
  87. 'front-end' => array(
  88. 'test' => 'https://protection-qa.trustedshops.com/ts/protectionservices/ApplicationRequestService?wsdl',
  89. 'production' => 'https://protection.trustedshops.com/ts/protectionservices/ApplicationRequestService?wsdl',
  90. ),
  91. );
  92. // Configuration vars
  93. private static $SHOPSW;
  94. private static $ET_CID;
  95. private static $ET_LID;
  96. /**
  97. * Its must look like :
  98. * array(
  99. * 'lang_iso(ex: FR)' => array('stateEnum'=>'', 'typeEnum'=>'', 'url'=>'', 'tsID'=>'', 'user'=>'', 'password'=>''),
  100. * ...
  101. * )
  102. * @var array
  103. */
  104. private static $CERTIFICATE;
  105. private static $DEFAULT_LANG;
  106. private static $CAT_ID;
  107. private static $ENV_API;
  108. /**
  109. * save shop url
  110. * @var string
  111. */
  112. private $site_url;
  113. /**
  114. * Payment type used by Trusted Shops.
  115. * @var array
  116. */
  117. private static $payments_type;
  118. public function __construct()
  119. {
  120. // need to set this in constructor to allow translation
  121. TSBuyerProtection::$payments_type = array(
  122. 'DIRECT_DEBIT' => $this->l('Direct debit'),
  123. 'CREDIT_CARD' => $this->l('Credit Card'),
  124. 'INVOICE' => $this->l('Invoice'),
  125. 'CASH_ON_DELIVERY' => $this->l('Cash on delivery'),
  126. 'PREPAYMENT' => $this->l('Prepayment'),
  127. 'CHEQUE' => $this->l('Cheque'),
  128. 'PAYBOX' => $this->l('Paybox'),
  129. 'PAYPAL' => $this->l('PayPal'),
  130. 'CASH_ON_PICKUP' => $this->l('Cash on pickup'),
  131. 'FINANCING' => $this->l('Financing'),
  132. 'LEASING' => $this->l('Leasing'),
  133. 'T_PAY' => $this->l('T-Pay'),
  134. 'CLICKANDBUY' => $this->l('Click&Buy'),
  135. 'GIROPAY' => $this->l('Giropay'),
  136. 'GOOGLE_CHECKOUT' => $this->l('Google Checkout'),
  137. 'SHOP_CARD' => $this->l('Online shop payment card'),
  138. 'DIRECT_E_BANKING' => $this->l('DIRECTebanking.com'),
  139. 'MONEYBOOKERS' => $this->l('moneybookers.com'),
  140. 'OTHER' => $this->l('Other method of payment'),
  141. );
  142. $this->tab_name = $this->l('Seal of Approval and Buyer Protection');
  143. $this->site_url = Tools::htmlentitiesutf8('http://'.$_SERVER['HTTP_HOST'].__PS_BASE_URI__);
  144. TSBPException::setTranslationObject($this);
  145. if (!method_exists('Tools', 'jsonDecode') || !method_exists('Tools', 'jsonEncode'))
  146. {
  147. $this->warnings[] = $this->l('Json functions must be implemented in your php version');
  148. }
  149. else
  150. {
  151. foreach ($this->available_languages as $iso => $lang)
  152. {
  153. if($lang === '')
  154. $this->available_languages[$iso] = Language::getLanguage(Language::getIdByIso($iso));
  155. TSBuyerProtection::$CERTIFICATE[strtoupper($iso)] = (array)Tools::jsonDecode(
  156. Tools::htmlentitiesDecodeUTF8(Configuration::get(TSBuyerProtection::PREFIX_TABLE.'CERTIFICATE_'.strtoupper($iso))));
  157. }
  158. if(TSBuyerProtection::$SHOPSW === NULL)
  159. {
  160. TSBuyerProtection::$SHOPSW = Configuration::get(TSBuyerProtection::PREFIX_TABLE.'SHOPSW');
  161. TSBuyerProtection::$ET_CID = Configuration::get(TSBuyerProtection::PREFIX_TABLE.'ET_CID');
  162. TSBuyerProtection::$ET_LID = Configuration::get(TSBuyerProtection::PREFIX_TABLE.'ET_LID');
  163. TSBuyerProtection::$DEFAULT_LANG = (int)Configuration::get('PS_LANG_DEFAULT');
  164. TSBuyerProtection::$CAT_ID = (int)Configuration::get(TSBuyerProtection::PREFIX_TABLE.'CAT_ID');
  165. TSBuyerProtection::$ENV_API = Configuration::get(TSBuyerProtection::PREFIX_TABLE.'ENV_API');
  166. }
  167. }
  168. }
  169. public function install()
  170. {
  171. if (!method_exists('Tools', 'jsonDecode') || !method_exists('Tools', 'jsonEncode'))
  172. return false;
  173. foreach ($this->available_languages as $iso=>$lang)
  174. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'CERTIFICATE_'.strtoupper($iso),
  175. Tools::htmlentitiesUTF8(Tools::jsonEncode(array('stateEnum'=>'', 'typeEnum'=>'', 'url'=>'', 'tsID'=>'', 'user'=>'', 'password'=>''))));
  176. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'SHOPSW', '');
  177. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ET_CID', '');
  178. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ET_LID', '');
  179. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ENV_API', TSBuyerProtection::ENV_PROD);
  180. $req = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'` (
  181. `id_item` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  182. `id_product` INT NOT NULL,
  183. `ts_id` VARCHAR( 33 ) NOT NULL,
  184. `id` INT NOT NULL,
  185. `currency` VARCHAR( 3 ) NOT NULL ,
  186. `gross_fee` DECIMAL( 20, 6 ) NOT NULL ,
  187. `net_fee` DECIMAL( 20, 6 ) NOT NULL ,
  188. `protected_amount_decimal` INT NOT NULL ,
  189. `protection_duration_int` INT NOT NULL ,
  190. `ts_product_id` TEXT NOT NULL ,
  191. `creation_date` VARCHAR( 25 ) NOT NULL
  192. );
  193. ';
  194. Db::getInstance()->Execute($req);
  195. $req = 'CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.TSBuyerProtection::DB_APPLI.'` (
  196. `id_application` INT NOT NULL PRIMARY KEY,
  197. `ts_id` VARCHAR( 33 ) NOT NULL,
  198. `id_order` INT NOT NULL,
  199. `statut_number` INT NOT NULL DEFAULT \'0\',
  200. `creation_date` DATETIME NOT NULL,
  201. `last_update` DATETIME NOT NULL
  202. );
  203. ';
  204. Db::getInstance()->Execute($req);
  205. //add hidden category
  206. $category = new Category();
  207. $languages = Language::getLanguages(true);
  208. foreach ($this->available_languages as $iso=>$lang)
  209. {
  210. $category->name[Language::getIdByIso(strtolower($iso))] = 'Trustedshops';
  211. $category->link_rewrite[Language::getIdByIso(strtolower($iso))] = 'trustedshops';
  212. }
  213. // If the default lang is different than available languages :
  214. // (Bug occurred otherwise)
  215. if (!array_key_exists(Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT')), $this->available_languages))
  216. {
  217. $category->name[(int)Configuration::get('PS_LANG_DEFAULT')] = 'Trustedshops';
  218. $category->link_rewrite[(int)Configuration::get('PS_LANG_DEFAULT')] = 'trustedshops';
  219. }
  220. $category->id_parent = 0;
  221. $category->level_depth = 0;
  222. $category->active = 0;
  223. $category->add();
  224. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'CAT_ID', intval($category->id));
  225. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'SECURE_KEY', strtoupper(Tools::passwdGen(16)));
  226. return true;
  227. }
  228. public function uninstall()
  229. {
  230. foreach ($this->available_languages as $iso=>$lang)
  231. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'CERTIFICATE_'.strtoupper($iso));
  232. $category = new Category((int)TSBuyerProtection::$CAT_ID);
  233. $category->delete();
  234. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'CAT_ID');
  235. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'SHOPSW');
  236. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'ET_CID');
  237. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'ET_LID');
  238. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'ENV_API');
  239. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'SECURE_KEY');
  240. return true;
  241. }
  242. /**
  243. * Just for return the file path
  244. * @return string
  245. */
  246. public function getCronFilePath()
  247. {
  248. return $this->site_url.'modules/'.self::$module_name.'/cron_garantee.php?secure_key='.Configuration::get(TSBuyerProtection::PREFIX_TABLE.'SECURE_KEY');
  249. }
  250. /**
  251. * This method is used to access of TrustedShops API
  252. * from a SoapClient object.
  253. *
  254. * @uses TSBuyerProtection::$webservice_urls with TSBuyerProtection::$ENV_API
  255. * To get the api url according to the environment (test or production)
  256. * @param string $type
  257. * @return SoapClient
  258. */
  259. private function _getClient($type = TSBuyerProtection::WEBSERVICE_BO)
  260. {
  261. $url = TSBuyerProtection::$webservice_urls[$type][TSBuyerProtection::$ENV_API];
  262. $client = new SoapClient($url);
  263. return $client;
  264. }
  265. /**
  266. * Checks the Trusted Shops IDs entered in the shop administration
  267. * and returns the characteristics of the corresponding certificate.
  268. *
  269. * @uses TSBuyerProtection::_getClient()
  270. * @param string $certificate certificate code already send by Trusted Shops
  271. */
  272. private function _checkCertificate($certificate)
  273. {
  274. $array_state = array(
  275. 'PRODUCTION' => $this->l('The certificate is valid'),
  276. 'CANCELLED' => $this->l('The certificate has expired'),
  277. 'DISABLED' => $this->l('The certificate has been disabled'),
  278. 'INTEGRATION' => $this->l('The shop is currently being certified'),
  279. 'INVALID_TS_ID' => $this->l('No certificate has been allocated to the Trusted Shops ID'),
  280. 'TEST' => $this->l('Test certificate'),
  281. );
  282. $client = $this->_getClient();
  283. $validation = false;
  284. try {
  285. $validation = $client->checkCertificate($certificate);
  286. } catch (SoapFault $fault) {
  287. $this->errors[] = $this->l('Code #').$fault->faultcode.',<br />'.$this->l('message:').$fault->faultstring;
  288. }
  289. if(is_int($validation))
  290. throw new TSBPException($validation, TSBPException::ADMINISTRATION);
  291. if (!$validation OR array_key_exists($validation->stateEnum, $array_state))
  292. {
  293. if ($validation->stateEnum === 'TEST' || $validation->stateEnum === 'PRODUCTION' || $validation->stateEnum === 'INTEGRATION')
  294. {
  295. $this->confirmations[] = $array_state[$validation->stateEnum];
  296. return $validation;
  297. }
  298. else
  299. {
  300. $this->errors[] = $array_state[$validation->stateEnum];
  301. return false;
  302. }
  303. }
  304. else
  305. {
  306. $this->errors[] = $this->l('Unknown error.');
  307. }
  308. }
  309. /**
  310. * Checks the shop's web service access credentials.
  311. *
  312. * @uses TSBuyerProtection::_getClient()
  313. * @param string $ts_id
  314. * @param string $user
  315. * @param string $password
  316. */
  317. private function _checkLogin($ts_id, $user, $password)
  318. {
  319. $client = $this->_getClient();
  320. $return = 0;
  321. try {
  322. $return = $client->checkLogin($ts_id, $user, $password);
  323. } catch (SoapClient $fault) {
  324. $this->errors[] = $this->l('Code #').$fault->faultcode.',<br />'.$this->l('message:').$fault->faultstring;
  325. }
  326. if ($return < 0)
  327. throw new TSBPException($return, TSBPException::ADMINISTRATION);
  328. return true;
  329. }
  330. /**
  331. * Returns the characteristics of the buyer protection products
  332. * that are allocated individually to each certificate by Trusted Shops.
  333. *
  334. * @uses TSBuyerProtection::_getClient()
  335. * @param string $ts_id
  336. */
  337. private function _getProtectionItems($ts_id)
  338. {
  339. $client = $this->_getClient();
  340. try {
  341. $items = $client->getProtectionItems($ts_id);
  342. } catch (SoapFault $fault) {
  343. $this->errors[] = $this->l('Code #').$fault->faultcode.',<br />'.$this->l('message:').$fault->faultstring;
  344. }
  345. if (isset($items->item))
  346. return $items->item;
  347. return false;
  348. }
  349. /**
  350. * Check validity for params required for TSBuyerProtection::_requestForProtectionV2()
  351. *
  352. * @param array $params
  353. */
  354. private function _requestForProtectionV2ParamsValidator($params)
  355. {
  356. $bool_flag = true;
  357. $mandatory_keys = array(
  358. array('name'=>'tsID', 'validator'=>array('isCleanHtml'),),
  359. array('name'=>'tsProductID', 'validator'=>array('isCleanHtml'),),
  360. array('name'=>'amount', 'validator'=>array('isFloat'),),
  361. array('name'=>'currency', 'length'=>3, 'validator'=>array('isString'),),
  362. array('name'=>'paymentType', 'validator'=>array('isString'),),
  363. array('name'=>'buyerEmail', 'validator'=>array('isEmail'),),
  364. array('name'=>'shopCustomerID', 'validator'=>array('isInt'),),
  365. array('name'=>'shopOrderID', 'validator'=>array('isInt'),),
  366. array('name'=>'orderDate', 'ereg'=>'#[0-9]{4}\-[0-9]{2}\-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}#',),
  367. array('name'=>'shopSystemVersion','validator'=>array('isCleanHtml'),),
  368. array('name'=>'wsUser','validator'=>array('isCleanHtml'),),
  369. array('name'=>'wsPassword', 'validator'=>array('isCleanHtml'),),
  370. );
  371. foreach ($mandatory_keys as $key)
  372. {
  373. $bool_flag = (!array_key_exists($key['name'], $params)) ? false : $bool_flag;
  374. if ($bool_flag)
  375. {
  376. if (isset($key['length']))
  377. $bool_flag = strlen((string)$params[$key['name']]) === $key['length'];
  378. if (isset($key['length-min']))
  379. $bool_flag = strlen((string)$params[$key['name']]) > $key['length-min'];
  380. if (isset($key['length-max']))
  381. $bool_flag = strlen((string)$params[$key['name']]) < $key['length-max'];
  382. if (isset($key['validator']))
  383. foreach ($key['validator'] as $validator)
  384. if (method_exists('Validate', $validator))
  385. $bool_flag = !Validate::$validator((string)$params[$key['name']]) ? false : $bool_flag;
  386. if(isset($key['ereg']))
  387. $bool_flag = !preg_match($key['ereg'], $params[$key['name']]) ? false : $bool_flag ;
  388. }
  389. if (!$bool_flag)
  390. {
  391. $this->errors[] = sprintf($this->l('The field %s is wrong, please ensure it was correctly filled.'), $key['name']);
  392. break;
  393. }
  394. }
  395. return $bool_flag;
  396. }
  397. /**
  398. * Create the Buyer Protection application by the web service.
  399. * Applications are saved by Trusted Shops and are processed at regular intervals.
  400. *
  401. * @uses TSBuyerProtection::_getClient()
  402. * @uses TSBuyerProtection::_requestForProtectionV2ParamsValidator()
  403. * to check required params
  404. * @see TSBuyerProtection::cronTasks()
  405. * @param array $params
  406. */
  407. private function _requestForProtectionV2($params)
  408. {
  409. $client = $this->_getClient(TSBuyerProtection::WEBSERVICE_FO);
  410. $testing_params = $this->_requestForProtectionV2ParamsValidator($params);
  411. $code = 0;
  412. $sql = '
  413. SELECT *
  414. FROM `'._DB_PREFIX_.TSBuyerProtection::DB_APPLI.'`
  415. WHERE `id_order` = "'.(int)$params['shopOrderID'].'"
  416. ';
  417. $order = Db::getInstance()->ExecuteS($sql);
  418. // If an order was already added, no need to continue.
  419. // Otherwise a new application is created by TrustedShops.
  420. // this can occurred when order confirmation page is reload.
  421. if(isset($order[0]))
  422. return false;
  423. if ($testing_params)
  424. {
  425. try {
  426. $code = $client->requestForProtectionV2($params['tsID'], $params['tsProductID'], $params['amount'], $params['currency'], $params['paymentType'], $params['buyerEmail'], $params['shopCustomerID'], $params['shopOrderID'], $params['orderDate'], $params['shopSystemVersion'], $params['wsUser'], $params['wsPassword']);
  427. if ($code < 0)
  428. throw new TSBPException($code, TSBPException::FRONT_END);
  429. } catch (SoapFault $fault) {
  430. $this->errors[] = $this->l('Code #').$fault->faultcode.',<br />'.$this->l('message:').$fault->faultstring;
  431. } catch (TSBPException $e) {
  432. $this->errors[] = $e->getMessage();
  433. }
  434. if ($code > 0)
  435. {
  436. $date = date('Y-m-d H:i:s');
  437. $sql = '
  438. INSERT INTO `'._DB_PREFIX_.TSBuyerProtection::DB_APPLI.'`
  439. (
  440. `id_application`,
  441. `ts_id`,
  442. `id_order`,
  443. `creation_date`,
  444. `last_update`
  445. )
  446. VALUES
  447. (
  448. "'.pSQL($code).'",
  449. "'.pSQL($params['tsID']).'",
  450. "'.pSQL($params['shopOrderID']).'",
  451. "'.$date.'",
  452. "'.$date.'"
  453. )
  454. ';
  455. Db::getInstance()->Execute($sql);
  456. // To reset product quantity in database.
  457. $sql = '
  458. SELECT `id_product`
  459. FROM `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'`
  460. WHERE `ts_product_id` = "'.(int)$params['tsProductID'].'"
  461. ';
  462. $ts_product = Db::getInstance()->ExecuteS($sql);
  463. $product = new Product($ts_product[0]['id_product']);
  464. $product->quantity = 1000;
  465. $product->update();
  466. }
  467. }
  468. else
  469. $this->errors[] = $this->l('Some parameters sending to "requestForProtectionV2" method are wrong or missing.');
  470. }
  471. /**
  472. * With the getRequestState() method,
  473. * the status of a guarantee application is requested
  474. * and in the event of a successful transaction,
  475. * the guarantee number is returned.
  476. *
  477. * @uses TSBuyerProtection::_getClient()
  478. * @param array $params
  479. * @throws TSBPException
  480. */
  481. private function _getRequestState($params)
  482. {
  483. $client = $this->_getClient(TSBuyerProtection::WEBSERVICE_FO);
  484. $code = 0;
  485. try {
  486. $code = $client->getRequestState($params['tsID'], $params['applicationID']);
  487. if ($code < 0)
  488. throw new TSBPException($code, TSBPException::FRONT_END);
  489. } catch (SoapFault $fault) {
  490. $this->errors[] = $this->l('Code #').$fault->faultcode.',<br />'.$this->l('message:').$fault->faultstring;
  491. } catch (TSBPException $e) {
  492. $this->errors[] = $e->getMessage();
  493. }
  494. return $code;
  495. }
  496. /**
  497. * Check statut of last applications
  498. * saved with TSBuyerProtection::_requestForProtectionV2()
  499. *
  500. * Negative value means an error occurred.
  501. * Error code are managed in TSBPException.
  502. * @see (exception) TSBPException::_getFrontEndMessage() method
  503. *
  504. * Trusted Shops recommends that the request
  505. * should be automated by a cronjob with an interval of 10 minutes.
  506. * @see /../cron_garantee.php
  507. *
  508. * A message is added to the sheet order in Back-office,
  509. * @see Message class
  510. *
  511. * @uses TSBuyerProtection::_getRequestState()
  512. * @uses Message class
  513. * @return void
  514. */
  515. public function cronTask()
  516. {
  517. // get the last 20min to get the api number (to be sure)
  518. $mktime = mktime(date('H'), date('i')-20, date('s'), date('m'), date('d'), date('Y'));
  519. $date = date('Y-m-d H:i:s', $mktime);
  520. $db_name = _DB_PREFIX_.TSBuyerProtection::DB_APPLI;
  521. $sql = '
  522. SELECT *
  523. FROM `'.$db_name.'`
  524. WHERE `last_update` >= "'.$date.'" OR `statut_number` <= 0
  525. ';
  526. $to_check = Db::getInstance()->ExecuteS($sql);
  527. foreach ($to_check as $application)
  528. {
  529. $code = $this->_getRequestState(array('tsID'=>$application['ts_id'], 'applicationID'=>$application['id_application']));
  530. if (!empty($this->errors))
  531. {
  532. $return_message = '<p style="color:red;">'.$this->l('Trusted Shops API returns an error concerning the application #').$application['id_application'].': <br />'.implode(', <br />', $this->errors).'</p>';
  533. $this->errors = array();
  534. }
  535. elseif ($code > 0)
  536. {
  537. $return_message = sprintf($this->l('Trusted Shops application number %1$d was successfully processed. The guarantee number is: %2$d'), $application['id_application'], $code);
  538. }
  539. $sql = '
  540. UPDATE `'.$db_name.'`
  541. SET `statut_number` = "'.$code.'"
  542. WHERE `id_application` >= "'.$application['id_application'].'"
  543. ';
  544. Db::getInstance()->Execute($sql);
  545. $msg = new Message();
  546. $msg->message = $return_message;
  547. $msg->id_order = (int)$application['id_order'];
  548. $msg->private = 1;
  549. $msg->add();
  550. }
  551. }
  552. /**
  553. * Registration link to Trusted Shops
  554. *
  555. * @param string $shopsw
  556. * @param string $et_cid
  557. * @param string $et_lid
  558. * @param string $lang
  559. * @return boolean|string boolean in case of $lang is not supported by Trusted Shops
  560. * string return is the url to access of form subscription
  561. */
  562. private function _makeRegistrationLink($shopsw, $et_cid, $et_lid, $lang)
  563. {
  564. if(array_key_exists($lang, $this->registration_link))
  565. return $this->registration_link[$lang].sprintf('?shopsw=%s&et_cid=%s&et_lid=%s', urlencode($shopsw), urlencode($et_cid), urlencode($et_lid));
  566. return false;
  567. }
  568. /**
  569. * Method to display or redirect the subscription link.
  570. *
  571. * @param string $link
  572. */
  573. private function _getRegistrationLink($link)
  574. {
  575. return '<script type="text/javascript" >$().ready(function(){window.open("'.$link.'");});</script>
  576. <noscript><p><a href="'.$link.'" target="_blank" title="'.$this->l('Registration Link').'" class="link">'.$this->l('Click to get the Registration Link').'</a><p></noscript>';
  577. }
  578. /**
  579. * saved paramter to acces of particular subscribtion link.
  580. *
  581. * @return string the registration link.
  582. */
  583. private function _submitRegistrationLink()
  584. {
  585. // @todo : ask for more infos about values types
  586. TSBuyerProtection::$SHOPSW = (Validate::isCleanHtml(Tools::getValue('shopsw'))) ? Tools::getValue('shopsw') : '';
  587. TSBuyerProtection::$ET_CID = (Validate::isCleanHtml(Tools::getValue('et_cid'))) ? Tools::getValue('et_cid') : '';
  588. TSBuyerProtection::$ET_LID = (Validate::isCleanHtml(Tools::getValue('et_lid'))) ? Tools::getValue('et_lid') : '';
  589. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'SHOPSW', TSBuyerProtection::$SHOPSW);
  590. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ET_CID', TSBuyerProtection::$ET_CID);
  591. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ET_LID', TSBuyerProtection::$ET_LID);
  592. $link_registration = $this->_makeRegistrationLink(TSBuyerProtection::$SHOPSW, TSBuyerProtection::$ET_CID, TSBuyerProtection::$ET_LID, Tools::getValue('lang'));
  593. $this->confirmations[] = $this->l('Registration link has been created. Follow this link if you were not redirected earlier:').'&nbsp;<a href="'.$link_registration.'" class="link">&gt;'.$this->l('Link').'&lt;</a>';
  594. return $link_registration;
  595. }
  596. /**
  597. * Save in special database each buyer protection product for a certificate,
  598. * Each Trusted Shops particular characteristics is saved.
  599. * Create a product in Prestashop database to allow added each of them in cart.
  600. *
  601. * @param array|stdClass $protection_items
  602. * @param string $ts_id
  603. */
  604. private function _saveProtectionItems($protection_items, $ts_id)
  605. {
  606. $sql = '
  607. DELETE ts, p, pl
  608. FROM `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'` AS ts
  609. LEFT JOIN `ps_product` AS p ON ts.`id_product` = p.`id_product`
  610. LEFT JOIN `ps_product_lang` AS pl ON ts.`id_product` = pl.`id_product`
  611. WHERE ts.`ts_id`="'.$ts_id.'"';
  612. Db::getInstance()->Execute($sql);
  613. foreach ($protection_items as $key=>$item)
  614. {
  615. //add hidden product
  616. $product = new Product();
  617. foreach ($this->available_languages as $iso=>$lang)
  618. {
  619. $language = Language::getIdByIso(strtolower($iso));
  620. if ((int)$language !== 0)
  621. {
  622. $product->name[$language] = 'TrustedShops guarantee';
  623. $product->link_rewrite[$language] = 'trustedshops_guarantee';
  624. }
  625. }
  626. // If the default lang is different than available languages :
  627. // (Bug occurred otherwise)
  628. if (!array_key_exists(Language::getIsoById((int)Configuration::get('PS_LANG_DEFAULT')), $this->available_languages))
  629. {
  630. $product->name[(int)Configuration::get('PS_LANG_DEFAULT')] = 'Trustedshops';
  631. $product->link_rewrite[(int)Configuration::get('PS_LANG_DEFAULT')] = 'trustedshops';
  632. }
  633. $product->quantity = 1000;
  634. $product->price = ToolsCore::convertPrice($item->grossFee,Currency::getIdByIsoCode($item->currency));
  635. $product->id_category_default = TSBuyerProtection::$CAT_ID;
  636. $product->active = true;
  637. $product->id_tax = 0;
  638. $product->add();
  639. if ($product->id)
  640. {
  641. $sql = '
  642. INSERT INTO `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'` (
  643. `creation_date`,
  644. `id_product`,
  645. `ts_id`,
  646. `id`,
  647. `currency`,
  648. `gross_fee`,
  649. `net_fee`,
  650. `protected_amount_decimal`,
  651. `protection_duration_int`,
  652. `ts_product_id`
  653. ) VALUES (
  654. "'.pSQL($item->creationDate).'",
  655. "'.pSQL($product->id).'",
  656. "'.pSQL($ts_id).'",
  657. "'.(int)$item->id.'",
  658. "'.pSQL($item->currency).'",
  659. "'.pSQL($item->grossFee).'",
  660. "'.pSQL($item->netFee).'",
  661. "'.pSQL($item->protectedAmountDecimal).'",
  662. "'.pSQL($item->protectionDurationInt).'",
  663. "'.pSQL($item->tsProductID).'"
  664. )';
  665. Db::getInstance()->Execute($sql);
  666. }
  667. else {
  668. $this->errors['products'] = $this->l('Product wasn\'t saved.');
  669. }
  670. }
  671. }
  672. /**
  673. * Check and add a Trusted Shops certificate in shop.
  674. *
  675. * @uses TSBuyerProtection::_getProtectionItems()
  676. * to get all buyer protection products from Trusted Shops
  677. * @uses TSBuyerProtection::_saveProtectionItems()
  678. * to save buyer protection products in shop
  679. * @return boolean true if certificate is added successfully, false otherwise
  680. */
  681. private function _submitAddCertificate()
  682. {
  683. $checked_certificate = false;
  684. try {
  685. $checked_certificate = $this->_checkCertificate(ToolsCore::getValue('new_certificate'));
  686. } catch (TSBPException $e) {
  687. $this->errors[] = $e->getMessage();
  688. }
  689. if ($checked_certificate)
  690. {
  691. TSBuyerProtection::$CERTIFICATE[strtoupper($checked_certificate->certificationLanguage)] = array('stateEnum'=>$checked_certificate->stateEnum, 'typeEnum'=>$checked_certificate->typeEnum, 'url'=>$checked_certificate->url, 'tsID'=>$checked_certificate->tsID, 'user'=>'', 'password'=>'');
  692. // update the configuration var
  693. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'CERTIFICATE_'.strtoupper($checked_certificate->certificationLanguage), Tools::htmlentitiesUTF8(Tools::jsonEncode(TSBuyerProtection::$CERTIFICATE[strtoupper($checked_certificate->certificationLanguage)])));
  694. $this->confirmations[] = $this->l('Certificate has been added successfully.');
  695. if ($checked_certificate->typeEnum === 'EXCELLENCE')
  696. {
  697. try {
  698. $protection_items = $this->_getProtectionItems($checked_certificate->tsID);
  699. if($protection_items)
  700. $this->_saveProtectionItems($protection_items, $checked_certificate->tsID);
  701. } catch (TSBPException $e) {
  702. $this->errors[] = $e->getMessage();
  703. }
  704. }
  705. return true;
  706. }
  707. return false;
  708. }
  709. /**
  710. * Apply delete or edit action to a certificate
  711. *
  712. * @return boolean|array
  713. * - false if action concerned multiple certificate
  714. * (in normal way, this never occurred )
  715. * - return required $certificate to edit.
  716. * - true in other case.
  717. */
  718. private function _submitEditCertificate()
  719. {
  720. $edit = Tools::getValue('certificate_edit');
  721. $delete = Tools::getValue('certificate_delete');
  722. if ((is_array($edit) AND count($edit) > 1) OR (is_array($delete) AND count($delete) > 1))
  723. {
  724. $this->errors[] = $this->l('You must edit or delete a Certificate one at a time');
  725. return false;
  726. }
  727. // delete action :
  728. if (is_array($delete) AND isset(TSBuyerProtection::$CERTIFICATE[$delete[0]]['tsID']))
  729. {
  730. $certificate_to_delete = TSBuyerProtection::$CERTIFICATE[$delete[0]]['tsID'];
  731. Configuration::deleteByName(TSBuyerProtection::PREFIX_TABLE.'CERTIFICATE_'.strtoupper($delete[0]));
  732. unset(TSBuyerProtection::$CERTIFICATE[$delete[0]]);
  733. $this->confirmations[] = $this->l('The certificate')
  734. .' "'.$certificate_to_delete.'" ('.$this->l('language').' : '.$delete[0].') '
  735. .$this->l('has been deleted successfully');
  736. }
  737. // edit action :
  738. if (is_array($edit))
  739. {
  740. $return = TSBuyerProtection::$CERTIFICATE[$edit[0]];
  741. $return['language'] = $edit[0];
  742. return $return;
  743. }
  744. return true;
  745. }
  746. /**
  747. * Change the certificate values.
  748. * concerns only excellence certificate
  749. * for payment type, login and password values.
  750. *
  751. * @uses TSBuyerProtection::_checkLogin()
  752. * @return true;
  753. */
  754. private function _submitChangeCertificate()
  755. {
  756. $iso_lang = Tools::getValue('iso_lang');
  757. $user = Tools::getValue('user');
  758. $password = Tools::getValue('password');
  759. $all_payment_type = Tools::getValue('choosen_payment_type');
  760. if($user != '' AND $password != '')
  761. {
  762. TSBuyerProtection::$CERTIFICATE[$iso_lang]['payment_type'] = array();
  763. if ($all_payment_type)
  764. {
  765. if (is_array($all_payment_type))
  766. foreach ($all_payment_type as $key=>$module_id)
  767. TSBuyerProtection::$CERTIFICATE[$iso_lang]['payment_type'][(string)$key] = $module_id;
  768. }
  769. $check_login = false;
  770. try {
  771. $check_login = $this->_checkLogin(TSBuyerProtection::$CERTIFICATE[$iso_lang]['tsID'], $user, $password);
  772. } catch (TSBPException $e) {
  773. $this->errors[] = $e->getMessage();
  774. }
  775. if($check_login)
  776. {
  777. TSBuyerProtection::$CERTIFICATE[$iso_lang]['user'] = $user;
  778. TSBuyerProtection::$CERTIFICATE[$iso_lang]['password'] = $password;
  779. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'CERTIFICATE_'.$iso_lang, Tools::htmlentitiesUTF8(Tools::jsonEncode(TSBuyerProtection::$CERTIFICATE[$iso_lang])));
  780. $this->confirmations[] = $this->l('Certificate login has been successful.');
  781. }
  782. }
  783. else
  784. {
  785. $this->errors[] = $this->l('You have to set a username and a password before any change.');
  786. }
  787. return true;
  788. }
  789. /**
  790. * Change the environment for working.
  791. * Not use anymore but keeped
  792. * @return true
  793. */
  794. private function _submitEnvironment()
  795. {
  796. TSBuyerProtection::$ENV_API = Tools::getValue('env_api');
  797. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ENV_API', TSBuyerProtection::$ENV_API);
  798. return true;
  799. }
  800. /*
  801. ** Update the env_api
  802. */
  803. public function _setEnvApi($env_api)
  804. {
  805. if (Configuration::get(TSBuyerProtection::PREFIX_TABLE.'ENV_API') != $env_api)
  806. Configuration::updateValue(TSBuyerProtection::PREFIX_TABLE.'ENV_API', $env_api);
  807. TSBuyerProtection::$ENV_API = $env_api;
  808. }
  809. /**
  810. * Dispatch post process depends on each formular
  811. *
  812. * @return array depend on the needs about each formular.
  813. */
  814. private function _preProcess()
  815. {
  816. $posts_return = array();
  817. /*if (Tools::isSubmit('submit_registration_link'))
  818. $posts_return['registration_link'] = $this->_submitRegistrationLink();*/
  819. if (Tools::isSubmit('submit_add_certificate'))
  820. $posts_return['add_certificate'] = $this->_submitAddCertificate();
  821. if (Tools::isSubmit('submit_edit_certificate'))
  822. $posts_return['edit_certificate'] = $this->_submitEditCertificate();
  823. if (Tools::isSubmit('submit_change_certificate'))
  824. $posts_return['change_certificate'] = $this->_submitChangeCertificate();
  825. return $posts_return;
  826. }
  827. /**
  828. * Display each formaular in back-office
  829. *
  830. * @see Module::getContent()
  831. * @return string for displaying form.
  832. */
  833. public function getContent()
  834. {
  835. $out = '';
  836. $posts_return = $this->_preProcess();
  837. if(empty($this->errors))
  838. {
  839. $out .= '';
  840. }
  841. $out .= $this->_displayPresentation();
  842. $out .= '<br />';
  843. //$out .= $this->_displayFormRegistrationLink(( isset($posts_return['registration_link']) ? $posts_return['registration_link'] : false ));
  844. $out .= '<br />';
  845. $out .= $this->_displayFormAddCertificate();
  846. $out .= '<br />';
  847. $bool_display_certificats = false;
  848. if (is_array(self::$CERTIFICATE))
  849. foreach (self::$CERTIFICATE as $certif)
  850. $bool_display_certificats = (isset($certif['tsID']) && $certif['tsID'] != '')? true : $bool_display_certificats;
  851. if ($bool_display_certificats)
  852. $out .= $this->_displayFormCertificatesList();
  853. if (isset($posts_return['edit_certificate']) && $posts_return['edit_certificate'] &&
  854. is_array($posts_return['edit_certificate']))
  855. {
  856. $out .= '<br />';
  857. $out .= $this->_displayFormEditCertificate($posts_return['edit_certificate']);
  858. }
  859. $out .= '<br />';
  860. $out .= $this->_displayInfoCronTask();
  861. return $out;
  862. }
  863. private function _displayPresentation()
  864. {
  865. return '
  866. <div style="text-align:right; margin:10px 20px 10px 0">
  867. <img src="'.__PS_BASE_URI__.'modules/'.self::$module_name.'/img/siegel.gif" alt="logo"/>
  868. </diV>
  869. <h3>'.$this->l('Seal of Approval and Buyer Protection').'</h3>
  870. <p>'.$this->l('Trusted Shops is the well-known internet Seal of Approval for online shops which also offers customers a Buyer Protection. During the audit, your online shop is subjected to extensive and thorough tests. This audit, consisting of over 100 individual criteria, is based on the requirements of consumer protection, national and European laws.').'</p>
  871. <h3>'.$this->l('More trust leads to more sales!').'</h3>
  872. <p>'.$this->l('The Trusted Shops seal of approval is the optimal way to increase the trust of your online customers. Trust increases customers\' willingness to buy from you.').'</p>
  873. <h3>'.$this->l('Less abandoned purchases').'</h3>
  874. <p>'.$this->l('Give your online customers a strong reason to buy with the Trusted Shops Buyer Protection. This additional security leads to less shopping basket abandonment').'</p>
  875. <h3>'.$this->l('Profitable and long-term customer relationship').'</h3>
  876. <p>'.$this->l('For many online shoppers, the Trusted Shops Seal of Approval with Buyer Protection is an effective sign of quality for safe shopping on the internet. One-time buyers become regular customers.').'</p><br />
  877. <h3>'.$this->l('Environment type').'</h3>
  878. <p>'.$this->l('You are currently using the mode :').' <b>'.TSBuyerProtection::$ENV_API.'</b></p><br />';
  879. }
  880. private function _displayFormRegistrationLink($link = false)
  881. {
  882. $out = '
  883. <form action="'.$this->_makeFormAction($_SERVER['REQUEST_URI'], $this->id_tab).'" method="post" >
  884. <fieldset>
  885. <legend><img src="../img/admin/cog.gif" alt="" />'.$this->l('Get the Registration Link').'</legend>
  886. <p>'.$this->l('This variable was sent to you via e-mail by TrustedShops').'</p>
  887. <label>'.$this->l('Internal identification of shop software at Trusted Shops').'</label>
  888. <div class="margin-form">
  889. <input type="text" name="shopsw" value="'.TSBuyerProtection::$SHOPSW.'"/>
  890. </div>
  891. <br />
  892. <br class="clear" />
  893. <label>'.$this->l('Etracker channel').'</label>
  894. <div class="margin-form">
  895. <input type="text" name="et_cid" value="'.TSBuyerProtection::$ET_CID.'"/>
  896. </div>
  897. <br class="clear" />
  898. <label>'.$this->l('Etracker campaign').'</label>
  899. <div class="margin-form">
  900. <input type="text" name="et_lid" value="'.TSBuyerProtection::$ET_LID.'"/>
  901. </div>
  902. <label>'.$this->l('Language').'</label>
  903. <div class="margin-form">
  904. <select name="lang" >';
  905. foreach ($this->available_languages as $iso=>$lang)
  906. if(is_array($lang))
  907. $out .= '<option value="'.$iso.'" '.((int)$lang['id_lang'] === TSBuyerProtection::$DEFAULT_LANG ? 'selected' : '' ).'>'.$lang['name'].'</option>';
  908. $out .= '</select>
  909. </div>
  910. <div style="text-align:center;">';
  911. // If Javascript is deactivated
  912. if ($link !== false)
  913. $out .= $this->_getRegistrationLink($link);
  914. $out .='<input type="submit" name="submit_registration_link" class="button" value="'.$this->l('send').'"/>
  915. </div>
  916. </fieldset>
  917. </form>';
  918. return $out;
  919. }
  920. private function _displayFormAddCertificate()
  921. {
  922. $out = '
  923. <form action="'.$this->_makeFormAction($_SERVER['REQUEST_URI'], $this->id_tab).'" method="post" >
  924. <fieldset>
  925. <legend><img src="../img/admin/cog.gif" alt="" />'.$this->l('Add Trusted Shops certificate').'</legend>
  926. <label>'.$this->l('New certificate').'</label>
  927. <div class="margin-form">
  928. <input type="text" name="new_certificate" value="" style="width:300px;"/>&nbsp;
  929. <input type="submit" name="submit_add_certificate" class="button" value="'.$this->l('Add it').'"/>
  930. </div>
  931. </fieldset>
  932. </form>';
  933. return $out;
  934. }
  935. private function _displayFormCertificatesList()
  936. {
  937. $out = '';
  938. $out .= '
  939. <script type="text/javascript">
  940. $().ready(function()
  941. {
  942. $(\'#certificate_list\').find(\'input[type=checkbox]\').click(function()
  943. {
  944. $(\'#certificate_list\').find(\'input[type=checkbox]\').not($(this)).removeAttr(\'checked\');
  945. });
  946. });
  947. </script>
  948. <form action="'.$this->_makeFormAction($_SERVER['REQUEST_URI'], $this->id_tab).'" method="post" >
  949. <fieldset>
  950. <legend><img src="../img/admin/cog.gif" alt="" />'.$this->l('Manage Trusted Shops certificates').'</legend>
  951. <table width="100%">
  952. <thead>
  953. <tr style="text-align:center;">
  954. <th>'.$this->l('Certificate').'</th>
  955. <th>'.$this->l('Language').'</th>
  956. <th>'.$this->l('State').'</th>
  957. <th>'.$this->l('Type').'</th>
  958. <th>'.$this->l('Shop url').'</th>
  959. <th>'.$this->l('Edit').'</th>
  960. <th>'.$this->l('Delete').'</th>
  961. </tr>
  962. </thead>
  963. <tbody id="certificate_list">';
  964. foreach (TSBuyerProtection::$CERTIFICATE as $lang=>$certificate)
  965. {
  966. $certificate = (array)$certificate;
  967. if (isset($certificate['tsID']) AND $certificate['tsID'] !== '')
  968. {
  969. $out .= '
  970. <tr style="text-align:center;">
  971. <td>'.$certificate['tsID'].'</td>
  972. <td>'.$lang.'</td>
  973. <td>'.$certificate['stateEnum'].'</td>
  974. <td>'.$certificate['typeEnum'].'</td>
  975. <td>'.$certificate['url'].'</td>
  976. <td>';
  977. if ($certificate['typeEnum'] === 'EXCELLENCE') {
  978. $out .= '<input type="checkbox" name="certificate_edit[]" value="'.$lang.'" />';
  979. $out .= $certificate['user'] == '' ? '<br /><b style="color:red;font-size:0.7em;">'.$this->l('Login or password missing').'</b>' : '';
  980. } else {
  981. $out .= $this->l('No need');
  982. }
  983. $out .= '
  984. </td>
  985. <td>';
  986. if ($certificate['typeEnum'] === 'EXCELLENCE') {
  987. $out .= '<input type="checkbox" name="certificate_delete[]" value="'.$lang.'" />';
  988. } else {
  989. $out .= $this->l('No need');
  990. }
  991. $out .= '
  992. </td>
  993. </tr>';
  994. }
  995. }
  996. $out .='
  997. </tbody>
  998. </table>
  999. <div style="text-align:center;"><input type="submit" name="submit_edit_certificate" class="button" value="'.$this->l('Edit certificate').'"/></div>
  1000. </fieldset>
  1001. </form>
  1002. ';
  1003. return $out;
  1004. }
  1005. /**
  1006. * Check if a module is payment module.
  1007. *
  1008. * Method instanciate a $module by its name,
  1009. * Module::getInstanceByName() rather than Module::getInstanceById()
  1010. * is used for cache improvement and avoid an sql request.
  1011. *
  1012. * Method test if PaymentMethod::getCurrency() is a method from the module.
  1013. *
  1014. * @see Module::getInstanceByName() in classes/Module.php
  1015. * @param string $module name of the module
  1016. */
  1017. private static function _isPaymentModule($module)
  1018. {
  1019. $return = false;
  1020. $module = Module::getInstanceByName($module);
  1021. if (method_exists($module, 'getCurrency')){
  1022. $return = clone $module;
  1023. }
  1024. unset($module);
  1025. return $return;
  1026. }
  1027. private function _displayFormEditCertificate($certificate)
  1028. {
  1029. $installed_modules = Module::getModulesInstalled();
  1030. $payment_module_collection = '';
  1031. foreach ($installed_modules as $k=>$value)
  1032. if($return = TSBuyerProtection::_isPaymentModule($value['name']))
  1033. $payment_module_collection[$value['id_module']] = $value;
  1034. $out = '
  1035. <script type="text/javascript" src="'.$this->site_url.'modules/trustedshops/lib/js/payment.js" ></script>
  1036. <script type="text/javascript">
  1037. $().ready(function()
  1038. {
  1039. TSPayment.payment_type = $.parseJSON(\''.Tools::jsonEncode(TSBuyerProtection::$payments_type).'\');
  1040. TSPayment.payment_module = $.parseJSON(\''.Tools::jsonEncode($payment_module_collection).'\');
  1041. $(\'.payment-module-label\').css(TSPayment.module_box.css).fadeIn();
  1042. $(\'.choosen_payment_type\').each(function()
  1043. {
  1044. TSPayment.deleteModuleFromList($(this).val());
  1045. TSPayment.setLabelModuleName($(this).val());
  1046. });
  1047. TSPayment.init();
  1048. });
  1049. </script>
  1050. <form action="'.$this->_makeFormAction($_SERVER['REQUEST_URI'], $this->id_tab).'" method="post" >
  1051. <fieldset>
  1052. <legend><img src="../img/admin/tab-tools.gif" alt="" />'.$this->l('Edit certificate').'</legend>
  1053. <input type="hidden" name="iso_lang" value="'.$certificate['language'].'" />
  1054. <label>'.$this->l('Language').'</label>
  1055. <div class="margin-form">'.$certificate['language'].'</div>
  1056. <label>'.$this->l('Shop url').'</label>
  1057. <div class="margin-form">'.$certificate['url'].'</div>
  1058. <label>'.$this->l('Certificate id').'</label>
  1059. <div class="margin-form">'.$certificate['tsID'].'</div>
  1060. <label>'.$this->l('User Name').' <sup>*</sup></label>
  1061. <div class="margin-form"><input type="text" name="user" value="'.$certificate['user'].'" style="width:300px;"/></div>
  1062. <label>'.$this->l('Password').' <sup>*</sup></label>
  1063. <div class="margin-form"><input type="text" name="password" value="'.$certificate['password'].'" style="width:300px;"/></div>
  1064. <div id="payment-type">
  1065. <label>'.$this->l('Payment type to edit').' <sup>*</sup></label>
  1066. <div class="margin-form">
  1067. <select name="payment_type">';
  1068. foreach (TSBuyerProtection::$payments_type as $type=>$translation)
  1069. $out .= ' <option value="'.$type.'" >'.$translation.'</option>';
  1070. $out .= ' </select>&nbsp;'
  1071. .$this->l('with')
  1072. .'&nbsp;
  1073. <select name="payment_module">';
  1074. foreach ($payment_module_collection as $module_info)
  1075. $out .= ' <option value="'.$module_info['id_module'].'" >'.$module_info['name'].'</option>';
  1076. $out .= ' </select>&nbsp;'
  1077. .$this->l('payment module')
  1078. .'&nbsp;<input type="button" value="'.$this->l('Add it').'" class="button" name="add_payment_module" />
  1079. </div><!-- .margin-form -->
  1080. <div id="payment_type_list">';
  1081. $input_output = '';
  1082. if (isset($certificate['payment_type']) AND !empty($certificate['payment_type']))
  1083. {
  1084. foreach ($certificate['payment_type'] as $payment_type=>$modules)
  1085. {
  1086. $out .= ' <label style="clear:both;" class="payment-type-label" >'.TSBuyerProtection::$payments_type[$payment_type].'</label>';
  1087. $out .= ' <div class="margin-form" id="block-payment-'.$payment_type.'">';
  1088. foreach ($modules as $module_id)
  1089. {
  1090. $out .= '<b class="payment-module-label" id="label-module-'.$module_id.'"></b>';
  1091. $input_output .= '<input type="hidden" value="'.$module_id.'" class="choosen_payment_type" name="choosen_payment_type['.$payment_type.'][]">';
  1092. }
  1093. $out .= ' </div><!-- .margin-form -->';
  1094. }
  1095. }
  1096. $out .= '</div><!-- #payment_type_list -->
  1097. </div><!-- #payment-type -->
  1098. <p id="input-hidden-val" style="display:none;">'.$input_output.'</p>
  1099. <p style="text-align:center;">
  1100. <input type="submit" name="submit_change_certificate" class="button" value="'.$this->l('Update it').'"/>
  1101. </p>
  1102. </fieldset>
  1103. </form>';
  1104. return $out;
  1105. }
  1106. private function _displayInfoCronTask()
  1107. {
  1108. $out = '<fieldset>
  1109. <legend><img src="../img/admin/warning.gif" alt="" />'.$this->l('Cronjob configuration').'</legend>';
  1110. $out .= '<p>'
  1111. .$this->l('You need to set a cron Task on your server, working with your EXCELLENT certificate.').'<br />'
  1112. .$this->l('The file you need to call:').' <b style="color:red;">'.$this->getCronFilePath().'</b><br />'
  1113. .$this->l('Trusted Shops recommends that the request should be automated by a cronjob with an interval of 10 minutes.')
  1114. .'</p>';
  1115. $out .= '</fieldset>';
  1116. return $out;
  1117. }
  1118. public function hookRightColumn($params)
  1119. {
  1120. $lang = Language::getIsoById($params['cookie']->id_lang);
  1121. $lang = strtoupper($lang);
  1122. if (array_key_exists($lang, $this->available_languages) AND isset(TSBuyerProtection::$CERTIFICATE[$lang]['tsID']))
  1123. {
  1124. TSBuyerProtection::$smarty->assign('trusted_shops_id', TSBuyerProtection::$CERTIFICATE[$lang]['tsID']);
  1125. TSBuyerProtection::$smarty->assign('onlineshop_name', ConfigurationCore::get('PS_SHOP_NAME'));
  1126. $url = str_replace(array('#shop_id#', '#shop_name#'), array(TSBuyerProtection::$CERTIFICATE[$lang]['tsID'], urlencode(str_replace('_', '-', ConfigurationCore::get('PS_SHOP_NAME')))), TSBuyerProtection::$certificate_link[$lang]);
  1127. TSBuyerProtection::$smarty->assign('trusted_shops_url', $url);
  1128. return $this->display(TSBuyerProtection::$module_name, 'seal_of_approval.tpl');
  1129. }
  1130. }
  1131. /**
  1132. * For Excellence certificate display Buyer protection products.
  1133. * An error message if the certificate is not totally filled
  1134. *
  1135. * @param array $params
  1136. * @return string tpl content
  1137. */
  1138. public function hookPaymentTop($params)
  1139. {
  1140. $lang = Language::getIsoById($params['cookie']->id_lang);
  1141. $lang = strtoupper($lang);
  1142. if (!isset(TSBuyerProtection::$CERTIFICATE[$lang]) ||
  1143. !isset(TSBuyerProtection::$CERTIFICATE[$lang]['typeEnum']))
  1144. return '';
  1145. // This hook is available only with EXCELLENCE certificate.
  1146. if(TSBuyerProtection::$CERTIFICATE[$lang]['typeEnum'] == 'CLASSIC' OR (TSBuyerProtection::$CERTIFICATE[$lang]['stateEnum'] !== 'INTEGRATION' AND TSBuyerProtection::$CERTIFICATE[$lang]['stateEnum'] !== 'PRODUCTION' AND TSBuyerProtection::$CERTIFICATE[$lang]['stateEnum'] !== 'TEST'))
  1147. return '';
  1148. // If login parameters missing for the certificate an error occurred
  1149. if ((TSBuyerProtection::$CERTIFICATE[$lang]['user'] == '' OR TSBuyerProtection::$CERTIFICATE[$lang]['password'] == '') AND TSBuyerProtection::$CERTIFICATE[$lang]['typeEnum'] == 'EXCELLENCE')
  1150. {
  1151. return '
  1152. <p style="color:red;text-align:center;font-size:14px;font-weight:bold;">'
  1153. .$this->l('The Trusted Shop Buyer Protection needs a login to succeed. Please contact the shop administrator.')
  1154. .'<br />'
  1155. .$this->l('Problem occurred with your language:').' "'.$lang
  1156. .'"</p>';
  1157. }
  1158. if (array_key_exists($lang, $this->available_languages))
  1159. {
  1160. $currency = new Currency((int)$params['cookie']->id_currency);
  1161. $sql = '
  1162. SELECT * FROM `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'`
  1163. WHERE 1
  1164. AND ts_id ="'.TSBuyerProtection::$CERTIFICATE[$lang]['tsID'].'"
  1165. AND `protected_amount_decimal` >= "'.$params['cart']->getOrderTotal(true, Cart::BOTH).'"
  1166. AND `currency` = "'.$currency->iso_code.'"
  1167. ORDER BY `protected_amount_decimal`
  1168. LIMIT 0,1';
  1169. $items = Db::getInstance()->ExecuteS($sql);
  1170. if (empty($items))
  1171. {
  1172. $sql = '
  1173. SELECT * FROM `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'`
  1174. WHERE 1
  1175. AND ts_id ="'.TSBuyerProtection::$CERTIFICATE[$lang]['tsID'].'"
  1176. AND `protected_amount_decimal` <= "'.$params['cart']->getOrderTotal(true, Cart::BOTH).'"
  1177. AND `currency` = "'.$currency->iso_code.'"
  1178. ORDER BY `protected_amount_decimal`
  1179. LIMIT 0,1';
  1180. $items = Db::getInstance()->ExecuteS($sql);
  1181. }
  1182. TSBuyerProtection::$smarty->assign(array(
  1183. 'tax_label' => 'TTC',
  1184. 'buyer_protection_items' => $items)
  1185. );
  1186. }
  1187. return $this->display(TSBuyerProtection::$module_name, 'display_products.tpl');
  1188. }
  1189. /**
  1190. * This prepare values to create the Trusted Shops web service
  1191. * for Excellence certificate.
  1192. *
  1193. * @see TSBuyerProtection::_requestForProtectionV2() method
  1194. * @param array $params
  1195. * @param string $lang
  1196. * @return string empty if no error occurred or no item was set.
  1197. */
  1198. private function _orderConfirmationExcellence($params, $lang)
  1199. {
  1200. $currency = new Currency((int)$params['objOrder']->id_currency);
  1201. $order_products = $params['objOrder']->getProducts();
  1202. $order_item_ids = array();
  1203. foreach ($order_products as $product)
  1204. $order_item_ids[] = $product['product_id'];
  1205. $sql = '
  1206. SELECT * FROM `'._DB_PREFIX_.TSBuyerProtection::DB_ITEMS.'`
  1207. WHERE 1
  1208. AND `id_product` IN ('.implode(',', $order_item_ids).')
  1209. AND `ts_id` ="'.TSBuyerProtection::$CERTIFICATE[$lang]['tsID'].'"
  1210. AND `currency` = "'.$currency->iso_code.'"
  1211. ';
  1212. $item = Db::getInstance()->ExecuteS($sql);
  1213. // No items ? means no buyer protection products was bought.
  1214. if(empty($item))
  1215. return '';
  1216. // In normal context this never occurred,
  1217. // because of a buyer could never add multiple Buyer protection products.
  1218. if (count($item) > 1)
  1219. {
  1220. $this->errors[] = $this->l('A buyer can\'t buy multiple Buyer Protection Products.');
  1221. die($this->errors);
  1222. }
  1223. $item = $item[0];
  1224. $customer = new Customer($params['objOrder']->id_customer);
  1225. $payment_module = Module::getInstanceByName($params['objOrder']->module);
  1226. $arr_params = array();
  1227. foreach (TSBuyerProtection::$CERTIFICATE[$lang]['payment_type'] as $payment_type => $id_modules)
  1228. {
  1229. if(in_array($payment_module->id, $id_modules))
  1230. {
  1231. $arr_params['paymentType'] = (string)$payment_type;
  1232. break;
  1233. }
  1234. }
  1235. if ($arr_params['paymentType'] == '')
  1236. $arr_params['paymentType'] = 'OTHER';
  1237. $arr_params['tsID'] = TSBuyerProtection::$CERTIFICATE[$lang]['tsID'];
  1238. $arr_params['tsProductID'] = $item['ts_product_id'];
  1239. $arr_params['amount'] = $params['total_to_pay'];
  1240. $arr_params['currency'] = $currency->iso_code;
  1241. $arr_params['buyerEmail'] = $customer->email;
  1242. $arr_params['shopCustomerID'] = $customer->id;
  1243. $arr_params['shopOrderID'] = $params['objOrder']->id;
  1244. $arr_params['orderDate'] = date('Y-m-d\TH:i:s', strtotime($params['objOrder']->date_add));
  1245. $arr_params['shopSystemVersion'] = 'Prestashop '._PS_VERSION_;
  1246. $arr_params['wsUser'] = TSBuyerProtection::$CERTIFICATE[$lang]['user'];
  1247. $arr_params['wsPassword'] = TSBuyerProtection::$CERTIFICATE[$lang]['password'];
  1248. $this->_requestForProtectionV2($ar

Large files files are truncated, but you can click here to view the full file