choiceai - Version 1.1.1

Version Notes

Choice AI plugin

Download this release

Release Info

Developer BrainSINS
Extension choiceai
Version 1.1.1
Comparing to
See all releases


Code changes from version 1.0.12 to 1.1.1

Files changed (55) hide show
  1. app/code/community/ChoiceAI/Personalisation/Block/Base/Script.php +10 -4
  2. app/code/community/ChoiceAI/Personalisation/Block/Event/Analytics/Listpage.php +6 -3
  3. app/code/community/ChoiceAI/Personalisation/Block/Event/Analytics/Search.php +6 -3
  4. app/code/community/ChoiceAI/Personalisation/Block/Event/Catalog/Product/View.php +45 -39
  5. app/code/community/ChoiceAI/Personalisation/Block/Event/Checkout/Cart/Index.php +37 -32
  6. app/code/community/ChoiceAI/Personalisation/Block/Event/Checkout/Onepage/Success.php +119 -118
  7. app/code/community/ChoiceAI/Personalisation/Block/Searchpage/Addparam.php +6 -3
  8. app/code/community/ChoiceAI/Personalisation/Helper/Data.php +23 -10
  9. app/code/community/ChoiceAI/Personalisation/Model/Observer.php +109 -110
  10. app/code/community/ChoiceAI/Personalisation/controllers/ApiController.php +1030 -305
  11. app/code/community/ChoiceAI/Personalisation/etc/config.xml +1 -1
  12. app/code/community/ChoiceAI/Personalisation/sql/personalisation_setup/install-1.0.12.php +0 -31
  13. app/code/community/ChoiceAI/Personalisation/sql/personalisation_setup/install-1.1.1.php +37 -0
  14. app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Attribute.php +46 -45
  15. app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Boolean.php +21 -20
  16. app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Category.php +34 -33
  17. app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Decimal.php +46 -45
  18. app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Price.php +50 -50
  19. app/code/local/ChoiceAI/Search/Block/Catalog/Layer/View.php +112 -109
  20. app/code/local/ChoiceAI/Search/Block/Catalog/Product/List.php +1 -0
  21. app/code/local/ChoiceAI/Search/Block/Catalog/Product/List/Toolbar.php +10 -7
  22. app/code/local/ChoiceAI/Search/Block/Catalogsearch/Enterprise/Layer.php +4 -3
  23. app/code/local/ChoiceAI/Search/Block/Catalogsearch/Layer.php +116 -115
  24. app/code/local/ChoiceAI/Search/Block/Catalogsearch/Layer/Filter/Attribute.php +47 -46
  25. app/code/local/ChoiceAI/Search/Block/Catalogsearch/Result.php +5 -3
  26. app/code/local/ChoiceAI/Search/Helper/Choiceaisearch.php +16 -15
  27. app/code/local/ChoiceAI/Search/Helper/Data.php +450 -425
  28. app/code/local/ChoiceAI/Search/Helper/Productimg.php +5 -5
  29. app/code/local/ChoiceAI/Search/Model/Catalog/Category.php +8 -8
  30. app/code/local/ChoiceAI/Search/Model/Catalog/Config.php +125 -121
  31. app/code/local/ChoiceAI/Search/Model/Catalog/Layer.php +38 -37
  32. app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Attribute.php +173 -168
  33. app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Boolean.php +43 -41
  34. app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Category.php +138 -132
  35. app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Decimal.php +191 -190
  36. app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Price.php +162 -154
  37. app/code/local/ChoiceAI/Search/Model/Catalog/Product/Url.php +4 -4
  38. app/code/local/ChoiceAI/Search/Model/Catalogsearch/Layer.php +31 -31
  39. app/code/local/ChoiceAI/Search/Model/Catalogsearch/Layer/Filter/Attribute.php +17 -16
  40. app/code/local/ChoiceAI/Search/Model/Resource/Catalog/Product/Collection.php +383 -373
  41. app/code/local/ChoiceAI/Search/Model/Resource/Engine/Abstract.php +13 -11
  42. app/code/local/ChoiceAI/Search/Model/Resource/Engine/Choiceaisearch.php +288 -276
  43. app/code/local/ChoiceAI/Search/Model/Resource/Engine/Choiceaisearch/Client.php +5 -4
  44. app/code/local/ChoiceAI/Search/etc/config.xml +2 -2
  45. app/code/local/ChoiceAI/Searchcore/Helper/Constants.php +6 -5
  46. app/code/local/ChoiceAI/Searchcore/Helper/Data.php +37 -22
  47. app/code/local/ChoiceAI/Searchcore/etc/config.xml +1 -1
  48. app/design/frontend/base/default/template/choiceai/personalisation/analytics/listpage.phtml +20 -23
  49. app/design/frontend/base/default/template/choiceai/personalisation/analytics/search.phtml +20 -23
  50. app/design/frontend/base/default/template/choiceai/personalisation/base/addparam.phtml +3 -24
  51. app/design/frontend/base/default/template/choiceai/personalisation/base/script.phtml +39 -39
  52. app/design/frontend/default/default/template/choiceai/personalisation/base/script.phtml +38 -38
  53. lib/ChoiceAI/Client.php +312 -291
  54. lib/ChoiceAI/Service.php +174 -181
  55. package.xml +5 -5
app/code/community/ChoiceAI/Personalisation/Block/Base/Script.php CHANGED
@@ -6,25 +6,31 @@
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
- class ChoiceAI_Personalisation_Block_Base_Script extends Mage_Core_Block_Template {
 
10
 
11
- protected function _construct() {
 
12
  parent::_construct();
13
  $this->setTemplate('choiceai/personalisation/base/script.phtml');
14
  }
15
 
16
- protected function _toHtml() {
 
17
  if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled()) {
18
  return '';
19
  }
 
20
  return parent::_toHtml();
21
  }
22
 
23
- public function getUser() {
 
24
  if (Mage::getSingleton('customer/session')->isLoggedIn()) {
25
  $user = Mage::getSingleton('customer/session')->getCustomer();
26
  return $user;
27
  }
 
28
  return null;
29
  }
30
 
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
+ class ChoiceAI_Personalisation_Block_Base_Script extends Mage_Core_Block_Template
10
+ {
11
 
12
+ protected function _construct()
13
+ {
14
  parent::_construct();
15
  $this->setTemplate('choiceai/personalisation/base/script.phtml');
16
  }
17
 
18
+ protected function _toHtml()
19
+ {
20
  if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled()) {
21
  return '';
22
  }
23
+
24
  return parent::_toHtml();
25
  }
26
 
27
+ public function getUser()
28
+ {
29
  if (Mage::getSingleton('customer/session')->isLoggedIn()) {
30
  $user = Mage::getSingleton('customer/session')->getCustomer();
31
  return $user;
32
  }
33
+
34
  return null;
35
  }
36
 
app/code/community/ChoiceAI/Personalisation/Block/Event/Analytics/Listpage.php CHANGED
@@ -12,14 +12,17 @@
12
  * @copyright Copyright (c) MineWhat
13
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
14
  */
15
- class ChoiceAI_Personalisation_Block_Event_Analytics_Listpage extends Mage_Core_Block_Template {
 
16
 
17
- protected function _construct() {
 
18
  parent::_construct();
19
  $this->setTemplate('choiceai/personalisation/analytics/listpage.phtml');
20
  }
21
 
22
- public function engineStatus(){
 
23
  return Mage::helper('choiceai_search')->isActiveEngine();
24
  }
25
 
12
  * @copyright Copyright (c) MineWhat
13
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
14
  */
15
+ class ChoiceAI_Personalisation_Block_Event_Analytics_Listpage extends Mage_Core_Block_Template
16
+ {
17
 
18
+ protected function _construct()
19
+ {
20
  parent::_construct();
21
  $this->setTemplate('choiceai/personalisation/analytics/listpage.phtml');
22
  }
23
 
24
+ public function engineStatus()
25
+ {
26
  return Mage::helper('choiceai_search')->isActiveEngine();
27
  }
28
 
app/code/community/ChoiceAI/Personalisation/Block/Event/Analytics/Search.php CHANGED
@@ -12,14 +12,17 @@
12
  * @copyright Copyright (c) MineWhat
13
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
14
  */
15
- class ChoiceAI_Personalisation_Block_Event_Analytics_Search extends Mage_Core_Block_Template {
 
16
 
17
- protected function _construct() {
 
18
  parent::_construct();
19
  $this->setTemplate('choiceai/personalisation/analytics/search.phtml');
20
  }
21
 
22
- public function engineStatus(){
 
23
  return Mage::helper('choiceai_search')->isActiveEngine();
24
  }
25
 
12
  * @copyright Copyright (c) MineWhat
13
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
14
  */
15
+ class ChoiceAI_Personalisation_Block_Event_Analytics_Search extends Mage_Core_Block_Template
16
+ {
17
 
18
+ protected function _construct()
19
+ {
20
  parent::_construct();
21
  $this->setTemplate('choiceai/personalisation/analytics/search.phtml');
22
  }
23
 
24
+ public function engineStatus()
25
+ {
26
  return Mage::helper('choiceai_search')->isActiveEngine();
27
  }
28
 
app/code/community/ChoiceAI/Personalisation/Block/Event/Catalog/Product/View.php CHANGED
@@ -1,39 +1,45 @@
1
- <?php
2
-
3
- /**
4
- * @category ChoiceAI
5
- * @package ChoiceAI_Personalisation
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Personalisation_Block_Event_Catalog_Product_View extends Mage_Core_Block_Template {
10
-
11
- protected function _construct() {
12
- parent::_construct();
13
- $this->setTemplate('choiceai/personalisation/event/catalog/product/view.phtml');
14
- }
15
-
16
- public function getCurrentProduct() {
17
- return Mage::registry('current_product');
18
- }
19
-
20
- public function getAssociatedProducts($_product) {
21
-
22
- if($_product->getTypeId() == "configurable") {
23
- $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
24
- $simple_collection = $conf->getUsedProductCollection()->addAttributeToSelect(array('id', 'sku', 'price'))->addFilterByRequiredOptions();
25
- return $simple_collection;
26
- } else {
27
- return array();
28
- }
29
-
30
- }
31
-
32
- protected function _toHtml() {
33
- if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled()) {
34
- return '';
35
- }
36
- return parent::_toHtml();
37
- }
38
-
39
- }
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * @category ChoiceAI
5
+ * @package ChoiceAI_Personalisation
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Personalisation_Block_Event_Catalog_Product_View extends Mage_Core_Block_Template
10
+ {
11
+
12
+ protected function _construct()
13
+ {
14
+ parent::_construct();
15
+ $this->setTemplate('choiceai/personalisation/event/catalog/product/view.phtml');
16
+ }
17
+
18
+ public function getCurrentProduct()
19
+ {
20
+ return Mage::registry('current_product');
21
+ }
22
+
23
+ public function getAssociatedProducts($_product)
24
+ {
25
+
26
+ if ($_product->getTypeId() == "configurable") {
27
+ $conf = Mage::getModel('catalog/product_type_configurable')->setProduct($_product);
28
+ return $conf->getUsedProductCollection()->addAttributeToSelect(array('id', 'sku', 'price'))
29
+ ->addFilterByRequiredOptions();
30
+ } else {
31
+ return array();
32
+ }
33
+
34
+ }
35
+
36
+ protected function _toHtml()
37
+ {
38
+ if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled()) {
39
+ return '';
40
+ }
41
+
42
+ return parent::_toHtml();
43
+ }
44
+
45
+ }
app/code/community/ChoiceAI/Personalisation/Block/Event/Checkout/Cart/Index.php CHANGED
@@ -1,32 +1,37 @@
1
- <?php
2
-
3
- /**
4
- * @category ChoiceAI
5
- * @package ChoiceAI_Personalisation
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Personalisation_Block_Event_Checkout_Cart_Index extends Mage_Core_Block_Template {
10
-
11
- protected function _construct() {
12
- parent::_construct();
13
- $this->setTemplate('choiceai/personalisation/event/checkout/cart/index.phtml');
14
- }
15
-
16
- public function getProductToShoppingCart() {
17
- if (($product = Mage::getModel('core/session')->getProductToShoppingCart())) {
18
- Mage::getModel('core/session')->unsProductToShoppingCart();
19
- return $product;
20
- }
21
-
22
- return null;
23
- }
24
-
25
- protected function _toHtml() {
26
- if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled()) {
27
- return '';
28
- }
29
- return parent::_toHtml();
30
- }
31
-
32
- }
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * @category ChoiceAI
5
+ * @package ChoiceAI_Personalisation
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Personalisation_Block_Event_Checkout_Cart_Index extends Mage_Core_Block_Template
10
+ {
11
+
12
+ protected function _construct()
13
+ {
14
+ parent::_construct();
15
+ $this->setTemplate('choiceai/personalisation/event/checkout/cart/index.phtml');
16
+ }
17
+
18
+ public function getProductToShoppingCart()
19
+ {
20
+ if (($product = Mage::getModel('core/session')->getProductToShoppingCart())) {
21
+ Mage::getModel('core/session')->unsProductToShoppingCart();
22
+ return $product;
23
+ }
24
+
25
+ return null;
26
+ }
27
+
28
+ protected function _toHtml()
29
+ {
30
+ if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled()) {
31
+ return '';
32
+ }
33
+
34
+ return parent::_toHtml();
35
+ }
36
+
37
+ }
app/code/community/ChoiceAI/Personalisation/Block/Event/Checkout/Onepage/Success.php CHANGED
@@ -1,118 +1,119 @@
1
- <?php
2
-
3
- /**
4
- * @category ChoiceAI
5
- * @package ChoiceAI_Personalisation
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Personalisation_Block_Event_Checkout_Onepage_Success extends Mage_Core_Block_Template {
10
-
11
- protected function _construct() {
12
- parent::_construct();
13
- $this->setTemplate('choiceai/personalisation/event/checkout/onepage/success.phtml');
14
- }
15
-
16
- public function getOrderInfo() {
17
- try {
18
- $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
19
-
20
- $order = Mage::getSingleton('sales/order');
21
- $order->load($lastOrderId);
22
-
23
-
24
- if ($order && $order->getId()) {
25
-
26
- $orderInfo['items'] = array();
27
-
28
- $orderedItems = $order->getAllItems();
29
-
30
- foreach($orderedItems as $item) {
31
-
32
- if($item->getProductType() == "bundle") {
33
-
34
- $orderInfo['items'][$item->getItemId()] = array(
35
- 'id' => $item->getProductId(),
36
- 'parentId' => '',
37
- 'sku' => $item->getSku(),
38
- 'qty' => $item->getQtyOrdered(),
39
- 'price' => $item->getPrice(),
40
- 'bundle' => array()
41
- );
42
-
43
- } else if($item->getProductType() != "configurable") {
44
-
45
- if($orderInfo['items'][$item->getParentItemId()] != null) {
46
- $bundleItems = $orderInfo['items'][$item->getParentItemId()]['bundle'];
47
- $bundleItem = array(
48
- 'pid' => $item->getProductId(),
49
- 'sku' => $item->getSku(),
50
- 'qty' => $item->getQtyOrdered(),
51
- 'price' => $item->getPrice()
52
- );
53
- $bundleItems[] = $bundleItem;
54
- $orderInfo['items'][$item->getParentItemId()]['bundle'] = $bundleItems;
55
-
56
- } else {
57
-
58
- $parentId = '';
59
- $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($item->getProductId());
60
- if($parentIds != null && count($parentIds) > 0) {
61
- $parentId = $parentIds[0];
62
- }
63
- $orderInfo['items'][] = array(
64
- 'id' => $item->getProductId(),
65
- 'parentId' => $parentId,
66
- 'sku' => $item->getSku(),
67
- 'qty' => $item->getQtyOrdered(),
68
- 'price' => $item->getPrice(),
69
- 'bundle' => array()
70
- );
71
-
72
-
73
- }
74
-
75
- }
76
-
77
- }
78
-
79
- $orderInfo['orderId'] = $order->getIncrementId();
80
- $orderInfo['email'] = $order->getCustomerEmail();
81
- $orderInfo['createdAt'] = $order->getCreatedAt();
82
-
83
- $currency = $order->getOrderCurrency();
84
- if (is_object($currency)) {
85
- $orderInfo['currency'] = $currency->getCurrencyCode();
86
- }
87
- $paymentMethod = $order->getPayment()->getMethodInstance()->getTitle();
88
- $orderInfo['paymentMethod'] = $paymentMethod;
89
-
90
- return $orderInfo;
91
- }
92
- } catch (Exception $e) {}
93
-
94
-
95
- return null;
96
- }
97
-
98
- protected function _toHtml() {
99
- if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled() || !$this->isOrderConfirmation()) {
100
- return '';
101
- }
102
- return parent::_toHtml();
103
- }
104
-
105
- protected function isOrderConfirmation() {
106
- return strpos($this->_getRouteName(), 'checkout') !== false
107
- && $this->_getActionName() == 'success';
108
- }
109
-
110
- protected function _getRouteName() {
111
- return $this->getRequest()->getRequestedRouteName();
112
- }
113
-
114
- protected function _getActionName() {
115
- return $this->getRequest()->getRequestedActionName();
116
- }
117
-
118
- }
 
1
+ <?php
2
+
3
+ /**
4
+ * @category ChoiceAI
5
+ * @package ChoiceAI_Personalisation
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Personalisation_Block_Event_Checkout_Onepage_Success extends Mage_Core_Block_Template
10
+ {
11
+
12
+ protected function _construct()
13
+ {
14
+ parent::_construct();
15
+ $this->setTemplate('choiceai/personalisation/event/checkout/onepage/success.phtml');
16
+ }
17
+
18
+ public function getOrderInfo()
19
+ {
20
+ try {
21
+ $lastOrderId = Mage::getSingleton('checkout/session')->getLastOrderId();
22
+
23
+ $order = Mage::getSingleton('sales/order');
24
+ $order->load($lastOrderId);
25
+
26
+
27
+ if ($order && $order->getId()) {
28
+ $orderInfo['items'] = array();
29
+
30
+ $orderedItems = $order->getAllItems();
31
+
32
+ foreach ($orderedItems as $item) {
33
+ if ($item->getProductType() == "bundle") {
34
+ $orderInfo['items'][$item->getItemId()] = array(
35
+ 'id' => $item->getProductId(),
36
+ 'parentId' => '',
37
+ 'sku' => $item->getSku(),
38
+ 'qty' => $item->getQtyOrdered(),
39
+ 'price' => $item->getPrice(),
40
+ 'bundle' => array()
41
+ );
42
+ } else if ($item->getProductType() != "configurable") {
43
+ if ($orderInfo['items'][$item->getParentItemId()] != null) {
44
+ $bundleItems = $orderInfo['items'][$item->getParentItemId()]['bundle'];
45
+ $bundleItem = array(
46
+ 'pid' => $item->getProductId(),
47
+ 'sku' => $item->getSku(),
48
+ 'qty' => $item->getQtyOrdered(),
49
+ 'price' => $item->getPrice()
50
+ );
51
+ $bundleItems[] = $bundleItem;
52
+ $orderInfo['items'][$item->getParentItemId()]['bundle'] = $bundleItems;
53
+ } else {
54
+ $parentId = '';
55
+ $parentIds = Mage::getModel('catalog/product_type_configurable')->
56
+ getParentIdsByChild($item->getProductId());
57
+ if ($parentIds != null && !empty($parentIds)) {
58
+ $parentId = $parentIds[0];
59
+ }
60
+
61
+ $orderInfo['items'][] = array(
62
+ 'id' => $item->getProductId(),
63
+ 'parentId' => $parentId,
64
+ 'sku' => $item->getSku(),
65
+ 'qty' => $item->getQtyOrdered(),
66
+ 'price' => $item->getPrice(),
67
+ 'bundle' => array()
68
+ );
69
+ }
70
+ }
71
+ }
72
+
73
+ $orderInfo['orderId'] = $order->getIncrementId();
74
+ $orderInfo['email'] = $order->getCustomerEmail();
75
+ $orderInfo['createdAt'] = $order->getCreatedAt();
76
+
77
+ $currency = $order->getOrderCurrency();
78
+ if (is_object($currency)) {
79
+ $orderInfo['currency'] = $currency->getCurrencyCode();
80
+ }
81
+
82
+ $paymentMethod = $order->getPayment()->getMethodInstance()->getTitle();
83
+ $orderInfo['paymentMethod'] = $paymentMethod;
84
+
85
+ return $orderInfo;
86
+ }
87
+ } catch (Exception $e) {
88
+ return null;
89
+ }
90
+
91
+ return null;
92
+ }
93
+
94
+ protected function _toHtml()
95
+ {
96
+ if (!$this->helper('choiceai_personalisation')->isModuleOutputEnabled() || !$this->isOrderConfirmation()) {
97
+ return '';
98
+ }
99
+
100
+ return parent::_toHtml();
101
+ }
102
+
103
+ protected function isOrderConfirmation()
104
+ {
105
+ return strpos($this->_getRouteName(), 'checkout') !== false
106
+ && $this->_getActionName() == 'success';
107
+ }
108
+
109
+ protected function _getRouteName()
110
+ {
111
+ return $this->getRequest()->getRequestedRouteName();
112
+ }
113
+
114
+ protected function _getActionName()
115
+ {
116
+ return $this->getRequest()->getRequestedActionName();
117
+ }
118
+
119
+ }
app/code/community/ChoiceAI/Personalisation/Block/Searchpage/Addparam.php CHANGED
@@ -6,14 +6,17 @@
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
- class ChoiceAI_Personalisation_Block_Searchpage_Addparam extends Mage_Core_Block_Template {
 
10
 
11
- protected function _construct() {
 
12
  parent::_construct();
13
  $this->setTemplate('choiceai/personalisation/base/addparam.phtml');
14
  }
15
 
16
- public function engineStatus(){
 
17
  return Mage::helper('choiceai_search')->isActiveEngine();
18
  }
19
 
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
+ class ChoiceAI_Personalisation_Block_Searchpage_Addparam extends Mage_Core_Block_Template
10
+ {
11
 
12
+ protected function _construct()
13
+ {
14
  parent::_construct();
15
  $this->setTemplate('choiceai/personalisation/base/addparam.phtml');
16
  }
17
 
18
+ public function engineStatus()
19
+ {
20
  return Mage::helper('choiceai_search')->isActiveEngine();
21
  }
22
 
app/code/community/ChoiceAI/Personalisation/Helper/Data.php CHANGED
@@ -6,12 +6,14 @@
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
- class ChoiceAI_Personalisation_Helper_Data extends Mage_Core_Helper_Data {
 
10
 
11
  const CONFIG_ACTIVE = 'choiceai_personalisation/settings/active';
12
  const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
13
 
14
- public function isModuleEnabled($moduleName = null) {
 
15
  if (Mage::getStoreConfig(self::CONFIG_ACTIVE) == '0') {
16
  return false;
17
  }
@@ -19,20 +21,31 @@ class ChoiceAI_Personalisation_Helper_Data extends Mage_Core_Helper_Data {
19
  return parent::isModuleEnabled($moduleName = null);
20
  }
21
 
22
- public function getBaseScript($store = null) {
 
23
 
24
- $base_script = "";
25
 
26
  try {
27
-
28
- $base_script = "\n<!-- ChoiceAI Script begins -->\n<script type='text/javascript'>!function(){function t(){if(!window.CAISDK){var t=document.createElement('script'),n='beaconhttp.choice.ai';t.type='text/javascript',t.async=!0,'https:'==location.protocol&&(n='d3caf2da6t944y.cloudfront.net'),t.src='//'+n+'/site/ethno/ORG_HANDLE/choice.js';var e=document.getElementsByTagName('script')[0];e.parentNode.insertBefore(t,e)}}window.CAISDK&&window.CAISDK.reinit&&window.CAISDK.reinit(),!window.CAISDK && t()}();</script>\n<!-- ChoiceAI Script ends -->\n";
29
- $base_script = str_replace("ORG_HANDLE", split("_", Mage::getStoreConfig(self::CONFIG_API_KEY, $store))[0], $base_script);
30
-
 
 
 
 
 
 
 
 
 
 
31
  } catch (Exception $e) {
32
- $base_script = "";
33
  }
34
 
35
- return $base_script;
36
 
37
  }
38
 
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
+ class ChoiceAI_Personalisation_Helper_Data extends Mage_Core_Helper_Data
10
+ {
11
 
12
  const CONFIG_ACTIVE = 'choiceai_personalisation/settings/active';
13
  const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
14
 
15
+ public function isModuleEnabled($moduleName = null)
16
+ {
17
  if (Mage::getStoreConfig(self::CONFIG_ACTIVE) == '0') {
18
  return false;
19
  }
21
  return parent::isModuleEnabled($moduleName = null);
22
  }
23
 
24
+ public function getBaseScript($store = null)
25
+ {
26
 
27
+ // $baseScript = "";
28
 
29
  try {
30
+ $baseScript = "\n<!-- ChoiceAI Script begins -->\n<script type='text/javascript'>!function(){function t(){
31
+ if(!window.CAIBASE){var t=document.createElement('script'),n='beaconhttp.choice.ai';
32
+ t.type='text/javascript',t.async=!0,
33
+ 'https:'==location.protocol&&(n='d3caf2da6t944y.cloudfront.net'),t.src='//'+n+'/site/ethno/ORG_HANDLE/choice.js';
34
+ var e=document.getElementsByTagName('script')[0];e.parentNode.insertBefore(t,e)}}
35
+ window.CAIBASE&&window.CAIBASE.reinit&&window.CAIBASE.reinit(),!window.CAIBASE && t()}();</script>
36
+ \n<!-- ChoiceAI Script ends -->\n";
37
+ $baseScript = str_replace(
38
+ "ORG_HANDLE", explode(
39
+ "_", Mage::getStoreConfig(
40
+ self::CONFIG_API_KEY, $store
41
+ )
42
+ )[0], $baseScript
43
+ );
44
  } catch (Exception $e) {
45
+ $baseScript = "";
46
  }
47
 
48
+ return $baseScript;
49
 
50
  }
51
 
app/code/community/ChoiceAI/Personalisation/Model/Observer.php CHANGED
@@ -1,124 +1,123 @@
1
  <?php
2
 
3
- class ChoiceAI_Personalisation_Model_Observer {
4
-
5
- const CONFIG_ACTIVE = 'choiceai_personalisation/settings/active';
6
- const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
7
-
8
- public function onSaveSettings($observer) {
9
-
10
- $enabled = Mage::getStoreConfig(self::CONFIG_ACTIVE);
11
- $api_key = Mage::getStoreConfig(self::CONFIG_API_KEY);
12
- $store_url = Mage::getBaseUrl();
13
- $magento_version = Mage::getVersion();
14
-
15
- $error_message = "";
16
-
17
- try {
18
-
19
- $roles = Mage::getModel('api/roles')->getCollection()->addFieldToFilter('role_name', 'ChoiceAI');
20
-
21
- if ($roles && sizeof($roles) > 0) {
22
-
23
- $api_role = $roles->getFirstItem();
24
-
25
- } else {
26
-
27
- $api_role = Mage::getModel('api/roles')
28
- ->setName('ChoiceAI')
29
- ->setPid("ChoiceAI")
30
- ->setRoleType('G')
31
- ->save();
32
- }
33
-
34
- Mage::getModel('api/rules')
35
- ->setRoleId($api_role->getId())
36
- ->setResources(array('all'))
37
- ->saveRel();
38
-
39
- $users = Mage::getModel('api/user')->getCollection()->addFieldToFilter('email', 'magento@choice.ai');
40
- if ($users && sizeof($users) > 0) {
41
-
42
- $api_user = $users->getFirstItem();
43
-
44
- } else {
45
-
46
- $api_user = Mage::getModel('api/user');
47
- $api_user->setData(array(
48
- 'username' => 'choiceai',
49
- 'firstname' => 'ChoiceAI',
50
- 'lastname' => 'Personalisation',
51
- 'email' => 'magento@choice.ai',
52
- 'api_key' => $api_key,
53
- 'api_key_confirmation' => $api_key,
54
- 'is_active' => 1,
55
- 'user_roles' => '',
56
- 'assigned_user_role' => '',
57
- 'role_name' => '',
58
- 'roles' => array($api_role->getId())
59
- ));
60
-
61
- $api_user->save()->load($api_user->getId());
62
-
63
- }
 
 
 
64
 
65
- $api_user->setRoleIds(array($api_role->getId()))
66
- ->setRoleUserId($api_user->getUserId())
67
- ->saveRelations();
 
68
 
69
- } catch (Exception $e) {
70
- $error_message = $e->getMessage();
71
  }
72
 
73
- file_get_contents("https://app.choice.ai/stats/magentoinstall?enabled=".$enabled."&api_key=".$api_key."&store_url=".$store_url."&magentoversion=".$magento_version."&error=".$error_message);
 
74
 
75
- }
76
-
77
- public function logCartAdd($observer) {
78
 
79
- if (!$observer->getQuoteItem()->getProduct()->getId()) {
80
- return;
81
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82
 
83
- $product = $observer->getProduct();
84
- $id = $observer->getQuoteItem()->getProduct()->getId();
85
- $bundle = array();
86
-
87
- if($product->getTypeId() == 'bundle') {
88
-
89
- $id = $product->getId();
90
- $optionCollection = $product->getTypeInstance()->getOptionsCollection();
91
- $selectionCollection = $product->getTypeInstance()->getSelectionsCollection($product->getTypeInstance()->getOptionsIds());
92
- $options = $optionCollection->appendSelections($selectionCollection);
93
- foreach( $options as $option )
94
- {
95
- $_selections = $option->getSelections();
96
- foreach( $_selections as $selection )
97
- {
98
- $bundleItem = array();
99
- $bundleItem['pid'] = $selection->getId();
100
- $bundleItem['sku'] = $selection->getSku();
101
- $bundleItem['price'] = $selection->getPrice();
102
- $bundle[] = $bundleItem;
103
  }
104
- }
105
 
106
- }
 
 
 
 
 
 
 
 
107
 
108
- $parentId = '';
109
- $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($id);
110
- if($parentIds != null && count($parentIds) > 0) {
111
- $parentId = $parentIds[0];
112
  }
113
- Mage::getModel('core/session')->setProductToShoppingCart(
114
- array(
115
- 'id' => $id,
116
- 'sku' => $product->getSku(),
117
- 'parentId' => $parentId,
118
- 'qty' => $product->getQty(),
119
- 'bundle' => $bundle
120
- )
121
- );
122
-
123
- }
124
  }
1
  <?php
2
 
3
+ class ChoiceAI_Personalisation_Model_Observer
4
+ {
5
+
6
+ const CONFIG_ACTIVE = 'choiceai_personalisation/settings/active';
7
+ const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
8
+
9
+ public function onSaveSettings($observer)
10
+ {
11
+
12
+ $enabled = Mage::getStoreConfig(self::CONFIG_ACTIVE);
13
+ $apiKey = Mage::getStoreConfig(self::CONFIG_API_KEY);
14
+ $errorMessage = "";
15
+
16
+ try {
17
+ $roles = Mage::getModel('api/roles')->getCollection()->addFieldToFilter('role_name', 'ChoiceAI');
18
+
19
+ if ($roles && !empty($roles)) {
20
+ $apiRole = $roles->getFirstItem();
21
+ } else {
22
+ $apiRole = Mage::getModel('api/roles')
23
+ ->setName('ChoiceAI')
24
+ ->setPid("ChoiceAI")
25
+ ->setRoleType('G')
26
+ ->save();
27
+ }
28
+
29
+ Mage::getModel('api/rules')
30
+ ->setRoleId($apiRole->getId())
31
+ ->setResources(array('all'))
32
+ ->saveRel();
33
+
34
+ $users = Mage::getModel('api/user')->getCollection()->addFieldToFilter(
35
+ 'email',
36
+ 'magento@choice.ai'
37
+ );
38
+ if ($users && !empty($users)) {
39
+ $apiUser = $users->getFirstItem();
40
+ } else {
41
+ $apiUser = Mage::getModel('api/user');
42
+ $apiUser->setData(
43
+ array(
44
+ 'username' => 'choiceai',
45
+ 'firstname' => 'ChoiceAI',
46
+ 'lastname' => 'Personalisation',
47
+ 'email' => 'magento@choice.ai',
48
+ 'api_key' => $apiKey,
49
+ 'api_key_confirmation' => $apiKey,
50
+ 'is_active' => 1,
51
+ 'user_roles' => '',
52
+ 'assigned_user_role' => '',
53
+ 'role_name' => '',
54
+ 'roles' => array($apiRole->getId())
55
+ )
56
+ );
57
+
58
+ $apiUser->save()->load($apiUser->getId());
59
+ }
60
+
61
+ $apiUser->setRoleIds(array($apiRole->getId()))
62
+ ->setRoleUserId($apiUser->getUserId())
63
+ ->saveRelations();
64
+ } catch (Exception $e) {
65
+ $errorMessage = $e->getMessage();
66
+ }
67
 
68
+ file_get_contents(
69
+ "https://app.choice.ai/stats/magentoinstall?enabled=" . $enabled . "&api_key="
70
+ . $apiKey . "&error=" . $errorMessage
71
+ );
72
 
 
 
73
  }
74
 
75
+ public function logCartAdd($observer)
76
+ {
77
 
78
+ if (!$observer->getQuoteItem()->getProduct()->getId()) {
79
+ return;
80
+ }
81
 
82
+ $product = $observer->getProduct();
83
+ $id = $observer->getQuoteItem()->getProduct()->getId();
84
+ $bundle = array();
85
+
86
+ if ($product->getTypeId() == 'bundle') {
87
+ $id = $product->getId();
88
+ $optionCollection = $product->getTypeInstance()->getOptionsCollection();
89
+ $selectionCollection = $product->getTypeInstance()->getSelectionsCollection(
90
+ $product->getTypeInstance()
91
+ ->getOptionsIds()
92
+ );
93
+ $options = $optionCollection->appendSelections($selectionCollection);
94
+ foreach ($options as $option) {
95
+ $_selections = $option->getSelections();
96
+ foreach ($_selections as $selection) {
97
+ $bundleItem = array();
98
+ $bundleItem['pid'] = $selection->getId();
99
+ $bundleItem['sku'] = $selection->getSku();
100
+ $bundleItem['price'] = $selection->getPrice();
101
+ $bundle[] = $bundleItem;
102
+ }
103
+ }
104
+ }
105
 
106
+ $parentId = '';
107
+ $parentIds = Mage::getModel('catalog/product_type_configurable')->getParentIdsByChild($id);
108
+ if ($parentIds != null && !empty($parentIds)) {
109
+ $parentId = $parentIds[0];
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  }
 
111
 
112
+ Mage::getModel('core/session')->setProductToShoppingCart(
113
+ array(
114
+ 'id' => $id,
115
+ 'sku' => $product->getSku(),
116
+ 'parentId' => $parentId,
117
+ 'qty' => $product->getQty(),
118
+ 'bundle' => $bundle
119
+ )
120
+ );
121
 
 
 
 
 
122
  }
 
 
 
 
 
 
 
 
 
 
 
123
  }
app/code/community/ChoiceAI/Personalisation/controllers/ApiController.php CHANGED
@@ -7,21 +7,28 @@
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
 
10
- class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_Action {
 
11
 
12
  const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
13
  const CONFIG_KEY = 'choiceai_personalisation/settings/config';
14
- const API_VERSION = 3;
15
 
16
- public function _authorise() {
 
17
 
18
- $API_KEY = Mage::getStoreConfig(self::CONFIG_API_KEY);
19
 
20
  // Check for api access
21
- if(!$API_KEY && strlen($API_KEY) === 0) {
22
  // Api access disabled
23
  $this->getResponse()
24
- ->setBody(json_encode(array('status' => 'error', 'message' => 'API access disabled', 'version' => self::API_VERSION)))
 
 
 
 
 
25
  ->setHttpResponseCode(403)
26
  ->setHeader('Content-type', 'application/json', true);
27
  return false;
@@ -38,16 +45,26 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
38
  Mage::log('Unable to extract authorization header from request', null, 'choiceai.log');
39
  // Internal server error
40
  $this->getResponse()
41
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error, Authorization header not found', 'version' => self::API_VERSION)))
 
 
 
 
 
42
  ->setHttpResponseCode(500)
43
  ->setHeader('Content-type', 'application/json', true);
44
  return false;
45
  }
46
 
47
- if(trim($authHeader) !== trim($API_KEY)) {
48
  // Api access denied
49
  $this->getResponse()
50
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Api access denied', 'version' => self::API_VERSION)))
 
 
 
 
 
51
  ->setHttpResponseCode(401)
52
  ->setHeader('Content-type', 'application/json', true);
53
  return false;
@@ -57,30 +74,134 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
57
 
58
  }
59
 
60
- public function configAction() {
 
61
  try {
62
- if(!$this->_authorise()) {
63
  return $this;
64
  }
65
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  $responseObj = array();
67
 
68
- if ($_SERVER["REQUEST_METHOD"] == "GET") {
69
- $STORE_CONFIG = Mage::getStoreConfig(self::CONFIG_KEY);
70
  $responseObj["status"] = "ok";
71
- $responseObj["config"] = json_decode($STORE_CONFIG);
72
- } else if ($_SERVER["REQUEST_METHOD"] == "PUT") {
73
- $store_config = $this->getRequest()->getParam('config');
74
- if($store_config ==""){
75
  $input = file_get_contents('php://input');
76
  $input = utf8_encode($input);
77
- $store_config = json_encode(json_decode($input)->config);
78
  }
79
- $store_config_json = json_decode($store_config);
80
- if ($store_config_json == NULL) {
81
- throw new Exception();
 
82
  }
83
- Mage::getModel('core/config')->saveConfig(self::CONFIG_KEY, $store_config);
 
84
  Mage::app()->getStore()->resetConfig();
85
  $responseObj["status"] = "ok";
86
  } else {
@@ -88,24 +209,79 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
88
  $responseObj['message'] = 'Invalid request';
89
  }
90
 
91
- if(isset($_SERVER['REQUEST_SCHEME']) && isset($_SERVER['SERVER_NAME'])){
92
- $storeUrl = $_SERVER['REQUEST_SCHEME'] ."://". $_SERVER['SERVER_NAME'];
93
- } else{
94
  $storeUrl = Mage::getBaseUrl();
95
  }
 
96
  $responseObj['store_url'] = $storeUrl;
97
- $responseObj['installed'] = '1';
98
  $responseObj['api_version'] = self::API_VERSION;
99
- $responseObj['plugin_version'] = (string)Mage::getConfig()->getNode('modules/ChoiceAI_Personalisation/version');
 
100
  $responseObj['magento_version'] = Mage::getVersion();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  $this->getResponse()
102
  ->setBody(json_encode($responseObj))
103
  ->setHttpResponseCode(200)
104
  ->setHeader('Content-type', 'application/json', true);
105
-
106
- } catch(Exception $e) {
107
  $this->getResponse()
108
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
109
  ->setHttpResponseCode(500)
110
  ->setHeader('Content-type', 'application/json', true);
111
  }
@@ -113,15 +289,16 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
113
  return $this;
114
  }
115
 
116
- public function ordersAction() {
 
117
  try {
118
- if(!$this->_authorise()) {
119
  return $this;
120
  }
121
 
122
  $sections = explode('/', trim($this->getRequest()->getPathInfo(), '/'));
123
 
124
- if(isset($sections[3])) {
125
  // Looking for a specific order
126
  $orderId = $sections[3];
127
 
@@ -129,9 +306,10 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
129
 
130
  $extras = $this->getRequest()->getParam('extras');
131
  $debug = $this->getRequest()->getParam('mwdebug', 'false') === 'true';
132
- if($extras && strlen($extras)) {
133
  $extras = explode(',', $extras);
134
- for($i = 0;$i < sizeof($extras);$i++) {
 
135
  $extras[$i] = trim($extras[$i]);
136
  }
137
  }
@@ -140,13 +318,13 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
140
 
141
  $orderItems = $order->getItemsCollection()->load();
142
 
143
- foreach($orderItems as $key => $orderItem) {
144
  $items[] = array(
145
- 'name' => $orderItem->getName(),
146
- 'pid' => $orderItem->getProductId(),
147
- 'sku' => $orderItem->getSku(),
148
- 'qty' => $orderItem->getQtyOrdered(),
149
- 'price' => $orderItem->getPrice()
150
  );
151
  }
152
 
@@ -157,10 +335,10 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
157
  );
158
 
159
  $attributes = $order->debug();
160
- if($debug) {
161
  $responseObj['extras'] = $attributes;
162
  } else {
163
- foreach($extras as $key) {
164
  $responseObj['extras'][$key] = $attributes[$key];
165
  }
166
  }
@@ -173,7 +351,8 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
173
  } else {
174
  // Looking for a list of orders
175
  $currentTime = time();
176
- $fromDate = $this->getRequest()->getParam('fromDate', date('Y-m-d', ($currentTime - 86400)));
 
177
  $toDate = $this->getRequest()->getParam('toDate', date('Y-m-d', $currentTime));
178
 
179
  $orders = array();
@@ -184,26 +363,35 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
184
  ->addAttributeToSelect('created_at')
185
  ->addAttributeToSelect('increment_id')
186
  ->addAttributeToSelect('status')
187
- ->addAttributeToFilter('created_at', array('from' => $fromDate, 'to' => $toDate))
188
- ;
189
 
190
  foreach ($ordersCollection as $order) {
191
  $orders[] = array(
192
- 'order_id' => $order->getIncrementId(),
193
- 'status' => $order->getStatus(),
194
- 'email' => $order->getCustomerEmail(),
195
- 'created_at' => $order->getCreatedAt()
196
  );
197
  }
198
 
199
  $this->getResponse()
200
- ->setBody(json_encode(array('orders' => $orders, 'fromDate' => $fromDate, 'toDate' => $toDate, 'version' => self::API_VERSION)))
 
 
 
 
 
201
  ->setHttpResponseCode(200)
202
  ->setHeader('Content-type', 'application/json', true);
203
  }
204
- } catch(Exception $e) {
205
  $this->getResponse()
206
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
207
  ->setHttpResponseCode(500)
208
  ->setHeader('Content-type', 'application/json', true);
209
  }
@@ -211,44 +399,43 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
211
  return $this;
212
  }
213
 
214
- public function productattributesAction() {
 
215
  try {
216
- if(!$this->_authorise()) {
217
  return $this;
218
  }
219
 
220
  $sections = explode('/', trim($this->getRequest()->getPathInfo(), '/'));
221
 
222
- if(!isset($sections[3])) {
223
  // product id
224
- throw new Exception();
225
  }
226
 
227
  $productId = $sections[3];
228
 
229
  $product = Mage::getModel('catalog/product')->load($productId);
230
 
231
- $product_info = array();
232
 
233
- $product_info["is_available"] = $product->isAvailable();
234
- $product_info["name"] = $product->getName();
235
- $product_info["id"] = $product->getId();
236
- $product_info["sku"] = $product->getSku();
237
- $product_info["price"] = $product->getPrice();
238
- $product_info["final_price"] = $product->getFinalPrice();
239
- $product_info["special_price"] = $product->getSpecialPrice();
240
- $product_info["type"] = $product->getTypeId();
241
 
242
  $variants = array();
243
  $options = array();
244
 
245
  if ($product->getTypeId() == "configurable") {
246
-
247
  $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
248
  $attributeTypes = array();
249
 
250
  foreach ($productAttributeOptions as $productAttribute) {
251
-
252
  $attributes = array();
253
  foreach ($productAttribute['values'] as $attribute) {
254
  $attributes[] = array(
@@ -267,12 +454,10 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
267
  );
268
 
269
  $attributeTypes[] = $attributeType;
270
-
271
  }
272
 
273
  $associatedProducts = $product->getTypeInstance()->getUsedProducts();
274
  foreach ($associatedProducts as $associatedProduct) {
275
-
276
  $variant = array();
277
  $variant["is_available"] = $associatedProduct->isAvailable();
278
  $variant["id"] = $associatedProduct->getId();
@@ -291,21 +476,130 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
291
  }
292
 
293
  $this->getResponse()
294
- ->setBody(json_encode(array('product' => $product_info, 'variants' => $variants, 'options' => $options, 'version' => self::API_VERSION)))
 
 
 
 
 
295
  ->setHttpResponseCode(200)
296
  ->setHeader('Content-type', 'application/json', true);
297
- } catch(Exception $e) {
298
  $this->getResponse()
299
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
300
  ->setHttpResponseCode(500)
301
  ->setHeader('Content-type', 'application/json', true);
302
  }
 
303
  return $this;
 
304
  }
305
 
306
- public function productsAction() {
 
307
  try {
308
- if(!$this->_authorise()) {
309
  return $this;
310
  }
311
 
@@ -317,6 +611,9 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
317
  'sku',
318
  'image',
319
  'manufacturer',
 
 
 
320
  'price',
321
  'final_price',
322
  'special_price',
@@ -324,65 +621,117 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
324
  );
325
 
326
  $extras = $this->getRequest()->getParam('extras');
 
 
 
 
 
327
  $debug = $this->getRequest()->getParam('mwdebug', 'false') === 'true';
328
 
329
- if($extras && strlen($extras)) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
  $extras = explode(',', $extras);
331
- for($i = 0;$i < sizeof($extras);$i++) {
 
332
  $extras[$i] = trim($extras[$i]);
333
  $attributes[] = $extras[$i];
334
  }
335
  }
336
 
337
- if(isset($sections[3])) {
 
338
  // Looking for a specific product
339
  $productId = $sections[3];
 
 
340
 
341
- $product = Mage::getModel('catalog/product')->load($productId);
342
-
343
- $product = $this->getFormattedProduct($product, $extras, $debug);
344
- if($product !== null) {
345
- $products[] = $product;
346
- }else{
347
- throw new Exception("Failed to fetch the product");
348
  }
 
349
 
350
- } else {
351
  // Looking for a list of products
352
  $limit = $this->getRequest()->getParam('limit', 100);
353
  $offset = $this->getRequest()->getParam('offset', 1);
354
 
355
  $productsCollection = Mage::getModel('catalog/product')->getCollection();
356
 
 
357
  // Get only enabled products
358
- $productsCollection
359
- ->addAttributeToSelect($attributes)
360
- ->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED))
361
- ->getSelect()->limit($limit, $offset) //we can specify how many products we want to show on this page
362
- ;
 
363
 
364
- foreach($productsCollection as $product) {
365
- $product = $this->getFormattedProduct($product, $extras, $debug);
366
- if($product !== null) {
367
- $products[] = $product;
368
- }else{
369
- throw new Exception("Failed to fetch the product");
370
- }
371
  }
372
 
373
- }
 
 
 
374
 
375
- $currency = Mage::app()->getStore()->getCurrentCurrencyCode();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
376
 
377
  $this->getResponse()
378
- ->setBody(json_encode(array('products' => $products, 'currency' => $currency, 'version' => self::API_VERSION)))
379
  ->setHttpResponseCode(200)
380
  ->setHeader('Content-type', 'application/json', true);
381
-
382
-
383
- } catch(Exception $e) {
384
  $this->getResponse()
385
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
386
  ->setHttpResponseCode(500)
387
  ->setHeader('Content-type', 'application/json', true);
388
  }
@@ -391,9 +740,10 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
391
  }
392
 
393
 
394
- public function categoriesAction() {
 
395
  try {
396
- if(!$this->_authorise()) {
397
  return $this;
398
  }
399
 
@@ -406,6 +756,7 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
406
  'path',
407
  'is_anchor',
408
  'is_active',
 
409
  'created_at',
410
  'updated_at'
411
  );
@@ -417,25 +768,30 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
417
  $active = $this->getRequest()->getParam('active', 'false') === 'true';
418
  $isAnchor = $this->getRequest()->getParam('is_anchor', 'false') === 'true';
419
 
420
- if($level && strlen($level)) {
421
- $level = intval($level);
422
  } else {
423
  $level = null;
424
  }
425
 
426
- if(isset($sections[3])) {
427
  // Looking for a specific category
428
  $categoryId = $sections[3];
429
-
430
- $category = Mage::getModel('catalog/category')->load($categoryId);
431
-
432
- $category = $this->getFormattedCategory($category);
433
- if($category !== null && $category->id != null && is_array($category)) {
434
  $categories[] = $category;
435
- } else{
436
- throw new Exception("Category ".$categoryId." not found");
437
- }
438
 
 
 
 
 
 
 
 
439
  } else {
440
  // Looking for a list of categories
441
  $limit = $this->getRequest()->getParam('limit', 100);
@@ -443,51 +799,54 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
443
 
444
  $categoriesCollection = Mage::getModel('catalog/category')->getCollection();
445
 
446
- if($level != null) {
447
  $categoriesCollection
448
  ->addAttributeToFilter('level', $level) //we can specify the level of categories to be fetched
449
  ;
450
  }
451
 
452
- if($active != null) {
453
  $categoriesCollection
454
  ->addAttributeToFilter('is_active', 1) //if you want only active categories
455
  ;
456
  }
457
 
458
- if($isAnchor != null) {
459
  $categoriesCollection
460
- ->addAttributeToFilter('is_anchor', 1) // If you want categories which are shown in search facets
461
  ;
462
  }
463
 
464
  $categoriesCollection
465
  ->addAttributeToSelect($attributes)
466
- ->getSelect()->limit($limit, $offset) //we can specify how many categories we want to show on this page
467
  ;
468
 
469
- foreach($categoriesCollection as $category) {
470
  $category = $this->getFormattedCategory($category);
471
- if($category !== null && is_array($category)) {
472
  $categories[] = $category;
473
  }
474
  }
475
-
476
  }
477
 
478
  $this->getResponse()
479
  ->setBody(json_encode(array('categories' => $categories, 'version' => self::API_VERSION)))
480
  ->setHttpResponseCode(200)
481
  ->setHeader('Content-type', 'application/json', true);
482
-
483
- } catch(\Exception $e) {
484
- if($e->getMessage() != null)
485
  $message = $e->getMessage();
486
  else
487
  $message = 'Internal server error';
488
 
489
  $this->getResponse()
490
- ->setBody(json_encode(array('status' => 'error', 'message' => $message, 'version' => self::API_VERSION)))
 
 
 
 
 
491
  ->setHttpResponseCode(500)
492
  ->setHeader('Content-type', 'application/json', true);
493
  }
@@ -496,9 +855,10 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
496
  }
497
 
498
 
499
- public function facetattributesAction() {
 
500
  try {
501
- if(!$this->_authorise()) {
502
  return $this;
503
  }
504
 
@@ -509,9 +869,9 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
509
 
510
  $collection = Mage::getResourceModel('catalog/product_attribute_collection');
511
 
512
- if($isFilterable && is_numeric($isFilterable)){
513
- $collection->addFieldToFilter('is_filterable', (int) $isFilterable);
514
- } else{
515
  // Give only is filterable with results
516
  $collection->addFieldToFilter('is_filterable', 1);
517
  }
@@ -532,20 +892,20 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
532
  // "is_used_for_price_rules",
533
  // "used_in_product_listing"
534
  // );
535
- // //@TODO: Mysql error coming up
536
  // $collection->addFieldToSelect($fieldsToSelect);
537
 
538
  $collection->setOrder('position', 'ASC');
539
- $collection->setPageSize((int) $limit);
540
- $collection->setCurPage((int) $page);
541
  $collection->load();
542
 
543
- if($limit * ($page-1) < $collection->getSize()) {
544
  $allAttrs = array();
545
 
546
  foreach ($collection as $attr) {
547
  $newAttr = array();
548
- if($fields=="all") {
549
  $newAttr['attribute_id'] = $attr->getAttributeId();
550
  $newAttr['is_filterable'] = $attr->getIsFilterable();
551
  $newAttr['attribute_code'] = $attr->getAttributeCode();
@@ -560,7 +920,7 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
560
  $newAttr['is_used_for_promo_rules'] = $attr->getIsUsedForPromoRules();
561
  $newAttr['is_used_for_price_rules'] = $attr->getIsUsedForPriceRules();
562
  $newAttr['used_in_product_listing'] = $attr->getUsedInProductListing();
563
- } else{
564
  $newAttr['attribute_id'] = $attr->getAttributeId();
565
  $newAttr['is_filterable'] = $attr->getIsFilterable();
566
  $newAttr['attribute_code'] = $attr->getAttributeCode();
@@ -575,7 +935,7 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
575
 
576
  $allAttrs[] = $newAttr;
577
  }
578
- } else{
579
  $allAttrs = array();
580
  }
581
 
@@ -583,9 +943,14 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
583
  ->setBody(json_encode(array('attributes' => $allAttrs, 'version' => self::API_VERSION)))
584
  ->setHttpResponseCode(200)
585
  ->setHeader('Content-type', 'application/json', true);
586
- } catch(Exception $e) {
587
  $this->getResponse()
588
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
589
  ->setHttpResponseCode(500)
590
  ->setHeader('Content-type', 'application/json', true);
591
  }
@@ -594,16 +959,17 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
594
  }
595
 
596
 
597
- public function modifyfacetattributeAction() {
 
598
  try {
599
- if(!$this->_authorise()) {
600
  return $this;
601
  }
602
 
603
  $facetData = $this->getRequest()->getParam('newData', false);
604
  $newFacetData = json_decode($facetData);
605
 
606
- if(!$newFacetData){
607
  if ($facetData == "") {
608
  $input = file_get_contents('php://input');
609
  $input = utf8_encode($input);
@@ -611,8 +977,8 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
611
  }
612
  }
613
 
614
- if(!$newFacetData && !$newFacetData->attribute_id)
615
- throw new Exception("Insufficient data");
616
 
617
  // updates the facet
618
  $resourceModel = Mage::getResourceModel('catalog/product_attribute_collection');
@@ -624,25 +990,31 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
624
  foreach ($newFacetData as $key => $value) {
625
  $attributeObj->setData($key, $value);
626
  }
 
627
  $updateStatus = $attributeObj->save();
628
 
629
- if(!$updateStatus)
630
- throw new Exception("Couldn't update");
631
  else
632
  Mage::app()->getCache()->save(null, "sysFacets", array("facets"));
633
 
634
  $this->getResponse()
635
- ->setBody(json_encode(array("status"=>"ok", 'version' => self::API_VERSION)))
636
  ->setHttpResponseCode(200)
637
  ->setHeader('Content-type', 'application/json', true);
638
- } catch(Exception $e) {
639
- if($e->getMessage())
640
  $errorMsg = $e->getMessage();
641
  else
642
  $errorMsg = "Internal server error";
643
 
644
  $this->getResponse()
645
- ->setBody(json_encode(array('status' => 'error', 'message' => $errorMsg, 'version' => self::API_VERSION)))
 
 
 
 
 
646
  ->setHttpResponseCode(500)
647
  ->setHeader('Content-type', 'application/json', true);
648
  }
@@ -651,7 +1023,8 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
651
  }
652
 
653
  // Formats the attribute for save
654
- private function _prepareAttributeForSave($data) {
 
655
  /** @var $helperCatalog Mage_Catalog_Helper_Data */
656
  $helperCatalog = Mage::helper('catalog');
657
 
@@ -666,15 +1039,19 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
666
  if (!isset($data['is_configurable'])) {
667
  $data['is_configurable'] = 0;
668
  }
 
669
  if (!isset($data['is_filterable'])) {
670
  $data['is_filterable'] = 1;
671
  }
 
672
  if (!isset($data['is_filterable_in_search'])) {
673
  $data['is_filterable_in_search'] = 1;
674
  }
 
675
  if (!isset($data['apply_to'])) {
676
  $data['apply_to'] = array();
677
  }
 
678
  // set frontend labels array with store_id as keys
679
  if (isset($data['frontend_label']) && is_array($data['frontend_label'])) {
680
  $labels = array();
@@ -683,13 +1060,16 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
683
  $labelText = $helperCatalog->stripTags($label['label']);
684
  $labels[$storeId] = $labelText;
685
  }
 
686
  $data['frontend_label'] = $labels;
687
  }
 
688
  // set additional fields
689
  if (isset($data['additional_fields']) && is_array($data['additional_fields'])) {
690
  $data = array_merge($data, $data['additional_fields']);
691
  unset($data['additional_fields']);
692
  }
 
693
  //default value
694
  if (!empty($data['default_value'])) {
695
  $data['default_value'] = $helperCatalog->stripTags($data['default_value']);
@@ -699,31 +1079,33 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
699
  }
700
 
701
 
702
- public function addfacetattributeAction() {
 
703
  try {
704
- if(!$this->_authorise()) {
705
  return $this;
706
  }
707
 
708
  $facetData = $this->getRequest()->getParam('newData', false);
709
  $newFacetData = json_decode($facetData);
710
 
711
- if(!$newFacetData){
712
  if ($facetData == "") {
713
  $input = file_get_contents('php://input');
714
  $input = utf8_encode($input);
715
  $newFacetData = json_decode($input)->newData;
716
  }
717
  }
 
718
  $newFacetData = (array)$newFacetData;
719
 
720
  if (!$newFacetData || empty($newFacetData['attribute_code']) || !isset($newFacetData['frontend_label'])) {
721
- throw new Exception("Insufficient data");
722
  }
723
 
724
  //validate attribute_code
725
  if (!preg_match('/^[a-z][a-z_0-9]{0,254}$/', $newFacetData['attribute_code'])) {
726
- throw new Exception("Invalid attribute_code");
727
  }
728
 
729
  /** @var $model Mage_Catalog_Model_Resource_Eav_Attribute */
@@ -734,7 +1116,7 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
734
 
735
  $newFacetData['source_model'] = $helper->getAttributeSourceModelByInputType('multiselect');
736
  $newFacetData['backend_model'] = $helper->getAttributeBackendModelByInputType('multiselect');
737
- if (is_null($model->getIsUserDefined()) || $model->getIsUserDefined() != 0) {
738
  $newFacetData['backend_type'] = $model->getBackendTypeByInput('multiselect');
739
  }
740
 
@@ -752,17 +1134,22 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
752
  Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
753
 
754
  $this->getResponse()
755
- ->setBody(json_encode(array("status"=>"ok", 'version' => self::API_VERSION)))
756
  ->setHttpResponseCode(200)
757
  ->setHeader('Content-type', 'application/json', true);
758
- } catch(Exception $e) {
759
- if($e->getMessage())
760
  $errorMsg = $e->getMessage();
761
  else
762
  $errorMsg = "Internal server error";
763
 
764
  $this->getResponse()
765
- ->setBody(json_encode(array('status' => 'error', 'message' => $errorMsg, 'version' => self::API_VERSION)))
 
 
 
 
 
766
  ->setHttpResponseCode(500)
767
  ->setHeader('Content-type', 'application/json', true);
768
  }
@@ -771,11 +1158,11 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
771
  }
772
 
773
 
774
- public function usersAction() {
 
775
 
776
  try {
777
-
778
- if(!$this->_authorise()) {
779
  return $this;
780
  }
781
 
@@ -795,29 +1182,25 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
795
 
796
  $usersCollection = Mage::getModel('customer/customer')->getCollection();
797
 
798
- if($email != null && strlen($email) > 0) {
799
-
800
  $usersCollection
801
  ->addAttributeToFilter('email', $email);
802
-
803
  } else {
804
-
805
- $created_at_min = $this->getRequest()->getParam('created_at_min');
806
- $created_at_max = $this->getRequest()->getParam('created_at_max');
807
 
808
  $usersCollection->addAttributeToSelect($attributes);
809
 
810
- if($created_at_min != null && strlen($created_at_min) > 0) {
811
- $usersCollection->addAttributeToFilter('created_at', array('from' => $created_at_min));
812
  }
813
 
814
- if($created_at_max != null && strlen($created_at_max) > 0) {
815
- $usersCollection->addAttributeToFilter('created_at', array('to' => $created_at_max));
816
  }
817
 
818
  $usersCollection->getSelect()
819
  ->limit($limit, $offset);
820
-
821
  }
822
 
823
  $users = array();
@@ -838,10 +1221,14 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
838
  ->setBody(json_encode(array('users' => $users, 'version' => self::API_VERSION)))
839
  ->setHttpResponseCode(200)
840
  ->setHeader('Content-type', 'application/json', true);
841
-
842
- } catch(Exception $e) {
843
  $this->getResponse()
844
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
845
  ->setHttpResponseCode(500)
846
  ->setHeader('Content-type', 'application/json', true);
847
  }
@@ -850,168 +1237,485 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
850
 
851
  }
852
 
 
 
 
 
 
 
853
 
854
- public function stockAction() {
 
 
 
 
 
 
 
 
 
855
 
856
- try {
 
 
 
 
 
 
857
 
858
- if(!$this->_authorise()) {
859
- return $this;
 
 
 
 
 
860
  }
861
 
862
- $productId = $this->getRequest()->getParam('pid');
863
- $sku = $this->getRequest()->getParam('sku', 'false') === 'true';
 
 
864
 
 
865
 
866
- if(!$productId || strlen($productId) <= 0) {
 
 
 
 
 
 
 
867
 
868
- $this->getResponse()
869
- ->setBody(json_encode(array('status' => 'error', 'message' => 'product id required', 'version' => self::API_VERSION)))
870
- ->setHttpResponseCode(500)
871
- ->setHeader('Content-type', 'application/json', true);
872
 
873
- } else {
 
 
 
874
 
875
- // load product if sku is given
876
- if($sku) {
877
- $product = Mage::getModel('catalog/product')->loadByAttribute('sku', $productId);
878
- if($product == null) {
879
- $this->getResponse()
880
- ->setBody(json_encode(array('status' => 'error', 'message' => 'invalid sku', 'version' => self::API_VERSION)))
881
- ->setHttpResponseCode(500)
882
- ->setHeader('Content-type', 'application/json', true);
883
- return $this;
 
 
 
 
884
  }
885
- $productId = $product->getId();
886
  }
 
887
 
888
- // get stock info
889
- $stockObj = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
 
 
 
 
 
 
 
 
 
 
 
 
 
890
 
891
- $stock = $stockObj->getQty();
 
892
 
893
- $this->getResponse()
894
- ->setBody(json_encode(array('id' => $productId, 'stock' => $stock, 'version' => self::API_VERSION)))
895
- ->setHttpResponseCode(200)
896
- ->setHeader('Content-type', 'application/json', true);
 
 
 
 
 
897
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
898
  }
899
 
900
- } catch(Exception $e) {
901
  $this->getResponse()
902
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
 
 
 
 
 
903
  ->setHttpResponseCode(500)
904
  ->setHeader('Content-type', 'application/json', true);
905
  }
906
 
907
  return $this;
 
 
 
 
 
908
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
909
  }
910
 
 
 
911
 
912
- private function getFormattedProduct($product, $extras, $debug) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
913
 
914
  $formattedProduct = null;
915
 
916
  try {
917
  $formattedProduct = array(
918
- 'id' => $product->getId(),
919
- 'sku' => $product->getSku(),
920
- 'name' => $product->getName(),
921
- 'cat' => array(),
922
- 'manufacturer' => $product->getAttributeText('manufacturer'),
923
- 'price' => $product->getPrice(),
924
- 'final_price' => $product->getFinalPrice(),
925
- 'special_price' => $product->getSpecialPrice(),
926
- 'image' => $product->getImageUrl(),
927
- 'url' => $product->getProductUrl(),
928
- 'info' => $product->getShortDescription(),
929
- 'status' => $product->getStatus(),
930
- 'type' => $product->getTypeId(),
931
- 'created_at' => $product->getCreatedAt(),
932
- 'updated_at' => $product->getUpdatedAt()
 
 
 
 
 
933
  );
934
- if(!$formattedProduct['manufacturer'] || strlen($formattedProduct['manufacturer']) === 0) {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
935
  $product = Mage::getModel('catalog/product')->load($product->getId());
936
  $formattedProduct['manufacturer'] = $product->getAttributeText('manufacturer');
937
  }
938
 
939
- if($formattedProduct['type'] == "configurable") {
940
- // get associated product ids
941
- $associatedProducts = Mage::getModel('catalog/product_type_configurable')->getChildrenIds($formattedProduct['id']);
942
- $formattedProduct['associated_products'] = $associatedProducts;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943
  }
944
 
945
- // get stock info
946
- $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
947
- $formattedProduct['stock'] = $stock->getQty();
 
 
 
 
 
 
948
 
949
- if($debug) {
950
- $attributes = $product->getAttributes();
951
- foreach($attributes as $key => $value) {
952
- // Sanity check, or else crashes without proper error handling
953
- $existenceCheck = $product->getResource()->getAttribute($key);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
954
 
955
- if($existenceCheck)
956
- $formattedProduct['extras'][$key] = $product->getAttributeText($key);
957
  }
 
 
 
 
 
 
 
 
 
958
  } else {
959
- foreach($extras as $key) {
960
  // Sanity check, or else crashes without proper error handling
961
  $existenceCheck = $product->getResource()->getAttribute($key);
962
 
963
- if($existenceCheck)
964
  $formattedProduct['extras'][$key] = $product->getAttributeText($key);
965
  }
966
  }
967
 
968
  $categories = $product->getCategoryCollection()
969
  ->addAttributeToSelect('id')
970
- ->addAttributeToSelect('name')
971
- ->addAttributeToSelect('path')
972
- ->addAttributeToSelect('level');
973
- foreach($categories as $category) {
974
- $formattedCategory = array();
975
- $formattedCategory['id'] = $category->getId();
976
- $formattedCategory['name'] = $category->getName();
977
- $formattedCategory['level'] = $category->getLevel();
978
- $formattedCategory['path'] = $category->getPath();
979
- $formattedProduct['cat'][$formattedCategory['id']] = $formattedCategory;
 
980
  }
981
 
982
  return $formattedProduct;
983
- } catch(Exception $e) {
984
  return NULL;
985
  }
986
  }
987
 
988
- private function getFormattedCategory($category) {
 
989
 
990
  $formattedCategory = null;
991
 
992
  try {
993
  $formattedCategory = array(
994
- 'id' => $category->getId(),
995
- 'name' => $category->getName(),
996
- 'image' => $category->getImageUrl(),
997
- 'url' => $category->getUrl(),
998
- 'level' => $category->getLevel(),
999
- 'path' => $category->getPath(),
1000
- 'is_anchor' => $category->getIsAnchor(),
1001
- 'is_active' => $category->getIsActive(),
1002
- 'created_at' => $category->getCreatedAt(),
1003
- 'updated_at' => $category->getUpdatedAt()
 
 
1004
  );
1005
-
1006
- } catch(Exception $e) {}
1007
 
1008
  return $formattedCategory;
1009
  }
1010
 
1011
- public function sortbyAction() {
 
1012
 
1013
  try {
1014
- if(!$this->_authorise()) {
1015
  return $this;
1016
  }
1017
 
@@ -1036,22 +1740,31 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1036
 
1037
  foreach ($attributesData as $key => $attributeData) {
1038
  $sortByOptions[] = array(
1039
- "_id"=> $key,
1040
- "name"=> $attributeData,
1041
- "default"=> $key==$defaultSort ? true:false,
1042
- "order"=> $i
1043
  );
1044
  $i++;
1045
  }
1046
 
1047
  $this->getResponse()
1048
- ->setBody(json_encode(array('status' => "ok", 'options' => $sortByOptions, 'version' => self::API_VERSION)))
 
 
 
 
 
1049
  ->setHttpResponseCode(200)
1050
  ->setHeader('Content-type', 'application/json', true);
1051
-
1052
- } catch(Exception $e) {
1053
  $this->getResponse()
1054
- ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
1055
  ->setHttpResponseCode(500)
1056
  ->setHeader('Content-type', 'application/json', true);
1057
  }
@@ -1059,15 +1772,16 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1059
  return $this;
1060
  }
1061
 
1062
- public function choicepageAction() {
1063
- try{
1064
- if(!$this->_authorise()) {
 
1065
  return $this;
1066
  }
1067
 
1068
  $responseObj = array();
1069
-
1070
- if ($_SERVER["REQUEST_METHOD"] == "POST") {
1071
  // Create Choice page
1072
  // Expects title, url_path and content
1073
 
@@ -1077,12 +1791,13 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1077
  $input = utf8_encode($input);
1078
  $pageData = json_encode(json_decode($input)->data);
1079
  }
 
1080
  $pageData = json_decode($pageData);
1081
  $urlPath = $pageData->url_path;
1082
 
1083
- if(!$urlPath){
1084
  // What can this poor guy do without the path?
1085
- throw new Exception("No urlPath");
1086
  }
1087
 
1088
  // Ensure no other existing page contains the same URL path or say "identifier"
@@ -1093,18 +1808,20 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1093
  // $existingPages = Mage::getModel('cms/page')->load($collection->getFirstItem()->getId());
1094
 
1095
  // There can be multiple pages with same url path, but different store scope. Let's disable all
1096
- foreach ($collection as $existingPage){
1097
  // Page already exists && is_active
1098
- if($existingPage->getId()) {
1099
  // Delete all other pages having same URL
1100
  // and then continue adding our new page
1101
- // $this->updateChoiceUrl(false, $existingPage->getId(), array("is_active" => 0, "identifier" => $urlPath));
 
1102
  $existingPage->delete();
1103
  }
1104
  }
1105
 
1106
  // Setting default content if not provided
1107
- $pageContent = (!isset($pageData->content)) ? "<script>window._caichoicePage = true;</script><div id='caichoicePage'></div>" : $pageData->content;
 
1108
 
1109
  // Setting default Title if not available
1110
  $pageTitle = (!isset($pageData->title)) ? "Choice.AI" : $pageData->title;
@@ -1126,7 +1843,7 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1126
 
1127
  $responseObj["status"] = "ok";
1128
  $responseObj["id"] = $choicePage->getId();
1129
- } else if ($_SERVER["REQUEST_METHOD"] == "PUT") {
1130
  // Update Choice page's URL path
1131
  $newPageData = $this->getRequest()->getParam('data');
1132
 
@@ -1135,17 +1852,18 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1135
  $input = utf8_encode($input);
1136
  $newPageData = json_encode(json_decode($input)->data);
1137
  }
 
1138
  $newPageData = json_decode($newPageData);
1139
 
1140
  if ($newPageData == NULL || !isset($newPageData->page_id)) {
1141
- throw new Exception();
1142
  }
1143
 
1144
  $pageId = $newPageData->page_id;
1145
 
1146
  $this->updateChoiceUrl($newPageData, $pageId);
1147
  $responseObj["status"] = "ok";
1148
- } else if ($_SERVER["REQUEST_METHOD"] == "DELETE") {
1149
  $newPageData = $this->getRequest()->getParam('data');
1150
 
1151
  if ($newPageData == "") {
@@ -1153,17 +1871,18 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1153
  $input = utf8_encode($input);
1154
  $newPageData = json_encode(json_decode($input)->data);
1155
  }
 
1156
  $newPageData = json_decode($newPageData);
1157
 
1158
  if ($newPageData == NULL || !isset($newPageData->page_id)) {
1159
- throw new Exception();
1160
  }
1161
 
1162
  $pageId = $newPageData->page_id;
1163
 
1164
  $pagesCollection = Mage::getModel('cms/page')
1165
  ->getCollection()
1166
- ->addFieldToFilter('page_id', array("eq"=> $pageId));
1167
  $pageData = Mage::getModel('cms/page')->load($pagesCollection->getFirstItem()->getId());
1168
  $pageData->delete();
1169
  // Mage::app()->getStore()->resetConfig();
@@ -1179,9 +1898,14 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1179
  ->setBody(json_encode($responseObj))
1180
  ->setHttpResponseCode(200)
1181
  ->setHeader('Content-type', 'application/json', true);
1182
- } catch(Exception $e) {
1183
  $this->getResponse()
1184
- ->setBody(json_encode(array('emsg'=> $e->getMessage(), 'status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
 
 
 
 
 
1185
  ->setHttpResponseCode(500)
1186
  ->setHeader('Content-type', 'application/json', true);
1187
  }
@@ -1189,9 +1913,10 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1189
  return this;
1190
  }
1191
 
1192
- private function updateChoiceUrl($newPageData, $pageId, $dataToUpdate=false){
 
1193
  // Doesn't allow update without "identifier" field :/
1194
- if(!$dataToUpdate) {
1195
  // Update case
1196
  $dataToUpdate = array();
1197
 
@@ -1202,12 +1927,12 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1202
  $collection = Mage::getModel('cms/page')
1203
  ->getCollection()
1204
  ->addFieldToFilter('identifier', $urlPath)
1205
- ->addFieldToFilter('page_id', array("neq"=> $pageId));
1206
  $page = Mage::getModel('cms/page')->load($collection->getFirstItem()->getId());
1207
 
1208
  // URL path already being used?
1209
  if ($page->getId())
1210
- throw new Exception();
1211
  else
1212
  $dataToUpdate['identifier'] = $urlPath;
1213
  }
@@ -1226,11 +1951,11 @@ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_
1226
  // Ensuring proper scope per update
1227
  $dataToUpdate['stores'] = array(0);
1228
 
1229
- if(!isset($dataToUpdate['identifier'])){
1230
  // Get existing "identifier"
1231
  $pagesCollection = Mage::getModel('cms/page')
1232
  ->getCollection()
1233
- ->addFieldToFilter('page_id', array("eq"=> $pageId));
1234
  $pageData = Mage::getModel('cms/page')->load($pagesCollection->getFirstItem()->getId());
1235
 
1236
  $dataToUpdate['identifier'] = $pageData->getIdentifier();
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
 
10
+ class ChoiceAI_Personalisation_ApiController extends Mage_Core_Controller_Front_Action
11
+ {
12
 
13
  const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
14
  const CONFIG_KEY = 'choiceai_personalisation/settings/config';
15
+ const API_VERSION = 4;
16
 
17
+ public function _authorise()
18
+ {
19
 
20
+ $apiKey = Mage::getStoreConfig(self::CONFIG_API_KEY);
21
 
22
  // Check for api access
23
+ if (!$apiKey && strlen($apiKey) === 0) {
24
  // Api access disabled
25
  $this->getResponse()
26
+ ->setBody(
27
+ json_encode(
28
+ array('status' => 'error', 'message' => 'API access disabled', 'version' =>
29
+ self::API_VERSION)
30
+ )
31
+ )
32
  ->setHttpResponseCode(403)
33
  ->setHeader('Content-type', 'application/json', true);
34
  return false;
45
  Mage::log('Unable to extract authorization header from request', null, 'choiceai.log');
46
  // Internal server error
47
  $this->getResponse()
48
+ ->setBody(
49
+ json_encode(
50
+ array('status' => 'error', 'message' => 'Internal server error, Authorization
51
+ header not found', 'version' => self::API_VERSION)
52
+ )
53
+ )
54
  ->setHttpResponseCode(500)
55
  ->setHeader('Content-type', 'application/json', true);
56
  return false;
57
  }
58
 
59
+ if (trim($authHeader) !== trim($apiKey)) {
60
  // Api access denied
61
  $this->getResponse()
62
+ ->setBody(
63
+ json_encode(
64
+ array('status' => 'error', 'message' => 'Api access denied',
65
+ 'version' => self::API_VERSION)
66
+ )
67
+ )
68
  ->setHttpResponseCode(401)
69
  ->setHeader('Content-type', 'application/json', true);
70
  return false;
74
 
75
  }
76
 
77
+ public function taxAction()
78
+ {
79
  try {
80
+ if (!$this->_authorise()) {
81
  return $this;
82
  }
83
 
84
+ $responseObj = array();
85
+ $rates = Mage::getModel('tax/calculation_rate')
86
+ ->getCollection();
87
+ $taxRates = array();
88
+ foreach ($rates as $rate) {
89
+ $taxRate = array(
90
+ "name" => $rate->getCode(),
91
+ "country_id" => $rate->getTaxCountryId(),
92
+ "postcode" => $rate->getTaxPostcode(),
93
+ "state_id" => $rate->getTaxRegionId(),
94
+ "zip_from" => $rate->getZipFrom(),
95
+ "zip_is_range" => $rate->getZipIsRange(),
96
+ "zip_to" => $rate->getZipTo(),
97
+ "rate" => $rate->getRate()
98
+ );
99
+ $taxRate["country"] = Mage::app()->getLocale()->getCountryTranslation($taxRate["country_id"]);
100
+ if ($taxRate["state_id"] != "0") {
101
+ $region = Mage::getModel('directory/region')->load($taxRate["state_id"]);
102
+ $taxRate["state"] = $region->getName();
103
+ $taxRate["state_code"] = $region->getCode();
104
+ }
105
+
106
+ $titles = $rate->getTitles();
107
+ $taxTitles = array();
108
+ foreach ($titles as $title) {
109
+ $taxTitle = array(
110
+ "id" => $title->getId(),
111
+ "value" => $title->getValue()
112
+ );
113
+ $taxTitles[$title->getStoreId()] = $taxTitle;
114
+ }
115
+
116
+ $taxRate["titles"] = $taxTitles;
117
+ $taxRates[$rate->getId()] = $taxRate;
118
+ }
119
+
120
+ $responseObj["tax_rates"] = $taxRates;
121
+ $customerClasses = Mage::getModel('tax/class')
122
+ ->getCollection()
123
+ ->setClassTypeFilter(Mage_Tax_Model_Class::TAX_CLASS_TYPE_CUSTOMER)
124
+ ->toOptionArray();
125
+ $defaultCtc = array();
126
+ foreach ($customerClasses as $customerClass) {
127
+ $defaultTax = array(
128
+ "name" => $customerClass["label"]
129
+ );
130
+ $defaultCtc[$customerClass["value"]] = $defaultTax;
131
+ }
132
+
133
+ $responseObj["default_ctc"] = $defaultCtc;
134
+ $productClasses = Mage::getModel('tax/class')
135
+ ->getCollection()
136
+ ->setClassTypeFilter(Mage_Tax_Model_Class::TAX_CLASS_TYPE_PRODUCT)
137
+ ->toOptionArray();
138
+ $defaultPtc = array();
139
+ foreach ($productClasses as $productClass) {
140
+ $defaultTax = array(
141
+ "name" => $productClass["label"]
142
+ );
143
+ $defaultPtc[$productClass["value"]] = $defaultTax;
144
+ }
145
+
146
+ $responseObj["default_ptc"] = $defaultPtc;
147
+ $collection = Mage::getModel('tax/calculation_rule')->getCollection();
148
+ if ($collection->getSize()) {
149
+ $collection->addCustomerTaxClassesToResult()
150
+ ->addProductTaxClassesToResult()
151
+ ->addRatesToResult();
152
+ }
153
+
154
+ $taxRules = array();
155
+ if ($collection->getSize()) {
156
+ foreach ($collection as $rule) {
157
+ $taxRule = $rule->getData();
158
+ $taxRules[$rule->getId()] = $taxRule;
159
+ }
160
+ }
161
+
162
+ $responseObj['tax_rules'] = $taxRules;
163
+ $this->getResponse()
164
+ ->setBody(json_encode($responseObj))
165
+ ->setHttpResponseCode(200)
166
+ ->setHeader('Content-type', 'application/json', true);
167
+ } catch (Exception $e) {
168
+ $this->getResponse()
169
+ ->setBody(json_encode(array('status' => 'error', 'message' => 'Internal server error', 'version' => self::API_VERSION)))
170
+ ->setHttpResponseCode(500)
171
+ ->setHeader('Content-type', 'application/json', true);
172
+ }
173
+
174
+ return $this;
175
+ }
176
+
177
+ public function configAction()
178
+ {
179
+ try {
180
+ if (!$this->_authorise()) {
181
+ return $this;
182
+ }
183
+
184
+ $server = Mage::app()->getRequest()->getServer();
185
  $responseObj = array();
186
 
187
+ if ($server["REQUEST_METHOD"] == "GET") {
188
+ $storeConfig = Mage::getStoreConfig(self::CONFIG_KEY);
189
  $responseObj["status"] = "ok";
190
+ $responseObj["config"] = json_decode($storeConfig);
191
+ } else if ($server["REQUEST_METHOD"] == "PUT") {
192
+ $storeConfig = $this->getRequest()->getParam('config');
193
+ if ($storeConfig == "") {
194
  $input = file_get_contents('php://input');
195
  $input = utf8_encode($input);
196
+ $storeConfig = json_encode(json_decode($input)->config);
197
  }
198
+
199
+ $storeConfigJson = json_decode($storeConfig);
200
+ if ($storeConfigJson == NULL) {
201
+ Mage::throwException("Store config is null");
202
  }
203
+
204
+ Mage::getModel('core/config')->saveConfig(self::CONFIG_KEY, $storeConfig);
205
  Mage::app()->getStore()->resetConfig();
206
  $responseObj["status"] = "ok";
207
  } else {
209
  $responseObj['message'] = 'Invalid request';
210
  }
211
 
212
+ if (isset($server['REQUEST_SCHEME']) && isset($server['SERVER_NAME'])) {
213
+ $storeUrl = $server['REQUEST_SCHEME'] . "://" . $server['SERVER_NAME'];
214
+ } else {
215
  $storeUrl = Mage::getBaseUrl();
216
  }
217
+
218
  $responseObj['store_url'] = $storeUrl;
219
+ $responseObj['base_url'] = Mage::getBaseUrl();
220
  $responseObj['api_version'] = self::API_VERSION;
221
+ $responseObj['plugin_version'] = (string)Mage::getConfig()
222
+ ->getNode('modules/ChoiceAI_Personalisation/version');
223
  $responseObj['magento_version'] = Mage::getVersion();
224
+ $currencyCode = Mage::app()->getStore()->getCurrentCurrencyCode();
225
+ $responseObj['currency'] = Mage::app()->getLocale()->currency($currencyCode)->getSymbol();
226
+ $responseObj['currency_code'] = $currencyCode;
227
+ $responseObj['visibility_options'] = Mage::getSingleton('catalog/product_visibility')
228
+ ->getOptionArray();
229
+ $responseObj['formatted_price'] = Mage::helper('core')->currency(1234567890.99, true, false);
230
+ $responseObj['store_structure'] = Mage::getSingleton('adminhtml/system_store')
231
+ ->getStoresStructure();
232
+ $allStores = array();
233
+ $everyStore = Mage::app()->getStores();
234
+ foreach ($everyStore as $eachStore => $val) {
235
+ $currentStore = Mage::app()->getStore($eachStore);
236
+ // Gets the current store's details
237
+ $storeId = $currentStore->getStoreId();
238
+ $store = array(
239
+ "code" => $currentStore->getCode(),
240
+ "website_id" => $currentStore->getWebsiteId(),
241
+ "group_id" => $currentStore->getGroupId(),
242
+ "name" => $currentStore->getName(),
243
+ "is_active" => $currentStore->getIsActive(),
244
+ "locale_code" => Mage::getStoreConfig(
245
+ Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE,
246
+ $storeId
247
+ ),
248
+ "time_zone" => Mage::getStoreConfig(
249
+ Mage_Core_Model_Locale::XML_PATH_DEFAULT_TIMEZONE,
250
+ $storeId
251
+ ),
252
+ "secure_url" => Mage::getStoreConfig(
253
+ Mage_Core_Model_Store::XML_PATH_SECURE_BASE_LINK_URL,
254
+ $storeId
255
+ ),
256
+ "unsecure_url" => Mage::getStoreConfig(
257
+ Mage_Core_Model_Store::XML_PATH_UNSECURE_BASE_LINK_URL,
258
+ $storeId
259
+ )
260
+ );
261
+ $allStores[$storeId] = $store;
262
+ }
263
+
264
+ $responseObj['store_details'] = $allStores;
265
+ $responseObj['default_store_id'] = Mage::app()->getWebsite()->getDefaultGroup()->getDefaultStoreId();
266
+ $responseObj['layered_navigation'] = Mage::getStoreConfig('catalog/layered_navigation');
267
+ $responseObj['currency_options'] = Mage::getStoreConfig('currency/options');
268
+ $responseObj['store_information'] = Mage::getStoreConfig('general/store_information');
269
+ $responseObj['layered_navigation']['one_price_interval'] = $responseObj['layered_navigation']
270
+ ['one_price_interval'] == "1";
271
+ $responseObj['layered_navigation']['display_product_count'] = $responseObj['layered_navigation']
272
+ ['display_product_count'] == "1";
273
  $this->getResponse()
274
  ->setBody(json_encode($responseObj))
275
  ->setHttpResponseCode(200)
276
  ->setHeader('Content-type', 'application/json', true);
277
+ } catch (Exception $e) {
 
278
  $this->getResponse()
279
+ ->setBody(
280
+ json_encode(
281
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
282
+ self::API_VERSION)
283
+ )
284
+ )
285
  ->setHttpResponseCode(500)
286
  ->setHeader('Content-type', 'application/json', true);
287
  }
289
  return $this;
290
  }
291
 
292
+ public function ordersAction()
293
+ {
294
  try {
295
+ if (!$this->_authorise()) {
296
  return $this;
297
  }
298
 
299
  $sections = explode('/', trim($this->getRequest()->getPathInfo(), '/'));
300
 
301
+ if (isset($sections[3])) {
302
  // Looking for a specific order
303
  $orderId = $sections[3];
304
 
306
 
307
  $extras = $this->getRequest()->getParam('extras');
308
  $debug = $this->getRequest()->getParam('mwdebug', 'false') === 'true';
309
+ if ($extras && $extras !== "") {
310
  $extras = explode(',', $extras);
311
+ $count = count($extras);
312
+ for ($i = 0; $i < $count; $i++) {
313
  $extras[$i] = trim($extras[$i]);
314
  }
315
  }
318
 
319
  $orderItems = $order->getItemsCollection()->load();
320
 
321
+ foreach ($orderItems as $key => $orderItem) {
322
  $items[] = array(
323
+ 'name' => $orderItem->getName(),
324
+ 'pid' => $orderItem->getProductId(),
325
+ 'sku' => $orderItem->getSku(),
326
+ 'qty' => $orderItem->getQtyOrdered(),
327
+ 'price' => $orderItem->getPrice()
328
  );
329
  }
330
 
335
  );
336
 
337
  $attributes = $order->debug();
338
+ if ($debug) {
339
  $responseObj['extras'] = $attributes;
340
  } else {
341
+ foreach ($extras as $key) {
342
  $responseObj['extras'][$key] = $attributes[$key];
343
  }
344
  }
351
  } else {
352
  // Looking for a list of orders
353
  $currentTime = time();
354
+ $fromDate = $this->getRequest()
355
+ ->getParam('fromDate', date('Y-m-d', ($currentTime - 86400)));
356
  $toDate = $this->getRequest()->getParam('toDate', date('Y-m-d', $currentTime));
357
 
358
  $orders = array();
363
  ->addAttributeToSelect('created_at')
364
  ->addAttributeToSelect('increment_id')
365
  ->addAttributeToSelect('status')
366
+ ->addAttributeToFilter('created_at', array('from' => $fromDate, 'to' => $toDate));
 
367
 
368
  foreach ($ordersCollection as $order) {
369
  $orders[] = array(
370
+ 'order_id' => $order->getIncrementId(),
371
+ 'status' => $order->getStatus(),
372
+ 'email' => $order->getCustomerEmail(),
373
+ 'created_at' => $order->getCreatedAt()
374
  );
375
  }
376
 
377
  $this->getResponse()
378
+ ->setBody(
379
+ json_encode(
380
+ array('orders' => $orders, 'fromDate' => $fromDate, 'toDate' => $toDate,
381
+ 'version' => self::API_VERSION)
382
+ )
383
+ )
384
  ->setHttpResponseCode(200)
385
  ->setHeader('Content-type', 'application/json', true);
386
  }
387
+ } catch (Exception $e) {
388
  $this->getResponse()
389
+ ->setBody(
390
+ json_encode(
391
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
392
+ self::API_VERSION)
393
+ )
394
+ )
395
  ->setHttpResponseCode(500)
396
  ->setHeader('Content-type', 'application/json', true);
397
  }
399
  return $this;
400
  }
401
 
402
+ public function productattributesAction()
403
+ {
404
  try {
405
+ if (!$this->_authorise()) {
406
  return $this;
407
  }
408
 
409
  $sections = explode('/', trim($this->getRequest()->getPathInfo(), '/'));
410
 
411
+ if (!isset($sections[3])) {
412
  // product id
413
+ Mage::throwException("No product Id found");
414
  }
415
 
416
  $productId = $sections[3];
417
 
418
  $product = Mage::getModel('catalog/product')->load($productId);
419
 
420
+ $productInfo = array();
421
 
422
+ $productInfo["is_available"] = $product->isAvailable();
423
+ $productInfo["name"] = $product->getName();
424
+ $productInfo["id"] = $product->getId();
425
+ $productInfo["sku"] = $product->getSku();
426
+ $productInfo["price"] = $product->getPrice();
427
+ $productInfo["final_price"] = $product->getFinalPrice();
428
+ $productInfo["special_price"] = $product->getSpecialPrice();
429
+ $productInfo["type"] = $product->getTypeId();
430
 
431
  $variants = array();
432
  $options = array();
433
 
434
  if ($product->getTypeId() == "configurable") {
 
435
  $productAttributeOptions = $product->getTypeInstance(true)->getConfigurableAttributesAsArray($product);
436
  $attributeTypes = array();
437
 
438
  foreach ($productAttributeOptions as $productAttribute) {
 
439
  $attributes = array();
440
  foreach ($productAttribute['values'] as $attribute) {
441
  $attributes[] = array(
454
  );
455
 
456
  $attributeTypes[] = $attributeType;
 
457
  }
458
 
459
  $associatedProducts = $product->getTypeInstance()->getUsedProducts();
460
  foreach ($associatedProducts as $associatedProduct) {
 
461
  $variant = array();
462
  $variant["is_available"] = $associatedProduct->isAvailable();
463
  $variant["id"] = $associatedProduct->getId();
476
  }
477
 
478
  $this->getResponse()
479
+ ->setBody(
480
+ json_encode(
481
+ array('product' => $productInfo, 'variants' => $variants, 'options' => $options,
482
+ 'version' => self::API_VERSION)
483
+ )
484
+ )
485
  ->setHttpResponseCode(200)
486
  ->setHeader('Content-type', 'application/json', true);
487
+ } catch (Exception $e) {
488
  $this->getResponse()
489
+ ->setBody(
490
+ json_encode(
491
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
492
+ self::API_VERSION)
493
+ )
494
+ )
495
+ ->setHttpResponseCode(500)
496
+ ->setHeader('Content-type', 'application/json', true);
497
+ }
498
+
499
+ return $this;
500
+ }
501
+
502
+ public function urlsAction()
503
+ {
504
+
505
+ try {
506
+ if (!$this->_authorise()) {
507
+ return $this;
508
+ }
509
+
510
+ // $urls = array();
511
+ // $path = $this->getRequest()->getParam('path');
512
+ // $debug = $this->getRequest()->getParam('mwdebug', 'false') === 'true';
513
+
514
+ $urls = array();
515
+
516
+ //$pathData = Mage::getSingleton('core/factory')->getUrlRewriteInstance()->loadByRequestPath($path);
517
+
518
+ $this->getResponse()
519
+ ->setBody(json_encode(array('urls' => $urls, 'version' => self::API_VERSION)))
520
+ ->setHttpResponseCode(200)
521
+ ->setHeader('Content-type', 'application/json', true);
522
+ } catch (Exception $e) {
523
+ $this->getResponse()
524
+ ->setBody(
525
+ json_encode(
526
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
527
+ self::API_VERSION)
528
+ )
529
+ )
530
+ ->setHttpResponseCode(500)
531
+ ->setHeader('Content-type', 'application/json', true);
532
+ }
533
+
534
+ return $this;
535
+
536
+ }
537
+
538
+
539
+ protected function getMostViewedProducts()
540
+ {
541
+ // number of products to display
542
+ $productCount = 5;
543
+
544
+ // store ID
545
+ $storeId = Mage::app()->getStore()->getId();
546
+
547
+ // get today and last 30 days time
548
+ $today = time();
549
+ $last = $today - (60 * 60 * 24 * 30);
550
+
551
+ $from = date("Y-m-d", $last);
552
+ $to = date("Y-m-d", $today);
553
+
554
+ // get most viewed products for last 30 days
555
+ $products = Mage::getResourceModel('reports/product_collection')
556
+ ->addAttributeToSelect('*')
557
+ ->setStoreId($storeId)
558
+ ->addStoreFilter($storeId)
559
+ ->addViewsCount()
560
+ ->addViewsCount($from, $to)
561
+ ->setPageSize($productCount);
562
+
563
+ return $products;
564
+ }
565
+
566
+ public function reportsAction()
567
+ {
568
+
569
+ try {
570
+ if (!$this->_authorise()) {
571
+ return $this;
572
+ }
573
+
574
+ $urls = array();
575
+ $path = $this->getRequest()->getParam('report');
576
+ $debug = $this->getRequest()->getParam('mwdebug', 'false') === 'true';
577
+ $data = $this->getMostViewedProducts();
578
+
579
+ $this->getResponse()
580
+ ->setBody(json_encode(array('data' => $data, 'version' => self::API_VERSION)))
581
+ ->setHttpResponseCode(200)
582
+ ->setHeader('Content-type', 'application/json', true);
583
+ } catch (Exception $e) {
584
+ $this->getResponse()
585
+ ->setBody(
586
+ json_encode(
587
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
588
+ self::API_VERSION)
589
+ )
590
+ )
591
  ->setHttpResponseCode(500)
592
  ->setHeader('Content-type', 'application/json', true);
593
  }
594
+
595
  return $this;
596
+
597
  }
598
 
599
+ public function productsAction()
600
+ {
601
  try {
602
+ if (!$this->_authorise()) {
603
  return $this;
604
  }
605
 
611
  'sku',
612
  'image',
613
  'manufacturer',
614
+ 'visibility',
615
+ 'url_key',
616
+ 'url_path',
617
  'price',
618
  'final_price',
619
  'special_price',
621
  );
622
 
623
  $extras = $this->getRequest()->getParam('extras');
624
+ $fields = $this->getRequest()->getParam('fields');
625
+ $override = $this->getRequest()->getParam('override');
626
+ $attributeSetId = $this->getRequest()->getParam('attributeSetId');
627
+ $skusAlso = $this->getRequest()->getParam('skusAlso', 'false') === 'true';
628
+ $disabledAlso = $this->getRequest()->getParam('disabledAlso', 'false') === 'true';
629
  $debug = $this->getRequest()->getParam('mwdebug', 'false') === 'true';
630
 
631
+ if ($override && $override !== "") {
632
+ $override = explode(',', $override);
633
+ if (!empty($override)) {
634
+ $overrideAttributes = array();
635
+ $size = count($override);
636
+ for ($i = 0; $i < $size; $i++) {
637
+ $override[$i] = trim($override[$i]);
638
+ $overrideAttributes[] = $override[$i];
639
+ }
640
+
641
+ if (!empty($overrideAttributes)) {
642
+ $attributes = $overrideAttributes;
643
+ }
644
+ }
645
+ }
646
+
647
+ if ($fields && $fields != "") {
648
+ $fields = explode(',', $fields);
649
+ $size = count($fields);
650
+ for ($i = 0; $i < $size; $i++) {
651
+ $fields[$i] = trim($fields[$i]);
652
+ }
653
+ }
654
+
655
+ if ($extras && $extras != "") {
656
  $extras = explode(',', $extras);
657
+ $size = count($extras);
658
+ for ($i = 0; $i < $size; $i++) {
659
  $extras[$i] = trim($extras[$i]);
660
  $attributes[] = $extras[$i];
661
  }
662
  }
663
 
664
+ $productId = null;
665
+ if (isset($sections[3])) {
666
  // Looking for a specific product
667
  $productId = $sections[3];
668
+ if ($productId != "count") {
669
+ $product = Mage::getModel('catalog/product')->load($productId);
670
 
671
+ $product = $this->getFormattedProduct($product, $extras, $debug, $fields);
672
+ if ($product !== null) {
673
+ $products[] = $product;
674
+ } else {
675
+ Mage::throwException("Failed to fetch the product");
676
+ }
 
677
  }
678
+ }
679
 
680
+ if (!$productId || $productId == "count") {
681
  // Looking for a list of products
682
  $limit = $this->getRequest()->getParam('limit', 100);
683
  $offset = $this->getRequest()->getParam('offset', 1);
684
 
685
  $productsCollection = Mage::getModel('catalog/product')->getCollection();
686
 
687
+ $productsCollection->addAttributeToSelect($attributes);
688
  // Get only enabled products
689
+ if (!$disabledAlso) {
690
+ $productsCollection->addAttributeToFilter(
691
+ 'status', array('eq' =>
692
+ Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
693
+ );
694
+ }
695
 
696
+ if ($attributeSetId) {
697
+ $productsCollection->addFieldToFilter('attribute_set_id', $attributeSetId);
 
 
 
 
 
698
  }
699
 
700
+ if (!$skusAlso) {
701
+ Mage::getSingleton('catalog/product_visibility')
702
+ ->addVisibleInSiteFilterToCollection($productsCollection);
703
+ }
704
 
705
+ if ($productId == "count") {
706
+ $product["count"] = $productsCollection->getSize();
707
+ $products[] = $product;
708
+ } else {
709
+ //we can specify how many products we want to show on this page
710
+ $productsCollection->getSelect()->limit($limit, $offset);
711
+
712
+ foreach ($productsCollection as $product) {
713
+ $product = $this->getFormattedProduct($product, $extras, false, $fields);
714
+ if ($product !== null) {
715
+ $products[] = $product;
716
+ } else {
717
+ Mage::throwException("Failed to fetch the product");
718
+ }
719
+ }
720
+ }
721
+ }
722
 
723
  $this->getResponse()
724
+ ->setBody(json_encode(array('products' => $products, 'version' => self::API_VERSION)))
725
  ->setHttpResponseCode(200)
726
  ->setHeader('Content-type', 'application/json', true);
727
+ } catch (Exception $e) {
 
 
728
  $this->getResponse()
729
+ ->setBody(
730
+ json_encode(
731
+ array('status' => 'error', 'message' => 'Internal server error',
732
+ 'version' => self::API_VERSION)
733
+ )
734
+ )
735
  ->setHttpResponseCode(500)
736
  ->setHeader('Content-type', 'application/json', true);
737
  }
740
  }
741
 
742
 
743
+ public function categoriesAction()
744
+ {
745
  try {
746
+ if (!$this->_authorise()) {
747
  return $this;
748
  }
749
 
756
  'path',
757
  'is_anchor',
758
  'is_active',
759
+ 'include_in_menu',
760
  'created_at',
761
  'updated_at'
762
  );
768
  $active = $this->getRequest()->getParam('active', 'false') === 'true';
769
  $isAnchor = $this->getRequest()->getParam('is_anchor', 'false') === 'true';
770
 
771
+ if ($level && $level !== "") {
772
+ $level = (int)$level;
773
  } else {
774
  $level = null;
775
  }
776
 
777
+ if (isset($sections[3])) {
778
  // Looking for a specific category
779
  $categoryId = $sections[3];
780
+ if ($categoryId == "count") {
781
+ $categoriesCollection = Mage::getResourceModel('catalog/category_collection');
782
+ $category = array();
783
+ $category["count"] = $categoriesCollection->getSize();
 
784
  $categories[] = $category;
785
+ } else {
786
+ $category = Mage::getModel('catalog/category')->load($categoryId);
 
787
 
788
+ $category = $this->getFormattedCategory($category);
789
+ if ($category !== null && $category["id"] != null && is_array($category)) {
790
+ $categories[] = $category;
791
+ } else {
792
+ Mage::throwException("Category " . $categoryId . " not found");
793
+ }
794
+ }
795
  } else {
796
  // Looking for a list of categories
797
  $limit = $this->getRequest()->getParam('limit', 100);
799
 
800
  $categoriesCollection = Mage::getModel('catalog/category')->getCollection();
801
 
802
+ if ($level != null) {
803
  $categoriesCollection
804
  ->addAttributeToFilter('level', $level) //we can specify the level of categories to be fetched
805
  ;
806
  }
807
 
808
+ if ($active != null) {
809
  $categoriesCollection
810
  ->addAttributeToFilter('is_active', 1) //if you want only active categories
811
  ;
812
  }
813
 
814
+ if ($isAnchor != null) {
815
  $categoriesCollection
816
+ ->addAttributeToFilter('is_anchor', 1) // categories which are shown in search facets
817
  ;
818
  }
819
 
820
  $categoriesCollection
821
  ->addAttributeToSelect($attributes)
822
+ ->getSelect()->limit($limit, $offset) //specify how many categories we want to show on this page
823
  ;
824
 
825
+ foreach ($categoriesCollection as $category) {
826
  $category = $this->getFormattedCategory($category);
827
+ if ($category !== null && is_array($category)) {
828
  $categories[] = $category;
829
  }
830
  }
 
831
  }
832
 
833
  $this->getResponse()
834
  ->setBody(json_encode(array('categories' => $categories, 'version' => self::API_VERSION)))
835
  ->setHttpResponseCode(200)
836
  ->setHeader('Content-type', 'application/json', true);
837
+ } catch (Exception $e) {
838
+ if ($e->getMessage() != null)
 
839
  $message = $e->getMessage();
840
  else
841
  $message = 'Internal server error';
842
 
843
  $this->getResponse()
844
+ ->setBody(
845
+ json_encode(
846
+ array('status' => 'error', 'message' => $message, 'version'
847
+ => self::API_VERSION)
848
+ )
849
+ )
850
  ->setHttpResponseCode(500)
851
  ->setHeader('Content-type', 'application/json', true);
852
  }
855
  }
856
 
857
 
858
+ public function facetattributesAction()
859
+ {
860
  try {
861
+ if (!$this->_authorise()) {
862
  return $this;
863
  }
864
 
869
 
870
  $collection = Mage::getResourceModel('catalog/product_attribute_collection');
871
 
872
+ if ($isFilterable && is_numeric($isFilterable)) {
873
+ $collection->addFieldToFilter('is_filterable', (int)$isFilterable);
874
+ } else {
875
  // Give only is filterable with results
876
  $collection->addFieldToFilter('is_filterable', 1);
877
  }
892
  // "is_used_for_price_rules",
893
  // "used_in_product_listing"
894
  // );
895
+ // //TO DO: Mysql error coming up
896
  // $collection->addFieldToSelect($fieldsToSelect);
897
 
898
  $collection->setOrder('position', 'ASC');
899
+ $collection->setPageSize((int)$limit);
900
+ $collection->setCurPage((int)$page);
901
  $collection->load();
902
 
903
+ if ($limit * ($page - 1) < $collection->getSize()) {
904
  $allAttrs = array();
905
 
906
  foreach ($collection as $attr) {
907
  $newAttr = array();
908
+ if ($fields == "all") {
909
  $newAttr['attribute_id'] = $attr->getAttributeId();
910
  $newAttr['is_filterable'] = $attr->getIsFilterable();
911
  $newAttr['attribute_code'] = $attr->getAttributeCode();
920
  $newAttr['is_used_for_promo_rules'] = $attr->getIsUsedForPromoRules();
921
  $newAttr['is_used_for_price_rules'] = $attr->getIsUsedForPriceRules();
922
  $newAttr['used_in_product_listing'] = $attr->getUsedInProductListing();
923
+ } else {
924
  $newAttr['attribute_id'] = $attr->getAttributeId();
925
  $newAttr['is_filterable'] = $attr->getIsFilterable();
926
  $newAttr['attribute_code'] = $attr->getAttributeCode();
935
 
936
  $allAttrs[] = $newAttr;
937
  }
938
+ } else {
939
  $allAttrs = array();
940
  }
941
 
943
  ->setBody(json_encode(array('attributes' => $allAttrs, 'version' => self::API_VERSION)))
944
  ->setHttpResponseCode(200)
945
  ->setHeader('Content-type', 'application/json', true);
946
+ } catch (Exception $e) {
947
  $this->getResponse()
948
+ ->setBody(
949
+ json_encode(
950
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
951
+ self::API_VERSION)
952
+ )
953
+ )
954
  ->setHttpResponseCode(500)
955
  ->setHeader('Content-type', 'application/json', true);
956
  }
959
  }
960
 
961
 
962
+ public function modifyfacetattributeAction()
963
+ {
964
  try {
965
+ if (!$this->_authorise()) {
966
  return $this;
967
  }
968
 
969
  $facetData = $this->getRequest()->getParam('newData', false);
970
  $newFacetData = json_decode($facetData);
971
 
972
+ if (!$newFacetData) {
973
  if ($facetData == "") {
974
  $input = file_get_contents('php://input');
975
  $input = utf8_encode($input);
977
  }
978
  }
979
 
980
+ if (!$newFacetData && !$newFacetData->attribute_id)
981
+ Mage::throwException("Insufficient data");
982
 
983
  // updates the facet
984
  $resourceModel = Mage::getResourceModel('catalog/product_attribute_collection');
990
  foreach ($newFacetData as $key => $value) {
991
  $attributeObj->setData($key, $value);
992
  }
993
+
994
  $updateStatus = $attributeObj->save();
995
 
996
+ if (!$updateStatus)
997
+ Mage::throwException("Couldn't update");
998
  else
999
  Mage::app()->getCache()->save(null, "sysFacets", array("facets"));
1000
 
1001
  $this->getResponse()
1002
+ ->setBody(json_encode(array("status" => "ok", 'version' => self::API_VERSION)))
1003
  ->setHttpResponseCode(200)
1004
  ->setHeader('Content-type', 'application/json', true);
1005
+ } catch (Exception $e) {
1006
+ if ($e->getMessage())
1007
  $errorMsg = $e->getMessage();
1008
  else
1009
  $errorMsg = "Internal server error";
1010
 
1011
  $this->getResponse()
1012
+ ->setBody(
1013
+ json_encode(
1014
+ array('status' => 'error', 'message' => $errorMsg, 'version' =>
1015
+ self::API_VERSION)
1016
+ )
1017
+ )
1018
  ->setHttpResponseCode(500)
1019
  ->setHeader('Content-type', 'application/json', true);
1020
  }
1023
  }
1024
 
1025
  // Formats the attribute for save
1026
+ protected function _prepareAttributeForSave($data)
1027
+ {
1028
  /** @var $helperCatalog Mage_Catalog_Helper_Data */
1029
  $helperCatalog = Mage::helper('catalog');
1030
 
1039
  if (!isset($data['is_configurable'])) {
1040
  $data['is_configurable'] = 0;
1041
  }
1042
+
1043
  if (!isset($data['is_filterable'])) {
1044
  $data['is_filterable'] = 1;
1045
  }
1046
+
1047
  if (!isset($data['is_filterable_in_search'])) {
1048
  $data['is_filterable_in_search'] = 1;
1049
  }
1050
+
1051
  if (!isset($data['apply_to'])) {
1052
  $data['apply_to'] = array();
1053
  }
1054
+
1055
  // set frontend labels array with store_id as keys
1056
  if (isset($data['frontend_label']) && is_array($data['frontend_label'])) {
1057
  $labels = array();
1060
  $labelText = $helperCatalog->stripTags($label['label']);
1061
  $labels[$storeId] = $labelText;
1062
  }
1063
+
1064
  $data['frontend_label'] = $labels;
1065
  }
1066
+
1067
  // set additional fields
1068
  if (isset($data['additional_fields']) && is_array($data['additional_fields'])) {
1069
  $data = array_merge($data, $data['additional_fields']);
1070
  unset($data['additional_fields']);
1071
  }
1072
+
1073
  //default value
1074
  if (!empty($data['default_value'])) {
1075
  $data['default_value'] = $helperCatalog->stripTags($data['default_value']);
1079
  }
1080
 
1081
 
1082
+ public function addfacetattributeAction()
1083
+ {
1084
  try {
1085
+ if (!$this->_authorise()) {
1086
  return $this;
1087
  }
1088
 
1089
  $facetData = $this->getRequest()->getParam('newData', false);
1090
  $newFacetData = json_decode($facetData);
1091
 
1092
+ if (!$newFacetData) {
1093
  if ($facetData == "") {
1094
  $input = file_get_contents('php://input');
1095
  $input = utf8_encode($input);
1096
  $newFacetData = json_decode($input)->newData;
1097
  }
1098
  }
1099
+
1100
  $newFacetData = (array)$newFacetData;
1101
 
1102
  if (!$newFacetData || empty($newFacetData['attribute_code']) || !isset($newFacetData['frontend_label'])) {
1103
+ Mage::throwException("Insufficient data");
1104
  }
1105
 
1106
  //validate attribute_code
1107
  if (!preg_match('/^[a-z][a-z_0-9]{0,254}$/', $newFacetData['attribute_code'])) {
1108
+ Mage::throwException("Invalid attribute_code");
1109
  }
1110
 
1111
  /** @var $model Mage_Catalog_Model_Resource_Eav_Attribute */
1116
 
1117
  $newFacetData['source_model'] = $helper->getAttributeSourceModelByInputType('multiselect');
1118
  $newFacetData['backend_model'] = $helper->getAttributeBackendModelByInputType('multiselect');
1119
+ if ($model->getIsUserDefined() !== null || $model->getIsUserDefined() != 0) {
1120
  $newFacetData['backend_type'] = $model->getBackendTypeByInput('multiselect');
1121
  }
1122
 
1134
  Mage::app()->cleanCache(array(Mage_Core_Model_Translate::CACHE_TAG));
1135
 
1136
  $this->getResponse()
1137
+ ->setBody(json_encode(array("status" => "ok", 'version' => self::API_VERSION)))
1138
  ->setHttpResponseCode(200)
1139
  ->setHeader('Content-type', 'application/json', true);
1140
+ } catch (Exception $e) {
1141
+ if ($e->getMessage())
1142
  $errorMsg = $e->getMessage();
1143
  else
1144
  $errorMsg = "Internal server error";
1145
 
1146
  $this->getResponse()
1147
+ ->setBody(
1148
+ json_encode(
1149
+ array('status' => 'error', 'message' => $errorMsg, 'version' =>
1150
+ self::API_VERSION)
1151
+ )
1152
+ )
1153
  ->setHttpResponseCode(500)
1154
  ->setHeader('Content-type', 'application/json', true);
1155
  }
1158
  }
1159
 
1160
 
1161
+ public function usersAction()
1162
+ {
1163
 
1164
  try {
1165
+ if (!$this->_authorise()) {
 
1166
  return $this;
1167
  }
1168
 
1182
 
1183
  $usersCollection = Mage::getModel('customer/customer')->getCollection();
1184
 
1185
+ if ($email != null && $email !== "") {
 
1186
  $usersCollection
1187
  ->addAttributeToFilter('email', $email);
 
1188
  } else {
1189
+ $createdAtMin = $this->getRequest()->getParam('created_at_min');
1190
+ $createdAtMax = $this->getRequest()->getParam('created_at_max');
 
1191
 
1192
  $usersCollection->addAttributeToSelect($attributes);
1193
 
1194
+ if ($createdAtMin != null && $createdAtMin !== null) {
1195
+ $usersCollection->addAttributeToFilter('created_at', array('from' => $createdAtMin));
1196
  }
1197
 
1198
+ if ($createdAtMax != null && $createdAtMax !== null) {
1199
+ $usersCollection->addAttributeToFilter('created_at', array('to' => $createdAtMax));
1200
  }
1201
 
1202
  $usersCollection->getSelect()
1203
  ->limit($limit, $offset);
 
1204
  }
1205
 
1206
  $users = array();
1221
  ->setBody(json_encode(array('users' => $users, 'version' => self::API_VERSION)))
1222
  ->setHttpResponseCode(200)
1223
  ->setHeader('Content-type', 'application/json', true);
1224
+ } catch (Exception $e) {
 
1225
  $this->getResponse()
1226
+ ->setBody(
1227
+ json_encode(
1228
+ array('status' => 'error', 'message' => 'Internal server error', 'version' =>
1229
+ self::API_VERSION)
1230
+ )
1231
+ )
1232
  ->setHttpResponseCode(500)
1233
  ->setHeader('Content-type', 'application/json', true);
1234
  }
1237
 
1238
  }
1239
 
1240
+ public function stocksAction()
1241
+ {
1242
+ try {
1243
+ if (!$this->_authorise()) {
1244
+ return $this;
1245
+ }
1246
 
1247
+ $attributes = array(
1248
+ 'visibility',
1249
+ 'price',
1250
+ 'final_price',
1251
+ 'special_price'
1252
+ );
1253
+ $skusAlso = $this->getRequest()->getParam('skusAlso', 'false') === 'true';
1254
+ $disabledAlso = $this->getRequest()->getParam('disabledAlso', 'false') === 'true';
1255
+ $attributeSetId = $this->getRequest()->getParam('attributeSetId');
1256
+ $sections = explode('/', trim($this->getRequest()->getPathInfo(), '/'));
1257
 
1258
+ $products = array();
1259
+ $productId = null;
1260
+ if (isset($sections[3])) {
1261
+ // Looking for a specific product
1262
+ $productId = $sections[3];
1263
+ if ($productId != "count") {
1264
+ $product = Mage::getModel('catalog/product')->load($productId);
1265
 
1266
+ $product = $this->getStockFormattedProduct($product);
1267
+ if ($product !== null) {
1268
+ $products[] = $product;
1269
+ } else {
1270
+ Mage::throwException("Failed to fetch the product");
1271
+ }
1272
+ }
1273
  }
1274
 
1275
+ if (!$productId || $productId == "count") {
1276
+ // Looking for a list of products
1277
+ $limit = $this->getRequest()->getParam('limit', 100);
1278
+ $offset = $this->getRequest()->getParam('offset', 1);
1279
 
1280
+ $productsCollection = Mage::getModel('catalog/product')->getCollection();
1281
 
1282
+ $productsCollection->addAttributeToSelect($attributes);
1283
+ // Get only enabled products
1284
+ if (!$disabledAlso) {
1285
+ $productsCollection->addAttributeToFilter(
1286
+ 'status', array('eq' =>
1287
+ Mage_Catalog_Model_Product_Status::STATUS_ENABLED)
1288
+ );
1289
+ }
1290
 
1291
+ if ($attributeSetId) {
1292
+ $productsCollection->addFieldToFilter('attribute_set_id', $attributeSetId);
1293
+ }
 
1294
 
1295
+ if (!$skusAlso) {
1296
+ Mage::getSingleton('catalog/product_visibility')
1297
+ ->addVisibleInSiteFilterToCollection($productsCollection);
1298
+ }
1299
 
1300
+ if ($productId == "count") {
1301
+ $product["count"] = $productsCollection->getSize();
1302
+ $products[] = $product;
1303
+ } else {
1304
+ //we can specify how many products we want to show on this page
1305
+ $productsCollection->getSelect()->limit($limit, $offset);
1306
+ foreach ($productsCollection as $product) {
1307
+ $product = $this->getStockFormattedProduct($product);
1308
+ if ($product !== null) {
1309
+ $products[] = $product;
1310
+ } else {
1311
+ Mage::throwException("Failed to fetch the product");
1312
+ }
1313
  }
 
1314
  }
1315
+ }
1316
 
1317
+ $this->getResponse()
1318
+ ->setBody(json_encode(array('products' => $products, 'version' => self::API_VERSION)))
1319
+ ->setHttpResponseCode(200)
1320
+ ->setHeader('Content-type', 'application/json', true);
1321
+ } catch (Exception $e) {
1322
+ $this->getResponse()
1323
+ ->setBody(
1324
+ json_encode(
1325
+ array('status' => 'error', 'message' => 'Internal server error', 'version'
1326
+ => self::API_VERSION)
1327
+ )
1328
+ )
1329
+ ->setHttpResponseCode(500)
1330
+ ->setHeader('Content-type', 'application/json', true);
1331
+ }
1332
 
1333
+ return $this;
1334
+ }
1335
 
1336
+ public function attributeSetsAction()
1337
+ {
1338
+ try {
1339
+ if (!$this->_authorise()) {
1340
+ return $this;
1341
+ }
1342
+
1343
+ $sections = explode('/', trim($this->getRequest()->getPathInfo(), '/'));
1344
+ $attributeSets = array();
1345
 
1346
+ if (isset($sections[3])) {
1347
+ // Looking for a specific product
1348
+ $attributeSetId = $sections[3];
1349
+ if ($attributeSetId == "count") {
1350
+ $attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection');
1351
+ $attributeSetCollection->setEntityTypeFilter('4'); // 4 is Catalog Product Entity Type ID
1352
+
1353
+ $attributeSet = array();
1354
+ $attributeSet["count"] = $attributeSetCollection->getSize();
1355
+ $attributeSets[] = $attributeSet;
1356
+ } else {
1357
+ $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
1358
+ $attributeSetModel->load($attributeSetId);
1359
+ $attributeSet = $this->getFormattedAttributeSet($attributeSetModel);
1360
+
1361
+ if ($attributeSet !== null) {
1362
+ $attributeSets[] = $attributeSet;
1363
+ } else {
1364
+ Mage::throwException("Failed to fetch the attribute set");
1365
+ }
1366
+ }
1367
+ } else {
1368
+ $attributeSetCollection = Mage::getResourceModel('eav/entity_attribute_set_collection');
1369
+ $attributeSetCollection->setEntityTypeFilter('4'); // 4 is Catalog Product Entity Type ID
1370
+ foreach ($attributeSetCollection as $id => $attributeSetModel) {
1371
+ $attributeSet = $this->getFormattedAttributeSet($attributeSetModel);
1372
+ if ($attributeSet !== null) {
1373
+ $attributeSets[] = $attributeSet;
1374
+ } else {
1375
+ Mage::throwException("Failed to fetch the attribute set");
1376
+ }
1377
+ }
1378
  }
1379
 
 
1380
  $this->getResponse()
1381
+ ->setBody(json_encode(array('attributeSets' => $attributeSets, 'version' => self::API_VERSION)))
1382
+ ->setHttpResponseCode(200)
1383
+ ->setHeader('Content-type', 'application/json', true);
1384
+ } catch (Exception $e) {
1385
+ $this->getResponse()
1386
+ ->setBody(
1387
+ json_encode(
1388
+ array('status' => 'error', 'message' => 'Internal server error', 'version'
1389
+ => self::API_VERSION)
1390
+ )
1391
+ )
1392
  ->setHttpResponseCode(500)
1393
  ->setHeader('Content-type', 'application/json', true);
1394
  }
1395
 
1396
  return $this;
1397
+ }
1398
+
1399
+ protected function getFormattedAttributeSet($attributeSetModel)
1400
+ {
1401
+ $attributeSet = null;
1402
 
1403
+ try {
1404
+ $attributeSet = array(
1405
+ 'id' => $attributeSetModel->getId(),
1406
+ 'name' => $attributeSetModel->getAttributeSetName(),
1407
+ 'groups' => array()
1408
+ );
1409
+ $groups = Mage::getModel('eav/entity_attribute_group')
1410
+ ->getResourceCollection()
1411
+ ->setAttributeSetFilter($attributeSet['id'])
1412
+ ->setSortOrder()
1413
+ ->load();
1414
+ foreach ($groups as $group) {
1415
+ $groupName = $group->getAttributeGroupName();
1416
+ $attributeSet['groups'][$groupName] = array();
1417
+ $attributes = Mage::getResourceModel('catalog/product_attribute_collection')
1418
+ ->setAttributeGroupFilter($group->getId())
1419
+ ->load();
1420
+ if ($attributes->getSize() > 0) {
1421
+ foreach ($attributes->getItems() as $attribute) {
1422
+ /* @var $child Mage_Eav_Model_Entity_Attribute */
1423
+ $key = $attribute->getAttributeCode();
1424
+ $attributeSet['groups'][$groupName][] = $key;
1425
+ }
1426
+ }
1427
+
1428
+ // }
1429
+ }
1430
+
1431
+ return $attributeSet;
1432
+ } catch (Exception $e) {
1433
+ return NULL;
1434
+ }
1435
  }
1436
 
1437
+ protected function getStockFormattedProduct($product)
1438
+ {
1439
 
1440
+ $formattedProduct = null;
1441
+
1442
+ try {
1443
+ $formattedProduct = array(
1444
+ 'id' => $product->getId(),
1445
+ 'sku' => $product->getSku(),
1446
+ 'price' => $product->getPrice(),
1447
+ 'final_price' => $product->getFinalPrice(),
1448
+ 'special_price' => $product->getSpecialPrice(),
1449
+ 'status' => $product->getStatus(),
1450
+ 'visible_in_site' => $product->isVisibleInSiteVisibility(),
1451
+ 'extras' => array(),
1452
+ 'created_at' => $product->getCreatedAt(),
1453
+ 'updated_at' => $product->getUpdatedAt()
1454
+ );
1455
+ $formattedProduct['extras']['visibility'] = $product->getAttributeText('visibility');
1456
+ $formattedProduct['visible_in_site'] = $product->isVisibleInSiteVisibility();
1457
+ // get stock info
1458
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1459
+ $formattedProduct['stock'] = $stock->getQty();
1460
+ return $formattedProduct;
1461
+ } catch (Exception $e) {
1462
+ return NULL;
1463
+ }
1464
+ }
1465
+
1466
+ protected function getFormattedProduct($product, $extras, $debug, $fields)
1467
+ {
1468
 
1469
  $formattedProduct = null;
1470
 
1471
  try {
1472
  $formattedProduct = array(
1473
+ 'id' => $product->getId(),
1474
+ 'sku' => $product->getSku(),
1475
+ 'name' => $product->getName(),
1476
+ 'cat' => array(),
1477
+ 'manufacturer' => $product->getAttributeText('manufacturer'),
1478
+ 'url_key' => $product->getUrlKey(),
1479
+ 'url_path' => $product->getUrlPath(),
1480
+ 'price' => $product->getPrice(),
1481
+ 'final_price' => $product->getFinalPrice(),
1482
+ 'special_price' => $product->getSpecialPrice(),
1483
+ 'image' => $product->getImageUrl(),
1484
+ 'url' => $product->getProductUrl(),
1485
+ 'info' => $product->getShortDescription(),
1486
+ 'status' => $product->getStatus() == "1",
1487
+ 'type' => $product->getTypeId(),
1488
+ 'created_at' => $product->getCreatedAt(),
1489
+ 'visible_in_site' => $product->isVisibleInSiteVisibility(),
1490
+ 'is_in_stock' => $product->getIsInStock() == "1",
1491
+ 'is_saleable' => $product->isSaleable(),
1492
+ 'updated_at' => $product->getUpdatedAt()
1493
  );
1494
+ if ($debug || in_array("supporting_products", $fields)) {
1495
+ $formattedProduct["related_products"] = $product->getRelatedProductIds();
1496
+ $formattedProduct["cross_sell_products"] = $product->getCrossSellProductIds();
1497
+ $formattedProduct["up_sell_products"] = $product->getUpSellProductIds();
1498
+ }
1499
+
1500
+ if ($debug || in_array("images", $fields)) {
1501
+ $images = array();
1502
+ foreach ($product->getMediaGalleryImages() as $image) { //will load all gallery images in loop
1503
+ $images[] = $image->getUrl();
1504
+ }
1505
+
1506
+ $formattedProduct['base_image'] = Mage::getModel('catalog/product_media_config')
1507
+ ->getMediaUrl($product->getImage());
1508
+ $formattedProduct['images'] = $images;
1509
+ }
1510
+
1511
+ if (!$formattedProduct['manufacturer'] || strlen($formattedProduct['manufacturer']) === 0) {
1512
  $product = Mage::getModel('catalog/product')->load($product->getId());
1513
  $formattedProduct['manufacturer'] = $product->getAttributeText('manufacturer');
1514
  }
1515
 
1516
+ if ($formattedProduct['type'] == "configurable") {
1517
+ if ($debug || in_array("associated_products", $fields)) {
1518
+ // get associated product ids
1519
+ $associatedProducts = Mage::getModel('catalog/product_type_configurable')
1520
+ ->getChildrenIds($formattedProduct['id']);
1521
+ if (is_array($associatedProducts) && !empty($associatedProducts)) {
1522
+ $formattedProduct['associated_products'] = array_keys($associatedProducts[0]);
1523
+ } else {
1524
+ $formattedProduct['associated_products'] = array();
1525
+ }
1526
+ }
1527
+
1528
+ if ($debug || in_array("options", $fields)) {
1529
+ $options = array();
1530
+ $productAttributeOptions = $product->getTypeInstance(true)
1531
+ ->getConfigurableAttributesAsArray($product);
1532
+ $attributeTypes = array();
1533
+
1534
+ foreach ($productAttributeOptions as $productAttribute) {
1535
+ $attributes = array();
1536
+ foreach ($productAttribute['values'] as $attribute) {
1537
+ $attributes[] = array(
1538
+ "id" => $attribute["value_index"],
1539
+ "name" => $attribute["store_label"]
1540
+ );
1541
+ }
1542
+
1543
+ $attributeType = $productAttribute["attribute_code"];
1544
+ $options[] = array(
1545
+ "id" => $productAttribute["id"],
1546
+ "key" => $attributeType,
1547
+ "name" => $productAttribute["store_label"],
1548
+ "values" => $attributes,
1549
+ "position" => $productAttribute["position"]
1550
+ );
1551
+
1552
+ $attributeTypes[] = $attributeType;
1553
+ }
1554
+
1555
+ $formattedProduct['options'] = $options;
1556
+ }
1557
+
1558
+ $totalStock = 0;
1559
+ $isInStock = false;
1560
+ $isSaleable = false;
1561
+ if ($debug || in_array("variants", $fields)) {
1562
+ $variants = array();
1563
+ $associatedProducts = $product->getTypeInstance()->getUsedProducts();
1564
+ foreach ($associatedProducts as $associatedProduct) {
1565
+ $variant = array();
1566
+ $variant["is_available"] = $associatedProduct->isAvailable();
1567
+ $variant["id"] = $associatedProduct->getId();
1568
+ $variant["sku"] = $associatedProduct->getSku();
1569
+ $variant["price"] = $associatedProduct->getPrice();
1570
+ $variant["final_price"] = $associatedProduct->getFinalPrice();
1571
+ $variant["special_price"] = $associatedProduct->getSpecialPrice();
1572
+ $isInStock = $isInStock || ($associatedProduct->getIsInStock() == "1");
1573
+ $isSaleable = $isSaleable || $associatedProduct->isSaleable();
1574
+ $stock = Mage::getModel('cataloginventory/stock_item')
1575
+ ->loadByProduct($associatedProduct);
1576
+ $variant['stock'] = $stock->getQty();
1577
+ $totalStock += (int)$variant['stock'];
1578
+ $associatedProductData = $associatedProduct->getData();
1579
+ foreach ($attributeTypes as $attributeType) {
1580
+ $variant[$attributeType] = $associatedProductData[$attributeType];
1581
+ }
1582
+
1583
+ $variants[] = $variant;
1584
+ }
1585
+
1586
+ $formattedProduct['variants'] = $variants;
1587
+ } else {
1588
+ $associatedProducts = $product->getTypeInstance()->getUsedProducts();
1589
+ foreach ($associatedProducts as $associatedProduct) {
1590
+ $isInStock = $isInStock || ($associatedProduct->getIsInStock() == "1");
1591
+ $isSaleable = $isSaleable || $associatedProduct->isSaleable();
1592
+ $stock = Mage::getModel('cataloginventory/stock_item')
1593
+ ->loadByProduct($associatedProduct);
1594
+ $totalStock += (int)$stock->getQty();
1595
+ }
1596
+ }
1597
+
1598
+ $formattedProduct['stock'] = $totalStock;
1599
+ $formattedProduct['is_in_stock'] = $isInStock;
1600
+ $formattedProduct['is_saleable'] = $isSaleable;
1601
+ } else {
1602
+ // get stock info
1603
+ $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct($product);
1604
+ $formattedProduct['stock'] = $stock->getQty();
1605
  }
1606
 
1607
+ if ($debug || in_array("attributeSet", $fields)) {
1608
+ // kept just in case to verify data not to be used actively
1609
+ $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
1610
+ $attributeSetId = $product->getAttributeSetId();
1611
+ $attributeSetModel->load($attributeSetId);
1612
+ $attributeSetName = $attributeSetModel->getAttributeSetName();
1613
+ $formattedProduct['attributeSetId'] = $attributeSetId;
1614
+ $formattedProduct['attributeSetName'] = $attributeSetName;
1615
+ }
1616
 
1617
+ if ($debug) {
1618
+ // kept just in case to verify data not to be used actively
1619
+ $attributeSetModel = Mage::getModel("eav/entity_attribute_set");
1620
+ $attributeSetId = $product->getAttributeSetId();
1621
+ $attributeSetModel->load($attributeSetId);
1622
+ $attributeSetName = $attributeSetModel->getAttributeSetName();
1623
+ $formattedProduct['extras']['attributeSetId'] = $attributeSetId;
1624
+ $formattedProduct['extras']['attributeSetName'] = $attributeSetName;
1625
+ $groups = Mage::getModel('eav/entity_attribute_group')
1626
+ ->getResourceCollection()
1627
+ ->setAttributeSetFilter($attributeSetId)
1628
+ ->setSortOrder()
1629
+ ->load();
1630
+ foreach ($groups as $group) {
1631
+ // if($group->getAttributeGroupName() == 'Clothing'){ // set name
1632
+ $groupName = $group->getAttributeGroupName();
1633
+ //$groupId = $group->getAttributeGroupId();
1634
+ $formattedProduct['extras'][$groupName] = array();
1635
+ $attributes = Mage::getResourceModel('catalog/product_attribute_collection')
1636
+ ->setAttributeGroupFilter($group->getId())
1637
+ ->load();
1638
+ if ($attributes->getSize() > 0) {
1639
+ foreach ($attributes->getItems() as $attribute) {
1640
+ /* @var $child Mage_Eav_Model_Entity_Attribute */
1641
+ $key = $attribute->getAttributeCode();
1642
+ $formattedProduct['extras'][$groupName][$key] = $product->getAttributeText($key);
1643
+ }
1644
+ }
1645
 
1646
+ // }
 
1647
  }
1648
+
1649
+ // $attributes = $product->getAttributes();
1650
+ // foreach ($attributes as $key => $value) {
1651
+ // // Sanity check, or else crashes without proper error handling
1652
+ // $existenceCheck = $product->getResource()->getAttribute($key);
1653
+ //
1654
+ // if ($existenceCheck)
1655
+ // $formattedProduct['extras'][$key] = $product->getAttributeText($key);
1656
+ // }
1657
  } else {
1658
+ foreach ($extras as $key) {
1659
  // Sanity check, or else crashes without proper error handling
1660
  $existenceCheck = $product->getResource()->getAttribute($key);
1661
 
1662
+ if ($existenceCheck)
1663
  $formattedProduct['extras'][$key] = $product->getAttributeText($key);
1664
  }
1665
  }
1666
 
1667
  $categories = $product->getCategoryCollection()
1668
  ->addAttributeToSelect('id')
1669
+ ->addAttributeToSelect('name');
1670
+ // ->addAttributeToSelect('path')
1671
+ // ->addAttributeToSelect('level');
1672
+ foreach ($categories as $category) {
1673
+ // $formattedCategory = array();
1674
+ // $formattedCategory['id'] = $category->getId();
1675
+ // $formattedCategory['name'] = $category->getName();
1676
+ // $formattedCategory['level'] = $category->getLevel();
1677
+ // $formattedCategory['path'] = $category->getPath();
1678
+ // $formattedProduct['cat'][$formattedCategory['id']] = $formattedCategory;
1679
+ $formattedProduct['cat'][$category->getId()] = $category->getName();
1680
  }
1681
 
1682
  return $formattedProduct;
1683
+ } catch (Exception $e) {
1684
  return NULL;
1685
  }
1686
  }
1687
 
1688
+ protected function getFormattedCategory($category)
1689
+ {
1690
 
1691
  $formattedCategory = null;
1692
 
1693
  try {
1694
  $formattedCategory = array(
1695
+ 'id' => $category->getId(),
1696
+ 'name' => $category->getName(),
1697
+ 'image' => $category->getImageUrl(),
1698
+ 'url' => $category->getUrl(),
1699
+ 'level' => $category->getLevel(),
1700
+ 'path' => $category->getPath(),
1701
+ 'included_in_menu' => $category->getIncludeInMenu() == "1",
1702
+ 'is_anchor' => $category->getIsAnchor() == "1",
1703
+ 'is_active' => $category->getIsActive() == "1",
1704
+ 'count' => $category->getProductCount(),
1705
+ 'created_at' => $category->getCreatedAt(),
1706
+ 'updated_at' => $category->getUpdatedAt()
1707
  );
1708
+ } catch (Exception $e) {
1709
+ }
1710
 
1711
  return $formattedCategory;
1712
  }
1713
 
1714
+ public function sortbyAction()
1715
+ {
1716
 
1717
  try {
1718
+ if (!$this->_authorise()) {
1719
  return $this;
1720
  }
1721
 
1740
 
1741
  foreach ($attributesData as $key => $attributeData) {
1742
  $sortByOptions[] = array(
1743
+ "_id" => $key,
1744
+ "name" => $attributeData,
1745
+ "default" => $key == $defaultSort ? true : false,
1746
+ "order" => $i
1747
  );
1748
  $i++;
1749
  }
1750
 
1751
  $this->getResponse()
1752
+ ->setBody(
1753
+ json_encode(
1754
+ array('status' => "ok", 'options' => $sortByOptions, 'version'
1755
+ => self::API_VERSION)
1756
+ )
1757
+ )
1758
  ->setHttpResponseCode(200)
1759
  ->setHeader('Content-type', 'application/json', true);
1760
+ } catch (Exception $e) {
 
1761
  $this->getResponse()
1762
+ ->setBody(
1763
+ json_encode(
1764
+ array('status' => 'error', 'message' => 'Internal server error',
1765
+ 'version' => self::API_VERSION)
1766
+ )
1767
+ )
1768
  ->setHttpResponseCode(500)
1769
  ->setHeader('Content-type', 'application/json', true);
1770
  }
1772
  return $this;
1773
  }
1774
 
1775
+ public function choicepageAction()
1776
+ {
1777
+ try {
1778
+ if (!$this->_authorise()) {
1779
  return $this;
1780
  }
1781
 
1782
  $responseObj = array();
1783
+ $server = Mage::app()->getRequest()->getServer();
1784
+ if ($server["REQUEST_METHOD"] == "POST") {
1785
  // Create Choice page
1786
  // Expects title, url_path and content
1787
 
1791
  $input = utf8_encode($input);
1792
  $pageData = json_encode(json_decode($input)->data);
1793
  }
1794
+
1795
  $pageData = json_decode($pageData);
1796
  $urlPath = $pageData->url_path;
1797
 
1798
+ if (!$urlPath) {
1799
  // What can this poor guy do without the path?
1800
+ Mage::throwException("No urlPath");
1801
  }
1802
 
1803
  // Ensure no other existing page contains the same URL path or say "identifier"
1808
  // $existingPages = Mage::getModel('cms/page')->load($collection->getFirstItem()->getId());
1809
 
1810
  // There can be multiple pages with same url path, but different store scope. Let's disable all
1811
+ foreach ($collection as $existingPage) {
1812
  // Page already exists && is_active
1813
+ if ($existingPage->getId()) {
1814
  // Delete all other pages having same URL
1815
  // and then continue adding our new page
1816
+ // $this->updateChoiceUrl(false, $existingPage->getId(), array("is_active" => 0,
1817
+ // "identifier" => $urlPath));
1818
  $existingPage->delete();
1819
  }
1820
  }
1821
 
1822
  // Setting default content if not provided
1823
+ $pageContent = (!isset($pageData->content)) ?
1824
+ "<script>window._caichoicePage = true;</script><div id='caichoicePage'></div>" : $pageData->content;
1825
 
1826
  // Setting default Title if not available
1827
  $pageTitle = (!isset($pageData->title)) ? "Choice.AI" : $pageData->title;
1843
 
1844
  $responseObj["status"] = "ok";
1845
  $responseObj["id"] = $choicePage->getId();
1846
+ } else if ($server["REQUEST_METHOD"] == "PUT") {
1847
  // Update Choice page's URL path
1848
  $newPageData = $this->getRequest()->getParam('data');
1849
 
1852
  $input = utf8_encode($input);
1853
  $newPageData = json_encode(json_decode($input)->data);
1854
  }
1855
+
1856
  $newPageData = json_decode($newPageData);
1857
 
1858
  if ($newPageData == NULL || !isset($newPageData->page_id)) {
1859
+ Mage::throwException("page id not found");
1860
  }
1861
 
1862
  $pageId = $newPageData->page_id;
1863
 
1864
  $this->updateChoiceUrl($newPageData, $pageId);
1865
  $responseObj["status"] = "ok";
1866
+ } else if ($server["REQUEST_METHOD"] == "DELETE") {
1867
  $newPageData = $this->getRequest()->getParam('data');
1868
 
1869
  if ($newPageData == "") {
1871
  $input = utf8_encode($input);
1872
  $newPageData = json_encode(json_decode($input)->data);
1873
  }
1874
+
1875
  $newPageData = json_decode($newPageData);
1876
 
1877
  if ($newPageData == NULL || !isset($newPageData->page_id)) {
1878
+ Mage::throwException("page id not found");
1879
  }
1880
 
1881
  $pageId = $newPageData->page_id;
1882
 
1883
  $pagesCollection = Mage::getModel('cms/page')
1884
  ->getCollection()
1885
+ ->addFieldToFilter('page_id', array("eq" => $pageId));
1886
  $pageData = Mage::getModel('cms/page')->load($pagesCollection->getFirstItem()->getId());
1887
  $pageData->delete();
1888
  // Mage::app()->getStore()->resetConfig();
1898
  ->setBody(json_encode($responseObj))
1899
  ->setHttpResponseCode(200)
1900
  ->setHeader('Content-type', 'application/json', true);
1901
+ } catch (Exception $e) {
1902
  $this->getResponse()
1903
+ ->setBody(
1904
+ json_encode(
1905
+ array('emsg' => $e->getMessage(), 'status' => 'error',
1906
+ 'message' => 'Internal server error', 'version' => self::API_VERSION)
1907
+ )
1908
+ )
1909
  ->setHttpResponseCode(500)
1910
  ->setHeader('Content-type', 'application/json', true);
1911
  }
1913
  return this;
1914
  }
1915
 
1916
+ protected function updateChoiceUrl($newPageData, $pageId, $dataToUpdate = false)
1917
+ {
1918
  // Doesn't allow update without "identifier" field :/
1919
+ if (!$dataToUpdate) {
1920
  // Update case
1921
  $dataToUpdate = array();
1922
 
1927
  $collection = Mage::getModel('cms/page')
1928
  ->getCollection()
1929
  ->addFieldToFilter('identifier', $urlPath)
1930
+ ->addFieldToFilter('page_id', array("neq" => $pageId));
1931
  $page = Mage::getModel('cms/page')->load($collection->getFirstItem()->getId());
1932
 
1933
  // URL path already being used?
1934
  if ($page->getId())
1935
+ Mage::throwException("Url path already being used");
1936
  else
1937
  $dataToUpdate['identifier'] = $urlPath;
1938
  }
1951
  // Ensuring proper scope per update
1952
  $dataToUpdate['stores'] = array(0);
1953
 
1954
+ if (!isset($dataToUpdate['identifier'])) {
1955
  // Get existing "identifier"
1956
  $pagesCollection = Mage::getModel('cms/page')
1957
  ->getCollection()
1958
+ ->addFieldToFilter('page_id', array("eq" => $pageId));
1959
  $pageData = Mage::getModel('cms/page')->load($pagesCollection->getFirstItem()->getId());
1960
 
1961
  $dataToUpdate['identifier'] = $pageData->getIdentifier();
app/code/community/ChoiceAI/Personalisation/etc/config.xml CHANGED
@@ -10,7 +10,7 @@
10
  <config>
11
  <modules>
12
  <ChoiceAI_Personalisation>
13
- <version>1.0.12</version>
14
  </ChoiceAI_Personalisation>
15
  </modules>
16
  <global>
10
  <config>
11
  <modules>
12
  <ChoiceAI_Personalisation>
13
+ <version>1.1.1</version>
14
  </ChoiceAI_Personalisation>
15
  </modules>
16
  <global>
app/code/community/ChoiceAI/Personalisation/sql/personalisation_setup/install-1.0.12.php DELETED
@@ -1,31 +0,0 @@
1
- <?php
2
- /**
3
- * Created by PhpStorm.
4
- * User: harkirat
5
- * Date: 13/7/17
6
- * Time: 2:47 PM
7
- */
8
-
9
- /* @var $installer Mage_Core_Model_Resource_Setup */
10
-
11
- $installer = $this;
12
-
13
- $installer->startSetup();
14
- $pluginVersion = "1.0.12";
15
- $magentoVersion = Mage::getVersion();
16
-
17
- if(isset($_SERVER['REQUEST_SCHEME']) && isset($_SERVER['SERVER_NAME'])){
18
- $storeUrl = $_SERVER['REQUEST_SCHEME'] ."://". $_SERVER['SERVER_NAME'];
19
- } else{
20
- $storeUrl = Mage::getBaseUrl();
21
- }
22
-
23
- $ctx = stream_context_create(array('http'=>
24
- array(
25
- 'timeout' => 5, //Wait for only 5 secs at max
26
- )
27
- ));
28
-
29
- file_get_contents("https://app.choice.ai/stats/magentoinstall?installed=1&store_url=".$storeUrl."&magento_version=".$magentoVersion."&plugin_version=".$pluginVersion, false, $ctx);
30
-
31
- $installer->endSetup();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/code/community/ChoiceAI/Personalisation/sql/personalisation_setup/install-1.1.1.php ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Created by PhpStorm.
4
+ * User: harkirat
5
+ * Date: 13/7/17
6
+ * Time: 2:47 PM
7
+ */
8
+
9
+ /* @var $installer Mage_Core_Model_Resource_Setup */
10
+
11
+ $installer = $this;
12
+
13
+ $installer->startSetup();
14
+ $pluginVersion = "1.1.1";
15
+ $magentoVersion = Mage::getVersion();
16
+ $server = Mage::app()->getRequest()->getServer();
17
+ if (isset($server['REQUEST_SCHEME']) && isset($server['SERVER_NAME'])) {
18
+ $storeUrl = $server['REQUEST_SCHEME'] . "://" . $server['SERVER_NAME'];
19
+ } else {
20
+ $storeUrl = Mage::getBaseUrl();
21
+ }
22
+
23
+ $ctx = stream_context_create(
24
+ array('http' =>
25
+ array(
26
+ 'timeout' => 5, //Wait for only 5 secs at max
27
+ )
28
+ )
29
+ );
30
+
31
+ file_get_contents(
32
+ "https://app.choice.ai/stats/magentoinstall?installed=1&base_url=" . Mage::getBaseUrl() .
33
+ "store_url=" . $storeUrl . "&magento_version=" . $magentoVersion . "&plugin_version=" . $pluginVersion,
34
+ false, $ctx
35
+ );
36
+
37
+ $installer->endSetup();
app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Attribute.php CHANGED
@@ -1,45 +1,46 @@
1
- <?php
2
- /**
3
- *
4
- * @package ChoiceAI_Search
5
- * @copyright Copyright (c) MineWhat
6
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
- */
8
- class ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Block_Layer_Filter_Abstract
9
- {
10
- /**
11
- * Defines specific filter model name.
12
- *
13
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
14
- */
15
- public function __construct()
16
- {
17
- parent::__construct();
18
- $this->_filterModelName = 'choiceai_search/catalog_layer_filter_attribute';
19
- }
20
-
21
- /**
22
- * Prepares filter model.
23
- *
24
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
25
- */
26
- protected function _prepareFilter()
27
- {
28
- $this->_filter->setAttributeModel($this->getAttributeModel());
29
-
30
- return $this;
31
- }
32
-
33
- /**
34
- * Adds facet condition to filter.
35
- *
36
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute::addFacetCondition()
37
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
38
- */
39
- public function addFacetCondition()
40
- {
41
- $this->_filter->addFacetCondition();
42
-
43
- return $this;
44
- }
45
- }
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Block_Layer_Filter_Abstract
10
+ {
11
+ /**
12
+ * Defines specific filter model name.
13
+ *
14
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
15
+ */
16
+ public function __construct()
17
+ {
18
+ parent::__construct();
19
+ $this->_filterModelName = 'choiceai_search/catalog_layer_filter_attribute';
20
+ }
21
+
22
+ /**
23
+ * Prepares filter model.
24
+ *
25
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
26
+ */
27
+ protected function _prepareFilter()
28
+ {
29
+ $this->_filter->setAttributeModel($this->getAttributeModel());
30
+
31
+ return $this;
32
+ }
33
+
34
+ /**
35
+ * Adds facet condition to filter.
36
+ *
37
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute::addFacetCondition()
38
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
39
+ */
40
+ public function addFacetCondition()
41
+ {
42
+ $this->_filter->addFacetCondition();
43
+
44
+ return $this;
45
+ }
46
+ }
app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Boolean.php CHANGED
@@ -1,20 +1,21 @@
1
- <?php
2
- /**
3
- *
4
- * @package ChoiceAI_Search
5
- * @copyright Copyright (c) MineWhat
6
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
- */
8
- class ChoiceAI_Search_Block_Catalog_Layer_Filter_Boolean extends ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
9
- {
10
- /**
11
- * Defines specific filter model name.
12
- *
13
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Boolean
14
- */
15
- public function __construct()
16
- {
17
- parent::__construct();
18
- $this->_filterModelName = 'choiceai_search/catalog_layer_filter_boolean';
19
- }
20
- }
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Block_Catalog_Layer_Filter_Boolean extends ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
10
+ {
11
+ /**
12
+ * Defines specific filter model name.
13
+ *
14
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Boolean
15
+ */
16
+ public function __construct()
17
+ {
18
+ parent::__construct();
19
+ $this->_filterModelName = 'choiceai_search/catalog_layer_filter_boolean';
20
+ }
21
+ }
app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Category.php CHANGED
@@ -1,33 +1,34 @@
1
- <?php
2
- /**
3
- *
4
- * @package ChoiceAI_Search
5
- * @copyright Copyright (c) MineWhat
6
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
- */
8
- class ChoiceAI_Search_Block_Catalog_Layer_Filter_Category extends Mage_Catalog_Block_Layer_Filter_Abstract
9
- {
10
- /**
11
- * Defines specific filter model name.
12
- *
13
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
14
- */
15
- public function __construct()
16
- {
17
- parent::__construct();
18
- $this->_filterModelName = 'choiceai_search/catalog_layer_filter_category';
19
- }
20
-
21
- /**
22
- * Adds facet condition to filter.
23
- *
24
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Category::addFacetCondition()
25
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
26
- */
27
- public function addFacetCondition()
28
- {
29
- $this->_filter->addFacetCondition();
30
-
31
- return $this;
32
- }
33
- }
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Block_Catalog_Layer_Filter_Category extends Mage_Catalog_Block_Layer_Filter_Abstract
10
+ {
11
+ /**
12
+ * Defines specific filter model name.
13
+ *
14
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
15
+ */
16
+ public function __construct()
17
+ {
18
+ parent::__construct();
19
+ $this->_filterModelName = 'choiceai_search/catalog_layer_filter_category';
20
+ }
21
+
22
+ /**
23
+ * Adds facet condition to filter.
24
+ *
25
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Category::addFacetCondition()
26
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Attribute
27
+ */
28
+ public function addFacetCondition()
29
+ {
30
+ $this->_filter->addFacetCondition();
31
+
32
+ return $this;
33
+ }
34
+ }
app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Decimal.php CHANGED
@@ -1,45 +1,46 @@
1
- <?php
2
- /**
3
- *
4
- * @package ChoiceAI_Search
5
- * @copyright Copyright (c) MineWhat
6
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
- */
8
- class ChoiceAI_Search_Block_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Block_Layer_Filter_Abstract
9
- {
10
- /**
11
- * Defines specific filter model name.
12
- *
13
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
14
- */
15
- public function __construct()
16
- {
17
- parent::__construct();
18
- $this->_filterModelName = 'choiceai_search/catalog_layer_filter_decimal';
19
- }
20
-
21
- /**
22
- * Prepares filter model.
23
- *
24
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Decimal
25
- */
26
- protected function _prepareFilter()
27
- {
28
- $this->_filter->setAttributeModel($this->getAttributeModel());
29
-
30
- return $this;
31
- }
32
-
33
- /**
34
- * Adds facet condition to filter.
35
- *
36
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal::addFacetCondition()
37
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Decimal
38
- */
39
- public function addFacetCondition()
40
- {
41
- $this->_filter->addFacetCondition();
42
-
43
- return $this;
44
- }
45
- }
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Block_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Block_Layer_Filter_Abstract
10
+ {
11
+ /**
12
+ * Defines specific filter model name.
13
+ *
14
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
15
+ */
16
+ public function __construct()
17
+ {
18
+ parent::__construct();
19
+ $this->_filterModelName = 'choiceai_search/catalog_layer_filter_decimal';
20
+ }
21
+
22
+ /**
23
+ * Prepares filter model.
24
+ *
25
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Decimal
26
+ */
27
+ protected function _prepareFilter()
28
+ {
29
+ $this->_filter->setAttributeModel($this->getAttributeModel());
30
+
31
+ return $this;
32
+ }
33
+
34
+ /**
35
+ * Adds facet condition to filter.
36
+ *
37
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal::addFacetCondition()
38
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Decimal
39
+ */
40
+ public function addFacetCondition()
41
+ {
42
+ $this->_filter->addFacetCondition();
43
+
44
+ return $this;
45
+ }
46
+ }
app/code/local/ChoiceAI/Search/Block/Catalog/Layer/Filter/Price.php CHANGED
@@ -1,50 +1,50 @@
1
- <?php
2
- /**
3
- *
4
- * @package ChoiceAI_Search
5
- * @copyright Copyright (c) MineWhat
6
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
- */
8
- class ChoiceAI_Search_Block_Catalog_Layer_Filter_Price extends Mage_Catalog_Block_Layer_Filter_Abstract
9
- {
10
- /**
11
- * Defines specific filter model name.
12
- *
13
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Price
14
- */
15
- public function __construct()
16
- {
17
- parent::__construct();
18
- $this->_filterModelName = 'choiceai_search/catalog_layer_filter_price';
19
- }
20
-
21
- /**
22
- * Prepares filter model.
23
- *
24
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Price
25
- */
26
- protected function _prepareFilter()
27
- {
28
- $this->_filter->setAttributeModel($this->getAttributeModel());
29
-
30
- return $this;
31
- }
32
-
33
- /**
34
- * Adds facet condition to filter.
35
- *
36
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Price::addFacetCondition()
37
- * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Price
38
- */
39
- public function addFacetCondition()
40
- {
41
- if (!$this->getRequest()->getParam('price')) {
42
- $this->_filter->addFacetCondition();
43
- }
44
-
45
- return $this;
46
- }
47
-
48
-
49
-
50
- }
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Block_Catalog_Layer_Filter_Price extends Mage_Catalog_Block_Layer_Filter_Abstract
10
+ {
11
+ /**
12
+ * Defines specific filter model name.
13
+ *
14
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Price
15
+ */
16
+ public function __construct()
17
+ {
18
+ parent::__construct();
19
+ $this->_filterModelName = 'choiceai_search/catalog_layer_filter_price';
20
+ }
21
+
22
+ /**
23
+ * Prepares filter model.
24
+ *
25
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Price
26
+ */
27
+ protected function _prepareFilter()
28
+ {
29
+ $this->_filter->setAttributeModel($this->getAttributeModel());
30
+
31
+ return $this;
32
+ }
33
+
34
+ /**
35
+ * Adds facet condition to filter.
36
+ *
37
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Price::addFacetCondition()
38
+ * @return ChoiceAI_Search_Block_Catalog_Layer_Filter_Price
39
+ */
40
+ public function addFacetCondition()
41
+ {
42
+ if (!$this->getRequest()->getParam('price')) {
43
+ $this->_filter->addFacetCondition();
44
+ }
45
+
46
+ return $this;
47
+ }
48
+
49
+
50
+ }
app/code/local/ChoiceAI/Search/Block/Catalog/Layer/View.php CHANGED
@@ -1,109 +1,112 @@
1
- <?php
2
- /**
3
- * Overrides default layer view process to define custom filter blocks.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Block_Catalog_Layer_View extends Mage_Catalog_Block_Layer_View
10
- {
11
- /**
12
- * Boolean block name.
13
- *
14
- * @var string
15
- */
16
- protected $_booleanFilterBlockName;
17
-
18
- /**
19
- * Registers current layer in registry.
20
- *
21
- * @see Mage_Catalog_Block_Product_List::getLayer()
22
- */
23
- protected function _construct()
24
- {
25
- parent::_construct();
26
- Mage::unregister('current_layer');
27
- Mage::register('current_layer', $this->getLayer());
28
- }
29
-
30
- /**
31
- * Modifies default block names to specific ones if engine is active.
32
- */
33
- protected function _initBlocks()
34
- {
35
- parent::_initBlocks();
36
- if (Mage::helper('choiceai_search')->isActiveEngine()) {
37
- $this->_categoryBlockName = 'choiceai_search/catalog_layer_filter_category';
38
- $this->_attributeFilterBlockName = 'choiceai_search/catalog_layer_filter_attribute';
39
- $this->_priceFilterBlockName = 'choiceai_search/catalog_layer_filter_price';
40
- $this->_decimalFilterBlockName = 'choiceai_search/catalog_layer_filter_decimal';
41
- $this->_booleanFilterBlockName = 'choiceai_search/catalog_layer_filter_boolean';
42
- }
43
- }
44
-
45
- /**
46
- * Prepares layout if engine is active.
47
- * Difference between parent method is addFacetCondition() call on each created block.
48
- *
49
- * @return ChoiceAI_Search_Block_Catalog_Layer_View
50
- */
51
- protected function _prepareLayout()
52
- {
53
- if (Mage::helper('choiceai_search')->isActiveEngine()) {
54
- $stateBlock = $this->getLayout()->createBlock($this->_stateBlockName)
55
- ->setLayer($this->getLayer());
56
-
57
- $categoryBlock = $this->getLayout()->createBlock($this->_categoryBlockName)
58
- ->setLayer($this->getLayer())
59
- ->init();
60
-
61
- $this->setChild('layer_state', $stateBlock);
62
- $this->setChild('category_filter', $categoryBlock->addFacetCondition());
63
-
64
- $filterableAttributes = $this->_getFilterableAttributes();
65
- $filters = array();
66
- foreach ($filterableAttributes as $attribute) {
67
- if ($attribute->getAttributeCode() == 'price') {
68
- $filterBlockName = $this->_priceFilterBlockName;
69
- } elseif ($attribute->getBackendType() == 'decimal') {
70
- $filterBlockName = $this->_decimalFilterBlockName;
71
- } elseif ($attribute->getSourceModel() == 'eav/entity_attribute_source_boolean') {
72
- $filterBlockName = $this->_booleanFilterBlockName;
73
- } else {
74
- $filterBlockName = $this->_attributeFilterBlockName;
75
- }
76
-
77
- $filters[$attribute->getAttributeCode() . '_filter'] = $this->getLayout()->createBlock($filterBlockName)
78
- ->setLayer($this->getLayer())
79
- ->setAttributeModel($attribute)
80
- ->init();
81
- }
82
-
83
- foreach ($filters as $filterName => $block) {
84
- $this->setChild($filterName, $block->addFacetCondition());
85
- }
86
-
87
- $this->getLayer()->apply();
88
-
89
- // Causing a request to the data server, without sort by param
90
- $this->getLayer()->getProductCollection()->load();
91
- } else {
92
- parent::_prepareLayout();
93
- }
94
-
95
- return $this;
96
- }
97
-
98
- /**
99
- * Returns current catalog layer.
100
- *
101
- * @return ChoiceAI_Search_Model_Catalog_Layer|Mage_Catalog_Model_Layer
102
- */
103
- public function getLayer(){
104
- if (Mage::helper('choiceai_search')->isActiveEngine()) {
105
- return Mage::getSingleton('choiceai_search/catalog_layer');
106
- }
107
- return parent::getLayer();
108
- }
109
- }
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Overrides default layer view process to define custom filter blocks.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Block_Catalog_Layer_View extends Mage_Catalog_Block_Layer_View
11
+ {
12
+ /**
13
+ * Boolean block name.
14
+ *
15
+ * @var string
16
+ */
17
+ protected $_booleanFilterBlockName;
18
+
19
+ /**
20
+ * Registers current layer in registry.
21
+ *
22
+ * @see Mage_Catalog_Block_Product_List::getLayer()
23
+ */
24
+ protected function _construct()
25
+ {
26
+ parent::_construct();
27
+ Mage::unregister('current_layer');
28
+ Mage::register('current_layer', $this->getLayer());
29
+ }
30
+
31
+ /**
32
+ * Modifies default block names to specific ones if engine is active.
33
+ */
34
+ protected function _initBlocks()
35
+ {
36
+ parent::_initBlocks();
37
+ if (Mage::helper('choiceai_search')->isActiveEngine()) {
38
+ $this->_categoryBlockName = 'choiceai_search/catalog_layer_filter_category';
39
+ $this->_attributeFilterBlockName = 'choiceai_search/catalog_layer_filter_attribute';
40
+ $this->_priceFilterBlockName = 'choiceai_search/catalog_layer_filter_price';
41
+ $this->_decimalFilterBlockName = 'choiceai_search/catalog_layer_filter_decimal';
42
+ $this->_booleanFilterBlockName = 'choiceai_search/catalog_layer_filter_boolean';
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Prepares layout if engine is active.
48
+ * Difference between parent method is addFacetCondition() call on each created block.
49
+ *
50
+ * @return ChoiceAI_Search_Block_Catalog_Layer_View
51
+ */
52
+ protected function _prepareLayout()
53
+ {
54
+ if (Mage::helper('choiceai_search')->isActiveEngine()) {
55
+ $stateBlock = $this->getLayout()->createBlock($this->_stateBlockName)
56
+ ->setLayer($this->getLayer());
57
+
58
+ $categoryBlock = $this->getLayout()->createBlock($this->_categoryBlockName)
59
+ ->setLayer($this->getLayer())
60
+ ->init();
61
+
62
+ $this->setChild('layer_state', $stateBlock);
63
+ $this->setChild('category_filter', $categoryBlock->addFacetCondition());
64
+
65
+ $filterableAttributes = $this->_getFilterableAttributes();
66
+ $filters = array();
67
+ foreach ($filterableAttributes as $attribute) {
68
+ if ($attribute->getAttributeCode() == 'price') {
69
+ $filterBlockName = $this->_priceFilterBlockName;
70
+ } elseif ($attribute->getBackendType() == 'decimal') {
71
+ $filterBlockName = $this->_decimalFilterBlockName;
72
+ } elseif ($attribute->getSourceModel() == 'eav/entity_attribute_source_boolean') {
73
+ $filterBlockName = $this->_booleanFilterBlockName;
74
+ } else {
75
+ $filterBlockName = $this->_attributeFilterBlockName;
76
+ }
77
+
78
+ $filters[$attribute->getAttributeCode() . '_filter'] = $this->getLayout()->createBlock($filterBlockName)
79
+ ->setLayer($this->getLayer())
80
+ ->setAttributeModel($attribute)
81
+ ->init();
82
+ }
83
+
84
+ foreach ($filters as $filterName => $block) {
85
+ $this->setChild($filterName, $block->addFacetCondition());
86
+ }
87
+
88
+ $this->getLayer()->apply();
89
+
90
+ // Causing a request to the data server, without sort by param
91
+ $this->getLayer()->getProductCollection()->load();
92
+ } else {
93
+ parent::_prepareLayout();
94
+ }
95
+
96
+ return $this;
97
+ }
98
+
99
+ /**
100
+ * Returns current catalog layer.
101
+ *
102
+ * @return ChoiceAI_Search_Model_Catalog_Layer|Mage_Catalog_Model_Layer
103
+ */
104
+ public function getLayer()
105
+ {
106
+ if (Mage::helper('choiceai_search')->isActiveEngine()) {
107
+ return Mage::getSingleton('choiceai_search/catalog_layer');
108
+ }
109
+
110
+ return parent::getLayer();
111
+ }
112
+ }
app/code/local/ChoiceAI/Search/Block/Catalog/Product/List.php CHANGED
@@ -46,6 +46,7 @@ class ChoiceAI_Search_Block_Catalog_Product_List extends Mage_Catalog_Block_Prod
46
  if ($helper->isActiveEngine()) {
47
  return Mage::getSingleton('choiceai_search/catalogsearch_layer');
48
  }
 
49
  return parent::getLayer();
50
  }
51
 
46
  if ($helper->isActiveEngine()) {
47
  return Mage::getSingleton('choiceai_search/catalogsearch_layer');
48
  }
49
+
50
  return parent::getLayer();
51
  }
52
 
app/code/local/ChoiceAI/Search/Block/Catalog/Product/List/Toolbar.php CHANGED
@@ -6,7 +6,8 @@
6
  * Time: 6:04 PM
7
  */
8
 
9
- class ChoiceAI_Search_Block_Catalog_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar {
 
10
 
11
  const IS_ACTIVE = 'choiceai_personalisation/settings/active';
12
 
@@ -18,13 +19,15 @@ class ChoiceAI_Search_Block_Catalog_Product_List_Toolbar extends Mage_Catalog_Bl
18
  */
19
  public function getCurrentOrder()
20
  {
 
 
21
  // To set currently selected sort by option to extended/overridden one, in case of search/productlist
22
- if(Mage::helper('choiceai_search')->isActiveEngine()) {
23
- if ((!isset($_REQUEST['order']) ||is_null($_REQUEST['order'])) && isset($_SESSION['plist_sort_by'])) {
24
- return $_SESSION['plist_sort_by'];
25
- } else if (isset($_SESSION['plist_sort_by']) && isset($_REQUEST['order']) && $_REQUEST['order'] == $_SESSION['plist_sort_by']) {
26
- return $_SESSION['plist_sort_by'];
27
- } else{
28
  return parent::getCurrentOrder();
29
  }
30
  } else {
6
  * Time: 6:04 PM
7
  */
8
 
9
+ class ChoiceAI_Search_Block_Catalog_Product_List_Toolbar extends Mage_Catalog_Block_Product_List_Toolbar
10
+ {
11
 
12
  const IS_ACTIVE = 'choiceai_personalisation/settings/active';
13
 
19
  */
20
  public function getCurrentOrder()
21
  {
22
+ $order = Mage::app()->getRequest()->getQuery('order');
23
+ $session = Mage::getSingleton('core/session');
24
  // To set currently selected sort by option to extended/overridden one, in case of search/productlist
25
+ if (Mage::helper('choiceai_search')->isActiveEngine()) {
26
+ if ((!isset($order) || $order === null) && isset($session['plist_sort_by'])) {
27
+ return $session['plist_sort_by'];
28
+ } else if (isset($session['plist_sort_by']) && isset($order) && $order == $session['plist_sort_by']) {
29
+ return $session['plist_sort_by'];
30
+ } else {
31
  return parent::getCurrentOrder();
32
  }
33
  } else {
app/code/local/ChoiceAI/Search/Block/Catalogsearch/Enterprise/Layer.php CHANGED
@@ -1,4 +1,5 @@
1
  <?php
 
2
  /**
3
  * Overrides default layer view process to define custom filter blocks.
4
  *
@@ -29,7 +30,7 @@ class ChoiceAI_Search_Block_Catalogsearch_Enterprise_Layer extends Enterprise_Se
29
  $this->_attributeFilterBlockName = 'choiceai_search/catalogsearch_layer_filter_attribute';
30
  $this->_priceFilterBlockName = 'choiceai_search/catalog_layer_filter_price';
31
  $this->_decimalFilterBlockName = 'choiceai_search/catalog_layer_filter_decimal';
32
- $this->_booleanFilterBlockName = 'choiceai_search/catalog_layer_filter_boolean';
33
  }
34
  }
35
 
@@ -44,7 +45,6 @@ class ChoiceAI_Search_Block_Catalogsearch_Enterprise_Layer extends Enterprise_Se
44
  /** @var $helper ChoiceAI_Search_Helper_Data */
45
  $helper = Mage::helper('choiceai_search');
46
  if ($helper->isActiveEngine()) {
47
-
48
  $stateBlock = $this->getLayout()->createBlock($this->_stateBlockName)
49
  ->setLayer($this->getLayer());
50
 
@@ -80,7 +80,7 @@ class ChoiceAI_Search_Block_Catalogsearch_Enterprise_Layer extends Enterprise_Se
80
 
81
  $this->getLayer()->apply();
82
  $this->getLayer()->getProductCollection()->load();
83
- }else{
84
  parent::_prepareLayout();
85
  }
86
 
@@ -110,6 +110,7 @@ class ChoiceAI_Search_Block_Catalogsearch_Enterprise_Layer extends Enterprise_Se
110
  if ($helper->isActiveEngine()) {
111
  return Mage::getSingleton('choiceai_search/catalogsearch_layer');
112
  }
 
113
  return parent::getLayer();
114
  }
115
  }
1
  <?php
2
+
3
  /**
4
  * Overrides default layer view process to define custom filter blocks.
5
  *
30
  $this->_attributeFilterBlockName = 'choiceai_search/catalogsearch_layer_filter_attribute';
31
  $this->_priceFilterBlockName = 'choiceai_search/catalog_layer_filter_price';
32
  $this->_decimalFilterBlockName = 'choiceai_search/catalog_layer_filter_decimal';
33
+ $this->_booleanFilterBlockName = 'choiceai_search/catalog_layer_filter_boolean';
34
  }
35
  }
36
 
45
  /** @var $helper ChoiceAI_Search_Helper_Data */
46
  $helper = Mage::helper('choiceai_search');
47
  if ($helper->isActiveEngine()) {
 
48
  $stateBlock = $this->getLayout()->createBlock($this->_stateBlockName)
49
  ->setLayer($this->getLayer());
50
 
80
 
81
  $this->getLayer()->apply();
82
  $this->getLayer()->getProductCollection()->load();
83
+ } else {
84
  parent::_prepareLayout();
85
  }
86
 
110
  if ($helper->isActiveEngine()) {
111
  return Mage::getSingleton('choiceai_search/catalogsearch_layer');
112
  }
113
+
114
  return parent::getLayer();
115
  }
116
  }
app/code/local/ChoiceAI/Search/Block/Catalogsearch/Layer.php CHANGED
@@ -1,115 +1,116 @@
1
- <?php
2
- /**
3
- * Overrides default layer view process to define custom filter blocks.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Block_Catalogsearch_Layer extends Mage_CatalogSearch_Block_Layer
10
- {
11
- /**
12
- * Boolean block name.
13
- *
14
- * @var string
15
- */
16
- protected $_booleanFilterBlockName;
17
-
18
- /**
19
- * Modifies default block names to specific ones if engine is active.
20
- */
21
- protected function _initBlocks()
22
- {
23
- parent::_initBlocks();
24
-
25
- if (Mage::helper('choiceai_search')->isActiveEngine()) {
26
- Mage::unregister('current_layer');
27
- Mage::register('current_layer', $this->getLayer());
28
- $this->_categoryBlockName = 'choiceai_search/catalog_layer_filter_category';
29
- $this->_attributeFilterBlockName = 'choiceai_search/catalogsearch_layer_filter_attribute';
30
- $this->_priceFilterBlockName = 'choiceai_search/catalog_layer_filter_price';
31
- $this->_decimalFilterBlockName = 'choiceai_search/catalog_layer_filter_decimal';
32
- $this->_booleanFilterBlockName = 'choiceai_search/catalog_layer_filter_boolean';
33
- }
34
- }
35
-
36
- /**
37
- * Prepares layout if engine is active.
38
- * Difference between parent method is addFacetCondition() call on each created block.
39
- *
40
- * @return ChoiceAI_Search_Block_Catalogsearch_Layer
41
- */
42
- protected function _prepareLayout()
43
- {
44
- /** @var $helper ChoiceAI_Search_Helper_Data */
45
- $helper = Mage::helper('choiceai_search');
46
- if ($helper->isActiveEngine()) {
47
-
48
- $stateBlock = $this->getLayout()->createBlock($this->_stateBlockName)
49
- ->setLayer($this->getLayer());
50
-
51
- $categoryBlock = $this->getLayout()->createBlock($this->_categoryBlockName)
52
- ->setLayer($this->getLayer())
53
- ->init();
54
-
55
- $this->setChild('layer_state', $stateBlock);
56
- $this->setChild('category_filter', $categoryBlock->addFacetCondition());
57
-
58
- $filterableAttributes = $this->_getFilterableAttributes();
59
- $filters = array();
60
- foreach ($filterableAttributes as $attribute) {
61
- if ($attribute->getAttributeCode() == 'price') {
62
- $filterBlockName = $this->_priceFilterBlockName;
63
- } elseif ($attribute->getSourceModel() == 'eav/entity_attribute_source_boolean') {
64
- $filterBlockName = $this->_booleanFilterBlockName;
65
- } elseif ($attribute->getBackendType() == 'decimal') {
66
- $filterBlockName = $this->_decimalFilterBlockName;
67
- } else {
68
- $filterBlockName = $this->_attributeFilterBlockName;
69
- }
70
-
71
- $filters[$attribute->getAttributeCode() . '_filter'] = $this->getLayout()->createBlock($filterBlockName)
72
- ->setLayer($this->getLayer())
73
- ->setAttributeModel($attribute)
74
- ->init();
75
- }
76
-
77
- foreach ($filters as $filterName => $block) {
78
- $this->setChild($filterName, $block->addFacetCondition());
79
- }
80
-
81
- $this->getLayer()->apply();
82
- $this->getLayer()->getProductCollection()->load();
83
- }else{
84
- parent::_prepareLayout();
85
- }
86
-
87
- return $this;
88
- }
89
-
90
- /**
91
- * Checks display availability of layer block.
92
- *
93
- * @return bool
94
- */
95
- public function canShowBlock()
96
- {
97
- $this->getLayer()->getProductCollection();
98
- return ($this->canShowOptions() || count($this->getLayer()->getState()->getFilters()));
99
- }
100
-
101
- /**
102
- * Returns current catalog layer.
103
- *
104
- * @return ChoiceAI_Search_Model_Catalogsearch_Layer|Mage_Catalog_Model_Layer
105
- */
106
- public function getLayer()
107
- {
108
- /** @var $helper ChoiceAI_Search_Helper_Data */
109
- $helper = Mage::helper('choiceai_search');
110
- if ($helper->isActiveEngine()) {
111
- return Mage::getSingleton('choiceai_search/catalogsearch_layer');
112
- }
113
- return parent::getLayer();
114
- }
115
- }
 
1
+ <?php
2
+
3
+ /**
4
+ * Overrides default layer view process to define custom filter blocks.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Block_Catalogsearch_Layer extends Mage_CatalogSearch_Block_Layer
11
+ {
12
+ /**
13
+ * Boolean block name.
14
+ *
15
+ * @var string
16
+ */
17
+ protected $_booleanFilterBlockName;
18
+
19
+ /**
20
+ * Modifies default block names to specific ones if engine is active.
21
+ */
22
+ protected function _initBlocks()
23
+ {
24
+ parent::_initBlocks();
25
+
26
+ if (Mage::helper('choiceai_search')->isActiveEngine()) {
27
+ Mage::unregister('current_layer');
28
+ Mage::register('current_layer', $this->getLayer());
29
+ $this->_categoryBlockName = 'choiceai_search/catalog_layer_filter_category';
30
+ $this->_attributeFilterBlockName = 'choiceai_search/catalogsearch_layer_filter_attribute';
31
+ $this->_priceFilterBlockName = 'choiceai_search/catalog_layer_filter_price';
32
+ $this->_decimalFilterBlockName = 'choiceai_search/catalog_layer_filter_decimal';
33
+ $this->_booleanFilterBlockName = 'choiceai_search/catalog_layer_filter_boolean';
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Prepares layout if engine is active.
39
+ * Difference between parent method is addFacetCondition() call on each created block.
40
+ *
41
+ * @return ChoiceAI_Search_Block_Catalogsearch_Layer
42
+ */
43
+ protected function _prepareLayout()
44
+ {
45
+ /** @var $helper ChoiceAI_Search_Helper_Data */
46
+ $helper = Mage::helper('choiceai_search');
47
+ if ($helper->isActiveEngine()) {
48
+ $stateBlock = $this->getLayout()->createBlock($this->_stateBlockName)
49
+ ->setLayer($this->getLayer());
50
+
51
+ $categoryBlock = $this->getLayout()->createBlock($this->_categoryBlockName)
52
+ ->setLayer($this->getLayer())
53
+ ->init();
54
+
55
+ $this->setChild('layer_state', $stateBlock);
56
+ $this->setChild('category_filter', $categoryBlock->addFacetCondition());
57
+
58
+ $filterableAttributes = $this->_getFilterableAttributes();
59
+ $filters = array();
60
+ foreach ($filterableAttributes as $attribute) {
61
+ if ($attribute->getAttributeCode() == 'price') {
62
+ $filterBlockName = $this->_priceFilterBlockName;
63
+ } elseif ($attribute->getSourceModel() == 'eav/entity_attribute_source_boolean') {
64
+ $filterBlockName = $this->_booleanFilterBlockName;
65
+ } elseif ($attribute->getBackendType() == 'decimal') {
66
+ $filterBlockName = $this->_decimalFilterBlockName;
67
+ } else {
68
+ $filterBlockName = $this->_attributeFilterBlockName;
69
+ }
70
+
71
+ $filters[$attribute->getAttributeCode() . '_filter'] = $this->getLayout()->createBlock($filterBlockName)
72
+ ->setLayer($this->getLayer())
73
+ ->setAttributeModel($attribute)
74
+ ->init();
75
+ }
76
+
77
+ foreach ($filters as $filterName => $block) {
78
+ $this->setChild($filterName, $block->addFacetCondition());
79
+ }
80
+
81
+ $this->getLayer()->apply();
82
+ $this->getLayer()->getProductCollection()->load();
83
+ } else {
84
+ parent::_prepareLayout();
85
+ }
86
+
87
+ return $this;
88
+ }
89
+
90
+ /**
91
+ * Checks display availability of layer block.
92
+ *
93
+ * @return bool
94
+ */
95
+ public function canShowBlock()
96
+ {
97
+ $this->getLayer()->getProductCollection();
98
+ return ($this->canShowOptions() || count($this->getLayer()->getState()->getFilters()));
99
+ }
100
+
101
+ /**
102
+ * Returns current catalog layer.
103
+ *
104
+ * @return ChoiceAI_Search_Model_Catalogsearch_Layer|Mage_Catalog_Model_Layer
105
+ */
106
+ public function getLayer()
107
+ {
108
+ /** @var $helper ChoiceAI_Search_Helper_Data */
109
+ $helper = Mage::helper('choiceai_search');
110
+ if ($helper->isActiveEngine()) {
111
+ return Mage::getSingleton('choiceai_search/catalogsearch_layer');
112
+ }
113
+
114
+ return parent::getLayer();
115
+ }
116
+ }
app/code/local/ChoiceAI/Search/Block/Catalogsearch/Layer/Filter/Attribute.php CHANGED
@@ -1,46 +1,47 @@
1
- <?php
2
- /**
3
- * Handles attribute filtering in layered navigation in a query search context.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Block_Catalogsearch_Layer_Filter_Attribute extends Mage_Catalog_Block_Layer_Filter_Abstract
10
- {
11
- /**
12
- * Defines specific filter model name.
13
- *
14
- * @see ChoiceAI_Search_Model_Catalogsearch_Layer_Filter_Attribute
15
- */
16
- public function __construct()
17
- {
18
- parent::__construct();
19
- $this->_filterModelName = 'choiceai_search/catalogsearch_layer_filter_attribute';
20
- }
21
-
22
- /**
23
- * Prepares filter model.
24
- *
25
- * @return ChoiceAI_Search_Block_Catalogsearch_Layer_Filter_Attribute
26
- */
27
- protected function _prepareFilter()
28
- {
29
- $this->_filter->setAttributeModel($this->getAttributeModel());
30
-
31
- return $this;
32
- }
33
-
34
- /**
35
- * Adds facet condition to filter.
36
- *
37
- * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute::addFacetCondition()
38
- * @return ChoiceAI_Search_Block_Catalogsearch_Layer_Filter_Attribute
39
- */
40
- public function addFacetCondition()
41
- {
42
- $this->_filter->addFacetCondition();
43
-
44
- return $this;
45
- }
46
- }
 
1
+ <?php
2
+
3
+ /**
4
+ * Handles attribute filtering in layered navigation in a query search context.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Block_Catalogsearch_Layer_Filter_Attribute extends Mage_Catalog_Block_Layer_Filter_Abstract
11
+ {
12
+ /**
13
+ * Defines specific filter model name.
14
+ *
15
+ * @see ChoiceAI_Search_Model_Catalogsearch_Layer_Filter_Attribute
16
+ */
17
+ public function __construct()
18
+ {
19
+ parent::__construct();
20
+ $this->_filterModelName = 'choiceai_search/catalogsearch_layer_filter_attribute';
21
+ }
22
+
23
+ /**
24
+ * Prepares filter model.
25
+ *
26
+ * @return ChoiceAI_Search_Block_Catalogsearch_Layer_Filter_Attribute
27
+ */
28
+ protected function _prepareFilter()
29
+ {
30
+ $this->_filter->setAttributeModel($this->getAttributeModel());
31
+
32
+ return $this;
33
+ }
34
+
35
+ /**
36
+ * Adds facet condition to filter.
37
+ *
38
+ * @see ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute::addFacetCondition()
39
+ * @return ChoiceAI_Search_Block_Catalogsearch_Layer_Filter_Attribute
40
+ */
41
+ public function addFacetCondition()
42
+ {
43
+ $this->_filter->addFacetCondition();
44
+
45
+ return $this;
46
+ }
47
+ }
app/code/local/ChoiceAI/Search/Block/Catalogsearch/Result.php CHANGED
@@ -6,8 +6,10 @@
6
  * Time: 12:47 PM
7
  */
8
 
9
- class ChoiceAI_Search_Block_Catalogsearch_Result extends Mage_CatalogSearch_Block_Result {
 
10
  const IS_ACTIVE = 'choiceai_personalisation/settings/active';
 
11
  /**
12
  * Set search available list orders
13
  *
@@ -15,7 +17,7 @@ class ChoiceAI_Search_Block_Catalogsearch_Result extends Mage_CatalogSearch_Bloc
15
  */
16
  public function setListOrders()
17
  {
18
- if(Mage::helper('choiceai_search')->isActiveEngine()) {
19
  $category = Mage::getSingleton('catalog/layer')
20
  ->getCurrentCategory();
21
  /* @var $category Mage_Catalog_Model_Category */
@@ -27,7 +29,7 @@ class ChoiceAI_Search_Block_Catalogsearch_Result extends Mage_CatalogSearch_Bloc
27
  ->setAvailableOrders($availableOrders)
28
  ->setDefaultDirection('desc');
29
  // ->setSortBy('relevance');
30
- }else{
31
  return parent::setListOrders();
32
  }
33
 
6
  * Time: 12:47 PM
7
  */
8
 
9
+ class ChoiceAI_Search_Block_Catalogsearch_Result extends Mage_CatalogSearch_Block_Result
10
+ {
11
  const IS_ACTIVE = 'choiceai_personalisation/settings/active';
12
+
13
  /**
14
  * Set search available list orders
15
  *
17
  */
18
  public function setListOrders()
19
  {
20
+ if (Mage::helper('choiceai_search')->isActiveEngine()) {
21
  $category = Mage::getSingleton('catalog/layer')
22
  ->getCurrentCategory();
23
  /* @var $category Mage_Catalog_Model_Category */
29
  ->setAvailableOrders($availableOrders)
30
  ->setDefaultDirection('desc');
31
  // ->setSortBy('relevance');
32
+ } else {
33
  return parent::setListOrders();
34
  }
35
 
app/code/local/ChoiceAI/Search/Helper/Choiceaisearch.php CHANGED
@@ -1,15 +1,16 @@
1
- <?php
2
- /**
3
- *
4
- * @package ChoiceAI_Search
5
- * @copyright Copyright (c) MineWhat
6
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
- */
8
- class ChoiceAI_Search_Helper_ChoiceAIsearch extends ChoiceAI_Search_Helper_Data
9
- {
10
-
11
- public function getEngineConfigData($prefix = '', $website = null)
12
- {
13
- return Mage::helper('choiceai_searchcore')->getEngineConfigData($prefix, $website);
14
- }
15
- }
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Helper_ChoiceAIsearch extends ChoiceAI_Search_Helper_Data
10
+ {
11
+
12
+ public function getEngineConfigData($prefix = '', $website = null)
13
+ {
14
+ return Mage::helper('choiceai_searchcore')->getEngineConfigData($prefix, $website);
15
+ }
16
+ }
app/code/local/ChoiceAI/Search/Helper/Data.php CHANGED
@@ -1,425 +1,450 @@
1
- <?php
2
-
3
- /**
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Helper_Data extends Mage_Core_Helper_Abstract
10
- {
11
- /**
12
- * Allowed languages.
13
- * Example: array('en_US' => 'en', 'fr_FR' => 'fr')
14
- *
15
- * @var array
16
- */
17
- protected $_languageCodes = array();
18
-
19
- /**
20
- * Searchable attributes.
21
- *
22
- * @var array
23
- */
24
- protected $_searchableAttributes;
25
-
26
- /**
27
- * Sortable attributes.
28
- *
29
- * @var array
30
- */
31
- protected $_sortableAttributes;
32
-
33
- /**
34
- * Text field types.
35
- *
36
- * @var array
37
- */
38
- protected $_textFieldTypes = array(
39
- 'text',
40
- 'varchar',
41
- );
42
-
43
- /**
44
- * Unlocalized field types.
45
- *
46
- * @var array
47
- */
48
- protected $_unlocalizedFieldTypes = array(
49
- 'datetime',
50
- 'decimal',
51
- );
52
-
53
- /**
54
- * Boolean field which stores choiceai active or not
55
- *
56
- * @var boolean
57
- */
58
- public $is_active = NULL;
59
-
60
-
61
- const IS_ACTIVE = 'choiceai_personalisation/settings/active';
62
- const CONFIG_KEY = 'choiceai_personalisation/settings/config';
63
-
64
- /**
65
- * Returns attribute field name (localized if needed).
66
- *
67
- * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
68
- * @param string $localeCode
69
- * @return string
70
- */
71
- public function getAttributeFieldName($attribute, $localeCode = null)
72
- {
73
- if (is_string($attribute)) {
74
- $this->getSearchableAttributes(); // populate searchable attributes if not already set
75
- if (!isset($this->_searchableAttributes[$attribute])) {
76
- return $attribute;
77
- }
78
- $attribute = $this->_searchableAttributes[$attribute];
79
- }
80
- $attributeCode = $attribute->getAttributeCode();
81
- $backendType = $attribute->getBackendType();
82
-
83
- if ($attributeCode != 'score' && in_array($backendType, $this->_textFieldTypes)) {
84
- if (null === $localeCode) {
85
- $localeCode = $this->getLocaleCode();
86
- }
87
- // $languageCode = $this->getLanguageCodeByLocaleCode($localeCode);
88
- // $languageSuffix = "_fq";
89
- //$attributeCode .= $languageSuffix;
90
- }
91
-
92
- return $attributeCode;
93
- }
94
-
95
- /**
96
- * Returns search engine config data.
97
- *
98
- * @param string $prefix
99
- * @param mixed $store
100
- * @return array
101
- */
102
- public function getEngineConfigData($prefix = '', $website = null)
103
- {
104
- return Mage::helper('choiceai_searchcore')->getEngineConfigData($prefix, $website);
105
- }
106
-
107
- /**
108
- * Returns EAV config singleton.
109
- *
110
- * @return Mage_Eav_Model_Config
111
- */
112
- public function getEavConfig()
113
- {
114
- return Mage::getSingleton('eav/config');
115
- }
116
-
117
- /**
118
- * Returns language code of specified locale code.
119
- *
120
- * @param string $localeCode
121
- * @return bool
122
- */
123
- public function getLanguageCodeByLocaleCode($localeCode)
124
- {
125
- $localeCode = (string)$localeCode;
126
- if (!$localeCode) {
127
- return false;
128
- }
129
-
130
- if (!isset($this->_languageCodes[$localeCode])) {
131
- $languages = $this->getSupportedLanguages();
132
- $this->_languageCodes[$localeCode] = false;
133
- foreach ($languages as $code => $locales) {
134
- if (is_array($locales)) {
135
- if (in_array($localeCode, $locales)) {
136
- $this->_languageCodes[$localeCode] = $code;
137
- }
138
- } elseif ($localeCode == $locales) {
139
- $this->_languageCodes[$localeCode] = $code;
140
- }
141
- }
142
- }
143
-
144
- return $this->_languageCodes[$localeCode];
145
- }
146
-
147
- /**
148
- * Returns store locale code.
149
- *
150
- * @param null $store
151
- * @return string
152
- */
153
- public function getLocaleCode($store = null)
154
- {
155
- return Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $store);
156
- }
157
-
158
- /**
159
- * Returns searched parameter as array.
160
- *
161
- * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
162
- * @param mixed $value
163
- * @return array
164
- */
165
- public function getSearchParam($attribute, $value)
166
- {
167
- if (empty($value) ||
168
- (isset($value['from']) && empty($value['from']) &&
169
- isset($value['to']) && empty($value['to']))
170
- ) {
171
- return false;
172
- }
173
-
174
- $field = $this->getAttributeFieldName($attribute);
175
- $backendType = $attribute->getBackendType();
176
- if ($backendType == 'datetime') {
177
- $format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
178
- if (is_array($value)) {
179
- foreach ($value as &$val) {
180
- if (!is_empty_date($val)) {
181
- $date = new Zend_Date($val, $format);
182
- $val = $date->toString(Zend_Date::ISO_8601) . 'Z';
183
- }
184
- }
185
- unset($val);
186
- } else {
187
- if (!is_empty_date($value)) {
188
- $date = new Zend_Date($value, $format);
189
- $value = $date->toString(Zend_Date::ISO_8601) . 'Z';
190
- }
191
- }
192
- }
193
-
194
- if ($attribute->usesSource()) {
195
- $attribute->setStoreId(Mage::app()->getStore()->getId());
196
- }
197
-
198
- return array($field => $value);
199
- }
200
-
201
- /**
202
- * Defines supported languages for snowball filter.
203
- *
204
- * @return array
205
- */
206
- public function getSupportedLanguages()
207
- {
208
- $default = array(
209
- /**
210
- * SnowBall filter based
211
- */
212
- // Danish
213
- 'da' => 'da_DK',
214
- // Dutch
215
- 'nl' => 'nl_NL',
216
- // English
217
- 'en' => array('en_AU', 'en_CA', 'en_NZ', 'en_GB', 'en_US'),
218
- // Finnish
219
- 'fi' => 'fi_FI',
220
- // French
221
- 'fr' => array('fr_CA', 'fr_FR'),
222
- // German
223
- 'de' => array('de_DE', 'de_DE', 'de_AT'),
224
- // Italian
225
- 'it' => array('it_IT', 'it_CH'),
226
- // Norwegian
227
- 'nb' => array('nb_NO', 'nn_NO'),
228
- // Portuguese
229
- 'pt' => array('pt_BR', 'pt_PT'),
230
- // Romanian
231
- 'ro' => 'ro_RO',
232
- // Russian
233
- 'ru' => 'ru_RU',
234
- // Spanish
235
- 'es' => array('es_AR', 'es_CL', 'es_CO', 'es_CR', 'es_ES', 'es_MX', 'es_PA', 'es_PE', 'es_VE'),
236
- // Swedish
237
- 'sv' => 'sv_SE',
238
- // Turkish
239
- 'tr' => 'tr_TR',
240
-
241
- /**
242
- * Lucene class based
243
- */
244
- // Czech
245
- 'cs' => 'cs_CZ',
246
- // Greek
247
- 'el' => 'el_GR',
248
- // Thai
249
- 'th' => 'th_TH',
250
- // Chinese
251
- 'zh' => array('zh_CN', 'zh_HK', 'zh_TW'),
252
- // Japanese
253
- 'ja' => 'ja_JP',
254
- // Korean
255
- 'ko' => 'ko_KR'
256
- );
257
-
258
- return $default;
259
- }
260
-
261
- /**
262
- * Checks if configured engine is active.
263
- *
264
- * @return bool
265
- */
266
- public function isActiveEngine()
267
- {
268
- if (is_null($this->is_active)) {
269
- $storeConfig = json_decode(Mage::getStoreConfig(self::CONFIG_KEY));
270
- $sortbyObjs = $storeConfig->sortby;
271
-
272
- // Getting URL Path
273
- $currentReqPath = explode("?", $_SERVER['REQUEST_URI'])[0];
274
- $currentReqPath = rtrim($currentReqPath, "/");
275
-
276
- // Getting param keys in array var $paramPairs
277
- parse_str($_SERVER['QUERY_STRING'], $paramPairs);
278
- // Getting query keys
279
- $currentReqParams = array();
280
- if (count($paramPairs)) {
281
- foreach ($paramPairs as $key => $paramPair)
282
- $currentReqParams[] = $key;
283
- }
284
-
285
- // Refining URL path
286
- // My own local installation case: localhost/magento/
287
- if (strpos($currentReqPath, "/magento/") !== false)
288
- $currentReqPath = str_replace("/magento/", "/", $currentReqPath);
289
-
290
- // Making www.store.com/index.php/abcd => www.store.com/abcd
291
- if (strpos($currentReqPath, "/index.php/") !== false)
292
- $currentReqPath = str_replace("/index.php/", "/", $currentReqPath);
293
-
294
- $isPluginActive = Mage::getStoreConfig(self::IS_ACTIVE) == '1';
295
- $choiceOptions = array();
296
-
297
- if ($isPluginActive) {
298
- foreach ($sortbyObjs as $sortbyObj) {
299
- if (isset($sortbyObj->rule->paths)) {
300
- if (in_array($currentReqPath, $sortbyObj->rule->paths)) {
301
- $choiceOptions = $this->_getOptionsAddedByChoice($sortbyObj);
302
-
303
- if (count($choiceOptions) < 1)
304
- $this->is_active = true;
305
- else if (!isset($_REQUEST["order"]) && is_null($_REQUEST["order"]))
306
- $this->_setDefaultSortOption($sortbyObj, $storeConfig);
307
- break;
308
- }
309
- }
310
-
311
- if (isset($sortbyObj->rule->params)) {
312
- if (!empty(array_intersect($currentReqParams, $sortbyObj->rule->params))) {
313
- $choiceOptions = $this->_getOptionsAddedByChoice($sortbyObj);
314
-
315
- if (count($choiceOptions) < 1)
316
- $this->is_active = true;
317
- else if (!isset($_REQUEST["order"]) || is_null($_REQUEST["order"]))
318
- $this->_setDefaultSortOption($sortbyObj, $storeConfig);
319
- break;
320
- }
321
- }
322
- }
323
-
324
- Mage::register('expId', $sortbyObj->expId, true);
325
- $device = $this->getDevice($_SERVER['HTTP_USER_AGENT']);
326
-
327
- if (count($choiceOptions) && isset($_REQUEST["order"]) && in_array($_REQUEST["order"], $choiceOptions)) {
328
- if(isset($sortbyObj) && isset($sortbyObj->device)) {
329
- if (in_array("all", $sortbyObj->device) || in_array($device, $sortbyObj->device))
330
- $this->is_active = true;
331
- else
332
- $this->is_active = false;
333
- }
334
- else
335
- $this->is_active = false;
336
- }
337
- }
338
- }
339
-
340
- return $this->is_active;
341
- }
342
-
343
- private function getDevice($userAgent)
344
- {
345
- if (stripos($userAgent, "ipad") !== false) {
346
- return "desktoptablet";
347
- // return "tablet";
348
- } else if (stripos($userAgent, "android") !== false || stripos($userAgent, "mobile") !== false || stripos($userAgent, "iphone") !== false){
349
- return "desktoptablet";
350
- // return "mobile";
351
- } else
352
- return 'desktop';
353
- }
354
-
355
- // If sort order is default, $_REQUEST["order"] will not exist
356
- // This adds a default value in it
357
- // author: Harkirat
358
- private function _setDefaultSortOption($sortbyObj, $storeConfig)
359
- {
360
- if (isset($sortbyObj->extend)) {
361
- if (count($sortbyObj->extend)) {
362
- foreach ($sortbyObj->extend as $optionKey => $optionValue) {
363
- $_REQUEST['order'] = $optionKey;
364
- break;
365
- }
366
- } else {
367
- $this->is_active = true;
368
- }
369
- } else if (isset($sortbyObj->override) && $storeConfig->default_search_sort) {
370
- $_REQUEST["order"] = $storeConfig->default_search_sort;
371
- } else if (!isset($sortbyObj->override) && !isset($sortbyObj->extend)) {
372
- $_REQUEST["order"] = "takeover_mode";
373
- }
374
- // } else if(isset($_SESSION['catalog']) && isset($_SESSION['catalog']['sort_order'])){
375
- // // If prod list page, use the session value
376
- // // This case although seems useless
377
- // $_REQUEST["order"] = $_SESSION['catalog']['sort_order'];
378
- // }
379
- }
380
-
381
- /**
382
- * @param $sortbyObj
383
- * @return array
384
- */
385
- private function _getOptionsAddedByChoice($sortbyObj)
386
- {
387
- $options = array();
388
-
389
- if (isset($sortbyObj->override)) {
390
- // Search case, override all system options with choice
391
- foreach ($sortbyObj->override as $key => $caiOption)
392
- $options[] = $key;
393
- } elseif (isset($sortbyObj->extend)) {
394
- foreach ($sortbyObj->extend as $key => $option)
395
- $options[] = $key;
396
- }
397
-
398
- return $options;
399
- }
400
-
401
- /**
402
- * Checks if debug mode is enabled.
403
- *
404
- * @return bool
405
- */
406
- public function isDebugEnabled()
407
- {
408
- $config = $this->getEngineConfigData();
409
-
410
- return array_key_exists('enable_debug_mode', $config) && $config['enable_debug_mode'];
411
- }
412
-
413
- /**
414
- * Forces error display.
415
- * Used in Abstract.php model's search function
416
- *
417
- * @param string $error
418
- */
419
- public function showError($error)
420
- {
421
- echo Mage::app()->getLayout()->createBlock('core/messages')
422
- ->addError($error)->getGroupedHtml();
423
- }
424
-
425
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+ class ChoiceAI_Search_Helper_Data extends Mage_Core_Helper_Abstract
10
+ {
11
+ /**
12
+ * Allowed languages.
13
+ * Example: array('en_US' => 'en', 'fr_FR' => 'fr')
14
+ *
15
+ * @var array
16
+ */
17
+ protected $_languageCodes = array();
18
+
19
+ /**
20
+ * Searchable attributes.
21
+ *
22
+ * @var array
23
+ */
24
+ protected $_searchableAttributes;
25
+
26
+ /**
27
+ * Sortable attributes.
28
+ *
29
+ * @var array
30
+ */
31
+ protected $_sortableAttributes;
32
+
33
+ /**
34
+ * Text field types.
35
+ *
36
+ * @var array
37
+ */
38
+ protected $_textFieldTypes = array(
39
+ 'text',
40
+ 'varchar',
41
+ );
42
+
43
+ /**
44
+ * Unlocalized field types.
45
+ *
46
+ * @var array
47
+ */
48
+ protected $_unlocalizedFieldTypes = array(
49
+ 'datetime',
50
+ 'decimal',
51
+ );
52
+
53
+ /**
54
+ * Boolean field which stores choiceai active or not
55
+ *
56
+ * @var boolean
57
+ */
58
+ public $isActive = NULL;
59
+
60
+
61
+ const IS_ACTIVE = 'choiceai_personalisation/settings/active';
62
+ const CONFIG_KEY = 'choiceai_personalisation/settings/config';
63
+
64
+ /**
65
+ * Returns attribute field name (localized if needed).
66
+ *
67
+ * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
68
+ * @param string $localeCode
69
+ * @return string
70
+ */
71
+ public function getAttributeFieldName($attribute, $localeCode = null)
72
+ {
73
+ if (is_string($attribute)) {
74
+ $this->getSearchableAttributes(); // populate searchable attributes if not already set
75
+ if (!isset($this->_searchableAttributes[$attribute])) {
76
+ return $attribute;
77
+ }
78
+
79
+ $attribute = $this->_searchableAttributes[$attribute];
80
+ }
81
+
82
+ $attributeCode = $attribute->getAttributeCode();
83
+ $backendType = $attribute->getBackendType();
84
+
85
+ if ($attributeCode != 'score' && in_array($backendType, $this->_textFieldTypes)) {
86
+ if (null === $localeCode) {
87
+ $localeCode = $this->getLocaleCode();
88
+ }
89
+
90
+ // $languageCode = $this->getLanguageCodeByLocaleCode($localeCode);
91
+ // $languageSuffix = "_fq";
92
+ //$attributeCode .= $languageSuffix;
93
+ }
94
+
95
+ return $attributeCode;
96
+ }
97
+
98
+ /**
99
+ * Returns search engine config data.
100
+ *
101
+ * @param string $prefix
102
+ * @param mixed $store
103
+ * @return array
104
+ */
105
+ public function getEngineConfigData($prefix = '', $website = null)
106
+ {
107
+ return Mage::helper('choiceai_searchcore')->getEngineConfigData($prefix, $website);
108
+ }
109
+
110
+ /**
111
+ * Returns EAV config singleton.
112
+ *
113
+ * @return Mage_Eav_Model_Config
114
+ */
115
+ public function getEavConfig()
116
+ {
117
+ return Mage::getSingleton('eav/config');
118
+ }
119
+
120
+ /**
121
+ * Returns language code of specified locale code.
122
+ *
123
+ * @param string $localeCode
124
+ * @return bool
125
+ */
126
+ public function getLanguageCodeByLocaleCode($localeCode)
127
+ {
128
+ $localeCode = (string)$localeCode;
129
+ if (!$localeCode) {
130
+ return false;
131
+ }
132
+
133
+ if (!isset($this->_languageCodes[$localeCode])) {
134
+ $languages = $this->getSupportedLanguages();
135
+ $this->_languageCodes[$localeCode] = false;
136
+ foreach ($languages as $code => $locales) {
137
+ if (is_array($locales)) {
138
+ if (in_array($localeCode, $locales)) {
139
+ $this->_languageCodes[$localeCode] = $code;
140
+ }
141
+ } elseif ($localeCode == $locales) {
142
+ $this->_languageCodes[$localeCode] = $code;
143
+ }
144
+ }
145
+ }
146
+
147
+ return $this->_languageCodes[$localeCode];
148
+ }
149
+
150
+ /**
151
+ * Returns store locale code.
152
+ *
153
+ * @param null $store
154
+ * @return string
155
+ */
156
+ public function getLocaleCode($store = null)
157
+ {
158
+ return Mage::getStoreConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $store);
159
+ }
160
+
161
+ /**
162
+ * Returns searched parameter as array.
163
+ *
164
+ * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute
165
+ * @param mixed $value
166
+ * @return array
167
+ */
168
+ public function getSearchParam($attribute, $value)
169
+ {
170
+ if (empty($value) ||
171
+ (isset($value['from']) && empty($value['from']) &&
172
+ isset($value['to']) && empty($value['to']))
173
+ ) {
174
+ return false;
175
+ }
176
+
177
+ $field = $this->getAttributeFieldName($attribute);
178
+ $backendType = $attribute->getBackendType();
179
+ if ($backendType == 'datetime') {
180
+ $format = Mage::app()->getLocale()->getDateFormat(Mage_Core_Model_Locale::FORMAT_TYPE_SHORT);
181
+ if (is_array($value)) {
182
+ foreach ($value as &$val) {
183
+ if (!is_empty_date($val)) {
184
+ $date = new Zend_Date($val, $format);
185
+ $val = $date->toString(Zend_Date::ISO_8601) . 'Z';
186
+ }
187
+ }
188
+
189
+ unset($val);
190
+ } else {
191
+ if (!is_empty_date($value)) {
192
+ $date = new Zend_Date($value, $format);
193
+ $value = $date->toString(Zend_Date::ISO_8601) . 'Z';
194
+ }
195
+ }
196
+ }
197
+
198
+ if ($attribute->usesSource()) {
199
+ $attribute->setStoreId(Mage::app()->getStore()->getId());
200
+ }
201
+
202
+ return array($field => $value);
203
+ }
204
+
205
+ /**
206
+ * Defines supported languages for snowball filter.
207
+ *
208
+ * @return array
209
+ */
210
+ public function getSupportedLanguages()
211
+ {
212
+ $default = array(
213
+ /**
214
+ * SnowBall filter based
215
+ */
216
+ // Danish
217
+ 'da' => 'da_DK',
218
+ // Dutch
219
+ 'nl' => 'nl_NL',
220
+ // English
221
+ 'en' => array('en_AU', 'en_CA', 'en_NZ', 'en_GB', 'en_US'),
222
+ // Finnish
223
+ 'fi' => 'fi_FI',
224
+ // French
225
+ 'fr' => array('fr_CA', 'fr_FR'),
226
+ // German
227
+ 'de' => array('de_DE', 'de_DE', 'de_AT'),
228
+ // Italian
229
+ 'it' => array('it_IT', 'it_CH'),
230
+ // Norwegian
231
+ 'nb' => array('nb_NO', 'nn_NO'),
232
+ // Portuguese
233
+ 'pt' => array('pt_BR', 'pt_PT'),
234
+ // Romanian
235
+ 'ro' => 'ro_RO',
236
+ // Russian
237
+ 'ru' => 'ru_RU',
238
+ // Spanish
239
+ 'es' => array('es_AR', 'es_CL', 'es_CO', 'es_CR', 'es_ES', 'es_MX', 'es_PA', 'es_PE', 'es_VE'),
240
+ // Swedish
241
+ 'sv' => 'sv_SE',
242
+ // Turkish
243
+ 'tr' => 'tr_TR',
244
+
245
+ /**
246
+ * Lucene class based
247
+ */
248
+ // Czech
249
+ 'cs' => 'cs_CZ',
250
+ // Greek
251
+ 'el' => 'el_GR',
252
+ // Thai
253
+ 'th' => 'th_TH',
254
+ // Chinese
255
+ 'zh' => array('zh_CN', 'zh_HK', 'zh_TW'),
256
+ // Japanese
257
+ 'ja' => 'ja_JP',
258
+ // Korean
259
+ 'ko' => 'ko_KR'
260
+ );
261
+
262
+ return $default;
263
+ }
264
+
265
+ /**
266
+ * Checks if configured engine is active.
267
+ *
268
+ * @return bool
269
+ */
270
+ public function isActiveEngine()
271
+ {
272
+ if ($this->isActive === null) {
273
+ $server = Mage::app()->getRequest()->getServer();
274
+ $storeConfig = json_decode(Mage::getStoreConfig(self::CONFIG_KEY));
275
+ $sortbyObjs = $storeConfig->sortby;
276
+ // Getting URL Path
277
+ $currentReqPath = explode("?", $server['REQUEST_URI'])[0];
278
+ $currentReqPath = rtrim($currentReqPath, "/");
279
+ // Refining URL path
280
+ // My own local installation case: localhost/magento/
281
+ if (strpos($currentReqPath, "/magento/") !== false)
282
+ $currentReqPath = str_replace("/magento/", "/", $currentReqPath);
283
+
284
+ // Making www.store.com/index.php/abcd => www.store.com/abcd
285
+ if (strpos($currentReqPath, "/index.php/") !== false)
286
+ $currentReqPath = str_replace("/index.php/", "/", $currentReqPath);
287
+ // Getting param keys in array var $paramPairs
288
+ parse_str($server['QUERY_STRING'], $paramPairs);
289
+ // Getting query keys
290
+ $currentReqParams = array();
291
+ if (!empty($paramPairs)) {
292
+ foreach ($paramPairs as $key => $paramPair)
293
+ $currentReqParams[] = $key;
294
+ }
295
+
296
+ $isPluginActive = Mage::getStoreConfig(self::IS_ACTIVE) == '1';
297
+ $choiceOptions = array();
298
+
299
+ if ($isPluginActive) {
300
+ foreach ($sortbyObjs as $sortbyObj) {
301
+ if (isset($sortbyObj->rule->paths)) {
302
+ if (in_array($currentReqPath, $sortbyObj->rule->paths)) {
303
+ $choiceOptions = $this->_getOptionsAddedByChoice($sortbyObj);
304
+
305
+ $order = Mage::app()->getRequest()->getQuery('order');
306
+ if (empty($choiceOptions))
307
+ $this->isActive = true;
308
+ else if (!isset($order) || $order === null)
309
+ $this->_setDefaultSortOption($sortbyObj, $storeConfig);
310
+ break;
311
+ }
312
+ }
313
+
314
+ if (isset($sortbyObj->rule->params)) {
315
+ if (!empty(array_intersect($currentReqParams, $sortbyObj->rule->params))) {
316
+ $choiceOptions = $this->_getOptionsAddedByChoice($sortbyObj);
317
+ $order = Mage::app()->getRequest()->getQuery('order');
318
+ if (empty($choiceOptions))
319
+ $this->isActive = true;
320
+ else if (!isset($order) || $order === null)
321
+ $this->_setDefaultSortOption($sortbyObj, $storeConfig);
322
+ break;
323
+ }
324
+ }
325
+ }
326
+
327
+ $expId = $sortbyObj->expId;
328
+ if ($expId) {
329
+ Mage::register('expId', $expId, true);
330
+ $passback = Mage::getModel('core/cookie')->get("caiexperiment_" . $expId);
331
+ if ($passback) {
332
+ Mage::register('passback', $passback, true);
333
+ }
334
+
335
+ // magento sanitizes . with _ while reading from cookie
336
+ $contextId = Mage::getModel('core/cookie')->get(
337
+ "cai_" . str_replace(
338
+ ".",
339
+ "_", $currentReqPath
340
+ ) . $expId
341
+ );
342
+ if ($contextId) {
343
+ Mage::register('contextId', $contextId, true);
344
+ }
345
+ }
346
+
347
+ $server = Mage::app()->getRequest()->getServer();
348
+ $device = $this->getDevice($server['HTTP_USER_AGENT']);
349
+ $order = Mage::app()->getRequest()->getQuery('order');
350
+ if (!empty($choiceOptions) && isset($order) && in_array($order, $choiceOptions)) {
351
+ if (isset($sortbyObj) && isset($sortbyObj->device)) {
352
+ if (in_array("all", $sortbyObj->device) || in_array($device, $sortbyObj->device))
353
+ $this->isActive = true;
354
+ else
355
+ $this->isActive = false;
356
+ } else
357
+ $this->isActive = false;
358
+ }
359
+ }
360
+ }
361
+
362
+ return $this->isActive;
363
+ }
364
+
365
+ protected function getDevice($userAgent)
366
+ {
367
+ if (stripos($userAgent, "ipad") !== false) {
368
+ return "desktoptablet";
369
+ // return "tablet";
370
+ } else if (stripos($userAgent, "android") !== false || stripos($userAgent, "mobile") !== false ||
371
+ stripos($userAgent, "iphone") !== false) {
372
+ return "desktoptablet";
373
+ // return "mobile";
374
+ } else
375
+ return 'desktop';
376
+ }
377
+
378
+ // If sort order is default, $_REQUEST["order"] will not exist
379
+ // This adds a default value in it
380
+ // author: sumit
381
+ protected function _setDefaultSortOption($sortbyObj, $storeConfig)
382
+ {
383
+ if (isset($sortbyObj->extend)) {
384
+ if (!empty($sortbyObj->extend)) {
385
+ foreach ($sortbyObj->extend as $optionKey => $optionValue) {
386
+ // $_REQUEST['order'] = $optionKey;
387
+ Mage::app()->getRequest()->setQuery('order', $optionKey);
388
+ break;
389
+ }
390
+ } else {
391
+ $this->isActive = true;
392
+ }
393
+ } else if (isset($sortbyObj->override) && $storeConfig->default_search_sort) {
394
+ Mage::app()->getRequest()->setQuery('order', $storeConfig->default_search_sort);
395
+ } else if (!isset($sortbyObj->override) && !isset($sortbyObj->extend)) {
396
+ Mage::app()->getRequest()->setQuery('order', "takeover_mode");
397
+ }
398
+
399
+ // } else if(isset($_SESSION['catalog']) && isset($_SESSION['catalog']['sort_order'])){
400
+ // // If prod list page, use the session value
401
+ // // This case although seems useless
402
+ // $_REQUEST["order"] = $_SESSION['catalog']['sort_order'];
403
+ // }
404
+ }
405
+
406
+ /**
407
+ * @param $sortbyObj
408
+ * @return array
409
+ */
410
+ protected function _getOptionsAddedByChoice($sortbyObj)
411
+ {
412
+ $options = array();
413
+
414
+ if (isset($sortbyObj->override)) {
415
+ // Search case, override all system options with choice
416
+ foreach ($sortbyObj->override as $key => $caiOption)
417
+ $options[] = $key;
418
+ } elseif (isset($sortbyObj->extend)) {
419
+ foreach ($sortbyObj->extend as $key => $option)
420
+ $options[] = $key;
421
+ }
422
+
423
+ return $options;
424
+ }
425
+
426
+ /**
427
+ * Checks if debug mode is enabled.
428
+ *
429
+ * @return bool
430
+ */
431
+ public function isDebugEnabled()
432
+ {
433
+ $config = $this->getEngineConfigData();
434
+
435
+ return array_key_exists('enable_debug_mode', $config) && $config['enable_debug_mode'];
436
+ }
437
+
438
+ /**
439
+ * Forces error display.
440
+ * Used in Abstract.php model's search function
441
+ *
442
+ * @param string $error
443
+ */
444
+ public function showError($error)
445
+ {
446
+ // echo Mage::app()->getLayout()->createBlock('core/messages')
447
+ // ->addError($error)->getGroupedHtml();
448
+ }
449
+
450
+ }
app/code/local/ChoiceAI/Search/Helper/Productimg.php CHANGED
@@ -15,21 +15,22 @@ class ChoiceAI_Search_Helper_Productimg extends Mage_ConfigurableSwatches_Helper
15
  {
16
  $this->indexProductImages($product);
17
 
18
- if (count($this->_productImagesByLabel)) {
19
  //Get the product's image array and prepare the text
20
  $images = $this->_productImagesByLabel[$product->getId()];
21
  $text = Mage_ConfigurableSwatches_Helper_Data::normalizeKey($text);
22
 
23
  $resultImages = array(
24
  'standard' => isset($images[$text]) ? $images[$text] : null,
25
- 'swatch' => isset($images[$text . self::SWATCH_LABEL_SUFFIX]) ? $images[$text . self::SWATCH_LABEL_SUFFIX]
 
26
  : null,
27
  );
28
 
29
- if (!is_null($type) && array_key_exists($type, $resultImages)) {
30
  $image = $resultImages[$type];
31
  } else {
32
- $image = (!is_null($resultImages['swatch'])) ? $resultImages['swatch'] : $resultImages['standard'];
33
  }
34
  } else {
35
  $image = null;
@@ -40,4 +41,3 @@ class ChoiceAI_Search_Helper_Productimg extends Mage_ConfigurableSwatches_Helper
40
 
41
  }
42
 
43
- ?>
15
  {
16
  $this->indexProductImages($product);
17
 
18
+ if (!empty($this->_productImagesByLabel)) {
19
  //Get the product's image array and prepare the text
20
  $images = $this->_productImagesByLabel[$product->getId()];
21
  $text = Mage_ConfigurableSwatches_Helper_Data::normalizeKey($text);
22
 
23
  $resultImages = array(
24
  'standard' => isset($images[$text]) ? $images[$text] : null,
25
+ 'swatch' => isset($images[$text . self::SWATCH_LABEL_SUFFIX]) ?
26
+ $images[$text . self::SWATCH_LABEL_SUFFIX]
27
  : null,
28
  );
29
 
30
+ if ($type !== null && array_key_exists($type, $resultImages)) {
31
  $image = $resultImages[$type];
32
  } else {
33
+ $image = ($resultImages['swatch']) !== null ? $resultImages['swatch'] : $resultImages['standard'];
34
  }
35
  } else {
36
  $image = null;
41
 
42
  }
43
 
 
app/code/local/ChoiceAI/Search/Model/Catalog/Category.php CHANGED
@@ -22,17 +22,17 @@ class ChoiceAI_Search_Model_Catalog_Category extends Mage_Catalog_Model_Category
22
  $overtakeFlag = false;
23
 
24
  // Check if URL in takeover list
25
- $STORE_CONFIG = json_decode(Mage::getStoreConfig(self::CONFIG_KEY));
26
- $sortbyObjs = $STORE_CONFIG->sortby;
27
-
28
  // Getting URL Path
29
- $currentReqPath = explode("?", $_SERVER['REQUEST_URI'])[0];
30
 
31
  // Getting param keys in array var $paramPairs
32
- parse_str($_SERVER['QUERY_STRING'], $paramPairs);
33
  // Getting query keys
34
  $currentReqParams = array();
35
- if (count($paramPairs)) {
36
  foreach ($paramPairs as $key => $paramPair)
37
  $currentReqParams[] = $key;
38
  }
@@ -49,7 +49,7 @@ class ChoiceAI_Search_Model_Catalog_Category extends Mage_Catalog_Model_Category
49
  $isPluginActive = Mage::helper('choiceai_search')->isActiveEngine();
50
  // $isPluginActive = true;
51
 
52
- if($isPluginActive) {
53
  foreach ($sortbyObjs as $sortbyObj) {
54
  if (isset($sortbyObj->rule->paths)) {
55
  if (in_array($currentReqPath, $sortbyObj->rule->paths)) {
@@ -65,7 +65,7 @@ class ChoiceAI_Search_Model_Catalog_Category extends Mage_Catalog_Model_Category
65
  }
66
  }
67
 
68
- if($overtakeFlag)
69
  return Mage::getSingleton('catalog/config')->getAttributeUsedForSortByArray();
70
  else
71
  return parent::getAvailableSortByOptions();
22
  $overtakeFlag = false;
23
 
24
  // Check if URL in takeover list
25
+ $storeConfig = json_decode(Mage::getStoreConfig(self::CONFIG_KEY));
26
+ $sortbyObjs = $storeConfig->sortby;
27
+ $server = Mage::app()->getRequest()->getServer();
28
  // Getting URL Path
29
+ $currentReqPath = explode("?", $server['REQUEST_URI'])[0];
30
 
31
  // Getting param keys in array var $paramPairs
32
+ parse_str($server['QUERY_STRING'], $paramPairs);
33
  // Getting query keys
34
  $currentReqParams = array();
35
+ if (!empty($paramPairs)) {
36
  foreach ($paramPairs as $key => $paramPair)
37
  $currentReqParams[] = $key;
38
  }
49
  $isPluginActive = Mage::helper('choiceai_search')->isActiveEngine();
50
  // $isPluginActive = true;
51
 
52
+ if ($isPluginActive) {
53
  foreach ($sortbyObjs as $sortbyObj) {
54
  if (isset($sortbyObj->rule->paths)) {
55
  if (in_array($currentReqPath, $sortbyObj->rule->paths)) {
65
  }
66
  }
67
 
68
+ if ($overtakeFlag)
69
  return Mage::getSingleton('catalog/config')->getAttributeUsedForSortByArray();
70
  else
71
  return parent::getAvailableSortByOptions();
app/code/local/ChoiceAI/Search/Model/Catalog/Config.php CHANGED
@@ -1,121 +1,125 @@
1
- <?php
2
- /**
3
- * Overrides default layer model to handle custom product collection filtering.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Config extends Mage_Catalog_Model_Config
10
- {
11
- const IS_ACTIVE = 'choiceai_personalisation/settings/active';
12
- const CONFIG_KEY = 'choiceai_personalisation/settings/config';
13
-
14
- public $options = NULL;
15
-
16
- /**
17
- * Returns what sort by options are used by Magento, whether in listing or search
18
- *
19
- * Note by Harkirat: This function is called in both cases: product list and search
20
- *
21
- * @return array
22
- */
23
- public function getAttributeUsedForSortByArray()
24
- {
25
- try {
26
- if(is_null($this->options)) {
27
- // Check if URL in takeover list
28
- $STORE_CONFIG = json_decode(Mage::getStoreConfig(self::CONFIG_KEY));
29
- $sortbyObjs = $STORE_CONFIG->sortby;
30
-
31
- // Getting URL Path
32
- $currentReqPath = explode("?", $_SERVER['REQUEST_URI'])[0];
33
-
34
- // Getting param keys in array var $paramPairs
35
- parse_str($_SERVER['QUERY_STRING'], $paramPairs);
36
- // Getting query keys
37
- $currentReqParams = array();
38
- if (count($paramPairs)) {
39
- foreach ($paramPairs as $key => $paramPair)
40
- $currentReqParams[] = $key;
41
- }
42
-
43
- // Refining URL path
44
- // My own local installation case: localhost/magento/
45
- if (strpos($currentReqPath, "/magento/") !== false)
46
- $currentReqPath = str_replace("/magento/", "/", $currentReqPath);
47
-
48
- // Making www.store.com/index.php/abcd => www.store.com/abcd
49
- if (strpos($currentReqPath, "/index.php/") !== false)
50
- $currentReqPath = str_replace("/index.php/", "/", $currentReqPath);
51
-
52
-
53
- if (Mage::getStoreConfig(self::IS_ACTIVE) == '1') {
54
- foreach ($sortbyObjs as $sortbyObj) {
55
- if (isset($sortbyObj->rule)) {
56
- if (isset($sortbyObj->rule->paths)) {
57
- if (in_array($currentReqPath, $sortbyObj->rule->paths)) {
58
- $this->options = $this->getOptions($sortbyObj);
59
-
60
- if (empty($this->options)) {
61
- return parent::getAttributeUsedForSortByArray();
62
- }
63
- return $this->options;
64
- }
65
- }
66
-
67
- if (isset($sortbyObj->rule->params)) {
68
- if (!empty(array_intersect($currentReqParams, $sortbyObj->rule->params))) {
69
- $this->options = $this->getOptions($sortbyObj);
70
-
71
- if (empty($this->options)) {
72
- return parent::getAttributeUsedForSortByArray();
73
- }
74
- return $this->options;
75
- }
76
- }
77
- }
78
- }
79
- }
80
- } else{
81
- return $this->options;
82
- }
83
-
84
- $this->options = parent::getAttributeUsedForSortByArray();
85
- return $this->options;
86
- } catch (Exception $e){
87
- return parent::getAttributeUsedForSortByArray();
88
- }
89
- }
90
-
91
- private function getOptions($sortbyObj){
92
- $options = array();
93
-
94
- if(isset($sortbyObj->override)){
95
- // Search case, override all system options with choice
96
- $caiOptions = $sortbyObj->override;
97
-
98
- foreach ($caiOptions as $key => $caiOption)
99
- $options[$key] = Mage::helper('catalog')->__($caiOption);
100
- } else if(isset($sortbyObj->extend)) {
101
- // Product list page, add system options first, then add/replace ours
102
-
103
- $options = array(
104
- 'position' => Mage::helper('catalog')->__('Position')
105
- );
106
- foreach ($this->getAttributesUsedForSortBy() as $attribute) {
107
- /* @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
108
- $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
109
- }
110
-
111
- // Default options added above, now adding our option/s, which can either override or be a new option
112
- // If we add more overrides in future, this will still work
113
- foreach ($sortbyObj->extend as $key=>$option)
114
- $options[$key] = Mage::helper('catalog')->__($option);
115
-
116
- $_SESSION['plist_sort_by'] = $key;
117
- }
118
-
119
- return $options;
120
- }
121
- }
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Overrides default layer model to handle custom product collection filtering.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Config extends Mage_Catalog_Model_Config
11
+ {
12
+ const IS_ACTIVE = 'choiceai_personalisation/settings/active';
13
+ const CONFIG_KEY = 'choiceai_personalisation/settings/config';
14
+
15
+ public $options = NULL;
16
+
17
+ /**
18
+ * Returns what sort by options are used by Magento, whether in listing or search
19
+ *
20
+ * Note by Harkirat: This function is called in both cases: product list and search
21
+ *
22
+ * @return array
23
+ */
24
+ public function getAttributeUsedForSortByArray()
25
+ {
26
+ try {
27
+ if ($this->options === null) {
28
+ // Check if URL in takeover list
29
+ $storeConfig = json_decode(Mage::getStoreConfig(self::CONFIG_KEY));
30
+ $sortbyObjs = $storeConfig->sortby;
31
+ $server = Mage::app()->getRequest()->getServer();
32
+ // Getting URL Path
33
+ $currentReqPath = explode("?", $server['REQUEST_URI'])[0];
34
+
35
+ // Getting param keys in array var $paramPairs
36
+ parse_str($server['QUERY_STRING'], $paramPairs);
37
+ // Getting query keys
38
+ $currentReqParams = array();
39
+ if (!empty($paramPairs)) {
40
+ foreach ($paramPairs as $key => $paramPair)
41
+ $currentReqParams[] = $key;
42
+ }
43
+
44
+ // Refining URL path
45
+ // My own local installation case: localhost/magento/
46
+ if (strpos($currentReqPath, "/magento/") !== false)
47
+ $currentReqPath = str_replace("/magento/", "/", $currentReqPath);
48
+
49
+ // Making www.store.com/index.php/abcd => www.store.com/abcd
50
+ if (strpos($currentReqPath, "/index.php/") !== false)
51
+ $currentReqPath = str_replace("/index.php/", "/", $currentReqPath);
52
+
53
+
54
+ if (Mage::getStoreConfig(self::IS_ACTIVE) == '1') {
55
+ foreach ($sortbyObjs as $sortbyObj) {
56
+ if (isset($sortbyObj->rule)) {
57
+ if (isset($sortbyObj->rule->paths)) {
58
+ if (in_array($currentReqPath, $sortbyObj->rule->paths)) {
59
+ $this->options = $this->getOptions($sortbyObj);
60
+
61
+ if (empty($this->options)) {
62
+ return parent::getAttributeUsedForSortByArray();
63
+ }
64
+
65
+ return $this->options;
66
+ }
67
+ }
68
+
69
+ if (isset($sortbyObj->rule->params)) {
70
+ if (!empty(array_intersect($currentReqParams, $sortbyObj->rule->params))) {
71
+ $this->options = $this->getOptions($sortbyObj);
72
+
73
+ if (empty($this->options)) {
74
+ return parent::getAttributeUsedForSortByArray();
75
+ }
76
+
77
+ return $this->options;
78
+ }
79
+ }
80
+ }
81
+ }
82
+ }
83
+ } else {
84
+ return $this->options;
85
+ }
86
+
87
+ $this->options = parent::getAttributeUsedForSortByArray();
88
+ return $this->options;
89
+ } catch (Exception $e) {
90
+ return parent::getAttributeUsedForSortByArray();
91
+ }
92
+ }
93
+
94
+ protected function getOptions($sortbyObj)
95
+ {
96
+ $options = array();
97
+
98
+ if (isset($sortbyObj->override)) {
99
+ // Search case, override all system options with choice
100
+ $caiOptions = $sortbyObj->override;
101
+
102
+ foreach ($caiOptions as $key => $caiOption)
103
+ $options[$key] = Mage::helper('catalog')->__($caiOption);
104
+ } else if (isset($sortbyObj->extend)) {
105
+ // Product list page, add system options first, then add/replace ours
106
+
107
+ $options = array(
108
+ 'position' => Mage::helper('catalog')->__('Position')
109
+ );
110
+ foreach ($this->getAttributesUsedForSortBy() as $attribute) {
111
+ /* @var $attribute Mage_Eav_Model_Entity_Attribute_Abstract */
112
+ $options[$attribute->getAttributeCode()] = $attribute->getStoreLabel();
113
+ }
114
+
115
+ // Default options added above, now adding our option/s, which can either override or be a new option
116
+ // If we add more overrides in future, this will still work
117
+ foreach ($sortbyObj->extend as $key => $option)
118
+ $options[$key] = Mage::helper('catalog')->__($option);
119
+ $session = Mage::getSingleton('core/session');
120
+ $session['plist_sort_by'] = $key;
121
+ }
122
+
123
+ return $options;
124
+ }
125
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Layer.php CHANGED
@@ -1,37 +1,38 @@
1
- <?php
2
- /**
3
- * Overrides default layer model to handle custom product collection filtering.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Layer extends Mage_Catalog_Model_Layer
10
- {
11
- /**
12
- * Returns product collection for current category.
13
- *
14
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
15
- */
16
- public function getProductCollection()
17
- {
18
- /** @var $category Mage_Catalog_Model_Category */
19
- $category = $this->getCurrentCategory();
20
- /** @var $collection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
21
- if (isset($this->_productCollections[$category->getId()])) {
22
- $collection = $this->_productCollections[$category->getId()];
23
- } else {
24
- $collection = Mage::getResourceModel('choiceai_search/engine_choiceaisearch')
25
- ->getResultCollection()
26
- ->setStoreId($category->getStoreId())
27
- ->addCategoryId($category->getId())
28
- ->setQueryType('browse')
29
- ->addFqFilter(array('store_id' => $category->getStoreId()));
30
-
31
- $this->prepareProductCollection($collection);
32
- $this->_productCollections[$category->getId()] = $collection;
33
- }
34
-
35
- return $collection;
36
- }
37
- }
 
1
+ <?php
2
+
3
+ /**
4
+ * Overrides default layer model to handle custom product collection filtering.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Layer extends Mage_Catalog_Model_Layer
11
+ {
12
+ /**
13
+ * Returns product collection for current category.
14
+ *
15
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
16
+ */
17
+ public function getProductCollection()
18
+ {
19
+ /** @var $category Mage_Catalog_Model_Category */
20
+ $category = $this->getCurrentCategory();
21
+ /** @var $collection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
22
+ if (isset($this->_productCollections[$category->getId()])) {
23
+ $collection = $this->_productCollections[$category->getId()];
24
+ } else {
25
+ $collection = Mage::getResourceModel('choiceai_search/engine_choiceaisearch')
26
+ ->getResultCollection()
27
+ ->setStoreId($category->getStoreId())
28
+ ->addCategoryId($category->getId())
29
+ ->setQueryType('browse')
30
+ ->addFqFilter(array('store_id' => $category->getStoreId()));
31
+
32
+ $this->prepareProductCollection($collection);
33
+ $this->_productCollections[$category->getId()] = $collection;
34
+ }
35
+
36
+ return $collection;
37
+ }
38
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Attribute.php CHANGED
@@ -1,168 +1,173 @@
1
- <?php
2
- /**
3
- * Handles attribute filtering in layered navigation.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Model_Layer_Filter_Attribute
10
- {
11
- const MULTI_SELECT_FACET_SPLIT = '_';
12
-
13
- /**
14
- * Adds facet condition to product collection.
15
- *
16
- * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
17
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
18
- */
19
- public function addFacetCondition()
20
- {
21
- $this->getLayer()
22
- ->getProductCollection()
23
- ->addFacetCondition($this->_getFilterField());
24
-
25
- return $this;
26
- }
27
-
28
- /**
29
- * Retrieves request parameter and applies it to product collection.
30
- *
31
- * @param Zend_Controller_Request_Abstract $request
32
- * @param Mage_Core_Block_Abstract $filterBlock
33
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
34
- */
35
- public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
36
- {
37
- $filter = $request->getParam($this->_requestVar);
38
- if (is_array($filter) || null === $filter || strlen($filter) == 0) {
39
- return $this;
40
- }
41
- $filterValues = explode(self::MULTI_SELECT_FACET_SPLIT, $filter);
42
- $this->applyFilterToCollection($this, $filterValues);
43
- foreach($filterValues as $eachFilterValue) {
44
- $this->getLayer()->getState()->addFilter($this->_createItem($eachFilterValue, $eachFilterValue));
45
- }
46
-
47
- $this->_items = null;
48
-
49
- return $this;
50
- }
51
-
52
- /**
53
- * Applies filter to product collection.
54
- *
55
- * @param $filter
56
- * @param $value
57
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
58
- */
59
- public function applyFilterToCollection($filter, $value)
60
- {
61
- if(!is_array($value)) {
62
- return $this;
63
- }
64
- $attribute = $filter->getAttributeModel();
65
- $param = Mage::helper('choiceai_search')->getSearchParam($attribute, $value);
66
-
67
- $this->getLayer()
68
- ->getProductCollection()
69
- ->addSearchQfFilter($param);
70
-
71
- return $this;
72
- }
73
-
74
- /**
75
- * Returns facets data of current attribute.
76
- *
77
- * @return array
78
- */
79
- protected function _getFacets()
80
- {
81
- /** @var $productCollection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
82
- $productCollection = $this->getLayer()->getProductCollection();
83
- $fieldName = $this->_getFilterField();
84
- $facets = $productCollection->getFacetedData($fieldName);
85
- return $facets;
86
- }
87
-
88
-
89
- public function getMaxPriceInt()
90
- {
91
- $priceStat = Mage::getSingleton('choiceai_search/catalog_layer')->getProductCollection()->getStats('price');
92
- $productCollection = $this->getLayer()->getProductCollection();
93
- return isset($priceStat["max"])?$priceStat["max"]:0;
94
- }
95
-
96
-
97
- /**
98
- * Returns attribute field name.
99
- *
100
- * @return string
101
- */
102
- protected function _getFilterField()
103
- {
104
- /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
105
- $attribute = $this->getAttributeModel();
106
- $fieldName = Mage::helper('choiceai_search')->getAttributeFieldName($attribute);
107
-
108
- return $fieldName;
109
- }
110
-
111
- /**
112
- * Retrieves current items data.
113
- *
114
- * @return array
115
- */
116
- protected function _getItemsData()
117
- {
118
- $filter = array_key_exists($this->_requestVar, $_REQUEST)?$_REQUEST[$this->_requestVar]: '';
119
- $filterValues = explode(self::MULTI_SELECT_FACET_SPLIT, $filter);
120
- /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
121
- $attribute = $this->getAttributeModel();
122
- $this->_requestVar = $attribute->getAttributeCode();
123
- $facets = $this->_getFacets();
124
- $data = array();
125
-
126
- if (array_sum($facets) > 0) {
127
- foreach ($facets as $label => $count) {
128
- $isSelected = in_array($label, $filterValues);
129
- if (!$count && $this->_getIsFilterableAttribute($attribute) == self::OPTIONS_ONLY_WITH_RESULTS) {
130
- continue;
131
- }
132
- $data[] = array(
133
- 'label' => $label,
134
- 'value' => $label,
135
- 'count' => $count,
136
- );
137
- }
138
- }
139
-
140
- return $data;
141
- }
142
-
143
- /**
144
- * Returns option label if attribute uses options.
145
- *
146
- * @param int $optionId
147
- * @return bool|int|string
148
- */
149
- protected function _getOptionText($optionId)
150
- {
151
- if ($this->getAttributeModel()->getFrontendInput() == 'text') {
152
- return $optionId; // not an option id
153
- }
154
-
155
- return parent::_getOptionText($optionId);
156
- }
157
-
158
- /**
159
- * Checks if given filter is valid before being applied to product collection.
160
- *
161
- * @param string $filter
162
- * @return bool
163
- */
164
- protected function _isValidFilter($filter)
165
- {
166
- return !empty($filter);
167
- }
168
- }
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Handles attribute filtering in layered navigation.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute extends Mage_Catalog_Model_Layer_Filter_Attribute
11
+ {
12
+ const MULTI_SELECT_FACET_SPLIT = '_';
13
+
14
+ /**
15
+ * Adds facet condition to product collection.
16
+ *
17
+ * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
18
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
19
+ */
20
+ public function addFacetCondition()
21
+ {
22
+ $this->getLayer()
23
+ ->getProductCollection()
24
+ ->addFacetCondition($this->_getFilterField());
25
+
26
+ return $this;
27
+ }
28
+
29
+ /**
30
+ * Retrieves request parameter and applies it to product collection.
31
+ *
32
+ * @param Zend_Controller_Request_Abstract $request
33
+ * @param Mage_Core_Block_Abstract $filterBlock
34
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
35
+ */
36
+ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
37
+ {
38
+ $filter = $request->getParam($this->_requestVar);
39
+ if (is_array($filter) || null === $filter || strlen($filter) == 0) {
40
+ return $this;
41
+ }
42
+
43
+ $filterValues = explode(self::MULTI_SELECT_FACET_SPLIT, $filter);
44
+ $this->applyFilterToCollection($this, $filterValues);
45
+ foreach ($filterValues as $eachFilterValue) {
46
+ $this->getLayer()->getState()->addFilter($this->_createItem($eachFilterValue, $eachFilterValue));
47
+ }
48
+
49
+ $this->_items = null;
50
+
51
+ return $this;
52
+ }
53
+
54
+ /**
55
+ * Applies filter to product collection.
56
+ *
57
+ * @param $filter
58
+ * @param $value
59
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
60
+ */
61
+ public function applyFilterToCollection($filter, $value)
62
+ {
63
+ if (!is_array($value)) {
64
+ return $this;
65
+ }
66
+
67
+ $attribute = $filter->getAttributeModel();
68
+ $param = Mage::helper('choiceai_search')->getSearchParam($attribute, $value);
69
+
70
+ $this->getLayer()
71
+ ->getProductCollection()
72
+ ->addSearchQfFilter($param);
73
+
74
+ return $this;
75
+ }
76
+
77
+ /**
78
+ * Returns facets data of current attribute.
79
+ *
80
+ * @return array
81
+ */
82
+ protected function _getFacets()
83
+ {
84
+ /** @var $productCollection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
85
+ $productCollection = $this->getLayer()->getProductCollection();
86
+ $fieldName = $this->_getFilterField();
87
+ $facets = $productCollection->getFacetedData($fieldName);
88
+ return $facets;
89
+ }
90
+
91
+
92
+ public function getMaxPriceInt()
93
+ {
94
+ $priceStat = Mage::getSingleton('choiceai_search/catalog_layer')->getProductCollection()->getStats('price');
95
+ $productCollection = $this->getLayer()->getProductCollection();
96
+ return isset($priceStat["max"]) ? $priceStat["max"] : 0;
97
+ }
98
+
99
+
100
+ /**
101
+ * Returns attribute field name.
102
+ *
103
+ * @return string
104
+ */
105
+ protected function _getFilterField()
106
+ {
107
+ /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
108
+ $attribute = $this->getAttributeModel();
109
+ $fieldName = Mage::helper('choiceai_search')->getAttributeFieldName($attribute);
110
+
111
+ return $fieldName;
112
+ }
113
+
114
+ /**
115
+ * Retrieves current items data.
116
+ *
117
+ * @return array
118
+ */
119
+ protected function _getItemsData()
120
+ {
121
+ $params = Mage::app()->getRequest()->getParams();
122
+ $filter = array_key_exists($this->_requestVar, $params) ? $params[$this->_requestVar] : '';
123
+ $filterValues = explode(self::MULTI_SELECT_FACET_SPLIT, $filter);
124
+ /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
125
+ $attribute = $this->getAttributeModel();
126
+ $this->_requestVar = $attribute->getAttributeCode();
127
+ $facets = $this->_getFacets();
128
+ $data = array();
129
+
130
+ if (array_sum($facets) > 0) {
131
+ foreach ($facets as $label => $count) {
132
+ // $isSelected = in_array($label, $filterValues);
133
+ if (!$count && $this->_getIsFilterableAttribute($attribute) == self::OPTIONS_ONLY_WITH_RESULTS) {
134
+ continue;
135
+ }
136
+
137
+ $data[] = array(
138
+ 'label' => $label,
139
+ 'value' => $label,
140
+ 'count' => $count,
141
+ );
142
+ }
143
+ }
144
+
145
+ return $data;
146
+ }
147
+
148
+ /**
149
+ * Returns option label if attribute uses options.
150
+ *
151
+ * @param int $optionId
152
+ * @return bool|int|string
153
+ */
154
+ protected function _getOptionText($optionId)
155
+ {
156
+ if ($this->getAttributeModel()->getFrontendInput() == 'text') {
157
+ return $optionId; // not an option id
158
+ }
159
+
160
+ return parent::_getOptionText($optionId);
161
+ }
162
+
163
+ /**
164
+ * Checks if given filter is valid before being applied to product collection.
165
+ *
166
+ * @param string $filter
167
+ * @return bool
168
+ */
169
+ protected function _isValidFilter($filter)
170
+ {
171
+ return !empty($filter);
172
+ }
173
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Boolean.php CHANGED
@@ -1,41 +1,43 @@
1
- <?php
2
- /**
3
- * Handles boolean attribute filtering in layered navigation.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Layer_Filter_Boolean extends ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
10
- {
11
- /**
12
- * Returns facets data of current attribute.
13
- *
14
- * @return array
15
- */
16
- protected function _getFacets()
17
- {
18
- $facets = parent::_getFacets();
19
- $result = array();
20
- foreach ($facets as $value => $count) {
21
- $key = 0; // false by default
22
- if ($value === 'true' || $value === 'T' || $value === '1' || $value === 1 || $value === true) {
23
- $key = 1;
24
- }
25
- $result[$key] = $count;
26
- }
27
-
28
- return $result;
29
- }
30
-
31
- /**
32
- * Checks if given filter is valid before being applied to product collection.
33
- *
34
- * @param string $filter
35
- * @return bool
36
- */
37
- protected function _isValidFilter($filter)
38
- {
39
- return $filter === '0' || $filter === '1' || false === $filter || true === $filter;
40
- }
41
- }
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Handles boolean attribute filtering in layered navigation.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Layer_Filter_Boolean extends ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
11
+ {
12
+ /**
13
+ * Returns facets data of current attribute.
14
+ *
15
+ * @return array
16
+ */
17
+ protected function _getFacets()
18
+ {
19
+ $facets = parent::_getFacets();
20
+ $result = array();
21
+ foreach ($facets as $value => $count) {
22
+ $key = 0; // false by default
23
+ if ($value === 'true' || $value === 'T' || $value === '1' || $value === 1 || $value === true) {
24
+ $key = 1;
25
+ }
26
+
27
+ $result[$key] = $count;
28
+ }
29
+
30
+ return $result;
31
+ }
32
+
33
+ /**
34
+ * Checks if given filter is valid before being applied to product collection.
35
+ *
36
+ * @param string $filter
37
+ * @return bool
38
+ */
39
+ protected function _isValidFilter($filter)
40
+ {
41
+ return $filter === '0' || $filter === '1' || false === $filter || true === $filter;
42
+ }
43
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Category.php CHANGED
@@ -1,132 +1,138 @@
1
- <?php
2
- /**
3
- * Handles category filtering in layered navigation.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Layer_Filter_Category extends Mage_Catalog_Model_Layer_Filter_Category
10
- {
11
- /**
12
- * Adds category filter to product collection.
13
- *
14
- * @param Mage_Catalog_Model_Category $category
15
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
16
- */
17
- public function addCategoryFilter($category)
18
- {
19
- $value = array(
20
- 'categories' => $category->getId()
21
- );
22
- $this->getLayer()->getProductCollection()
23
- ->addFqFilter($value);
24
-
25
- return $this;
26
- }
27
-
28
- /**
29
- * Adds facet condition to product collection.
30
- *
31
- * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
32
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
33
- */
34
- public function addFacetCondition()
35
- {
36
- /** @var $category Mage_Catalog_Model_Category */
37
- $category = $this->getCategory();
38
- $childrenCategories = $category->getChildrenCategories();
39
-
40
- $useFlat = (bool) Mage::getStoreConfig('catalog/frontend/flat_catalog_category');
41
- $categories = ($useFlat)
42
- ? array_keys($childrenCategories)
43
- : array_keys($childrenCategories->toArray());
44
-
45
- $this->getLayer()->getProductCollection()->addFacetCondition('categories', $categories);
46
-
47
- return $this;
48
- }
49
-
50
- /**
51
- * Applies filter to product collection.
52
- *
53
- * @param $filter
54
- * @param $value
55
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
56
- */
57
- public function applyFilterToCollection($filter, $value)
58
- {
59
-
60
- $param = array("category" => array($value));
61
- $this->getLayer()
62
- ->getProductCollection()
63
- ->addSearchQfFilter($param);
64
-
65
- return $this;
66
- }
67
-
68
- /**
69
- * Retrieves request parameter and applies it to product collection.
70
- *
71
- * @param Zend_Controller_Request_Abstract $request
72
- * @param Mage_Core_Block_Abstract $filterBlock
73
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
74
- */
75
- public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
76
- {
77
- $filter = $request->getParam($this->getRequestVar());
78
- if (is_null($filter) || $filter == "") {
79
- return $this;
80
- }
81
- $this->applyFilterToCollection($this, $filter);
82
- $this->getLayer()->getState()->addFilter($this->_createItem($filter, $filter));
83
- $this->_items = null;
84
- return $this;
85
- }
86
-
87
- /**
88
- * Retrieves current items data.
89
- *
90
- * @return array
91
- */
92
- protected function _getItemsData()
93
- {
94
- $layer = $this->getLayer();
95
- /** @var $productCollection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
96
- $productCollection = $layer->getProductCollection();
97
- $facets = $productCollection->getFacetedData('category');
98
- $data = array();
99
- if (array_sum($facets) > 0) {
100
- $options = array();
101
- foreach ($facets as $label => $count) {
102
- $options[] = array(
103
- 'label' => $label,
104
- 'value' => $label,
105
- 'count' => $count,
106
- );
107
- }
108
- // }
109
- foreach ($options as $option) {
110
- if (is_array($option['value']) || !Mage::helper('core/string')->strlen($option['value'])) {
111
- continue;
112
- }
113
- $count = 0;
114
- $label = $option['label'];
115
- if (isset($facets[$option['value']])) {
116
- $count = (int) $facets[$option['value']];
117
- }
118
- if (!$count && $this->_getIsFilterableAttribute($attribute) == self::OPTIONS_ONLY_WITH_RESULTS) {
119
- continue;
120
- }
121
- $data[] = array(
122
- 'label' => $label,
123
- 'value' => $option['value'],
124
- 'count' => (int) $count,
125
- );
126
- }
127
-
128
- }
129
-
130
- return $data;
131
- }
132
- }
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Handles category filtering in layered navigation.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Layer_Filter_Category extends Mage_Catalog_Model_Layer_Filter_Category
11
+ {
12
+ /**
13
+ * Adds category filter to product collection.
14
+ *
15
+ * @param Mage_Catalog_Model_Category $category
16
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
17
+ */
18
+ public function addCategoryFilter($category)
19
+ {
20
+ $value = array(
21
+ 'categories' => $category->getId()
22
+ );
23
+ $this->getLayer()->getProductCollection()
24
+ ->addFqFilter($value);
25
+
26
+ return $this;
27
+ }
28
+
29
+ /**
30
+ * Adds facet condition to product collection.
31
+ *
32
+ * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
33
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
34
+ */
35
+ public function addFacetCondition()
36
+ {
37
+ /** @var $category Mage_Catalog_Model_Category */
38
+ $category = $this->getCategory();
39
+ $childrenCategories = $category->getChildrenCategories();
40
+
41
+ $useFlat = (bool)Mage::getStoreConfig('catalog/frontend/flat_catalog_category');
42
+ $categories = ($useFlat)
43
+ ? array_keys($childrenCategories)
44
+ : array_keys($childrenCategories->toArray());
45
+
46
+ $this->getLayer()->getProductCollection()->addFacetCondition('categories', $categories);
47
+
48
+ return $this;
49
+ }
50
+
51
+ /**
52
+ * Applies filter to product collection.
53
+ *
54
+ * @param $filter
55
+ * @param $value
56
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
57
+ */
58
+ public function applyFilterToCollection($filter, $value)
59
+ {
60
+
61
+ $param = array("category" => array($value));
62
+ $this->getLayer()
63
+ ->getProductCollection()
64
+ ->addSearchQfFilter($param);
65
+
66
+ return $this;
67
+ }
68
+
69
+ /**
70
+ * Retrieves request parameter and applies it to product collection.
71
+ *
72
+ * @param Zend_Controller_Request_Abstract $request
73
+ * @param Mage_Core_Block_Abstract $filterBlock
74
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Category
75
+ */
76
+ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
77
+ {
78
+ $filter = $request->getParam($this->getRequestVar());
79
+ if ($filter === null || $filter == "") {
80
+ return $this;
81
+ }
82
+
83
+ $this->applyFilterToCollection($this, $filter);
84
+ $this->getLayer()->getState()->addFilter($this->_createItem($filter, $filter));
85
+ $this->_items = null;
86
+ return $this;
87
+ }
88
+
89
+ /**
90
+ * Retrieves current items data.
91
+ *
92
+ * @return array
93
+ */
94
+ protected function _getItemsData()
95
+ {
96
+ $layer = $this->getLayer();
97
+ /** @var $productCollection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
98
+ $attribute = $this->getAttributeModel();
99
+ $productCollection = $layer->getProductCollection();
100
+ $facets = $productCollection->getFacetedData('category');
101
+ $data = array();
102
+ if (array_sum($facets) > 0) {
103
+ $options = array();
104
+ foreach ($facets as $label => $count) {
105
+ $options[] = array(
106
+ 'label' => $label,
107
+ 'value' => $label,
108
+ 'count' => $count,
109
+ );
110
+ }
111
+
112
+ // }
113
+ foreach ($options as $option) {
114
+ if (is_array($option['value']) || $option['value'] === "") {
115
+ continue;
116
+ }
117
+
118
+ $count = 0;
119
+ $label = $option['label'];
120
+ if (isset($facets[$option['value']])) {
121
+ $count = (int)$facets[$option['value']];
122
+ }
123
+
124
+ if (!$count && $this->_getIsFilterableAttribute($attribute) == self::OPTIONS_ONLY_WITH_RESULTS) {
125
+ continue;
126
+ }
127
+
128
+ $data[] = array(
129
+ 'label' => $label,
130
+ 'value' => $option['value'],
131
+ 'count' => (int)$count,
132
+ );
133
+ }
134
+ }
135
+
136
+ return $data;
137
+ }
138
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Decimal.php CHANGED
@@ -1,190 +1,191 @@
1
- <?php
2
- /**
3
- * Handles decimal attribute filtering in layered navigation.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Model_Layer_Filter_Decimal
10
- {
11
- const CACHE_TAG = 'MAXVALUE';
12
-
13
- /**
14
- * Adds facet condition to product collection.
15
- *
16
- * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
17
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
18
- */
19
- public function addFacetCondition()
20
- {
21
- $range = $this->getRange();
22
- $maxValue = $this->getMaxValue();
23
- if ($maxValue > 0) {
24
- $facets = array();
25
- $facetCount = (int) ceil($maxValue / $range);
26
-
27
- for ($i = 0; $i < $facetCount + 1; $i++) {
28
- $facets[] = array(
29
- 'from' => $i * $range,
30
- 'to' => ($i + 1) * $range,
31
- 'include_upper' => !($i < $facetCount)
32
- );
33
- }
34
-
35
- $fieldName = $this->_getFilterField();
36
- $this->getLayer()->getProductCollection()->addFacetCondition($fieldName, $facets);
37
- }
38
-
39
- return $this;
40
- }
41
-
42
- /**
43
- * Retrieves request parameter and applies it to product collection.
44
- *
45
- * @param Zend_Controller_Request_Abstract $request
46
- * @param Mage_Core_Block_Abstract $filterBlock
47
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
48
- */
49
- public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
50
- {
51
- $filter = $request->getParam($this->getRequestVar());
52
- if (!$filter) {
53
- return $this;
54
- }
55
-
56
- $filter = explode(',', $filter);
57
- if (count($filter) != 2) {
58
- return $this;
59
- }
60
-
61
- list($index, $range) = $filter;
62
-
63
- if ((int) $index && (int) $range) {
64
- $this->setRange((int) $range);
65
-
66
- $this->applyFilterToCollection($this, $range, $index);
67
- $this->getLayer()->getState()->addFilter(
68
- $this->_createItem($this->_renderItemLabel($range, $index), $filter)
69
- );
70
-
71
- $this->_items = array();
72
- }
73
-
74
- return $this;
75
- }
76
-
77
- /**
78
- * Apply decimal filter range to product collection.
79
- *
80
- * @param ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal $filter
81
- * @param int $range
82
- * @param int $index
83
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
84
- */
85
- public function applyFilterToCollection($filter, $range, $index)
86
- {
87
- $value = array(
88
- $this->_getFilterField() => array(
89
- 'from' => ($range * ($index - 1)),
90
- 'to' => $range * $index,
91
- )
92
- );
93
- $filter->getLayer()->getProductCollection()->addFqFilter($value);
94
-
95
- return $this;
96
- }
97
-
98
- public function getMaxValue()
99
- {
100
- $searchParams = $this->getLayer()->getProductCollection()->getExtendedSearchParams();
101
- $uniquePart = strtoupper(md5(serialize($searchParams)));
102
- $cacheKey = 'MAXVALUE_' . $this->getLayer()->getStateKey() . '_' . $uniquePart;
103
-
104
- $cachedData = Mage::app()->loadCache($cacheKey);
105
- if (!$cachedData) {
106
- $stats = $this->getLayer()->getProductCollection()->getStats($this->_getFilterField());
107
-
108
- $max = $stats[$this->_getFilterField()]['max'];
109
- if (!is_numeric($max)) {
110
- $max = parent::getMaxValue();
111
- }
112
-
113
- $cachedData = (float) $max;
114
- $tags = $this->getLayer()->getStateTags();
115
- $tags[] = self::CACHE_TAG;
116
- Mage::app()->saveCache($cachedData, $cacheKey, $tags);
117
- }
118
-
119
- return $cachedData;
120
- }
121
-
122
- /**
123
- * Returns decimal field name.
124
- *
125
- * @return string
126
- */
127
- protected function _getFilterField()
128
- {
129
- $fieldName = Mage::helper('choiceai_search')->getAttributeFieldName($this->getAttributeModel());
130
-
131
- return $fieldName;
132
- }
133
-
134
- /**
135
- * Retrieves current items data.
136
- *
137
- * @return array
138
- */
139
- protected function _getItemsData()
140
- {
141
- $range = $this->getRange();
142
- $fieldName = $this->_getFilterField();
143
- $facets = $this->getLayer()->getProductCollection()->getFacetedData($fieldName);
144
-
145
- $data = array();
146
- if (!empty($facets)) {
147
- foreach ($facets as $key => $count) {
148
- if ($count > 0) {
149
- preg_match('/TO ([\d\.]+)\]$/', $key, $rangeKey);
150
- $rangeKey = round($rangeKey[1] / $range);
151
- $data[] = array(
152
- 'label' => $this->_renderItemLabel($range, $rangeKey),
153
- 'value' => $rangeKey . ',' . $range,
154
- 'count' => $count,
155
- );
156
- }
157
- }
158
- }
159
-
160
- return $data;
161
- }
162
-
163
- /**
164
- * Renders decimal ranges.
165
- *
166
- * @param int $range
167
- * @param float $value
168
- * @return string
169
- */
170
- protected function _renderItemLabel($range, $value)
171
- {
172
- /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
173
- $attribute = $this->getAttributeModel();
174
-
175
- if ($attribute->getFrontendInput() == 'price') {
176
- return parent::_renderItemLabel($range, $value);
177
- }
178
-
179
- $from = ($value - 1) * $range;
180
- $to = $value * $range;
181
-
182
- if ($from != $to) {
183
- $to -= 0.01;
184
- }
185
-
186
- $to = Zend_Locale_Format::toFloat($to, array('locale' => Mage::helper('choiceai_search')->getLocaleCode()));
187
-
188
- return Mage::helper('catalog')->__('%s - %s', $from, $to);
189
- }
190
- }
 
1
+ <?php
2
+
3
+ /**
4
+ * Handles decimal attribute filtering in layered navigation.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal extends Mage_Catalog_Model_Layer_Filter_Decimal
11
+ {
12
+ const CACHE_TAG = 'MAXVALUE';
13
+
14
+ /**
15
+ * Adds facet condition to product collection.
16
+ *
17
+ * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
18
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
19
+ */
20
+ public function addFacetCondition()
21
+ {
22
+ $range = $this->getRange();
23
+ $maxValue = $this->getMaxValue();
24
+ if ($maxValue > 0) {
25
+ $facets = array();
26
+ $facetCount = (int)ceil($maxValue / $range);
27
+
28
+ for ($i = 0; $i < $facetCount + 1; $i++) {
29
+ $facets[] = array(
30
+ 'from' => $i * $range,
31
+ 'to' => ($i + 1) * $range,
32
+ 'include_upper' => !($i < $facetCount)
33
+ );
34
+ }
35
+
36
+ $fieldName = $this->_getFilterField();
37
+ $this->getLayer()->getProductCollection()->addFacetCondition($fieldName, $facets);
38
+ }
39
+
40
+ return $this;
41
+ }
42
+
43
+ /**
44
+ * Retrieves request parameter and applies it to product collection.
45
+ *
46
+ * @param Zend_Controller_Request_Abstract $request
47
+ * @param Mage_Core_Block_Abstract $filterBlock
48
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
49
+ */
50
+ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
51
+ {
52
+ $filter = $request->getParam($this->getRequestVar());
53
+ if (!$filter) {
54
+ return $this;
55
+ }
56
+
57
+ $filter = explode(',', $filter);
58
+ if (count($filter) != 2) {
59
+ return $this;
60
+ }
61
+
62
+ list($index, $range) = $filter;
63
+
64
+ if ((int)$index && (int)$range) {
65
+ $this->setRange((int)$range);
66
+
67
+ $this->applyFilterToCollection($this, $range, $index);
68
+ $this->getLayer()->getState()->addFilter(
69
+ $this->_createItem($this->_renderItemLabel($range, $index), $filter)
70
+ );
71
+
72
+ $this->_items = array();
73
+ }
74
+
75
+ return $this;
76
+ }
77
+
78
+ /**
79
+ * Apply decimal filter range to product collection.
80
+ *
81
+ * @param ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal $filter
82
+ * @param int $range
83
+ * @param int $index
84
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Decimal
85
+ */
86
+ public function applyFilterToCollection($filter, $range, $index)
87
+ {
88
+ $value = array(
89
+ $this->_getFilterField() => array(
90
+ 'from' => ($range * ($index - 1)),
91
+ 'to' => $range * $index,
92
+ )
93
+ );
94
+ $filter->getLayer()->getProductCollection()->addFqFilter($value);
95
+
96
+ return $this;
97
+ }
98
+
99
+ public function getMaxValue()
100
+ {
101
+ $searchParams = $this->getLayer()->getProductCollection()->getExtendedSearchParams();
102
+ $uniquePart = strtoupper(md5(serialize($searchParams)));
103
+ $cacheKey = 'MAXVALUE_' . $this->getLayer()->getStateKey() . '_' . $uniquePart;
104
+
105
+ $cachedData = Mage::app()->loadCache($cacheKey);
106
+ if (!$cachedData) {
107
+ $stats = $this->getLayer()->getProductCollection()->getStats($this->_getFilterField());
108
+
109
+ $max = $stats[$this->_getFilterField()]['max'];
110
+ if (!is_numeric($max)) {
111
+ $max = parent::getMaxValue();
112
+ }
113
+
114
+ $cachedData = (float)$max;
115
+ $tags = $this->getLayer()->getStateTags();
116
+ $tags[] = self::CACHE_TAG;
117
+ Mage::app()->saveCache($cachedData, $cacheKey, $tags);
118
+ }
119
+
120
+ return $cachedData;
121
+ }
122
+
123
+ /**
124
+ * Returns decimal field name.
125
+ *
126
+ * @return string
127
+ */
128
+ protected function _getFilterField()
129
+ {
130
+ $fieldName = Mage::helper('choiceai_search')->getAttributeFieldName($this->getAttributeModel());
131
+
132
+ return $fieldName;
133
+ }
134
+
135
+ /**
136
+ * Retrieves current items data.
137
+ *
138
+ * @return array
139
+ */
140
+ protected function _getItemsData()
141
+ {
142
+ $range = $this->getRange();
143
+ $fieldName = $this->_getFilterField();
144
+ $facets = $this->getLayer()->getProductCollection()->getFacetedData($fieldName);
145
+
146
+ $data = array();
147
+ if (!empty($facets)) {
148
+ foreach ($facets as $key => $count) {
149
+ if ($count > 0) {
150
+ preg_match('/TO ([\d\.]+)\]$/', $key, $rangeKey);
151
+ $rangeKey = round($rangeKey[1] / $range);
152
+ $data[] = array(
153
+ 'label' => $this->_renderItemLabel($range, $rangeKey),
154
+ 'value' => $rangeKey . ',' . $range,
155
+ 'count' => $count,
156
+ );
157
+ }
158
+ }
159
+ }
160
+
161
+ return $data;
162
+ }
163
+
164
+ /**
165
+ * Renders decimal ranges.
166
+ *
167
+ * @param int $range
168
+ * @param float $value
169
+ * @return string
170
+ */
171
+ protected function _renderItemLabel($range, $value)
172
+ {
173
+ /** @var $attribute Mage_Catalog_Model_Resource_Eav_Attribute */
174
+ $attribute = $this->getAttributeModel();
175
+
176
+ if ($attribute->getFrontendInput() == 'price') {
177
+ return parent::_renderItemLabel($range, $value);
178
+ }
179
+
180
+ $from = ($value - 1) * $range;
181
+ $to = $value * $range;
182
+
183
+ if ($from != $to) {
184
+ $to -= 0.01;
185
+ }
186
+
187
+ $to = Zend_Locale_Format::toFloat($to, array('locale' => Mage::helper('choiceai_search')->getLocaleCode()));
188
+
189
+ return Mage::helper('catalog')->__('%s - %s', $from, $to);
190
+ }
191
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Layer/Filter/Price.php CHANGED
@@ -1,154 +1,162 @@
1
- <?php
2
- /**
3
- * Handles price filtering in layered navigation.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Catalog_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Filter_Price
10
- {
11
- const CACHE_TAG = 'MAXPRICE';
12
-
13
- const DELIMITER = '-';
14
-
15
- /**
16
- * Returns cache tag.
17
- *
18
- * @return string
19
- */
20
- public function getCacheTag()
21
- {
22
- return self::CACHE_TAG;
23
- }
24
-
25
- /**
26
- * Retrieves max price for ranges definition.
27
- *
28
- * @return float
29
- */
30
- public function getMaxPriceMod()
31
- {
32
- $priceStat = Mage::getSingleton('choiceai_search/catalog_layer')->getProductCollection()->getStats('price');
33
- $productCollection = $this->getLayer()->getProductCollection();
34
- return isset($priceStat["max"])?(int)$priceStat["max"]:0;
35
- }
36
-
37
-
38
-
39
- /**
40
- * Retrieves min price for ranges definition.
41
- *
42
- * @return float
43
- */
44
- public function getMinPriceMod()
45
- {
46
- $priceStat = Mage::getSingleton('choiceai_search/catalog_layer')->getProductCollection()->getStats('price');
47
- $productCollection = $this->getLayer()->getProductCollection();
48
- return isset($priceStat["min"])?(int)$priceStat["min"]:0;
49
- }
50
-
51
- /**
52
- * Returns price field according to current customer group and website.
53
- *
54
- * @return string
55
- */
56
- protected function _getFilterField()
57
- {
58
- $websiteId = Mage::app()->getStore()->getWebsiteId();
59
- $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
60
- $priceField = 'price' ;
61
-
62
- return $priceField;
63
- }
64
-
65
- /**
66
- * Retrieves current items data.
67
- *
68
- * @return array
69
- */
70
- protected function _getItemsData()
71
- {
72
- // if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_IMPROVED) {
73
- // return $this->_getCalculatedItemsData();}
74
- if ($this->getInterval()) {
75
- return array();
76
- }
77
-
78
- $data = array();
79
- $facets = $this->getLayer()->getProductCollection()->getFacetedData($this->_getFilterField());
80
- if (!empty($facets)) {
81
- foreach ($facets as $key => $count) {
82
- if (!$count) {
83
- unset($facets[$key]);
84
- }
85
- }
86
- $i = 0;
87
- foreach ($facets as $key => $count) {
88
- $i++;
89
- preg_match('/^\[(\d*) TO (\d*)\]$/', $key, $rangeKey);
90
- $fromPrice = $rangeKey[1];
91
- $toPrice = $rangeKey[2];
92
- $data[] = array(
93
- 'label' => $this->_renderRangeLabel($fromPrice, $toPrice),
94
- 'value' => $fromPrice . self::DELIMITER . $toPrice,
95
- 'count' => $count
96
- );
97
- }
98
- }
99
-
100
- return $data;
101
- }
102
-
103
-
104
- /**
105
- * Adds facet condition to product collection.
106
- *
107
- * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
108
- * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
109
- */
110
- public function addFacetCondition()
111
- {
112
- $this->getLayer()
113
- ->getProductCollection()
114
- ->addFacetCondition($this->_getFilterField());
115
-
116
- return $this;
117
- }
118
-
119
-
120
- public function apply(Zend_Controller_Request_Abstract $request, $filterBlock){
121
-
122
- $filter = $request->getParam($this->_requestVar);
123
- if(null == $filter){
124
- return $this;
125
- }
126
- $filter =explode(self::DELIMITER, $filter);
127
- if (!is_array($filter) || null === $filter || sizeof($filter)<2 ) {
128
- return $this;
129
- }
130
- $this->applyFilterToCollection($this, $filter);
131
- $this->_items = null;
132
- return $this;
133
- }
134
-
135
-
136
- function applyFilterToCollection($filter,$filterValue){
137
- $field = $this->_getFilterField();
138
- $value = array(
139
- $field => array(
140
- 'include_upper' => 0
141
- )
142
- );
143
-
144
- if($filterValue[0]< $filterValue[1]){
145
- $value[$field]['from'] = $filterValue[0];
146
- $value[$field]['to'] = $filterValue[1];
147
- }else{
148
- $value[$field]['from'] = $filterValue[1];
149
- $value[$field]['to'] = $filterValue[0];
150
- }
151
- $this->getLayer()->getProductCollection()->addSearchQfFilter($value);
152
- return $this;
153
- }
154
- }
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Handles price filtering in layered navigation.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Catalog_Layer_Filter_Price extends Mage_Catalog_Model_Layer_Filter_Price
11
+ {
12
+ const CACHE_TAG = 'MAXPRICE';
13
+
14
+ const DELIMITER = '-';
15
+
16
+ /**
17
+ * Returns cache tag.
18
+ *
19
+ * @return string
20
+ */
21
+ public function getCacheTag()
22
+ {
23
+ return self::CACHE_TAG;
24
+ }
25
+
26
+ /**
27
+ * Retrieves max price for ranges definition.
28
+ *
29
+ * @return float
30
+ */
31
+ public function getMaxPriceMod()
32
+ {
33
+ $priceStat = Mage::getSingleton('choiceai_search/catalog_layer')->getProductCollection()
34
+ ->getStats('price');
35
+ // $productCollection = $this->getLayer()->getProductCollection();
36
+ return isset($priceStat["max"]) ? (int)$priceStat["max"] : 0;
37
+ }
38
+
39
+
40
+ /**
41
+ * Retrieves min price for ranges definition.
42
+ *
43
+ * @return float
44
+ */
45
+ public function getMinPriceMod()
46
+ {
47
+ $priceStat = Mage::getSingleton('choiceai_search/catalog_layer')->getProductCollection()
48
+ ->getStats('price');
49
+ // $productCollection = $this->getLayer()->getProductCollection();
50
+ return isset($priceStat["min"]) ? (int)$priceStat["min"] : 0;
51
+ }
52
+
53
+ /**
54
+ * Returns price field according to current customer group and website.
55
+ *
56
+ * @return string
57
+ */
58
+ protected function _getFilterField()
59
+ {
60
+ // $websiteId = Mage::app()->getStore()->getWebsiteId();
61
+ // $customerGroupId = Mage::getSingleton('customer/session')->getCustomerGroupId();
62
+ $priceField = 'price';
63
+
64
+ return $priceField;
65
+ }
66
+
67
+ /**
68
+ * Retrieves current items data.
69
+ *
70
+ * @return array
71
+ */
72
+ protected function _getItemsData()
73
+ {
74
+ //if (Mage::app()->getStore()->getConfig(self::XML_PATH_RANGE_CALCULATION) == self::RANGE_CALCULATION_IMPROVED) {
75
+ // return $this->_getCalculatedItemsData();}
76
+ if ($this->getInterval()) {
77
+ return array();
78
+ }
79
+
80
+ $data = array();
81
+ $facets = $this->getLayer()->getProductCollection()->getFacetedData($this->_getFilterField());
82
+ if (!empty($facets)) {
83
+ foreach ($facets as $key => $count) {
84
+ if (!$count) {
85
+ unset($facets[$key]);
86
+ }
87
+ }
88
+
89
+ $i = 0;
90
+ foreach ($facets as $key => $count) {
91
+ $i++;
92
+ $rangeKey = explode("-", $key);
93
+ $fromPrice = $rangeKey[0];
94
+ $toPrice = $rangeKey[1];
95
+ $data[] = array(
96
+ 'label' => $this->_renderRangeLabel($fromPrice, $toPrice),
97
+ 'value' => $fromPrice . self::DELIMITER . $toPrice,
98
+ 'count' => $count
99
+ );
100
+ }
101
+ }
102
+
103
+ return $data;
104
+ }
105
+
106
+
107
+ /**
108
+ * Adds facet condition to product collection.
109
+ *
110
+ * @see ChoiceAI_Search_Model_Resource_Catalog_Product_Collection::addFacetCondition()
111
+ * @return ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
112
+ */
113
+ public function addFacetCondition()
114
+ {
115
+ $this->getLayer()
116
+ ->getProductCollection()
117
+ ->addFacetCondition($this->_getFilterField());
118
+
119
+ return $this;
120
+ }
121
+
122
+
123
+ public function apply(Zend_Controller_Request_Abstract $request, $filterBlock)
124
+ {
125
+
126
+ $filter = $request->getParam($this->_requestVar);
127
+ if (null == $filter) {
128
+ return $this;
129
+ }
130
+
131
+ $filter = explode(self::DELIMITER, $filter);
132
+ if (!is_array($filter) || null === $filter || count($filter) < 2) {
133
+ return $this;
134
+ }
135
+
136
+ $this->applyFilterToCollection($this, $filter);
137
+ $this->_items = null;
138
+ return $this;
139
+ }
140
+
141
+
142
+ public function applyFilterToCollection($filter, $filterValue)
143
+ {
144
+ $field = $this->_getFilterField();
145
+ $value = array(
146
+ $field => array(
147
+ 'include_upper' => 0
148
+ )
149
+ );
150
+
151
+ if ($filterValue[0] < $filterValue[1]) {
152
+ $value[$field]['from'] = $filterValue[0];
153
+ $value[$field]['to'] = $filterValue[1];
154
+ } else {
155
+ $value[$field]['from'] = $filterValue[1];
156
+ $value[$field]['to'] = $filterValue[0];
157
+ }
158
+
159
+ $this->getLayer()->getProductCollection()->addSearchQfFilter($value);
160
+ return $this;
161
+ }
162
+ }
app/code/local/ChoiceAI/Search/Model/Catalog/Product/Url.php CHANGED
@@ -49,9 +49,9 @@ class ChoiceAI_Search_Model_Catalog_Product_Url extends Mage_Catalog_Model_Produ
49
  * @param bool $useSid forced SID mode
50
  * @return string
51
  */
52
- public function getProductUrl($product, $useSid = null)
53
- {
54
- return parent::getProductUrl($product, $useSid);
55
  // $toAppend = "cu=cai";
56
  //
57
  // if (Mage::helper('choiceai_search')->isActiveEngine()) {
@@ -68,6 +68,6 @@ class ChoiceAI_Search_Model_Catalog_Product_Url extends Mage_Catalog_Model_Produ
68
  // }
69
  // } else
70
  // return $prodUrl;
71
- }
72
 
73
  }
49
  * @param bool $useSid forced SID mode
50
  * @return string
51
  */
52
+ // public function getProductUrl($product, $useSid = null)
53
+ // {
54
+ // return parent::getProductUrl($product, $useSid);
55
  // $toAppend = "cu=cai";
56
  //
57
  // if (Mage::helper('choiceai_search')->isActiveEngine()) {
68
  // }
69
  // } else
70
  // return $prodUrl;
71
+ // }
72
 
73
  }
app/code/local/ChoiceAI/Search/Model/Catalogsearch/Layer.php CHANGED
@@ -1,31 +1,31 @@
1
- <?php
2
-
3
- /**
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
-
10
- class ChoiceAI_Search_Model_Catalogsearch_Layer extends Mage_CatalogSearch_Model_Layer
11
- {
12
- public function getProductCollection()
13
- {
14
- $category = $this->getCurrentCategory();
15
- if (isset($this->_productCollections[$category->getId()])) {
16
- $collection = $this->_productCollections[$category->getId()];
17
- } else {
18
- /** @var $collection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
19
- $collection = Mage::getResourceModel('choiceai_search/engine_choiceaisearch')
20
- //->getEngine()
21
- ->getResultCollection()
22
- ->setStoreId($category->getStoreId())
23
- ->setQueryType('search')
24
- ->addFqFilter(array('store_id' => $category->getStoreId()));
25
- $this->prepareProductCollection($collection);
26
- $this->_productCollections[$category->getId()] = $collection;
27
- }
28
-
29
- return $collection;
30
- }
31
- }
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+
10
+ class ChoiceAI_Search_Model_Catalogsearch_Layer extends Mage_CatalogSearch_Model_Layer
11
+ {
12
+ public function getProductCollection()
13
+ {
14
+ $category = $this->getCurrentCategory();
15
+ if (isset($this->_productCollections[$category->getId()])) {
16
+ $collection = $this->_productCollections[$category->getId()];
17
+ } else {
18
+ /** @var $collection ChoiceAI_Search_Model_Resource_Catalog_Product_Collection */
19
+ $collection = Mage::getResourceModel('choiceai_search/engine_choiceaisearch')
20
+ //->getEngine()
21
+ ->getResultCollection()
22
+ ->setStoreId($category->getStoreId())
23
+ ->setQueryType('search')
24
+ ->addFqFilter(array('store_id' => $category->getStoreId()));
25
+ $this->prepareProductCollection($collection);
26
+ $this->_productCollections[$category->getId()] = $collection;
27
+ }
28
+
29
+ return $collection;
30
+ }
31
+ }
app/code/local/ChoiceAI/Search/Model/Catalogsearch/Layer/Filter/Attribute.php CHANGED
@@ -1,16 +1,17 @@
1
- <?php
2
-
3
- /**
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
-
10
- class ChoiceAI_Search_Model_Catalogsearch_Layer_Filter_Attribute extends ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
11
- {
12
- protected function _getIsFilterableAttribute($attribute)
13
- {
14
- return $attribute->getIsFilterableInSearch();
15
- }
16
- }
 
1
+ <?php
2
+
3
+ /**
4
+ *
5
+ * @package ChoiceAI_Search
6
+ * @copyright Copyright (c) MineWhat
7
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
+ */
9
+
10
+ class ChoiceAI_Search_Model_Catalogsearch_Layer_Filter_Attribute extends
11
+ ChoiceAI_Search_Model_Catalog_Layer_Filter_Attribute
12
+ {
13
+ protected function _getIsFilterableAttribute($attribute)
14
+ {
15
+ return $attribute->getIsFilterableInSearch();
16
+ }
17
+ }
app/code/local/ChoiceAI/Search/Model/Resource/Catalog/Product/Collection.php CHANGED
@@ -1,373 +1,383 @@
1
- <?php
2
- /**
3
- * Custom catalog product collection model.
4
- *
5
- * @package ChoiceAI_Search
6
- * @copyright Copyright (c) MineWhat
7
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
- */
9
- class ChoiceAI_Search_Model_Resource_Catalog_Product_Collection extends Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
10
- {
11
- /**
12
- * @var ChoiceAI_Search_Model_Resource_Engine_Abstract Search engine.
13
- */
14
- protected $_engine;
15
-
16
- /**
17
- * @var array Faceted data.
18
- */
19
- protected $_facetedData = array();
20
-
21
- /**
22
- * @var array Facets conditions.
23
- */
24
- protected $_facetsConditions = array();
25
-
26
- /**
27
- * @var array General default query.
28
- */
29
- protected $_generalDefaultQuery = array('*' => '*');
30
-
31
- /**
32
- * @var string Search query text.
33
- */
34
- protected $_searchQueryText = '';
35
-
36
- /**
37
- * @var array Search query filters.
38
- */
39
- protected $_searchQueryFilters = array();
40
-
41
- protected $_searchCategoryFilters =array();
42
-
43
- /**
44
- * @var array Search query range filters.
45
- */
46
- protected $_searchQueryRangeFilters = array();
47
-
48
- /**
49
- * @var array Search entity ids.
50
- */
51
- protected $_searchedEntityIds = array();
52
-
53
- /**
54
- * @var array Sort by definition.
55
- */
56
- protected $_sortBy = array();
57
-
58
- protected $qt = 'search';
59
-
60
- protected $stats =array();
61
-
62
- /**
63
- * Adds facet condition to current collection.
64
- *
65
- * @param string $field
66
- * @param mixed $condition
67
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
68
- */
69
- public function addFacetCondition($field, $condition = null)
70
- {
71
- if (array_key_exists($field, $this->_facetsConditions)) {
72
- if (!empty($this->_facetsConditions[$field])){
73
- $this->_facetsConditions[$field] = array($this->_facetsConditions[$field]);
74
- }
75
- $this->_facetsConditions[$field][] = $condition;
76
- } else {
77
- $this->_facetsConditions[$field] = $condition;
78
- }
79
-
80
- return $this;
81
- }
82
-
83
- /**
84
- * Stores filter query.
85
- *
86
- * @param array $params
87
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
88
- */
89
- public function addFqFilter($params)
90
- {
91
- if (is_array($params)) {
92
- foreach ($params as $field => $value) {
93
- $this->_searchQueryFilters[$field] = $value;
94
- }
95
- }
96
-
97
- return $this;
98
- }
99
-
100
- /**
101
- * Stores filter query.
102
- *
103
- * @param array $params
104
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
105
- */
106
- public function addCategoryId($id)
107
- {
108
- $this->_searchCategoryFilters = $id;
109
-
110
- return $this;
111
- }
112
-
113
- /**
114
- * setting the query type
115
- */
116
- public function setQueryType($qt = 'search'){
117
- $this->qt = $qt;
118
- return $this;
119
- }
120
-
121
- /**
122
- * Stores range filter query.
123
- *
124
- * @param array $params
125
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
126
- */
127
- public function addFqRangeFilter($params)
128
- {
129
- if (is_array($params)) {
130
- foreach ($params as $field => $value) {
131
- $this->_searchQueryRangeFilters[$field] = $value;
132
- }
133
- }
134
-
135
- return $this;
136
- }
137
-
138
- /**
139
- * Stores query text filter.
140
- *
141
- * @param $query
142
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
143
- */
144
- public function addSearchFilter($query)
145
- {
146
- $this->_searchQueryText = $query;
147
-
148
- return $this;
149
- }
150
-
151
- /**
152
- * Stores search query filter.
153
- *
154
- * @param mixed $param
155
- * @param null $value
156
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
157
- */
158
- public function addSearchQfFilter($param, $value = null)
159
- {
160
- if (is_array($param)) {
161
- foreach ($param as $field => $value) {
162
- $this->addSearchQfFilter($field, $value);
163
- }
164
- } elseif (isset($value)) {
165
- if (isset($this->_searchQueryFilters[$param]) && !is_array($this->_searchQueryFilters[$param])) {
166
- $this->_searchQueryFilters[$param] = array($this->_searchQueryFilters[$param]);
167
- $this->_searchQueryFilters[$param][] = $value;
168
- } else {
169
- $this->_searchQueryFilters[$param] = $value;
170
- }
171
- }
172
-
173
- return $this;
174
- }
175
-
176
- /**
177
- * Aggregates search query filters.
178
- *
179
- * @return array
180
- */
181
- public function getExtendedSearchParams()
182
- {
183
- $result = $this->_searchQueryFilters;
184
- $result['query_text'] = $this->_searchQueryText;
185
-
186
- return $result;
187
- }
188
-
189
- /**
190
- * Returns faceted data.
191
- *
192
- * @param string $field
193
- * @return array
194
- */
195
- public function getFacetedData($field)
196
- {
197
-
198
- if (array_key_exists($field, $this->_facetedData)) {
199
- return $this->_facetedData[$field];
200
- }
201
-
202
- return array();
203
- }
204
-
205
- /**
206
- * Returns collection size.
207
- *
208
- * @return int
209
- */
210
- public function getSize()
211
- {
212
- if (is_null($this->_totalRecords)) {
213
- $query = $this->_getQuery();
214
- $params = $this->_getParams();
215
- $params['limit'] = 1;
216
- //$this->_engine->getIdsByQuery($query, $params);
217
- $this->_totalRecords = 1;
218
- //$this->_totalRecords = $this->_engine->getLastNumFound();
219
- }
220
-
221
- return $this->_totalRecords;
222
- }
223
-
224
- /**
225
- * Retrieves current collection stats.
226
- * Used for max price.
227
- *
228
- * @param $fields
229
- * @return mixed
230
- */
231
- public function getStats($field)
232
- {
233
- return isset($this->stats[$field])?$this->stats[$field]:array();
234
- }
235
-
236
- /**
237
- * Defines current search engine.
238
- *
239
- * @param ChoiceAI_Search_Model_Resource_Engine_Abstract $engine
240
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
241
- */
242
- public function setEngine(ChoiceAI_Search_Model_Resource_Engine_Abstract $engine)
243
- {
244
- $this->_engine = $engine;
245
-
246
- return $this;
247
- }
248
-
249
- /**
250
- * Stores sort order.
251
- *
252
- * @param string $attribute
253
- * @param string $dir
254
- * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
255
- */
256
- public function setOrder($attribute, $dir = self::SORT_ORDER_DESC)
257
- {
258
- $this->_sortBy[] = array($attribute => $dir);
259
-
260
- return $this;
261
- }
262
-
263
- /**
264
- * Handles collection filtering by ids retrieves from search engine.
265
- * Will also stores faceted data and total records.
266
- *
267
- * @return Mage_Catalog_Model_Resource_Product_Collection
268
- */
269
- protected function _beforeLoad()
270
- {
271
- if ($this->_engine) {
272
- $result = $this->_engine->getIdsByQuery($this->qt, $this->_getParams());
273
- $this->_facetedData = isset($result['faceted_data']) ? $result['faceted_data'] : array();
274
- $this->_totalRecords = isset($result['total_count']) ? $result['total_count'] : null;
275
- $this->stats = isset($result["stats"])?$result["stats"] :array();
276
- $this->results = isset($result["results"]) ? $result["results"] : array();
277
- }
278
-
279
- // Getting IDs of all products with the store
280
- // $productIdsArray = Mage::getModel('catalog/product')->getCollection()->getAllIds();
281
- foreach($this->results as $result){
282
- // Keeping only those products which are in the store!
283
- // @TODO: Filter those items if required
284
- // if(in_array($result['uniqueId'], $productIdsArray)) {
285
- $product = new Mage_Catalog_Model_Product();
286
- $result['id'] = $result['uniqueId'];
287
- $product->addData($result);
288
- $this->_items[$result['id']] = $product;
289
- // }
290
- }
291
-
292
- return parent::_beforeLoad();
293
- }
294
-
295
- /**
296
- * Load collection data into object items
297
- *
298
- * @return Mage_Eav_Model_Entity_Collection_Abstract
299
- */
300
- public function load($printQuery = false, $logQuery = false)
301
- {
302
- if ($this->isLoaded()) {
303
- return $this;
304
- }
305
- Varien_Profiler::start('__EAV_COLLECTION_BEFORE_LOAD__');
306
- Mage::dispatchEvent('eav_collection_abstract_load_before', array('collection' => $this));
307
- $this->_beforeLoad();
308
- Varien_Profiler::stop('__EAV_COLLECTION_BEFORE_LOAD__');
309
-
310
-
311
- Varien_Profiler::start('__EAV_COLLECTION_LOAD_ENT__');
312
- // $this->_loadEntities($printQuery, $logQuery);
313
- Varien_Profiler::stop('__EAV_COLLECTION_LOAD_ENT__');
314
- Varien_Profiler::start('__EAV_COLLECTION_LOAD_ATTR__');
315
- // $this->_loadAttributes($printQuery, $logQuery);
316
- Varien_Profiler::stop('__EAV_COLLECTION_LOAD_ATTR__');
317
-
318
- Varien_Profiler::start('__EAV_COLLECTION_ORIG_DATA__');
319
- /*
320
- foreach ($this->_items as $item) {
321
- $item->setOrigData();
322
- }*/
323
- Varien_Profiler::stop('__EAV_COLLECTION_ORIG_DATA__');
324
-
325
- $this->_setIsLoaded();
326
- Varien_Profiler::start('__EAV_COLLECTION_AFTER_LOAD__');
327
- $this->_afterLoad();
328
- Varien_Profiler::stop('__EAV_COLLECTION_AFTER_LOAD__');
329
- return $this;
330
- }
331
-
332
- /**
333
- * Retrieves parameters.
334
- *
335
- * @return array
336
- */
337
- protected function _getParams()
338
- {
339
- $store = Mage::app()->getStore($this->getStoreId());
340
- $params = array();
341
- $params['locale_code'] = $store->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE);
342
- $params['filters'] = $this->_searchQueryFilters;
343
- $params['category'] = $this->_searchCategoryFilters;
344
- $params['range_filters'] = $this->_searchQueryRangeFilters;
345
-
346
- if (!empty($this->_sortBy)) {
347
- $params['sort_by'] = $this->_sortBy;
348
- }
349
-
350
- if ($this->_pageSize !== false) {
351
- $page = ($this->_curPage > 0) ? (int) $this->_curPage : 1;
352
- $rowCount = ($this->_pageSize > 0) ? (int) $this->_pageSize : 1;
353
- $params['offset'] = $rowCount * ($page - 1);
354
- $params['limit'] = $rowCount;
355
- }
356
-
357
- if (!empty($this->_facetsConditions)) {
358
- $params['facets'] = $this->_facetsConditions;
359
- }
360
-
361
- return $params;
362
- }
363
-
364
- /**
365
- * Returns stored text query.
366
- *
367
- * @return string
368
- */
369
- protected function _getQuery()
370
- {
371
- return $this->_searchQueryText;
372
- }
373
- }
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Custom catalog product collection model.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Resource_Catalog_Product_Collection extends
11
+ Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Collection
12
+ {
13
+ /**
14
+ * @var ChoiceAI_Search_Model_Resource_Engine_Abstract Search engine.
15
+ */
16
+ protected $_engine;
17
+
18
+ /**
19
+ * @var array Faceted data.
20
+ */
21
+ protected $_facetedData = array();
22
+
23
+ /**
24
+ * @var array Facets conditions.
25
+ */
26
+ protected $_facetsConditions = array();
27
+
28
+ /**
29
+ * @var array General default query.
30
+ */
31
+ protected $_generalDefaultQuery = array('*' => '*');
32
+
33
+ /**
34
+ * @var string Search query text.
35
+ */
36
+ protected $_searchQueryText = '';
37
+
38
+ /**
39
+ * @var array Search query filters.
40
+ */
41
+ protected $_searchQueryFilters = array();
42
+
43
+ protected $_searchCategoryFilters = array();
44
+
45
+ /**
46
+ * @var array Search query range filters.
47
+ */
48
+ protected $_searchQueryRangeFilters = array();
49
+
50
+ /**
51
+ * @var array Search entity ids.
52
+ */
53
+ protected $_searchedEntityIds = array();
54
+
55
+ /**
56
+ * @var array Sort by definition.
57
+ */
58
+ protected $_sortBy = array();
59
+
60
+ protected $_qt = 'search';
61
+
62
+ protected $_stats = array();
63
+
64
+ /**
65
+ * Adds facet condition to current collection.
66
+ *
67
+ * @param string $field
68
+ * @param mixed $condition
69
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
70
+ */
71
+ public function addFacetCondition($field, $condition = null)
72
+ {
73
+ if (array_key_exists($field, $this->_facetsConditions)) {
74
+ if (!empty($this->_facetsConditions[$field])) {
75
+ $this->_facetsConditions[$field] = array($this->_facetsConditions[$field]);
76
+ }
77
+
78
+ $this->_facetsConditions[$field][] = $condition;
79
+ } else {
80
+ $this->_facetsConditions[$field] = $condition;
81
+ }
82
+
83
+ return $this;
84
+ }
85
+
86
+ /**
87
+ * Stores filter query.
88
+ *
89
+ * @param array $params
90
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
91
+ */
92
+ public function addFqFilter($params)
93
+ {
94
+ if (is_array($params)) {
95
+ foreach ($params as $field => $value) {
96
+ $this->_searchQueryFilters[$field] = $value;
97
+ }
98
+ }
99
+
100
+ return $this;
101
+ }
102
+
103
+ /**
104
+ * Stores filter query.
105
+ *
106
+ * @param array $params
107
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
108
+ */
109
+ public function addCategoryId($id)
110
+ {
111
+ $this->_searchCategoryFilters = $id;
112
+
113
+ return $this;
114
+ }
115
+
116
+ /**
117
+ * setting the query type
118
+ * @param string $qt
119
+ * @return $this
120
+ */
121
+ public function setQueryType($qt = 'search')
122
+ {
123
+ $this->_qt = $qt;
124
+ return $this;
125
+ }
126
+
127
+ /**
128
+ * Stores range filter query.
129
+ *
130
+ * @param array $params
131
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
132
+ */
133
+ public function addFqRangeFilter($params)
134
+ {
135
+ if (is_array($params)) {
136
+ foreach ($params as $field => $value) {
137
+ $this->_searchQueryRangeFilters[$field] = $value;
138
+ }
139
+ }
140
+
141
+ return $this;
142
+ }
143
+
144
+ /**
145
+ * Stores query text filter.
146
+ *
147
+ * @param $query
148
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
149
+ */
150
+ public function addSearchFilter($query)
151
+ {
152
+ $this->_searchQueryText = $query;
153
+
154
+ return $this;
155
+ }
156
+
157
+ /**
158
+ * Stores search query filter.
159
+ *
160
+ * @param mixed $param
161
+ * @param null $value
162
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
163
+ */
164
+ public function addSearchQfFilter($param, $value = null)
165
+ {
166
+ if (is_array($param)) {
167
+ foreach ($param as $field => $value) {
168
+ $this->addSearchQfFilter($field, $value);
169
+ }
170
+ } elseif (isset($value)) {
171
+ if (isset($this->_searchQueryFilters[$param]) && !is_array($this->_searchQueryFilters[$param])) {
172
+ $this->_searchQueryFilters[$param] = array($this->_searchQueryFilters[$param]);
173
+ $this->_searchQueryFilters[$param][] = $value;
174
+ } else {
175
+ $this->_searchQueryFilters[$param] = $value;
176
+ }
177
+ }
178
+
179
+ return $this;
180
+ }
181
+
182
+ /**
183
+ * Aggregates search query filters.
184
+ *
185
+ * @return array
186
+ */
187
+ public function getExtendedSearchParams()
188
+ {
189
+ $result = $this->_searchQueryFilters;
190
+ $result['query_text'] = $this->_searchQueryText;
191
+
192
+ return $result;
193
+ }
194
+
195
+ /**
196
+ * Returns faceted data.
197
+ *
198
+ * @param string $field
199
+ * @return array
200
+ */
201
+ public function getFacetedData($field)
202
+ {
203
+
204
+ if (array_key_exists($field, $this->_facetedData)) {
205
+ return $this->_facetedData[$field];
206
+ }
207
+
208
+ return array();
209
+ }
210
+
211
+ /**
212
+ * Returns collection size.
213
+ *
214
+ * @return int
215
+ */
216
+ public function getSize()
217
+ {
218
+ if ($this->_totalRecords === null) {
219
+ // $query = $this->_getQuery();
220
+ $params = $this->_getParams();
221
+ $params['limit'] = 1;
222
+ //$this->_engine->getIdsByQuery($query, $params);
223
+ $this->_totalRecords = 1;
224
+ //$this->_totalRecords = $this->_engine->getLastNumFound();
225
+ }
226
+
227
+ return $this->_totalRecords;
228
+ }
229
+
230
+ /**
231
+ * Retrieves current collection stats.
232
+ * Used for max price.
233
+ *
234
+ * @param $field
235
+ * @return mixed
236
+ * @internal param $fields
237
+ */
238
+ public function getStats($field)
239
+ {
240
+ return isset($this->_stats[$field]) ? $this->_stats[$field] : array();
241
+ }
242
+
243
+ /**
244
+ * Defines current search engine.
245
+ *
246
+ * @param ChoiceAI_Search_Model_Resource_Engine_Abstract $engine
247
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
248
+ */
249
+ public function setEngine(ChoiceAI_Search_Model_Resource_Engine_Abstract $engine)
250
+ {
251
+ $this->_engine = $engine;
252
+
253
+ return $this;
254
+ }
255
+
256
+ /**
257
+ * Stores sort order.
258
+ *
259
+ * @param string $attribute
260
+ * @param string $dir
261
+ * @return ChoiceAI_Search_Model_Resource_Catalog_Product_Collection
262
+ */
263
+ public function setOrder($attribute, $dir = self::SORT_ORDER_DESC)
264
+ {
265
+ $this->_sortBy[] = array($attribute => $dir);
266
+
267
+ return $this;
268
+ }
269
+
270
+ /**
271
+ * Handles collection filtering by ids retrieves from search engine.
272
+ * Will also stores faceted data and total records.
273
+ *
274
+ * @return Mage_Catalog_Model_Resource_Product_Collection
275
+ */
276
+ protected function _beforeLoad()
277
+ {
278
+ if ($this->_engine) {
279
+ $result = $this->_engine->getIdsByQuery($this->qt, $this->_getParams());
280
+ $this->_facetedData = isset($result['faceted_data']) ? $result['faceted_data'] : array();
281
+ $this->_totalRecords = isset($result['total_count']) ? $result['total_count'] : null;
282
+ $this->_stats = isset($result["stats"]) ? $result["stats"] : array();
283
+ $this->results = isset($result["results"]) ? $result["results"] : array();
284
+ }
285
+
286
+ // Getting IDs of all products with the store
287
+ // $productIdsArray = Mage::getModel('catalog/product')->getCollection()->getAllIds();
288
+ foreach ($this->results as $result) {
289
+ // Keeping only those products which are in the store!
290
+ // TO DO: Filter those items if required
291
+ // if(in_array($result['uniqueId'], $productIdsArray)) {
292
+ $product = new Mage_Catalog_Model_Product();
293
+ $result['id'] = $result['uniqueId'];
294
+ $product->addData($result);
295
+ $this->_items[$result['id']] = $product;
296
+ // }
297
+ }
298
+
299
+ return parent::_beforeLoad();
300
+ }
301
+
302
+ /**
303
+ * Load collection data into object items
304
+ *
305
+ * @param bool $printQuery
306
+ * @param bool $logQuery
307
+ * @return Mage_Eav_Model_Entity_Collection_Abstract
308
+ */
309
+ public function load($printQuery = false, $logQuery = false)
310
+ {
311
+ if ($this->isLoaded()) {
312
+ return $this;
313
+ }
314
+
315
+ Varien_Profiler::start('__EAV_COLLECTION_BEFORE_LOAD__');
316
+ Mage::dispatchEvent('eav_collection_abstract_load_before', array('collection' => $this));
317
+ $this->_beforeLoad();
318
+ Varien_Profiler::stop('__EAV_COLLECTION_BEFORE_LOAD__');
319
+
320
+
321
+ Varien_Profiler::start('__EAV_COLLECTION_LOAD_ENT__');
322
+ // $this->_loadEntities($printQuery, $logQuery);
323
+ Varien_Profiler::stop('__EAV_COLLECTION_LOAD_ENT__');
324
+ Varien_Profiler::start('__EAV_COLLECTION_LOAD_ATTR__');
325
+ // $this->_loadAttributes($printQuery, $logQuery);
326
+ Varien_Profiler::stop('__EAV_COLLECTION_LOAD_ATTR__');
327
+
328
+ Varien_Profiler::start('__EAV_COLLECTION_ORIG_DATA__');
329
+ /*
330
+ foreach ($this->_items as $item) {
331
+ $item->setOrigData();
332
+ }*/
333
+ Varien_Profiler::stop('__EAV_COLLECTION_ORIG_DATA__');
334
+
335
+ $this->_setIsLoaded();
336
+ Varien_Profiler::start('__EAV_COLLECTION_AFTER_LOAD__');
337
+ $this->_afterLoad();
338
+ Varien_Profiler::stop('__EAV_COLLECTION_AFTER_LOAD__');
339
+ return $this;
340
+ }
341
+
342
+ /**
343
+ * Retrieves parameters.
344
+ *
345
+ * @return array
346
+ */
347
+ protected function _getParams()
348
+ {
349
+ $store = Mage::app()->getStore($this->getStoreId());
350
+ $params = array();
351
+ $params['locale_code'] = $store->getConfig(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE);
352
+ $params['filters'] = $this->_searchQueryFilters;
353
+ $params['category'] = $this->_searchCategoryFilters;
354
+ $params['range_filters'] = $this->_searchQueryRangeFilters;
355
+
356
+ if (!empty($this->_sortBy)) {
357
+ $params['sort_by'] = $this->_sortBy;
358
+ }
359
+
360
+ if ($this->_pageSize !== false) {
361
+ $page = ($this->_curPage > 0) ? (int)$this->_curPage : 1;
362
+ $rowCount = ($this->_pageSize > 0) ? (int)$this->_pageSize : 1;
363
+ $params['offset'] = $rowCount * ($page - 1);
364
+ $params['limit'] = $rowCount;
365
+ }
366
+
367
+ if (!empty($this->_facetsConditions)) {
368
+ $params['facets'] = $this->_facetsConditions;
369
+ }
370
+
371
+ return $params;
372
+ }
373
+
374
+ /**
375
+ * Returns stored text query.
376
+ *
377
+ * @return string
378
+ */
379
+ protected function _getQuery()
380
+ {
381
+ return $this->_searchQueryText;
382
+ }
383
+ }
app/code/local/ChoiceAI/Search/Model/Resource/Engine/Abstract.php CHANGED
@@ -1,4 +1,5 @@
1
  <?php
 
2
  /**
3
  * Search client.
4
  *
@@ -64,15 +65,15 @@ abstract class ChoiceAI_Search_Model_Resource_Engine_Abstract
64
  'score'
65
  );
66
 
67
- /**
68
- * Get Indexer instance
69
- *
70
- * @return Mage_Index_Model_Indexer
71
- */
72
- protected function _getIndexer()
73
- {
74
- return Mage::getSingleton('index/indexer');
75
- }
76
 
77
  /**
78
  * Retrieves product ids for specified query.
@@ -92,12 +93,13 @@ abstract class ChoiceAI_Search_Model_Resource_Engine_Abstract
92
  $ids[] = $id['uniqueId'];
93
  }
94
  }
 
95
  $result = array(
96
  'ids' => $ids,
97
  'total_count' => (isset($resultTmp['total_count'])) ? $resultTmp['total_count'] : null,
98
  'faceted_data' => (isset($resultTmp['facets'])) ? $resultTmp['facets'] : array(),
99
- 'results' => array_key_exists('result', $resultTmp)?$resultTmp["result"]: array(),
100
- 'stats' => array_key_exists('stats', $resultTmp)?$resultTmp["stats"]: array()
101
  );
102
 
103
  return $result;
1
  <?php
2
+
3
  /**
4
  * Search client.
5
  *
65
  'score'
66
  );
67
 
68
+ /**
69
+ * Get Indexer instance
70
+ *
71
+ * @return Mage_Index_Model_Indexer
72
+ */
73
+ protected function _getIndexer()
74
+ {
75
+ return Mage::getSingleton('index/indexer');
76
+ }
77
 
78
  /**
79
  * Retrieves product ids for specified query.
93
  $ids[] = $id['uniqueId'];
94
  }
95
  }
96
+
97
  $result = array(
98
  'ids' => $ids,
99
  'total_count' => (isset($resultTmp['total_count'])) ? $resultTmp['total_count'] : null,
100
  'faceted_data' => (isset($resultTmp['facets'])) ? $resultTmp['facets'] : array(),
101
+ 'results' => array_key_exists('result', $resultTmp) ? $resultTmp["result"] : array(),
102
+ 'stats' => array_key_exists('stats', $resultTmp) ? $resultTmp["stats"] : array()
103
  );
104
 
105
  return $result;
app/code/local/ChoiceAI/Search/Model/Resource/Engine/Choiceaisearch.php CHANGED
@@ -1,276 +1,288 @@
1
- <?php
2
-
3
- /**
4
- * ChoiceAI engine.
5
- *
6
- * @package ChoiceAI_Search
7
- * @copyright Copyright (c) MineWhat
8
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
- */
10
- class ChoiceAI_Search_Model_Resource_Engine_ChoiceAIsearch extends ChoiceAI_Search_Model_Resource_Engine_Abstract
11
- {
12
- /**
13
- * Initializes search engine.
14
- *
15
- * @see
16
- */
17
- public function __construct()
18
- {
19
- $this->client = Mage::getResourceSingleton('choiceai_search/engine_choiceaisearch_client');
20
- }
21
-
22
- function _prepareFacetsQueryResponse($response = array()){
23
- $result = array();
24
- foreach ($response as $facetName=>$facetlist) {
25
- if($facetlist["type"]=='facet_fields'){
26
- $result[$facetName] = array();
27
- $count = 0;
28
- $facetKey ='';
29
- foreach($facetlist['values'] as $value){
30
- if($count++ % 2 == 0){
31
- $facetKey = $value;
32
- }else{
33
- $result[$facetName][$facetKey]=$value;
34
- }
35
- }
36
- }else if($facetlist["type"]=='facet_ranges'){
37
- $result[$facetName] = array();
38
- $count = 0;
39
- $facetKey = '';
40
- $gap = floatval($facetlist['values']['gap']);
41
- foreach($facetlist['values']['counts'] as $value){
42
- if($count++ % 2 == 0){
43
- $facetKey = floatval($value);
44
- }else{
45
- $result[$facetName]['['.$facetKey.' TO '.($facetKey + $gap).']']=$value;
46
- }
47
- }
48
- }
49
- }
50
- return $result;
51
- }
52
-
53
- /**
54
- * prepares the facet condition
55
- */
56
- public function _prepareFacetsConditions($facets = array()){
57
- $stringFacets = array();
58
- $rangeFacets = array();
59
- if(is_array($facets)){
60
- foreach($facets as $facetKey=>$facetValue){
61
- if(is_array($facetValue) && $facetValue != null && is_array($facetValue) && sizeof($facetValue) > 0 ){
62
- if(isset($facetValue['from']) && isset($facetValue["to"])){
63
- $facetValues= array();
64
- $eachFacetValue= $facetValue;
65
- if(!isset($eachFacetValue['from']) || $eachFacetValue['from'] == "" ){
66
- $eachFacetValue['from'] = '0';
67
- }
68
- if(!isset($eachFacetValue['to']) || $eachFacetValue['to'] == "" ){
69
- $eachFacetValue['to'] = '*';
70
- }
71
- $facetValues['from'] = $eachFacetValue['from'];
72
- $facetValues['to'] = $eachFacetValue['to'];
73
- $stringFacets[$facetKey][] = $facetValues;
74
- } else {
75
- $stringFacets[$facetKey] = $facetValue;
76
- }
77
- }
78
- }
79
- }
80
- $facets=array();
81
- $facets["attribute"] = $stringFacets;
82
- $facets["range"] = $rangeFacets;
83
- return $facets;
84
- }
85
-
86
- protected function _prepareResponse($data){
87
- /* @var $response ChoiceAI_ResultSet */
88
- if (!$data instanceof ChoiceAI_ResultSet || $data->getTotalHits()<=0) {
89
- return array();
90
- }
91
-
92
- $result = array();
93
-
94
- foreach ($data->getResults() as $doc) {
95
- $result[] =$doc->getHit();
96
- }
97
- return $result;
98
- }
99
-
100
- /**
101
- * Prepares sort fields.
102
- *
103
- * @param array $sortBy
104
- * @return array
105
- */
106
- protected function _prepareSortFields($sortBy=array())
107
- {
108
- $sort =array();
109
- if(!isset($sortBy) || sizeof($sortBy) == 0) {
110
- $sortParameter = array_key_exists('order',$_GET)?$_GET['order']:null;
111
- $sortBy = (!is_null($sortParameter))?
112
- array(array($sortParameter => (isset($_GET['dir']) && $_GET['dir'] == 'desc')?'desc':'asc')): array();
113
- $sessionSort = Mage::getSingleton('catalog/session')->getSortOrder();
114
- $sessionDir = Mage::getSingleton('catalog/session')->getSortDirection();
115
- $sortBy = (is_null($sortBy)|| sizeof($sortBy) == 0) && !is_null($sessionSort) ?
116
- array(array($sessionSort => ($sessionDir === 'desc')?'desc':'asc')):$sortBy;
117
- }
118
-
119
- foreach($sortBy as $value){
120
- foreach($value as $sortKey=>$sortValue){
121
- if($sortKey != "position" && $sortKey != "relevance"){
122
- if($sortValue == 'asc'){
123
- $sort[$sortKey] = 1;
124
- }else{
125
- $sort[$sortKey] = -1;
126
- }
127
- }
128
- }
129
- }
130
- return $sort;
131
- }
132
-
133
-
134
- public function getStats($data){
135
- $stats = $data->getStats();
136
- if(isset($stats) && is_array($stats)){
137
- return $stats;
138
- }
139
- return array();
140
- }
141
-
142
- /**
143
- * prepare limitN
144
- * @param $params
145
- * @return int|mixed
146
- */
147
- protected function _prepareLimit($params)
148
- {
149
- if(array_key_exists("limit", $params)) {
150
- $limit = (int)$params["limit"];
151
- }else{
152
- $limitInRequest = array_key_exists('limit', $_GET) ? $_GET['limit'] : null;
153
- $limitOnSession = Mage::getSingleton('catalog/session')->getLimitPage();
154
- if ($limitOnSession === "all" || $limitInRequest === "all") {
155
- $limitOnSession = 100;
156
- }
157
- $limit = ($limitInRequest > 0) ? (int)$limitInRequest : ($limitOnSession > 0 ? $limitOnSession : ((isset($_GET['mode']) && $_GET['mode'] == 'list') ? Mage::getStoreConfig('catalog/frontend/list_per_page') : Mage::getStoreConfig('catalog/frontend/grid_per_page')));
158
- }
159
-
160
- return $limit;
161
- }
162
-
163
- /**
164
- * Performs search and facetting
165
- *
166
- * Note: Called from app/code/local/ChoiceAI/Search/Model/Resource/Engine/Abstract.php's search function
167
- *
168
- * @param string $query
169
- * @param array $params
170
- * @param string $type
171
- * @return array
172
- */
173
- protected function _search($qt, $params = array(), $type = 'product')
174
- {
175
- $multiselectValue = Mage::getConfig()->getNode('default/choiceai/general/multiselect_facet');
176
- $multiselectValue = (!is_null($multiselectValue) &&
177
- sizeof($multiselectValue) && $multiselectValue[0] == 'true')?true:false;
178
- $limit = $this->_prepareLimit($params);
179
- if(isset($_GET['p'])){
180
- $page = ((int)$_GET['p'] > 0)?((int)$_GET['p'] - 1)* $limit:0;
181
- }else{
182
- $page = 0;
183
- }
184
-
185
- $facets = $this->_prepareFacetsConditions($params['filters']);
186
- $searchParams = array();
187
- $query = Mage::helper('catalogsearch')->getQueryText();
188
-
189
- if(isset($query) && $query != ''){
190
- $this->client = $this->client->setRuleset('search')->setQuery($query)->setFilters($facets['attribute']);
191
- }else{
192
- $this->client = $this->client->setRuleset('browse')->setCategoryId($params['category'])->setFilters($facets['attribute']);
193
- }
194
-
195
- // @TODO: Confirm this, till "?" only right?
196
- $urlPath = explode("?", $_SERVER['REQUEST_URI'])[0];
197
-
198
- $paramsString = isset($_SERVER['REDIRECT_QUERY_STRING']) ? $_SERVER['REDIRECT_QUERY_STRING'] : '';
199
-
200
- $getParamsToSend = array(
201
- 'v'=> 3,
202
- 'url' => $urlPath
203
- );
204
-
205
- // Checking if the following params are available in GET, if yes, we will forward them just as they are
206
- $pairs = [
207
- 'site'=> 'mwc',
208
- 'expId'=> 'expId',
209
- 'variantId'=> 'variantId',
210
- 'mwpreview'=> 'mwpreview',
211
- 'mwforce'=> 'mwforce',
212
- 'mwdevice'=> 'mwdevice',
213
- 'layout'=> 'layout',
214
- 'uitype'=> 'uitype',
215
- 'expforce'=> 'expforce',
216
- 'lrp'=>'lrp',
217
- 'llp'=>'llp',
218
- 'catPaths'=> 'catPaths',
219
- 'tagsList'=> 'tagsList'
220
- ];
221
-
222
- foreach ($pairs as $getParam => $paramNameForSending) {
223
- if (isset($_GET[$getParam]))
224
- $getParamsToSend[$paramNameForSending] = $_GET[$getParam];
225
- }
226
-
227
-
228
- if(trim($paramsString) != '')
229
- $getParamsToSend['p'] = $paramsString;
230
-
231
- if(isset($_SERVER['HTTP_REFERER']))
232
- $getParamsToSend['r'] = $_SERVER['HTTP_REFERER'];
233
-
234
- if(isset($_COOKIE['caicookie'])) {
235
- $getParamsToSend['u'] = $_COOKIE['caicookie'];
236
- }
237
- else
238
- {
239
- $getParamsToSend['isnew'] = true;
240
- }
241
-
242
- // Calls Client.php in lib
243
- $data = $this->client
244
- ->setOffset($page)
245
- ->setLimit($limit)
246
- ->setOtherOptions($getParamsToSend)
247
- ->setDebug(false)
248
- ->setSort($this->_prepareSortFields(array_key_exists('sort_by', $params)?$params['sort_by']:array()))
249
- ->search();
250
- if (!$data instanceof ChoiceAI_ResultSet) {
251
- return array();
252
- }
253
-
254
- // if($data->getSpellCheckQuery()) {
255
- // // Not being read anywhere, so why setting it?
256
- // Mage::unregister('spellcheckQuery');
257
- // Mage::register('spellcheckQuery', $data->getSpellCheckQuery());
258
- // }
259
-
260
-
261
- /* @var $data ChoiceAI_ResultSet */
262
- $result = array(
263
- 'total_count' => $data->getTotalHits(),
264
- 'result' => $this->_prepareResponse($data),
265
- 'stats' => $this->getStats($data)
266
- );
267
- $result['facets'] = $this->_prepareFacetsQueryResponse($data->getFacets());
268
- // Seems unused
269
- Mage::unregister('start');
270
- Mage::register('start', $page* Mage::getStoreConfig('catalog/frontend/grid_per_page'));
271
- return $result;
272
- }
273
-
274
- }
275
-
276
- ?>
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * ChoiceAI engine.
5
+ *
6
+ * @package ChoiceAI_Search
7
+ * @copyright Copyright (c) MineWhat
8
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
9
+ */
10
+ class ChoiceAI_Search_Model_Resource_Engine_ChoiceAIsearch extends ChoiceAI_Search_Model_Resource_Engine_Abstract
11
+ {
12
+ /**
13
+ * Initializes search engine.
14
+ *
15
+ * @see
16
+ */
17
+ public function __construct()
18
+ {
19
+ $this->client = Mage::getResourceSingleton('choiceai_search/engine_choiceaisearch_client');
20
+ }
21
+
22
+ protected function _prepareFacetsQueryResponse($response = array())
23
+ {
24
+ $result = array();
25
+ foreach ($response as $facetName => $facetlist) {
26
+ if ($facetlist["type"] == 'facet_fields') {
27
+ $result[$facetName] = array();
28
+ $count = 0;
29
+ $facetKey = '';
30
+ foreach ($facetlist['values'] as $value) {
31
+ if ($count++ % 2 == 0) {
32
+ $facetKey = $value;
33
+ } else {
34
+ $result[$facetName][$facetKey] = $value;
35
+ }
36
+ }
37
+ } else if ($facetlist["type"] == 'facet_ranges') {
38
+ $result[$facetName] = array();
39
+ $count = 0;
40
+ $facetKey = '';
41
+ $gap = floatval($facetlist['values']['gap']);
42
+ foreach ($facetlist['values']['counts'] as $value) {
43
+ if ($count++ % 2 == 0) {
44
+ $facetKey = floatval($value);
45
+ } else {
46
+ $result[$facetName]['[' . $facetKey . ' TO ' . ($facetKey + $gap) . ']'] = $value;
47
+ }
48
+ }
49
+ }
50
+ }
51
+
52
+ return $result;
53
+ }
54
+
55
+ /**
56
+ * prepares the facet condition
57
+ */
58
+ public function _prepareFacetsConditions($facets = array())
59
+ {
60
+ $stringFacets = array();
61
+ $rangeFacets = array();
62
+ if (is_array($facets)) {
63
+ foreach ($facets as $facetKey => $facetValue) {
64
+ if (is_array($facetValue) && $facetValue != null && is_array($facetValue) && count($facetValue) > 0) {
65
+ if (isset($facetValue['from']) && isset($facetValue["to"])) {
66
+ $facetValues = array();
67
+ $eachFacetValue = $facetValue;
68
+ if (!isset($eachFacetValue['from']) || $eachFacetValue['from'] == "") {
69
+ $eachFacetValue['from'] = '0';
70
+ }
71
+
72
+ if (!isset($eachFacetValue['to']) || $eachFacetValue['to'] == "") {
73
+ $eachFacetValue['to'] = '*';
74
+ }
75
+
76
+ $facetValues['from'] = $eachFacetValue['from'];
77
+ $facetValues['to'] = $eachFacetValue['to'];
78
+ $stringFacets[$facetKey][] = $facetValues;
79
+ } else {
80
+ $stringFacets[$facetKey] = $facetValue;
81
+ }
82
+ }
83
+ }
84
+ }
85
+
86
+ $facets = array();
87
+ $facets["attribute"] = $stringFacets;
88
+ $facets["range"] = $rangeFacets;
89
+ return $facets;
90
+ }
91
+
92
+ protected function _prepareResponse($data)
93
+ {
94
+ /* @var $response ChoiceAI_ResultSet */
95
+ if (!$data instanceof ChoiceAI_ResultSet || $data->getTotalHits() <= 0) {
96
+ return array();
97
+ }
98
+
99
+ $result = array();
100
+
101
+ foreach ($data->getResults() as $doc) {
102
+ $result[] = $doc->getHit();
103
+ }
104
+
105
+ return $result;
106
+ }
107
+
108
+ /**
109
+ * Prepares sort fields.
110
+ *
111
+ * @param array $sortBy
112
+ * @return array
113
+ */
114
+ protected function _prepareSortFields($sortBy = array())
115
+ {
116
+ $sort = array();
117
+ $query = Mage::app()->getRequest()->getQuery();
118
+ if (!isset($sortBy) || count($sortBy) == 0) {
119
+ $sortParameter = array_key_exists('order', $query) ? $query['order'] : null;
120
+ $sortBy = ($sortParameter !== null) ?
121
+ array(array($sortParameter => (isset($query['dir']) && $query['dir'] == 'desc') ? 'desc' : 'asc')) : array();
122
+ $sessionSort = Mage::getSingleton('catalog/session')->getSortOrder();
123
+ $sessionDir = Mage::getSingleton('catalog/session')->getSortDirection();
124
+ $sortBy = ($sortBy === null || count($sortBy) == 0) && $sessionSort !== null ?
125
+ array(array($sessionSort => ($sessionDir === 'desc') ? 'desc' : 'asc')) : $sortBy;
126
+ }
127
+
128
+ foreach ($sortBy as $value) {
129
+ foreach ($value as $sortKey => $sortValue) {
130
+ if ($sortKey != "position" && $sortKey != "relevance") {
131
+ if ($sortValue == 'asc') {
132
+ $sort[$sortKey] = 1;
133
+ } else {
134
+ $sort[$sortKey] = -1;
135
+ }
136
+ }
137
+ }
138
+ }
139
+
140
+ return $sort;
141
+ }
142
+
143
+
144
+ public function getStats($data)
145
+ {
146
+ $stats = $data->getStats();
147
+ if (isset($stats) && is_array($stats)) {
148
+ return $stats;
149
+ }
150
+
151
+ return array();
152
+ }
153
+
154
+ /**
155
+ * prepare limitN
156
+ * @param $params
157
+ * @return int|mixed
158
+ */
159
+ protected function _prepareLimit($params)
160
+ {
161
+ if (array_key_exists("limit", $params)) {
162
+ $limit = (int)$params["limit"];
163
+ } else {
164
+ $query = Mage::app()->getRequest()->getQuery();
165
+ $limitInRequest = array_key_exists('limit', $query) ? $query['limit'] : null;
166
+ $limitOnSession = Mage::getSingleton('catalog/session')->getLimitPage();
167
+ if ($limitOnSession === "all" || $limitInRequest === "all") {
168
+ $limitOnSession = 100;
169
+ }
170
+
171
+ $limit = ($limitInRequest > 0) ? (int)$limitInRequest : ($limitOnSession > 0 ? $limitOnSession : ((isset($query['mode']) && $query['mode'] == 'list') ? Mage::getStoreConfig('catalog/frontend/list_per_page') : Mage::getStoreConfig('catalog/frontend/grid_per_page')));
172
+ }
173
+
174
+ return $limit;
175
+ }
176
+
177
+ /**
178
+ * Performs search and facetting
179
+ *
180
+ * Note: Called from app/code/local/ChoiceAI/Search/Model/Resource/Engine/Abstract.php's search function
181
+ *
182
+ * @param string $query
183
+ * @param array $params
184
+ * @param string $type
185
+ * @return array
186
+ */
187
+ protected function _search($qt, $params = array(), $type = 'product')
188
+ {
189
+ // $multiselectValue = Mage::getConfig()->getNode('default/choiceai/general/multiselect_facet');
190
+ // $multiselectValue = (!is_null($multiselectValue) &&
191
+ // sizeof($multiselectValue) && $multiselectValue[0] == 'true') ? true : false;
192
+ $limit = $this->_prepareLimit($params);
193
+ $query = Mage::app()->getRequest()->getQuery();
194
+ if (isset($query['p'])) {
195
+ $page = ((int)$query['p'] > 0) ? ((int)$query['p'] - 1) * $limit : 0;
196
+ } else {
197
+ $page = 0;
198
+ }
199
+
200
+ $facets = $this->_prepareFacetsConditions($params['filters']);
201
+
202
+ $query = Mage::helper('catalogsearch')->getQueryText();
203
+
204
+ if (isset($query) && $query != '') {
205
+ $this->client = $this->client->setRuleset('search')->setQuery($query)->setFilters($facets['attribute']);
206
+ } else {
207
+ $this->client = $this->client->setRuleset('browse')->setCategoryId($params['category'])
208
+ ->setFilters($facets['attribute']);
209
+ }
210
+
211
+ $server = Mage::app()->getRequest()->getServer();
212
+ $urlPath = explode("?", $server['REQUEST_URI'])[0];
213
+
214
+ $paramsString = isset($server['REDIRECT_QUERY_STRING']) ? $server['REDIRECT_QUERY_STRING'] : '';
215
+
216
+ $getParamsToSend = array(
217
+ 'v' => 3,
218
+ 'url' => $urlPath
219
+ );
220
+
221
+ // Checking if the following params are available in GET, if yes, we will forward them just as they are
222
+ $pairs = array(
223
+ 'site' => 'mwc',
224
+ 'expId' => 'expId',
225
+ 'variantId' => 'variantId',
226
+ 'mwpreview' => 'mwpreview',
227
+ 'mwforce' => 'mwforce',
228
+ 'mwdevice' => 'mwdevice',
229
+ 'layout' => 'layout',
230
+ 'uitype' => 'uitype',
231
+ 'expforce' => 'expforce',
232
+ 'lrp' => 'lrp',
233
+ 'llp' => 'llp',
234
+ 'contextId' => 'contextId'
235
+ );
236
+ $query = Mage::app()->getRequest()->getQuery();
237
+ foreach ($pairs as $getParam => $paramNameForSending) {
238
+ if (isset($query[$getParam]))
239
+ $getParamsToSend[$paramNameForSending] = $query[$getParam];
240
+ }
241
+
242
+
243
+ if (trim($paramsString) != '')
244
+ $getParamsToSend['p'] = $paramsString;
245
+
246
+ if (isset($server['HTTP_REFERER']))
247
+ $getParamsToSend['r'] = $server['HTTP_REFERER'];
248
+ $cookie = Mage::app()->getRequest()->getCookie();
249
+ if (isset($cookie['caicookie'])) {
250
+ $getParamsToSend['u'] = $cookie['caicookie'];
251
+ } else {
252
+ $getParamsToSend['isnew'] = true;
253
+ }
254
+
255
+ // Calls Client.php in lib
256
+ $data = $this->client
257
+ ->setOffset($page)
258
+ ->setLimit($limit)
259
+ ->setOtherOptions($getParamsToSend)
260
+ ->setDebug(false)
261
+ ->setSort($this->_prepareSortFields(array_key_exists('sort_by', $params) ? $params['sort_by'] : array()))
262
+ ->search();
263
+ if (!$data instanceof ChoiceAI_ResultSet) {
264
+ return array();
265
+ }
266
+
267
+ // if($data->getSpellCheckQuery()) {
268
+ // // Not being read anywhere, so why setting it?
269
+ // Mage::unregister('spellcheckQuery');
270
+ // Mage::register('spellcheckQuery', $data->getSpellCheckQuery());
271
+ // }
272
+
273
+
274
+ /* @var $data ChoiceAI_ResultSet */
275
+ $result = array(
276
+ 'total_count' => $data->getTotalHits(),
277
+ 'result' => $this->_prepareResponse($data),
278
+ 'stats' => $this->getStats($data)
279
+ );
280
+ $result['facets'] = $this->_prepareFacetsQueryResponse($data->getFacets());
281
+ // Seems unused
282
+ Mage::unregister('start');
283
+ Mage::register('start', $page * Mage::getStoreConfig('catalog/frontend/grid_per_page'));
284
+ return $result;
285
+ }
286
+
287
+ }
288
+
app/code/local/ChoiceAI/Search/Model/Resource/Engine/Choiceaisearch/Client.php CHANGED
@@ -7,21 +7,22 @@
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
 
10
- class ChoiceAI_Search_Model_Resource_Engine_ChoiceAIsearch_Client extends ChoiceAI_Client{
 
11
 
12
  const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
13
 
14
- public function __construct()
15
  {
16
  $config = $this->_getHelper()->getEngineConfigData();
17
  $config['context'] = Mage::getStoreConfig(self::CONFIG_API_KEY);
18
  parent::__construct($config);
19
  }
20
-
21
  protected function _getHelper()
22
  {
23
  return Mage::helper('choiceai_search/choiceaisearch');
24
  }
25
 
26
  }
27
- ?>
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
 
10
+ class ChoiceAI_Search_Model_Resource_Engine_ChoiceAIsearch_Client extends ChoiceAI_Client
11
+ {
12
 
13
  const CONFIG_API_KEY = 'choiceai_personalisation/settings/api_key';
14
 
15
+ public function __construct()
16
  {
17
  $config = $this->_getHelper()->getEngineConfigData();
18
  $config['context'] = Mage::getStoreConfig(self::CONFIG_API_KEY);
19
  parent::__construct($config);
20
  }
21
+
22
  protected function _getHelper()
23
  {
24
  return Mage::helper('choiceai_search/choiceaisearch');
25
  }
26
 
27
  }
28
+
app/code/local/ChoiceAI/Search/etc/config.xml CHANGED
@@ -2,7 +2,7 @@
2
  <config>
3
  <modules>
4
  <ChoiceAI_Search>
5
- <version>1.0.12</version>
6
  </ChoiceAI_Search>
7
  </modules>
8
  <global>
@@ -18,7 +18,7 @@
18
  <rewrite>
19
  <config>ChoiceAI_Search_Model_Catalog_Config</config>
20
  <category>ChoiceAI_Search_Model_Catalog_Category</category>
21
- <product_url>ChoiceAI_Search_Model_Catalog_Product_Url</product_url>
22
  </rewrite>
23
  </catalog>
24
  </models>
2
  <config>
3
  <modules>
4
  <ChoiceAI_Search>
5
+ <version>1.1.1</version>
6
  </ChoiceAI_Search>
7
  </modules>
8
  <global>
18
  <rewrite>
19
  <config>ChoiceAI_Search_Model_Catalog_Config</config>
20
  <category>ChoiceAI_Search_Model_Catalog_Category</category>
21
+ <!--<product_url>ChoiceAI_Search_Model_Catalog_Product_Url</product_url>-->
22
  </rewrite>
23
  </catalog>
24
  </models>
app/code/local/ChoiceAI/Searchcore/Helper/Constants.php CHANGED
@@ -6,7 +6,8 @@
6
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
  */
8
 
9
- class ChoiceAI_Searchcore_Helper_Constants extends Mage_Core_Helper_Abstract {
 
10
 
11
  const SITE_KEY = "site_key";
12
 
@@ -100,9 +101,9 @@ class ChoiceAI_Searchcore_Helper_Constants extends Mage_Core_Helper_Abstract {
100
 
101
  const AUTOSUGGET_SIDE_TEMPLATE = 'sideTpl';
102
 
103
- static $AUTOSUGGEST_SIDECONTENTS = array(self::AUTOSUGGEST_SIDECONTENT_RIGHT, self::AUTOSUGGEST_SIDECONTENT_LEFT);
104
-
105
- static $AUTOSUGGEST_TEMPLATES = array(self::AUTOSUGGEST_TEMPLATE_1COLUMN, self::AUTOSUGGEST_TEMPLATE_2COLUMN);
106
 
107
  const SEARCH_MOD_STATUS = 'search_mod_status';
108
 
@@ -191,5 +192,5 @@ class ChoiceAI_Searchcore_Helper_Constants extends Mage_Core_Helper_Abstract {
191
  const AUTH_REQUEST_PARAM = 'auth';
192
 
193
  const LAST_UPLOAD_TIME = 'lastUpload';
194
-
195
  }
6
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
7
  */
8
 
9
+ class ChoiceAI_Searchcore_Helper_Constants extends Mage_Core_Helper_Abstract
10
+ {
11
 
12
  const SITE_KEY = "site_key";
13
 
101
 
102
  const AUTOSUGGET_SIDE_TEMPLATE = 'sideTpl';
103
 
104
+ // static $AUTOSUGGEST_SIDECONTENTS = array(self::AUTOSUGGEST_SIDECONTENT_RIGHT, self::AUTOSUGGEST_SIDECONTENT_LEFT);
105
+ //
106
+ // static $AUTOSUGGEST_TEMPLATES = array(self::AUTOSUGGEST_TEMPLATE_1COLUMN, self::AUTOSUGGEST_TEMPLATE_2COLUMN);
107
 
108
  const SEARCH_MOD_STATUS = 'search_mod_status';
109
 
192
  const AUTH_REQUEST_PARAM = 'auth';
193
 
194
  const LAST_UPLOAD_TIME = 'lastUpload';
195
+
196
  }
app/code/local/ChoiceAI/Searchcore/Helper/Data.php CHANGED
@@ -6,7 +6,8 @@
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
- class ChoiceAI_Searchcore_Helper_Data extends Mage_Core_Helper_Abstract {
 
10
 
11
  const LOG_FILE = "choiceai_searchcore.log";
12
 
@@ -20,10 +21,11 @@ class ChoiceAI_Searchcore_Helper_Data extends Mage_Core_Helper_Abstract {
20
  /**
21
  * Method to log
22
  *
23
- * @param int $level
24
  * @param string $message
25
  */
26
- public function log($level, $message) {
 
27
  Mage::log($message, $level, static::LOG_FILE, true);
28
  }
29
 
@@ -36,25 +38,30 @@ class ChoiceAI_Searchcore_Helper_Data extends Mage_Core_Helper_Abstract {
36
  */
37
  public function getEngineConfigData($prefix = '', Mage_Core_Model_Website $website = null, $original = false)
38
  {
39
- if(is_null($website)) {
40
  $website = Mage::app()->getWebsite();
41
  }
 
42
  $originalConfig = array();
43
- if($original) {
44
- $originalConfig = $this->getOriginalValue($prefix, $website);
45
  }
46
- if(is_null($this->engineConfigData)) {
 
47
  $this->engineConfigData = Mage::getConfig()
48
- ->getNode(ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX, 'websites',
49
- (int)$website->getWebsiteId());
 
 
50
  }
51
 
52
  if (!$this->engineConfigData) {
53
  return false;
54
  }
 
55
  if ($this->engineConfigData->hasChildren()) {
56
  $value = array();
57
- foreach ($this->engineConfigData->asArray() as $k=>$v) {
58
  if ($prefix != '' && preg_match("#^{$prefix}(.*)#", $k, $matches)) {
59
  $value[$k] = $v;
60
  }
@@ -62,26 +69,34 @@ class ChoiceAI_Searchcore_Helper_Data extends Mage_Core_Helper_Abstract {
62
  } else {
63
  $value = (string)$this->engineConfigData;
64
  }
65
- return array_merge($value,$originalConfig);
 
66
  }
67
 
68
- public function getOriginalValue($prefix = '', Mage_Core_Model_Website $website) {
 
69
  $configDataCollection = Mage::getModel('core/config_data')
70
- ->getCollection()
71
- ->addScopeFilter('websites', (int)$website->getWebsiteId(), ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX)
72
- ->load();
73
- $value = array();
74
- foreach($configDataCollection as $data) {
75
- $path = $data->getPath();
76
- if (substr($path, 0, strlen(ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX)) == ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX) {
77
- $path = substr($path, strlen(ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX) +1);
 
 
 
 
78
  }
 
79
  if ($prefix != '' && preg_match("#^{$prefix}(.*)#", $path, $matches)) {
80
  $value[$path] = $data->getValue();
81
  }
82
  }
83
- return $value;
 
84
  }
85
 
86
  }
87
- ?>
6
  * @copyright Copyright (c) MineWhat
7
  * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
8
  */
9
+ class ChoiceAI_Searchcore_Helper_Data extends Mage_Core_Helper_Abstract
10
+ {
11
 
12
  const LOG_FILE = "choiceai_searchcore.log";
13
 
21
  /**
22
  * Method to log
23
  *
24
+ * @param int $level
25
  * @param string $message
26
  */
27
+ public function log($level, $message)
28
+ {
29
  Mage::log($message, $level, static::LOG_FILE, true);
30
  }
31
 
38
  */
39
  public function getEngineConfigData($prefix = '', Mage_Core_Model_Website $website = null, $original = false)
40
  {
41
+ if ($website === null) {
42
  $website = Mage::app()->getWebsite();
43
  }
44
+
45
  $originalConfig = array();
46
+ if ($original) {
47
+ $originalConfig = $this->getOriginalValue($website, $prefix);
48
  }
49
+
50
+ if ($this->engineConfigData === null) {
51
  $this->engineConfigData = Mage::getConfig()
52
+ ->getNode(
53
+ ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX, 'websites',
54
+ (int)$website->getWebsiteId()
55
+ );
56
  }
57
 
58
  if (!$this->engineConfigData) {
59
  return false;
60
  }
61
+
62
  if ($this->engineConfigData->hasChildren()) {
63
  $value = array();
64
+ foreach ($this->engineConfigData->asArray() as $k => $v) {
65
  if ($prefix != '' && preg_match("#^{$prefix}(.*)#", $k, $matches)) {
66
  $value[$k] = $v;
67
  }
69
  } else {
70
  $value = (string)$this->engineConfigData;
71
  }
72
+
73
+ return array_merge($value, $originalConfig);
74
  }
75
 
76
+ public function getOriginalValue(Mage_Core_Model_Website $website, $prefix = '')
77
+ {
78
  $configDataCollection = Mage::getModel('core/config_data')
79
+ ->getCollection()
80
+ ->addScopeFilter(
81
+ 'websites', (int)$website->getWebsiteId(),
82
+ ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX
83
+ )
84
+ ->load();
85
+ $value = array();
86
+ foreach ($configDataCollection as $data) {
87
+ $path = $data->getPath();
88
+ if (substr($path, 0, strlen(ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX)) ==
89
+ ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX) {
90
+ $path = substr($path, strlen(ChoiceAI_Searchcore_Helper_Constants::CHOICEAI_CONFIG_PREFIX) + 1);
91
  }
92
+
93
  if ($prefix != '' && preg_match("#^{$prefix}(.*)#", $path, $matches)) {
94
  $value[$path] = $data->getValue();
95
  }
96
  }
97
+
98
+ return $value;
99
  }
100
 
101
  }
102
+
app/code/local/ChoiceAI/Searchcore/etc/config.xml CHANGED
@@ -1,7 +1,7 @@
1
  <config>
2
  <modules>
3
  <ChoiceAI_Searchcore>
4
- <version>1.0.12</version>
5
  </ChoiceAI_Searchcore>
6
  </modules>
7
  <global>
1
  <config>
2
  <modules>
3
  <ChoiceAI_Searchcore>
4
+ <version>1.1.1</version>
5
  </ChoiceAI_Searchcore>
6
  </modules>
7
  <global>
app/design/frontend/base/default/template/choiceai/personalisation/analytics/listpage.phtml CHANGED
@@ -1,25 +1,22 @@
1
- <?php
2
- // Passing passback if received from server
3
- if(Mage::registry("expId") && !Mage::registry("passback")) { ?>
4
- <script type="text/javascript">
5
- window._caiExistingPage = '<?php echo Mage::registry("expId") ?>';
6
- </script>
7
- <?php
8
- }
9
- if (Mage::registry("passback")) { ?>
10
- <script type="text/javascript">
11
- //<![CDATA[
12
- window._caiapi = window._caiapi || [];
13
- window._caiExistingPage = '<?php echo Mage::registry("passback")["expId"] ?>';
14
- _caiapi.push(['trackExperiment', <?php echo Mage::helper('core')->jsonEncode(Mage::registry("passback")) ?>]);
15
- //]]>
16
- </script>
17
- <?php
18
- }
19
- ?>
20
-
21
  <script type="text/javascript">
22
- //<![CDATA[
23
- window._caity = <?php echo $this->engineStatus() ? '"clistpage"' : '"category"' ?>;
24
- //]]>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <script type="text/javascript">
2
+ //<![CDATA[
3
+ window._caity = <?php echo $this->engineStatus() ? '"clistpage"' : '"category"' ?>;
4
+ <?php // Passing passback if received from server
5
+ if (Mage::registry("expId") && !Mage::registry("passback")) { ?>
6
+ window._caiExistingPage = '<?php echo Mage::registry("expId") ?>';
7
+ <?php
8
+ } if (Mage::registry("passback")) {
9
+ ?>
10
+ window._caiapi = window._caiapi || [];
11
+ window._caiExistingPage = '<?php echo Mage::registry("passback")["expId"] ?>';
12
+ _caiapi.push(['trackExperiment', <?php echo Mage::helper('core')->jsonEncode(Mage::registry("passback")) ?>]);
13
+ <?php if (Mage::registry("user_context") && Mage::registry("contextId")) { ?>
14
+ _caiapi.push(['trackContext', "<?php echo Mage::registry("user_context") ?>", "<?php echo Mage::registry("contextId") ?>"]);
15
+ <?php
16
+ }
17
+ ?>
18
+ <?php
19
+ }
20
+ ?>
21
+ //]]>
22
  </script>
app/design/frontend/base/default/template/choiceai/personalisation/analytics/search.phtml CHANGED
@@ -1,25 +1,22 @@
1
- <?php
2
- // Passing passback if received from server
3
- if(Mage::registry("expId") && !Mage::registry("passback")) { ?>
4
- <script type="text/javascript">
5
- window._caiExistingPage = '<?php echo Mage::registry("expId") ?>';
6
- </script>
7
- <?php
8
- }
9
- if (Mage::registry("passback")) { ?>
10
- <script type="text/javascript">
11
- //<![CDATA[
12
- window._caiapi = window._caiapi || [];
13
- window._caiExistingPage = '<?php echo Mage::registry("passback")["expId"] ?>';
14
- _caiapi.push(['trackExperiment', <?php echo Mage::helper('core')->jsonEncode(Mage::registry("passback")) ?>]);
15
- //]]>
16
- </script>
17
- <?php
18
- }
19
- ?>
20
-
21
  <script type="text/javascript">
22
- //<![CDATA[
23
- window._caity = <?php echo $this->engineStatus() ? '"csearch"' : '"search"' ?>;
24
- //]]>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  <script type="text/javascript">
2
+ //<![CDATA[
3
+ window._caity = <?php echo $this->engineStatus() ? '"csearch"' : '"search"' ?>;
4
+ <?php // Passing passback if received from server
5
+ if (Mage::registry("expId") && !Mage::registry("passback")) { ?>
6
+ window._caiExistingPage = '<?php echo Mage::registry("expId") ?>';
7
+ <?php
8
+ } if (Mage::registry("passback")) {
9
+ ?>
10
+ window._caiapi = window._caiapi || [];
11
+ window._caiExistingPage = '<?php echo Mage::registry("passback")["expId"] ?>';
12
+ _caiapi.push(['trackExperiment', <?php echo Mage::helper('core')->jsonEncode(Mage::registry("passback")) ?>]);
13
+ <?php if (Mage::registry("user_context") && Mage::registry("contextId")) { ?>
14
+ _caiapi.push(['trackContext', "<?php echo Mage::registry("user_context") ?>", "<?php echo Mage::registry("contextId") ?>"]);
15
+ <?php
16
+ }
17
+ ?>
18
+ <?php
19
+ }
20
+ ?>
21
+ //]]>
22
  </script>
app/design/frontend/base/default/template/choiceai/personalisation/base/addparam.phtml CHANGED
@@ -1,34 +1,13 @@
1
- <!-- not to be executed as it will give wrong result-->
2
  <?php if (false && $this->engineStatus()) : ?>
3
  <script type="text/javascript">
4
  var searchInput = document.getElementById("search_mini_form");
5
-
6
- <?php if(Mage::registry("tagsList") != '') : ?>
7
- var input = document.createElement("input");
8
- input.name = "tagsList";
9
- input.type = "hidden";
10
- input.value = "<?php echo Mage::registry("tagsList"); ?>";
11
-
12
- searchInput.appendChild(input);
13
- <?php endif; ?>
14
-
15
- <?php if(Mage::registry("catPaths") && Mage::registry("catPaths") != "") : ?>
16
  var input2 = document.createElement("input");
17
- input2.name = "catPaths";
18
  input2.type = "hidden";
19
- input2.value = '<?php echo Mage::registry("catPaths"); ?>';
20
 
21
  searchInput.appendChild(input2);
22
  <?php endif; ?>
23
-
24
-
25
- <?php if(Mage::registry("prodCountNow") != '') : ?>
26
- var input3 = document.createElement("input");
27
- input3.name = "ct";
28
- input3.type = "hidden";
29
- input3.value = <?php echo Mage::registry("prodCountNow"); ?>;
30
-
31
- searchInput.appendChild(input3);
32
- <?php endif; ?>
33
  </script>
34
  <?php endif; ?>
 
1
  <?php if (false && $this->engineStatus()) : ?>
2
  <script type="text/javascript">
3
  var searchInput = document.getElementById("search_mini_form");
4
+ <?php if(Mage::registry("contextId") && Mage::registry("contextId") != "") : ?>
 
 
 
 
 
 
 
 
 
 
5
  var input2 = document.createElement("input");
6
+ input2.name = "contextId";
7
  input2.type = "hidden";
8
+ input2.value = '<?php echo Mage::registry("contextId"); ?>';
9
 
10
  searchInput.appendChild(input2);
11
  <?php endif; ?>
 
 
 
 
 
 
 
 
 
 
12
  </script>
13
  <?php endif; ?>
app/design/frontend/base/default/template/choiceai/personalisation/base/script.phtml CHANGED
@@ -1,40 +1,40 @@
1
- <?php echo Mage::helper('choiceai_personalisation')->getBaseScript() ?>
2
- <?php
3
- $user = $this->getUser();
4
- if($user) {
5
- $email = $user->getEmail();
6
- if ($email && strlen($email) > 0) {
7
- ?>
8
- <script type="text/javascript">
9
- //<![CDATA[
10
- window._caiapi = window._caiapi || [];
11
- _caiapi.push(['trackUser', '<?php echo $email ?>']);
12
- //]]>
13
- </script>
14
- <?php
15
- }
16
- }
17
-
18
- $cart = Mage::getModel('checkout/cart')->getQuote();
19
- $cart_items = array();
20
- foreach ($cart->getAllVisibleItems() as $item) {
21
- $cart_item = array();
22
- $cart_item['pid'] = $item->getProductId();
23
- $cart_item['sku'] = $item->getSku();
24
- $cart_item['name'] = $item->getProduct()->getName();
25
- $cart_item['price'] = $item->getProduct()->getPrice();
26
- $cart_item['final_price'] = $item->getProduct()->getFinalPrice();
27
- $cart_item['special_price'] = $item->getProduct()->getSpecialPrice();
28
- $cart_item['type'] = $item->getProduct()->getTypeId();
29
- $cart_item['qty'] = $item->getQty();
30
- $cart_items[] = $cart_item;
31
- }
32
- ?>
33
-
34
- <script type="text/javascript">
35
- //<![CDATA[
36
- window._mwuserid = '<?php echo Mage::registry("caiuid")?>';
37
- window.CAI_CART_ITEMS = <?php echo json_encode($cart_items); ?>;
38
- window.CAI_MAGENTO_ADDTOCART_FORM_KEY = '<?php echo Mage::getSingleton('core/session')->getFormKey()?>';
39
- //]]>
40
  </script>
1
+ <?php echo Mage::helper('choiceai_personalisation')->getBaseScript() ?>
2
+ <?php
3
+ $user = $this->getUser();
4
+ if($user) {
5
+ $email = $user->getEmail();
6
+ if ($email && strlen($email) > 0) {
7
+ ?>
8
+ <script type="text/javascript">
9
+ //<![CDATA[
10
+ window._caiapi = window._caiapi || [];
11
+ _caiapi.push(['trackUser', '<?php echo $email ?>']);
12
+ //]]>
13
+ </script>
14
+ <?php
15
+ }
16
+ }
17
+
18
+ $cart = Mage::getModel('checkout/cart')->getQuote();
19
+ $cart_items = array();
20
+ foreach ($cart->getAllVisibleItems() as $item) {
21
+ $cart_item = array();
22
+ $cart_item['pid'] = $item->getProductId();
23
+ $cart_item['sku'] = $item->getSku();
24
+ $cart_item['name'] = $item->getProduct()->getName();
25
+ $cart_item['price'] = $item->getProduct()->getPrice();
26
+ $cart_item['final_price'] = $item->getProduct()->getFinalPrice();
27
+ $cart_item['special_price'] = $item->getProduct()->getSpecialPrice();
28
+ $cart_item['type'] = $item->getProduct()->getTypeId();
29
+ $cart_item['qty'] = $item->getQty();
30
+ $cart_items[] = $cart_item;
31
+ }
32
+ ?>
33
+
34
+ <script type="text/javascript">
35
+ //<![CDATA[
36
+ window._mwuserid = '<?php echo Mage::registry("caiuid")?>';
37
+ window.CAI_CART_ITEMS = <?php echo json_encode($cart_items); ?>;
38
+ window.CAI_MAGENTO_ADDTOCART_FORM_KEY = '<?php echo Mage::getSingleton('core/session')->getFormKey()?>';
39
+ //]]>
40
  </script>
app/design/frontend/default/default/template/choiceai/personalisation/base/script.phtml CHANGED
@@ -1,39 +1,39 @@
1
- <?php echo Mage::helper('choiceai_personalisation')->getBaseScript() ?>
2
- <?php
3
- $user = $this->getUser();
4
- if($user) {
5
- $email = $user->getEmail();
6
- if ($email && strlen($email) > 0) {
7
- ?>
8
- <script type="text/javascript">
9
- //<![CDATA[
10
- window._caiapi = window._caiapi || [];
11
- _caiapi.push(['trackUser', '<?php echo $email ?>']);
12
- //]]>
13
- </script>
14
- <?php
15
- }
16
- }
17
-
18
- $cart = Mage::getModel('checkout/cart')->getQuote();
19
- $cart_items = array();
20
- foreach ($cart->getAllVisibleItems() as $item) {
21
- $cart_item = array();
22
- $cart_item['pid'] = $item->getProductId();
23
- $cart_item['sku'] = $item->getSku();
24
- $cart_item['name'] = $item->getProduct()->getName();
25
- $cart_item['price'] = $item->getProduct()->getPrice();
26
- $cart_item['final_price'] = $item->getProduct()->getFinalPrice();
27
- $cart_item['special_price'] = $item->getProduct()->getSpecialPrice();
28
- $cart_item['type'] = $item->getProduct()->getTypeId();
29
- $cart_item['qty'] = $item->getQty();
30
- $cart_items[] = $cart_item;
31
- }
32
- ?>
33
-
34
- <script type="text/javascript">
35
- //<![CDATA[
36
- window.CAI_CART_ITEMS = <?php echo json_encode($cart_items); ?>;
37
- window.CAI_MAGENTO_ADDTOCART_FORM_KEY = '<?php echo Mage::getSingleton('core/session')->getFormKey()?>';
38
- //]]>
39
  </script>
1
+ <?php echo Mage::helper('choiceai_personalisation')->getBaseScript() ?>
2
+ <?php
3
+ $user = $this->getUser();
4
+ if($user) {
5
+ $email = $user->getEmail();
6
+ if ($email && strlen($email) > 0) {
7
+ ?>
8
+ <script type="text/javascript">
9
+ //<![CDATA[
10
+ window._caiapi = window._caiapi || [];
11
+ _caiapi.push(['trackUser', '<?php echo $email ?>']);
12
+ //]]>
13
+ </script>
14
+ <?php
15
+ }
16
+ }
17
+
18
+ $cart = Mage::getModel('checkout/cart')->getQuote();
19
+ $cart_items = array();
20
+ foreach ($cart->getAllVisibleItems() as $item) {
21
+ $cart_item = array();
22
+ $cart_item['pid'] = $item->getProductId();
23
+ $cart_item['sku'] = $item->getSku();
24
+ $cart_item['name'] = $item->getProduct()->getName();
25
+ $cart_item['price'] = $item->getProduct()->getPrice();
26
+ $cart_item['final_price'] = $item->getProduct()->getFinalPrice();
27
+ $cart_item['special_price'] = $item->getProduct()->getSpecialPrice();
28
+ $cart_item['type'] = $item->getProduct()->getTypeId();
29
+ $cart_item['qty'] = $item->getQty();
30
+ $cart_items[] = $cart_item;
31
+ }
32
+ ?>
33
+
34
+ <script type="text/javascript">
35
+ //<![CDATA[
36
+ window.CAI_CART_ITEMS = <?php echo json_encode($cart_items); ?>;
37
+ window.CAI_MAGENTO_ADDTOCART_FORM_KEY = '<?php echo Mage::getSingleton('core/session')->getFormKey()?>';
38
+ //]]>
39
  </script>
lib/ChoiceAI/Client.php CHANGED
@@ -5,289 +5,309 @@
5
  */
6
 
7
  include("Service.php");
8
- class ChoiceAI_Client {
9
- /**
10
- * Default ChoiceAIsearch ruleset
11
- */
12
- const DEFAULT_RULESET = 'search';
13
-
14
- /**
15
- * Default transport
16
- *
17
- * @var string
18
- */
19
- const DEFAULT_TRANSPORT = 'https';
20
-
21
- protected $params = array(
22
- 'ruleset' => self::DEFAULT_RULESET,
23
- 'multiSelectFacet' => false,
24
- 'filter' => array(),
25
- 'rangeFilter' =>array(),
26
- 'cond' => array(),
27
- 'query' => '',
28
- 'category-id' => ''
29
- );
30
-
31
- protected $address = '';
32
-
33
- protected $choiceaiResponse = null;
34
-
35
- protected $setFacets = null;
36
-
37
- protected $inStoreChoice = '';
38
-
39
- /**
40
- * Number of seconds after a timeout occurs for every request
41
- * If using indexing of file large value necessary.
42
- */
43
- const TIMEOUT = 300;
44
-
45
- /**
46
- * Config with defaults
47
- *
48
- * @var array
49
- */
50
- protected $_config = array(
51
- 'ruleset' => self::DEFAULT_RULESET,
52
- 'transport' => self::DEFAULT_TRANSPORT,
53
- 'timeout' => self::TIMEOUT,
54
- 'headers' => array()
55
- );
56
-
57
-
58
-
59
- /**
60
- * Creates a new ChoiceAI client
61
- *
62
- * @param array $config OPTIONAL Additional config options
63
- */
64
- public function __construct(array $config = array()) {
65
- $this->setConfig($config);
66
-
67
- //inStoreChoice
68
- $this->inStoreChoice = $this->_config['transport'].'://datav3.choice.ai/widget/v4/getInStoreChoice';
 
 
69
 
70
  //tagProducts
71
- $this->address = $this->_config['transport'].'://datav3.choice.ai/widget/v4/getTagProducts';
72
- }
73
-
74
- /**
75
- * Sets specific config values (updates and keeps default values)
76
- *
77
- * @param array $config Params
78
- */
79
- public function setConfig(array $config) {
80
- foreach ($config as $key => $value) {
81
- $this->_config[$key] = $value;
82
- }
83
-
84
- return $this;
85
- }
86
-
87
- /**
88
- * Returns a specific config key or the whole
89
- * config array if not set
90
- *
91
- * @param string $key Config key
92
- * @return array|string Config value
93
- */
94
- public function getConfig($key = '') {
95
- if (empty($key)) {
96
- return $this->_config;
97
- }
98
-
99
- if (!array_key_exists($key, $this->_config)) {
100
- throw new Exception('Config key is not set: ' . $key);
101
- }
102
-
103
- return $this->_config[$key];
104
- }
105
-
106
- /**
107
- * Sets / overwrites a specific config value
108
- *
109
- * @param string $key Key to set
110
- * @param mixed $value Value
111
- * @return ChoiceAI_Client Client object
112
- */
113
- public function setConfigValue($key, $value) {
114
- return $this->setConfig(array($key => $value));
115
- }
116
-
117
- /**
118
- * Returns connection port of this client
119
- *
120
- * @return int Connection port
121
- */
122
- public function getContext() {
123
- return $this->getConfig('context');
124
- }
125
-
126
- /**
127
- * Returns transport type to user
128
- *
129
- * @return string Transport type
130
- */
131
- public function getTransport() {
132
- return $this->getConfig('transport');
133
- }
134
-
135
-
136
- /**
137
- * sets the attribute filter
138
- * @param mixed $filter array
139
- * @return ChoiceAI_Client Client object
140
- */
141
- public function setFilters($filter =array()){
142
- if(isset($filter) && is_array($filter)){
143
- $this->params['filter'] = $filter;
144
- }
145
- return $this;
146
- }
147
-
148
- /**
149
- * sets the range filter
150
- * @param mixed $rangeFilter array
151
- * @return ChoiceAI_Client Client object
152
- */
153
- public function setRangeFilters($rangeFilter =array()){
154
- if(isset($rangeFilter) && is_array($rangeFilter)){
155
- $this->params['rangeFilter'] = $rangeFilter;
156
- }
157
- return $this;
158
- }
159
-
160
- /**
161
- * sets the offset
162
- * @param mixed $pg integer
163
- * @return ChoiceAI_Client Client object
164
- */
165
- public function setOffset($pg = 0){
 
 
 
 
 
 
 
 
166
  $this->params['start'] = $pg;
167
- return $this;
168
- }
169
-
170
- /**
171
- * sets the limit
172
- * @param mixed $limit integer
173
- * @return ChoiceAI_Client Client object
174
- */
175
- public function setLimit($limit = 20){
176
- $this->params['limit'] = $limit;
177
- return $this;
178
- }
179
-
180
- /**
181
- * sets the ruleset
182
- * @param mixed $ruleset string
183
- * @return ChoiceAI_Client Client object
184
- */
185
- public function setRuleset($ruleset = 'search'){
186
- if(isset($ruleset)){
187
- $this->params['ruleset'] = $ruleset;
188
- }else{
189
- $this->params['ruleset'] = 'search';
190
- }
191
- return $this;
192
- }
193
-
194
- /**
195
- * sets the sort
196
- * @param mixed $sorts array
197
- * @return ChoiceAI_Client Client object
198
- */
199
- public function setSort($sorts = array()){
200
- if(is_array($sorts) && count($sorts)){
201
- $this->params['sort'] = $sorts;
202
- }else{
 
 
 
203
  $this->params['sort'] = array("");
204
  }
205
- return $this;
206
- }
207
-
208
- /**
209
- * sets the facet fields, This is mainly used for
210
- * @param mixed $sorts array
211
- * @return ChoiceAI_Client Client object
212
- */
213
- public function setFacetFields($facetField = array()){
214
- if(isset($facetField) && is_array($facetField)){
215
- $this->params['facets'] = $facetField;
216
- }
217
- return $this;
218
- }
219
-
220
- /**
221
- * sets the other options which can be used
222
- * @param mixed $options array
223
- * @return ChoiceAI_Client Client object
224
- */
225
- public function setOtherOptions($options =array()){
226
- if(isset($options) && is_array($options)){
227
- $this->params['others'] = $options;
228
- }
229
- return $this;
230
- }
231
-
232
- /**
233
- * sets the search query
234
- * @param mixed $query search
235
- * @return ChoiceAI_Client Client object
236
- */
237
- public function setQuery($query = ''){
238
- if(isset($query)){
239
- $this->params['query'] = $query;
240
- }
241
- return $this;
242
- }
243
-
244
- /**
245
- * sets the Category Id
246
- * @param mixed $query search
247
- * @return ChoiceAI_Client Client object
248
- */
249
- public function setCategoryId($query = ''){
250
- if(isset($query)){
251
- $this->params['category-id'] = $query;
252
- }
253
- return $this;
254
- }
255
-
256
- /**
257
- * sets the Cond
258
- * @param mixed $query search
259
- * @return ChoiceAI_Client Client object
260
- */
261
- public function setCond($query = ''){
262
- if(isset($query)){
263
- $this->params['cond'] = $query;
264
- }
265
- return $this;
266
- }
267
-
268
- /**
269
- * sets the Cond
270
- * @param mixed $query search
271
- * @return ChoiceAI_Client Client object
272
- */
273
- public function setDebug($debug = false){
274
- if(isset($debug)){
275
- $this->params['debug'] = $debug;
276
- }
277
- return $this;
278
- }
279
-
280
- /**
281
- * sets the multiSelectFacet
282
- * @param mixed $multiSelectFacet boolean
283
- * @return ChoiceAI_Client Client object
284
- */
285
- public function setMultiSelectFacet($multiSelectFacet = false){
286
- if(isset($multiSelectFacet)){
287
- $this->params['multiSelectFacet'] = $multiSelectFacet;
288
- }
289
- return $this;
290
- }
 
 
 
 
 
 
 
291
 
292
 
293
  /**
@@ -308,8 +328,8 @@ class ChoiceAI_Client {
308
  $collection->addFieldToFilter(
309
  array("is_filterable", "is_filterable_in_search"),
310
  array(
311
- array("eq"=>1),
312
- array("eq"=>1)
313
  )
314
  );
315
  $collection->load();
@@ -336,22 +356,23 @@ class ChoiceAI_Client {
336
  }
337
  }
338
 
339
- /**
340
- *
341
- * Search through ChoiceAI api
342
- *
343
- * @return ChoiceAI_ResultSet object
344
- */
345
- public function search() {
346
- $service = new ChoiceAI_Service();
 
347
  $this->params["context"] = $this->getContext();
348
  $this->params["org"] = explode("_", $this->params["context"])[0];
349
 
350
  // Checks and sets facets in $this->setFacets
351
  $this->getFilters();
352
 
353
- if(is_null($this->choiceaiResponse)) {
354
- if ((int)$this->params['start'] > 0 || $this->setFacets != null) {
355
  $this->params["facets"] = $this->setFacets;
356
  $this->choiceaiResponse = $service->search($this->params, $this->address, "tag");
357
  } else {
@@ -361,6 +382,6 @@ class ChoiceAI_Client {
361
  } else {
362
  return $this->choiceaiResponse;
363
  }
364
- }
365
 
366
  }
5
  */
6
 
7
  include("Service.php");
8
+
9
+ class ChoiceAI_Client
10
+ {
11
+ /**
12
+ * Default ChoiceAIsearch ruleset
13
+ */
14
+ const DEFAULT_RULESET = 'search';
15
+
16
+ /**
17
+ * Default transport
18
+ *
19
+ * @var string
20
+ */
21
+ const DEFAULT_TRANSPORT = 'https';
22
+
23
+ protected $params = array(
24
+ 'ruleset' => self::DEFAULT_RULESET,
25
+ 'multiSelectFacet' => false,
26
+ 'filter' => array(),
27
+ 'rangeFilter' => array(),
28
+ 'cond' => array(),
29
+ 'query' => '',
30
+ 'category-id' => ''
31
+ );
32
+
33
+ protected $address = '';
34
+
35
+ protected $choiceaiResponse = null;
36
+
37
+ protected $setFacets = null;
38
+
39
+ protected $inStoreChoice = '';
40
+
41
+ /**
42
+ * Number of seconds after a timeout occurs for every request
43
+ * If using indexing of file large value necessary.
44
+ */
45
+ const TIMEOUT = 300;
46
+
47
+ /**
48
+ * Config with defaults
49
+ *
50
+ * @var array
51
+ */
52
+ protected $_config = array(
53
+ 'ruleset' => self::DEFAULT_RULESET,
54
+ 'transport' => self::DEFAULT_TRANSPORT,
55
+ 'timeout' => self::TIMEOUT,
56
+ 'headers' => array()
57
+ );
58
+
59
+
60
+ /**
61
+ * Creates a new ChoiceAI client
62
+ *
63
+ * @param array $config OPTIONAL Additional config options
64
+ */
65
+ public function __construct(array $config = array())
66
+ {
67
+ $this->setConfig($config);
68
+
69
+ //inStoreChoice
70
+ $this->inStoreChoice = $this->_config['transport'] . '://datav3.choice.ai/widget/v4/getInStoreChoice';
71
 
72
  //tagProducts
73
+ $this->address = $this->_config['transport'] . '://datav3.choice.ai/widget/v4/getTagProducts';
74
+ }
75
+
76
+ /**
77
+ * Sets specific config values (updates and keeps default values)
78
+ *
79
+ * @param array $config Params
80
+ */
81
+ public function setConfig(array $config)
82
+ {
83
+ foreach ($config as $key => $value) {
84
+ $this->_config[$key] = $value;
85
+ }
86
+
87
+ return $this;
88
+ }
89
+
90
+ /**
91
+ * Returns a specific config key or the whole
92
+ * config array if not set
93
+ *
94
+ * @param string $key Config key
95
+ * @return array|string Config value
96
+ */
97
+ public function getConfig($key = '')
98
+ {
99
+ if (empty($key)) {
100
+ return $this->_config;
101
+ }
102
+
103
+ if (!array_key_exists($key, $this->_config)) {
104
+ throw new Exception('Config key is not set: ' . $key);
105
+ }
106
+
107
+ return $this->_config[$key];
108
+ }
109
+
110
+ /**
111
+ * Sets / overwrites a specific config value
112
+ *
113
+ * @param string $key Key to set
114
+ * @param mixed $value Value
115
+ * @return ChoiceAI_Client Client object
116
+ */
117
+ public function setConfigValue($key, $value)
118
+ {
119
+ return $this->setConfig(array($key => $value));
120
+ }
121
+
122
+ /**
123
+ * Returns connection port of this client
124
+ *
125
+ * @return int Connection port
126
+ */
127
+ public function getContext()
128
+ {
129
+ return $this->getConfig('context');
130
+ }
131
+
132
+ /**
133
+ * Returns transport type to user
134
+ *
135
+ * @return string Transport type
136
+ */
137
+ public function getTransport()
138
+ {
139
+ return $this->getConfig('transport');
140
+ }
141
+
142
+
143
+ /**
144
+ * sets the attribute filter
145
+ * @param mixed $filter array
146
+ * @return ChoiceAI_Client Client object
147
+ */
148
+ public function setFilters($filter = array())
149
+ {
150
+ if (isset($filter) && is_array($filter)) {
151
+ $this->params['filter'] = $filter;
152
+ }
153
+ return $this;
154
+ }
155
+
156
+ /**
157
+ * sets the range filter
158
+ * @param mixed $rangeFilter array
159
+ * @return ChoiceAI_Client Client object
160
+ */
161
+ public function setRangeFilters($rangeFilter = array())
162
+ {
163
+ if (isset($rangeFilter) && is_array($rangeFilter)) {
164
+ $this->params['rangeFilter'] = $rangeFilter;
165
+ }
166
+ return $this;
167
+ }
168
+
169
+ /**
170
+ * sets the offset
171
+ * @param mixed $pg integer
172
+ * @return ChoiceAI_Client Client object
173
+ */
174
+ public function setOffset($pg = 0)
175
+ {
176
  $this->params['start'] = $pg;
177
+ return $this;
178
+ }
179
+
180
+ /**
181
+ * sets the limit
182
+ * @param mixed $limit integer
183
+ * @return ChoiceAI_Client Client object
184
+ */
185
+ public function setLimit($limit = 20)
186
+ {
187
+ $this->params['limit'] = $limit;
188
+ return $this;
189
+ }
190
+
191
+ /**
192
+ * sets the ruleset
193
+ * @param mixed $ruleset string
194
+ * @return ChoiceAI_Client Client object
195
+ */
196
+ public function setRuleset($ruleset = 'search')
197
+ {
198
+ if (isset($ruleset)) {
199
+ $this->params['ruleset'] = $ruleset;
200
+ } else {
201
+ $this->params['ruleset'] = 'search';
202
+ }
203
+ return $this;
204
+ }
205
+
206
+ /**
207
+ * sets the sort
208
+ * @param mixed $sorts array
209
+ * @return ChoiceAI_Client Client object
210
+ */
211
+ public function setSort($sorts = array())
212
+ {
213
+ if (is_array($sorts) && count($sorts)) {
214
+ $this->params['sort'] = $sorts;
215
+ } else {
216
  $this->params['sort'] = array("");
217
  }
218
+ return $this;
219
+ }
220
+
221
+ /**
222
+ * sets the facet fields, This is mainly used for
223
+ * @param mixed $sorts array
224
+ * @return ChoiceAI_Client Client object
225
+ */
226
+ public function setFacetFields($facetField = array())
227
+ {
228
+ if (isset($facetField) && is_array($facetField)) {
229
+ $this->params['facets'] = $facetField;
230
+ }
231
+ return $this;
232
+ }
233
+
234
+ /**
235
+ * sets the other options which can be used
236
+ * @param mixed $options array
237
+ * @return ChoiceAI_Client Client object
238
+ */
239
+ public function setOtherOptions($options = array())
240
+ {
241
+ if (isset($options) && is_array($options)) {
242
+ $this->params['others'] = $options;
243
+ }
244
+ return $this;
245
+ }
246
+
247
+ /**
248
+ * sets the search query
249
+ * @param mixed $query search
250
+ * @return ChoiceAI_Client Client object
251
+ */
252
+ public function setQuery($query = '')
253
+ {
254
+ if (isset($query)) {
255
+ $this->params['query'] = $query;
256
+ }
257
+ return $this;
258
+ }
259
+
260
+ /**
261
+ * sets the Category Id
262
+ * @param mixed $query search
263
+ * @return ChoiceAI_Client Client object
264
+ */
265
+ public function setCategoryId($query = '')
266
+ {
267
+ if (isset($query)) {
268
+ $this->params['category-id'] = $query;
269
+ }
270
+ return $this;
271
+ }
272
+
273
+ /**
274
+ * sets the Cond
275
+ * @param mixed $query search
276
+ * @return ChoiceAI_Client Client object
277
+ */
278
+ public function setCond($query = '')
279
+ {
280
+ if (isset($query)) {
281
+ $this->params['cond'] = $query;
282
+ }
283
+ return $this;
284
+ }
285
+
286
+ /**
287
+ * sets the Cond
288
+ * @param mixed $query search
289
+ * @return ChoiceAI_Client Client object
290
+ */
291
+ public function setDebug($debug = false)
292
+ {
293
+ if (isset($debug)) {
294
+ $this->params['debug'] = $debug;
295
+ }
296
+ return $this;
297
+ }
298
+
299
+ /**
300
+ * sets the multiSelectFacet
301
+ * @param mixed $multiSelectFacet boolean
302
+ * @return ChoiceAI_Client Client object
303
+ */
304
+ public function setMultiSelectFacet($multiSelectFacet = false)
305
+ {
306
+ if (isset($multiSelectFacet)) {
307
+ $this->params['multiSelectFacet'] = $multiSelectFacet;
308
+ }
309
+ return $this;
310
+ }
311
 
312
 
313
  /**
328
  $collection->addFieldToFilter(
329
  array("is_filterable", "is_filterable_in_search"),
330
  array(
331
+ array("eq" => 1),
332
+ array("eq" => 1)
333
  )
334
  );
335
  $collection->load();
356
  }
357
  }
358
 
359
+ /**
360
+ *
361
+ * Search through ChoiceAI api
362
+ *
363
+ * @return ChoiceAI_ResultSet object
364
+ */
365
+ public function search()
366
+ {
367
+ $service = new ChoiceAI_Service();
368
  $this->params["context"] = $this->getContext();
369
  $this->params["org"] = explode("_", $this->params["context"])[0];
370
 
371
  // Checks and sets facets in $this->setFacets
372
  $this->getFilters();
373
 
374
+ if (is_null($this->choiceaiResponse)) {
375
+ if (Mage::registry("contextId") && Mage::registry("passback") && ((int)$this->params['start'] > 0 || $this->setFacets != null)) {
376
  $this->params["facets"] = $this->setFacets;
377
  $this->choiceaiResponse = $service->search($this->params, $this->address, "tag");
378
  } else {
382
  } else {
383
  return $this->choiceaiResponse;
384
  }
385
+ }
386
 
387
  }
lib/ChoiceAI/Service.php CHANGED
@@ -1,181 +1,174 @@
1
- <?php
2
-
3
- /**
4
- * @copyright Copyright (c) MineWhat
5
- * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
6
- */
7
-
8
- include("ResultSet.php");
9
-
10
- class ChoiceAI_Service
11
- {
12
-
13
- public function getOptions($options)
14
- {
15
- if (!isset($options)) {
16
- return "";
17
- }
18
- $content = '';
19
- foreach ($options as $key => $value) {
20
- $content = $content . '&' . rawurlencode($key) . '=' . rawurlencode($value);
21
- }
22
-
23
- return $content;
24
- }
25
-
26
-
27
- /**
28
- * method to set sort fields
29
- *
30
- */
31
- public function getSorting($sorts)
32
- {
33
- $sortString = '';
34
-
35
- if (is_null($sorts) || !isset($sorts) || !is_array($sorts) || !sizeof($sorts) > 0) {
36
- return '';
37
- }
38
- foreach ($sorts as $sortKey => $sortValue) {
39
- if($sortKey)
40
- $sortString = "&caiSortBy=".$sortKey;
41
- }
42
- return $sortString;
43
- }
44
-
45
-
46
- /**
47
- * function to get queryParam
48
- * @param mixed $ruleset string
49
- * @return String query
50
- */
51
- function getQueryParam($params = array())
52
- {
53
- // ty is setting the type of search
54
- if ($params['ruleset'] == 'browse') {
55
- return 'ty=clistpage';
56
- } else {
57
- return 'ty=csearch&q=' . rawurlencode($params['query']);
58
- }
59
- }
60
-
61
- /**
62
- * function to prepare Url
63
- * @param mixed $params array
64
- * @param mixed $address string
65
- * @return String url
66
- */
67
- function prepare_url($params = array(), $address = "")
68
- {
69
- $url = $address
70
- . "?c=" . $params['context']
71
- . "&org=" . $params['org']
72
- . "&from=" . (isset($params['start']) ? $params['start'] : 0)
73
- . "&size=" . (isset($params['limit']) ? $params['limit'] : 20);
74
- $url = $url . '&' . $this->getQueryParam($params);
75
-
76
- // da
77
- // to be sent only if some count is there, regarding the current state, about results of screen before when the request was made
78
- if (isset($_GET['ct']) && $_GET['ct'] != "0")
79
- $url .= "&da=" . Mage::helper('core')->jsonEncode(array("lpimpressions" => $_GET['ct']));
80
- else
81
- $url .= "&da={}";
82
-
83
- if (Mage::registry("expId")) {
84
- $url .= "&existingPage=" . Mage::registry("expId");
85
- }
86
-
87
- // Facets, passing the facets from cache
88
- if(isset($params['facets'])){
89
- $url .= "&facets=".$params['facets'];
90
- }
91
-
92
- if (isset($params['sort']))
93
- $url .= $this->getSorting($params['sort']);
94
- if (isset($params['others']))
95
- $url .= $this->getOptions($params['others']);
96
-
97
- return $url;
98
- }
99
-
100
- /**
101
- *
102
- * function to fire search query
103
- * Harkirat: Earlier in place of apiType, there was "$spellcheck = false"
104
- *
105
- */
106
- public function search($params, $address, $apiType = false)
107
- {
108
- $url = $this->prepare_url($params, $address);
109
-
110
- $opts = array(
111
- 'http' => array(
112
- 'timeout' => 30
113
- )
114
- );
115
- if (isset($_SERVER['HTTP_USER_AGENT'])) {
116
- $opts['http']['header'] = "User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\r\n";
117
- }
118
-
119
- $context = stream_context_create($opts);
120
- $response = file_get_contents($url, false, $context);
121
-
122
- $choiceaiResponse = null;
123
- if (isset($response)) {
124
- $response = Mage::helper('core')->jsonDecode($response);
125
- $uidData = $response['uid'];
126
- if (isset($uidData)) {
127
- $uid = explode( ',', $uidData );
128
- Mage::register("caiuid",$uid[0],true);
129
- }
130
-
131
- $data = $response['data'];
132
-
133
- if ($apiType == "choice") {
134
- $data = $response['data']['automations'];
135
- if (isset($data[0]))
136
- $data = $data[0];
137
- else
138
- $data = array();
139
- } else {
140
- $data = $response['data'];
141
- }
142
-
143
- // tagsList, catPaths
144
- if (isset($data['tagsList'])) {
145
- if (isset($_SERVER['REDIRECT_QUERY_STRING']) && strpos($_SERVER['REDIRECT_QUERY_STRING'], "tagsList") === false)
146
- $_SERVER['REDIRECT_QUERY_STRING'] .= "&tagsList=" . Mage::helper('core')->jsonEncode($data['tagsList']);
147
-
148
- // Mage::register("tagsList", Mage::helper('core')->jsonEncode($data['tagsList']), true);
149
- }
150
- if (isset($data['catPaths'])) {
151
- if(empty($data['catPaths'])){
152
- if (isset($_SERVER['REDIRECT_QUERY_STRING']) && strpos($_SERVER['REDIRECT_QUERY_STRING'], "catPaths") === false)
153
- $_SERVER['REDIRECT_QUERY_STRING'] .= "&catPaths={}";
154
-
155
- // Mage::register("catPaths", "{}", true);
156
- }
157
- else{
158
- if (isset($_SERVER['REDIRECT_QUERY_STRING']) && strpos($_SERVER['REDIRECT_QUERY_STRING'], "catPaths") === false)
159
- $_SERVER['REDIRECT_QUERY_STRING'] .= "&catPaths=" . Mage::helper('core')->jsonEncode($data['catPaths']);
160
-
161
- // Mage::register("catPaths", Mage::helper('core')->jsonEncode($data['catPaths']), true);
162
- }
163
- }
164
-
165
- // for lpimpressions
166
- if (isset($data['ids'])) {
167
- Mage::register("prodCountNow", count($data['ids']), true);
168
- }
169
- if (isset($data['passback']) && !empty($data['passback'])) {
170
- Mage::register("passback", $data['passback'], true);
171
- }
172
-
173
- $choiceaiResponse = new ChoiceAI_ResultSet($data);
174
-
175
- }
176
-
177
- return $choiceaiResponse;
178
- }
179
- }
180
-
181
- ?>
1
+ <?php
2
+
3
+ /**
4
+ * @copyright Copyright (c) MineWhat
5
+ * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
6
+ */
7
+
8
+ include("ResultSet.php");
9
+
10
+ class ChoiceAI_Service
11
+ {
12
+
13
+ public function getOptions($options)
14
+ {
15
+ if (!isset($options)) {
16
+ return "";
17
+ }
18
+ $content = '';
19
+ foreach ($options as $key => $value) {
20
+ $content = $content . '&' . rawurlencode($key) . '=' . rawurlencode($value);
21
+ }
22
+
23
+ return $content;
24
+ }
25
+
26
+
27
+ /**
28
+ * method to set sort fields
29
+ *
30
+ */
31
+ public function getSorting($sorts)
32
+ {
33
+ $sortString = '';
34
+
35
+ if (is_null($sorts) || !isset($sorts) || !is_array($sorts) || !sizeof($sorts) > 0) {
36
+ return '';
37
+ }
38
+ foreach ($sorts as $sortKey => $sortValue) {
39
+ if ($sortKey)
40
+ $sortString = "&caiSortBy=" . $sortKey;
41
+ }
42
+ return $sortString;
43
+ }
44
+
45
+
46
+ /**
47
+ * function to get queryParam
48
+ * @param mixed $ruleset string
49
+ * @return String query
50
+ */
51
+ function getQueryParam($params = array())
52
+ {
53
+ // ty is setting the type of search
54
+ if ($params['ruleset'] == 'browse') {
55
+ return 'ty=clistpage';
56
+ } else {
57
+ return 'ty=csearch&q=' . rawurlencode($params['query']);
58
+ }
59
+ }
60
+
61
+ /**
62
+ * function to prepare Url
63
+ * @param mixed $params array
64
+ * @param mixed $address string
65
+ * @return String url
66
+ */
67
+ function prepare_url($params = array(), $address = "", $apiType = false)
68
+ {
69
+ $url = $address
70
+ . "?c=" . $params['context']
71
+ . "&org=" . $params['org']
72
+ . "&from=" . (isset($params['start']) ? $params['start'] : 0)
73
+ . "&size=" . (isset($params['limit']) ? $params['limit'] : 20);
74
+ $url = $url . '&' . $this->getQueryParam($params);
75
+
76
+ // da
77
+ // to be sent only if some count is there, regarding the current state, about results of screen before when the request was made
78
+ if (isset($_GET['ct']) && $_GET['ct'] != "0")
79
+ $url .= "&da=" . Mage::helper('core')->jsonEncode(array("lpimpressions" => $_GET['ct']));
80
+ else
81
+ $url .= "&da={}";
82
+
83
+ if (Mage::registry("expId")) {
84
+ $url .= "&existingPage=" . Mage::registry("expId");
85
+ }
86
+ if ($apiType == "tag") {
87
+ if (Mage::registry("passback")) {
88
+ // passback is php array
89
+ $url .= "&passback=" . Mage::helper('core')->jsonEncode(Mage::registry("passback"));
90
+ }
91
+ if (Mage::registry("contextId")) {
92
+ $url .= "&contextId=" . Mage::registry("contextId");
93
+ }
94
+ }
95
+
96
+ // Facets, passing the facets from cache
97
+ if (isset($params['facets'])) {
98
+ $url .= "&facets=" . $params['facets'];
99
+ }
100
+
101
+ if (isset($params['sort']))
102
+ $url .= $this->getSorting($params['sort']);
103
+ if (isset($params['others']))
104
+ $url .= $this->getOptions($params['others']);
105
+
106
+ return $url;
107
+ }
108
+
109
+ /**
110
+ *
111
+ * function to fire search query
112
+ * Harkirat: Earlier in place of apiType, there was "$spellcheck = false"
113
+ *
114
+ */
115
+ public function search($params, $address, $apiType = false)
116
+ {
117
+ $url = $this->prepare_url($params, $address, $apiType);
118
+ $base_url = $params['others']['url'];
119
+ if ($base_url && Mage::registry("expId")) {
120
+ Mage::register("user_context", "cai_" . $base_url . Mage::registry("expId"));
121
+ }
122
+ $opts = array(
123
+ 'http' => array(
124
+ 'timeout' => 30
125
+ )
126
+ );
127
+ if (isset($_SERVER['HTTP_USER_AGENT'])) {
128
+ $opts['http']['header'] = "User-Agent: " . $_SERVER['HTTP_USER_AGENT'] . "\r\n";
129
+ }
130
+
131
+ $context = stream_context_create($opts);
132
+ $response = file_get_contents($url, false, $context);
133
+
134
+ $choiceaiResponse = null;
135
+ if (isset($response)) {
136
+ $response = Mage::helper('core')->jsonDecode($response);
137
+ $uidData = $response['uid'];
138
+ if (isset($uidData)) {
139
+ $uid = explode(',', $uidData);
140
+ Mage::register("caiuid", $uid[0], true);
141
+ }
142
+ if ($apiType == "choice") {
143
+ $data = $response['data']['automations'];
144
+ if (isset($data[0]))
145
+ $data = $data[0];
146
+ else
147
+ $data = array();
148
+ } else {
149
+ $data = $response['data'];
150
+ }
151
+
152
+ if (isset($data['contextId'])) {
153
+ if (empty($data['contextId'])) {
154
+ Mage::unregister("contextId");
155
+ Mage::register("contextId", "x", true);
156
+ } else {
157
+ Mage::unregister("contextId");
158
+ Mage::register("contextId", $data['contextId'], true);
159
+ }
160
+ }
161
+ if (isset($data['passback']) && !empty($data['passback'])) {
162
+ Mage::unregister("passback");
163
+ Mage::register("passback", $data['passback'], true);
164
+ }
165
+
166
+ $choiceaiResponse = new ChoiceAI_ResultSet($data);
167
+
168
+ }
169
+
170
+ return $choiceaiResponse;
171
+ }
172
+ }
173
+
174
+ ?>
 
 
 
 
 
 
 
package.xml CHANGED
@@ -1,7 +1,7 @@
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>choiceai</name>
4
- <version>1.0.12</version>
5
  <stability>stable</stability>
6
  <license uri="http://opensource.org/licenses/osl-3.0.php">osl</license>
7
  <channel>community</channel>
@@ -9,10 +9,10 @@
9
  <summary>Choice AI</summary>
10
  <description>Choice AI</description>
11
  <notes>Choice AI plugin</notes>
12
- <authors><author><name>MineWhat Inc.</name><user>rahulb14</user><email>rahulb14@gmail.com</email></author><author><name>MineWhat Inc.</name><user>harkirat</user><email>harkirat1892@gmail.com</email></author></authors>
13
- <date>2017-07-13</date>
14
- <time>14:52:34</time>
15
- <contents><target name="magecommunity"><dir name="ChoiceAI"><dir name="Personalisation"><dir name="Block"><dir name="Base"><file name="Script.php" hash="af614113dea10a0a6d88281f615f1929"/></dir><dir name="Event"><dir name="Analytics"><file name="Listpage.php" hash="ebffb194cccf7fab9d6db59028bc7551"/><file name="Search.php" hash="6276c882a46630f77870a262cc158dfd"/></dir><dir name="Catalog"><dir name="Product"><file name="View.php" hash="233ac45484c22ecdf7063071406f71e2"/></dir></dir><dir name="Checkout"><dir name="Cart"><file name="Index.php" hash="e3bc31a08a994d72223d78ebde8a74f0"/></dir><dir name="Onepage"><file name="Success.php" hash="cc242d118e6b06bb3817d95b2322167c"/></dir></dir></dir><dir name="Searchpage"><file name="Addparam.php" hash="895157cf5ac87c294ab18c7b52412082"/></dir></dir><dir name="Helper"><file name="Data.php" hash="8ab9069ffe5aa66ef085124b8ff613d6"/></dir><dir name="Model"><file name="Observer.php" hash="3abfad9965e29886992d6c2e29bd5533"/></dir><dir name="controllers"><file name="ApiController.php" hash="c024fba9214158ffa069444e6dcaf936"/></dir><dir name="etc"><file name="adminhtml.xml" hash="2fc12bb0874c8f39963f1593b3954d2e"/><file name="config.xml" hash="9fa56c376f528455c0c1d12f7b8286b6"/><file name="system.xml" hash="6f4674088b4c392cc06f5a70f383fd54"/></dir><dir name="sql"><dir name="personalisation_setup"><file name="install-1.0.12.php" hash="40e64ff22ba466f54cf59d0f6ca171c2"/></dir></dir></dir></dir></target><target name="magelocal"><dir name="ChoiceAI"><dir name="Search"><dir name="Block"><dir name="Catalog"><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="7920f693a41c71120640e58e425774c4"/><file name="Boolean.php" hash="b4725e9e63c54a5f06e226b2ba07423c"/><file name="Category.php" hash="f9add3a866fd08695fb8541292e345b5"/><file name="Decimal.php" hash="90b1f1b0e78c9fb8192affd726306939"/><file name="Price.php" hash="8a5219290c7773300725e99931dd265e"/></dir><file name="View.php" hash="e6698a73b03ab006859d4788fd770f66"/></dir><dir name="Product"><dir name="List"><file name="Toolbar.php" hash="04fba36c5a57f409b56659a2ba8fb645"/></dir><file name="List.php" hash="3e0b59fca7f65b0d3f6a130eefb801b8"/></dir></dir><dir name="Catalogsearch"><dir name="Enterprise"><file name="Layer.php" hash="76d2e136cfd2bdb8336bebc3e949035b"/></dir><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="5d8377049114d7114468d083a06ae574"/></dir></dir><file name="Layer.php" hash="5cff5c396d96294cea2291b0f5f1b9d1"/><file name="Result.php" hash="28d419708e65be095a3905e0cdcdd56d"/></dir></dir><dir name="Helper"><file name="Choiceaisearch.php" hash="052795ea39da743fb0bf77f848b3123a"/><file name="Data.php" hash="1e1d8143831abc6ab7db8363ec34ed02"/><file name="Productimg.php" hash="7def046ff081389229b33285d2dbe6a5"/></dir><dir name="Model"><dir name="Catalog"><file name="Category.php" hash="d2898da3c579c4a8c6aba8ffa9f92e5c"/><file name="Config.php" hash="29bd684be415dfb46a562c4a18ebf93f"/><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="67b32680a7471e7a5d2ea210b6c9d612"/><file name="Boolean.php" hash="4de1790d8a6355c512b0a1aee663b8aa"/><file name="Category.php" hash="597c8b4fc8c5ca892456a799302a09a4"/><file name="Decimal.php" hash="fe9ae194e4540352fc7953d6988b09bb"/><file name="Price.php" hash="3c1e0e58d4b6995c3ca66ba6ed9c5987"/></dir></dir><file name="Layer.php" hash="21673a913e8510804df7906f881d7054"/><dir name="Product"><file name="Url.php" hash="13545877391be6a0fbd1b624d43b80f5"/></dir></dir><dir name="Catalogsearch"><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="0c08443cd3a964853e2eea7eab7ee550"/></dir></dir><file name="Layer.php" hash="7eb444d700b64d9655d9f5228c995688"/></dir><dir name="Resource"><dir name="Catalog"><dir name="Product"><file name="Collection.php" hash="1976dd848282e00158cabd6d7cf1528f"/></dir></dir><dir name="Engine"><file name="Abstract.php" hash="73c32a6e987875060d1d89692a34444b"/><dir name="Choiceaisearch"><file name="Client.php" hash="384c7d4597140b49912cc6633c4b3a8e"/></dir><file name="Choiceaisearch.php" hash="b7b8fc08b9433b81cbdc48e715299076"/></dir></dir></dir><dir name="etc"><file name="config.xml" hash="a9ff8724be0873d2b309b39a156bbd3d"/></dir></dir><dir name="Searchcore"><dir name="Helper"><file name="Constants.php" hash="aa53ac5d6cdc26e297d36c685cf1217c"/><file name="Data.php" hash="9df2c1f96a67c708bb039dbaf8f9b4d8"/></dir><dir name="etc"><file name="config.xml" hash="46df20f6fdedd61fa5a58d149e9d4ac8"/></dir></dir></dir></target><target name="magelib"><dir name="ChoiceAI"><file name="Client.php" hash="e6dfb5d68108d30dea6cf2055337f782"/><file name="Result.php" hash="b95b62cd11facae7f8318ad9e433cb42"/><file name="ResultSet.php" hash="228a8f2bca65527e3c3c68e49357339d"/><file name="Service.php" hash="d3ede493e0b67663569c18d8b3fe01ae"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="choiceai_personalisation.xml" hash="3f4490bde0510aa3752a51c602451d6c"/></dir><dir name="template"><dir name="choiceai"><dir name="personalisation"><dir name="analytics"><file name="listpage.phtml" hash="ac19a29e9ffb58f5056e1a7a968a626d"/><file name="search.phtml" hash="c7bc6540408024d048c6531d45d4807b"/></dir><dir name="base"><file name="addparam.phtml" hash="e9b7447c5ae2983796ab28c622d3684e"/><file name="script.phtml" hash="24af1501042170add901ae6746381c81"/></dir><dir name="event"><dir name="catalog"><dir name="product"><file name="view.phtml" hash="9513eaaa0bda55931dacb6d90b698f31"/></dir></dir><dir name="checkout"><dir name="cart"><file name="index.phtml" hash="6a27ac509cc1c8c78515b025479f135b"/></dir></dir></dir></dir></dir></dir></dir></dir><dir name="default"><dir name="default"><dir name="layout"><file name="choiceai_personalisation.xml" hash="95d72912f3b13c5a399e3b2e5b89dba9"/></dir><dir name="template"><dir name="choiceai"><dir name="personalisation"><dir name="base"><file name="script.phtml" hash="ec453c2d474c0dbd46c6e1c04b1645e0"/></dir></dir></dir></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="ChoiceAI_Personalisation.xml" hash="4bca20179604835e2e0e08298142c8bb"/></dir></target></contents>
16
  <compatible/>
17
  <dependencies><required><php><min>5.2.5</min><max>6.0.0</max></php></required></dependencies>
18
  </package>
1
  <?xml version="1.0"?>
2
  <package>
3
  <name>choiceai</name>
4
+ <version>1.1.1</version>
5
  <stability>stable</stability>
6
  <license uri="http://opensource.org/licenses/osl-3.0.php">osl</license>
7
  <channel>community</channel>
9
  <summary>Choice AI</summary>
10
  <description>Choice AI</description>
11
  <notes>Choice AI plugin</notes>
12
+ <authors><author><name>MineWhat Inc.</name><user>developer</user><email>info@minewhat.com</email></author></authors>
13
+ <date>2017-09-12</date>
14
+ <time>12:42:09</time>
15
+ <contents><target name="magecommunity"><dir name="ChoiceAI"><dir name="Personalisation"><dir name="Block"><dir name="Base"><file name="Script.php" hash="eab726e7726d6e5fd95181a1498bc7f6"/></dir><dir name="Event"><dir name="Analytics"><file name="Listpage.php" hash="719eaf3c4010aa99f179cb6d57ef5eed"/><file name="Search.php" hash="541f93b078bb5c1c9c332d6e5799f3cd"/></dir><dir name="Catalog"><dir name="Product"><file name="View.php" hash="fd49bda76230078b1c73653433bd4934"/></dir></dir><dir name="Checkout"><dir name="Cart"><file name="Index.php" hash="2b4606891440a5989b6a1dc1cc04f53c"/></dir><dir name="Onepage"><file name="Success.php" hash="a47a9b2873b23370179c7665410d9683"/></dir></dir></dir><dir name="Searchpage"><file name="Addparam.php" hash="8b3b9ff03062c1adf0e97eeb908fa423"/></dir></dir><dir name="Helper"><file name="Data.php" hash="93f0f0ab0fc4cba526212b4d331f1456"/></dir><dir name="Model"><file name="Observer.php" hash="ae99164ae045496f0bcb262787f3640e"/></dir><dir name="controllers"><file name="ApiController.php" hash="e9a45a0c4250600574ce20b86e980e67"/></dir><dir name="etc"><file name="adminhtml.xml" hash="2fc12bb0874c8f39963f1593b3954d2e"/><file name="config.xml" hash="30c8b1784229162ff9e9ca0ca4d5bb5a"/><file name="system.xml" hash="6f4674088b4c392cc06f5a70f383fd54"/></dir><dir name="sql"><dir name="personalisation_setup"><file name="install-1.1.1.php" hash="54742fa2b6575a3e030e7a7727a550f9"/></dir></dir></dir></dir></target><target name="magelocal"><dir name="ChoiceAI"><dir name="Search"><dir name="Block"><dir name="Catalog"><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="e2f802c710bfdfc9b69a06dd765af26f"/><file name="Boolean.php" hash="c36931232ffa73e583616b6b48e13be2"/><file name="Category.php" hash="aef164167e86f36264009001af9c224b"/><file name="Decimal.php" hash="d1197dd747df1d1589098d4d610bf7e3"/><file name="Price.php" hash="2cfd7e133fa5f6cb5f8c0a438e791396"/></dir><file name="View.php" hash="f57a03d26309a70b6708bc6c98271a5c"/></dir><dir name="Product"><dir name="List"><file name="Toolbar.php" hash="5381818dd8e11b98aa1bec2ea4eef4c7"/></dir><file name="List.php" hash="88c80880aca160e69f43bf1f0d0cbed5"/></dir></dir><dir name="Catalogsearch"><dir name="Enterprise"><file name="Layer.php" hash="e5c0b359cc512b9b85153102f9cc5d46"/></dir><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="e2fabc6ddf3e450f0524693ae016a8e7"/></dir></dir><file name="Layer.php" hash="eb4d9bed3b122cb1bca872511e37f688"/><file name="Result.php" hash="5c36fc31b817195d05bda9bed1eceb77"/></dir></dir><dir name="Helper"><file name="Choiceaisearch.php" hash="4390e071c177c35048fe8a29a2124926"/><file name="Data.php" hash="c89391a888d0d4ca5f3386ba2510c5c7"/><file name="Productimg.php" hash="d584a5a159e9c444d4e1a7f0b480bff6"/></dir><dir name="Model"><dir name="Catalog"><file name="Category.php" hash="c559d3cd038e9bba97ec6e0630c8efbf"/><file name="Config.php" hash="c9b02a50136d689657cd0ec27ee15485"/><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="b0fd11abfe008591d2a74776bbcb6995"/><file name="Boolean.php" hash="b9075945d3ebf89e93e06de47ae953d6"/><file name="Category.php" hash="1d1ffb39dfebeb0ed80e6054883e8633"/><file name="Decimal.php" hash="794185c1173fefddb64889b8495d5f0a"/><file name="Price.php" hash="82cba690b42b446fb81bdcfffce730a4"/></dir></dir><file name="Layer.php" hash="a760ee59ad6b4365613b9dc973fda799"/><dir name="Product"><file name="Url.php" hash="ea427f45dcb20a6f1bf58ba92a77a096"/></dir></dir><dir name="Catalogsearch"><dir name="Layer"><dir name="Filter"><file name="Attribute.php" hash="bd6e340d8045b6598386505b1031acf3"/></dir></dir><file name="Layer.php" hash="b811f0c6946c505f158478f301a26e7b"/></dir><dir name="Resource"><dir name="Catalog"><dir name="Product"><file name="Collection.php" hash="4444a08c5c2408df7c157bd160724d27"/></dir></dir><dir name="Engine"><file name="Abstract.php" hash="19fb1f6e05aa194a1e2b96ecd097d671"/><dir name="Choiceaisearch"><file name="Client.php" hash="7254cfc3acc3469c4f065187cfeff7f1"/></dir><file name="Choiceaisearch.php" hash="7952337448198902d12d24c312b0e468"/></dir></dir></dir><dir name="etc"><file name="config.xml" hash="cd5d24fa28fdc177eb32ea72515af8e6"/></dir></dir><dir name="Searchcore"><dir name="Helper"><file name="Constants.php" hash="69b3c29cc545eac58b36be09d88d83b6"/><file name="Data.php" hash="5d52b25d409f6a844468cdb4666d645f"/></dir><dir name="etc"><file name="config.xml" hash="7ace1ca15c2cf74f11d01bf4d97c33b1"/></dir></dir></dir></target><target name="magelib"><dir name="ChoiceAI"><file name="Client.php" hash="a26d5be15f3ee907cd123ed5a1a2a732"/><file name="Result.php" hash="b95b62cd11facae7f8318ad9e433cb42"/><file name="ResultSet.php" hash="228a8f2bca65527e3c3c68e49357339d"/><file name="Service.php" hash="93aa177034ea2681215f25ee0f198067"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="choiceai_personalisation.xml" hash="3f4490bde0510aa3752a51c602451d6c"/></dir><dir name="template"><dir name="choiceai"><dir name="personalisation"><dir name="analytics"><file name="listpage.phtml" hash="748e9b003b69805660fe48a1593d31bf"/><file name="search.phtml" hash="32f203caaa13c2434b26ba0dae01c6db"/></dir><dir name="base"><file name="addparam.phtml" hash="7ae70eb857d7e7762027496f3021209d"/><file name="script.phtml" hash="96c9deb93d5cbe8ba6a1c0266d928579"/></dir><dir name="event"><dir name="catalog"><dir name="product"><file name="view.phtml" hash="9513eaaa0bda55931dacb6d90b698f31"/></dir></dir><dir name="checkout"><dir name="cart"><file name="index.phtml" hash="6a27ac509cc1c8c78515b025479f135b"/></dir></dir></dir></dir></dir></dir></dir></dir><dir name="default"><dir name="default"><dir name="layout"><file name="choiceai_personalisation.xml" hash="95d72912f3b13c5a399e3b2e5b89dba9"/></dir><dir name="template"><dir name="choiceai"><dir name="personalisation"><dir name="base"><file name="script.phtml" hash="60b414f870c4b5bd761bfa2466d73707"/></dir></dir></dir></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="ChoiceAI_Personalisation.xml" hash="4bca20179604835e2e0e08298142c8bb"/></dir></target></contents>
16
  <compatible/>
17
  <dependencies><required><php><min>5.2.5</min><max>6.0.0</max></php></required></dependencies>
18
  </package>