Minematic_Connector - Version 1.0.0

Version Notes

First release version

Download this release

Release Info

Developer Minematic
Extension Minematic_Connector
Version 1.0.0
Comparing to
See all releases


Version 1.0.0

Files changed (29) hide show
  1. app/code/community/Minematic/.DS_Store +0 -0
  2. app/code/community/Minematic/Connector/.DS_Store +0 -0
  3. app/code/community/Minematic/Connector/Block/Connector.php +5 -0
  4. app/code/community/Minematic/Connector/Helper/.DS_Store +0 -0
  5. app/code/community/Minematic/Connector/Helper/Data.php +136 -0
  6. app/code/community/Minematic/Connector/Helper/push_api/.DS_Store +0 -0
  7. app/code/community/Minematic/Connector/Helper/push_api/MinematicClient.php +77 -0
  8. app/code/community/Minematic/Connector/Model/.DS_Store +0 -0
  9. app/code/community/Minematic/Connector/Model/Config.php +77 -0
  10. app/code/community/Minematic/Connector/Model/Config/CronDropdown.php +23 -0
  11. app/code/community/Minematic/Connector/Model/Config/StoreViewsDropdown.php +28 -0
  12. app/code/community/Minematic/Connector/Model/Observer.php +45 -0
  13. app/code/community/Minematic/Connector/Model/Synchronization.php +1271 -0
  14. app/code/community/Minematic/Connector/Model/System/.DS_Store +0 -0
  15. app/code/community/Minematic/Connector/Model/System/Config/.DS_Store +0 -0
  16. app/code/community/Minematic/Connector/Model/System/Config/Backend/.DS_Store +0 -0
  17. app/code/community/Minematic/Connector/Model/System/Config/Backend/Cron.php +34 -0
  18. app/code/community/Minematic/Connector/controllers/.DS_Store +0 -0
  19. app/code/community/Minematic/Connector/controllers/MinematicController.php +230 -0
  20. app/code/community/Minematic/Connector/etc/.DS_Store +0 -0
  21. app/code/community/Minematic/Connector/etc/config.xml +139 -0
  22. app/code/community/Minematic/Connector/etc/system.xml +133 -0
  23. app/code/community/Minematic/Connector/sql/.DS_Store +0 -0
  24. app/code/community/Minematic/Connector/sql/connector_setup/.DS_Store +0 -0
  25. app/code/community/Minematic/Connector/sql/connector_setup/mysql4-install-0.1.0.php +40 -0
  26. app/design/frontend/base/default/layout/minematic_connector.xml +8 -0
  27. app/design/frontend/base/default/template/minematic_connector/header_snippet.phtml +47 -0
  28. app/etc/modules/Minematic_Connector.xml +13 -0
  29. package.xml +18 -0
app/code/community/Minematic/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Block/Connector.php ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
1
+ <?php
2
+
3
+ class Minematic_Connector_Block_Connector extends Mage_Core_Block_Template {
4
+
5
+ }
app/code/community/Minematic/Connector/Helper/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Helper/Data.php ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Minematic_Connector_Helper_Data extends Mage_Core_Helper_Abstract
3
+ {
4
+ const M_PULL_LOG_FILENAME = 'minematic-request.log';
5
+ const M_PUSH_LOG_FILENAME = 'minematic-push-api.log';
6
+
7
+ const M_API_PATH = 'minematic_settings/general/apikey';
8
+ const M_CLIENT_ID_PATH = 'minematic_settings/general/clientid';
9
+ const M_JAVASCRIPT_CODE_PATH = 'minematic_settings/general/javascript_code';
10
+ const M_ENABLED_PATH = 'minematic_settings/general/enabled';
11
+ const M_KEY_HEADER = 'X-MINEMATIC-APIKEY';
12
+ const M_ID_HEADER = 'X-MINEMATIC-CLIENTID';
13
+ //const M_API_BASE_URI = 'http://128.199.242.4:8080/mdata/v1/';
14
+ const M_API_BASE_URI = 'https://www.minematic.com/mdata/v1/';
15
+
16
+ public function pushData($type, $data, $limit = 400) {
17
+ //Include Minematic CLient Class
18
+ include_once("push_api/MinematicClient.php");
19
+
20
+ //Intiantate class
21
+ $minematic = new MinematicClient(self::getAPIKey(), self::getMinematicURI());
22
+
23
+ //Data is pushed depending the page size (limit) specified in the Model
24
+ $result = $minematic->pushData($type, $data);
25
+
26
+ return true;
27
+ }
28
+
29
+ /**
30
+ * Log Module Error
31
+ * @param [type] $msg
32
+ * @param [type] $sync_type
33
+ * @return [type]
34
+ * @author edudeleon
35
+ * @date 2015-05-14
36
+ */
37
+ public function logModuleError($msg=null, $sync_type=null){
38
+ if (!empty($msg)){
39
+ Mage::log(" [ $sync_type ] ( $type ) :: " . $msg, null, "minematic_errors.log");
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Log Moduele synchronization process
45
+ * @param [type] $msg
46
+ * @param [type] $sync_type
47
+ * @param string $type
48
+ * @return [type]
49
+ * @author edudeleon
50
+ * @date 2015-05-14
51
+ */
52
+ public function logSyncProcess($msg=null, $sync_type=null, $type="REQUEST"){
53
+ if (!empty($msg)){
54
+ Mage::log(" [ $sync_type ] ( $type ) :: " . $msg, null, "minematic_sync_process.log");
55
+ }
56
+ }
57
+
58
+ public function getMinematicURI()
59
+ {
60
+ return self::M_API_BASE_URI;
61
+ }
62
+
63
+ public function isEnabled($store = null)
64
+ {
65
+ return Mage::getStoreConfig(self::M_ENABLED_PATH, $store);
66
+ }
67
+
68
+ public function getAPIKey($store = null)
69
+ {
70
+ return Mage::getStoreConfig(self::M_API_PATH, $store);
71
+ }
72
+
73
+ public function getClientID($store = null)
74
+ {
75
+ return Mage::getStoreConfig(self::M_CLIENT_ID_PATH, $store);
76
+ }
77
+
78
+ public function getJavascriptCode($store = null){
79
+ return Mage::getStoreConfig(self::M_JAVASCRIPT_CODE_PATH, $store);
80
+ }
81
+
82
+ public function getAPIKeyHeaderField() {
83
+ return self::M_KEY_HEADER;
84
+ }
85
+
86
+ public function getAPIClientIDHeaderField() {
87
+ return self::M_ID_HEADER;
88
+ }
89
+
90
+ /** deprecated */
91
+ public function logRequests($msg) {
92
+ if (!empty($msg))
93
+ {
94
+ Mage::log("PULL: " . $msg, null, self::M_PULL_LOG_FILENAME);
95
+ }
96
+ }
97
+
98
+ /** deprecated */
99
+ public function logPushAPI($msg = null) {
100
+ if (!empty($msg))
101
+ {
102
+ Mage::log("PUSH: " . $msg, null, self::M_PUSH_LOG_FILENAME);
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Prepare return message in Json format
108
+ * @param [type] $key
109
+ * @param [type] $msg
110
+ */
111
+ public function setReturnMessage($key, $msg) {
112
+ if (!empty($msg) && !empty($key)) {
113
+
114
+ $res = array();
115
+ $res[$key] = $msg;
116
+
117
+ return json_encode($res);
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Verify api_key and client Id
123
+ * @param [type] $api_key
124
+ * @param [type] $client_id
125
+ * @return [type]
126
+ * @author edudeleon
127
+ * @date 2015-05-14
128
+ */
129
+ public function valid_credentials($api_key, $client_id){
130
+ if ($this->getAPIKey() === $api_key && $this->getClientID() === $client_id){
131
+ return TRUE;
132
+ }
133
+ return FALSE;
134
+ }
135
+
136
+ }
app/code/community/Minematic/Connector/Helper/push_api/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Helper/push_api/MinematicClient.php ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class MinematicClient {
3
+
4
+ private $api_key;
5
+ private $end_point = 'https://www.minematic.com/mdata/v1/';
6
+
7
+ /**
8
+ * Constructor
9
+ * @param [type] $api_key
10
+ * @param [type] $ep
11
+ * @author edudeleon
12
+ * @date 2015-05-14
13
+ */
14
+ public function __construct($api_key, $ep = null) {
15
+ $this->api_key = $api_key;
16
+
17
+ if (!empty($ep))
18
+ {
19
+ $this->end_point = $ep;
20
+ }
21
+ }
22
+
23
+ /**
24
+ * Push data to Minematic server
25
+ * @param [type] $name
26
+ * @param [type] $data
27
+ * @return [type]
28
+ */
29
+ public function pushData($name, $data)
30
+ {
31
+ if (!empty($name) && !empty($data))
32
+ {
33
+ $endpoint = $this->end_point . $name;
34
+
35
+ $request_data = array(
36
+ "key" => $this->api_key,
37
+ $name => $data,
38
+ );
39
+
40
+ return $this->push($endpoint, $request_data);
41
+ }
42
+ }
43
+
44
+ /**
45
+ * Curh push method
46
+ * @param [type] $endpoint
47
+ * @param [type] $request_data
48
+ * @param string $request_type
49
+ * @return [type]
50
+ */
51
+ private function push($endpoint, $request_data, $request_type = 'post') {
52
+ $request_data = json_encode($request_data);
53
+
54
+ $headers = array('Accept: application/json', 'Content-Type: application/json');
55
+
56
+ $handle = curl_init();
57
+
58
+ curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
59
+ curl_setopt($handle, CURLOPT_URL, $endpoint);
60
+ curl_setopt($handle, CURLOPT_HTTPHEADER, $headers);
61
+ curl_setopt($handle, CURLOPT_POST, true);
62
+ curl_setopt($handle, CURLOPT_POSTFIELDS, $request_data);
63
+
64
+ $result = curl_exec($handle);
65
+
66
+ $code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
67
+
68
+ curl_close($handle);
69
+
70
+ if ($code > 200)
71
+ {
72
+ Mage::helper('connector')->logSyncProcess('[API response] ' . $code . ' ' . $result, "API " . $endpoint, "POST");
73
+ }
74
+
75
+ return $code;
76
+ }
77
+ }
app/code/community/Minematic/Connector/Model/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Model/Config.php ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Minematic Connector config model
4
+ *
5
+ * @package Minematic_Connector
6
+ * @author edudeleon
7
+ */
8
+ class Minematic_Connector_Model_Config extends Mage_Core_Model_Abstract
9
+ {
10
+
11
+ /*
12
+ * Last sync data for ITEMS
13
+ */
14
+ const ITEMS_LAST_SYNC_DATETIME = 'items_last_sync_datetime';
15
+ const ITEMS_LAST_SYNC_TYPE = 'items_last_sync_type';
16
+
17
+ /*
18
+ * Last sync data for USERS
19
+ */
20
+ const USERS_LAST_SYNC_DATETIME = 'users_last_sync_datetime';
21
+ const USERS_LAST_SYNC_TYPE = 'users_last_sync_type';
22
+
23
+ /*
24
+ * Last sync data for EVENTS
25
+ */
26
+ const EVENTS_LAST_SYNC_DATETIME = 'events_last_sync_datetime';
27
+ const EVENTS_LAST_SYNC_TYPE = 'events_last_sync_type';
28
+
29
+ /*
30
+ * Last SYNC type [magento/minematic]
31
+ */
32
+
33
+ /*
34
+ * Sync types
35
+ */
36
+ const SYNC_TYPE_MAGENTO_SIDE = 'magento'; // Magento Customer Side (Cron Job)
37
+ const SYNC_TYPE_MINEMATIC_SIDE = 'minematic'; // Minematic Side (old sync way)
38
+
39
+
40
+ /*
41
+ * Elements to sync
42
+ */
43
+ const DATA_TYPE_ALL = 'ALL';
44
+ const DATA_TYPE_ITEMS = 'ITEMS';
45
+ const DATA_TYPE_USERS = 'USERS';
46
+ const DATA_TYPE_EVENTS = 'EVENTS';
47
+
48
+ /*
49
+ * Limit for arrays used to post data
50
+ */
51
+ const SYNC_LIMIT = 100;
52
+
53
+ /*
54
+ * Events types
55
+ */
56
+ const EVENT_TYPE_ALL = "ALL";
57
+ const EVENT_TYPE_PAID = "PAID";
58
+ const EVENT_TYPE_OTHERS = "OTHERS";
59
+
60
+ /*
61
+ * Core config paths for custom fields
62
+ */
63
+ const ADDITIONAL_ITEM_FIELDS = "minematic_settings/general/product_fields";
64
+ const ADDITIONAL_USER_FIELDS = "minematic_settings/general/customer_fields";
65
+ const ADDITIONAL_EVENT_FIELDS = "minematic_settings/general/event_fields";
66
+
67
+ /**
68
+ * Cron Expression Path in core_config_data
69
+ */
70
+ const CRON_EXPRESSION_PATH = 'crontab/jobs/minematic_sync_data/schedule/cron_expr';
71
+
72
+ /**
73
+ * Store View Config Path
74
+ */
75
+ const CONFIG_PATH_STORE_VIEW = 'minematic_settings/general/store_view';
76
+
77
+ }
app/code/community/Minematic/Connector/Model/Config/CronDropdown.php ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Minematic_Connector_Model_Config_CronDropdown
3
+ {
4
+
5
+ /**
6
+ * Drowpdown options to run module cron tasks
7
+ * @return [type]
8
+ * @author edudeleon
9
+ * @date 2015-05-05
10
+ */
11
+ public function toOptionArray()
12
+ {
13
+ for($i = 1; $i <= 24; $i++){
14
+ $hours_dropdown[] = array(
15
+ 'value' => $i,
16
+ 'label' => ($i==1) ? ("Every ". $i." Hour") : "Every ". $i." Hours",
17
+ );
18
+ }
19
+
20
+ return $hours_dropdown;
21
+ }
22
+
23
+ }
app/code/community/Minematic/Connector/Model/Config/StoreViewsDropdown.php ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Minematic_Connector_Model_Config_StoreViewsDropdown{
3
+
4
+ /**
5
+ * Drowpdown options with store views
6
+ * @return [type]
7
+ * @author edudeleon
8
+ * @date 2015-05-14
9
+ */
10
+ public function toOptionArray(){
11
+ foreach (Mage::app()->getWebsites() as $website) {
12
+ $website_name = $website->getName();
13
+ foreach ($website->getGroups() as $group) {
14
+ $group_name = $group->getName();
15
+
16
+ $stores = $group->getStores();
17
+ foreach ($stores as $store_id => $store) {
18
+ $store_views[] = array(
19
+ 'value' => $store_id,
20
+ 'label' => $website_name . " > ". $group_name . " > " . $store->getName(),
21
+ );
22
+ }
23
+ }
24
+ }
25
+
26
+ return $store_views;
27
+ }
28
+ }
app/code/community/Minematic/Connector/Model/Observer.php ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Class used to handle cron tasks
5
+ *
6
+ * @author Eduardo De Leon
7
+ * @email edudeleon@gmail.com
8
+ */
9
+ class Minematic_Connector_Model_Observer
10
+ {
11
+
12
+ /**
13
+ * Method called by Magento Crontab
14
+ * Call sync_data method in synchronization model to send all data to Minematic
15
+ * @return [type]
16
+ * @author edudeleon
17
+ * @date 2015-05-13
18
+ */
19
+ public function run_sync_process(){
20
+ //Verify if module is enabled
21
+ if(Mage::helper('connector')->isEnabled()) {
22
+
23
+ //Set sync type
24
+ $sync_type = Minematic_Connector_Model_Config::SYNC_TYPE_MAGENTO_SIDE;
25
+
26
+ //Log Starting sync process msg
27
+ Mage::helper('connector')->logSyncProcess("Starting synchronization task job...", $sync_type);
28
+
29
+ try {
30
+
31
+ //Sync all data
32
+ Mage::getModel('connector/synchronization')->sync_data($sync_type, Minematic_Connector_Model_Config::DATA_TYPE_ALL);
33
+
34
+ } catch (Exception $e) {
35
+
36
+ // Logging Exceptions
37
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), $sync_type, "ERROR");
38
+
39
+ }
40
+
41
+ //Log Finishing sync process msg
42
+ Mage::helper('connector')->logSyncProcess("Finishing synchronization task job.", $sync_type);
43
+ }
44
+ }
45
+ }
app/code/community/Minematic/Connector/Model/Synchronization.php ADDED
@@ -0,0 +1,1271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ /**
3
+ * Class used to sync data between Magento and Minematic
4
+ */
5
+ class Minematic_Connector_Model_Synchronization{
6
+
7
+ //Private variables
8
+ private $_result_sync_message;
9
+ private $_result_sync_http_code_response;
10
+
11
+ /**
12
+ * Class constructor
13
+ * Initializate variables and set server configs for sync process
14
+ * @return [type]
15
+ * @author edudeleon
16
+ * @date 2015-05-11
17
+ */
18
+ public function __construct(){
19
+ // Init variables
20
+ $this->_result_sync_message = "";
21
+ $this->_result_sync_http_code_response = "";
22
+
23
+ $this->total_events = 0;
24
+
25
+ //Set memory limit and max excecution time for data sync process (importatnt for migration)
26
+ ini_set('memory_limit','512M');
27
+ set_time_limit(900); // max execution time (15 mins)
28
+
29
+ //Init website_id/store_id variables
30
+ $this->store_id = "";
31
+ $this->website_id = "";
32
+ $this->_init_store_variables(); //Init variables
33
+ }
34
+
35
+ /**
36
+ * Set values for store_id and website_id variables
37
+ * @return [type]
38
+ * @author edudeleon
39
+ * @date 2015-05-14
40
+ */
41
+ public function _init_store_variables(){
42
+ //Check if Store Id is defined in module configuration
43
+ if(Mage::getStoreConfig(Minematic_Connector_Model_Config::CONFIG_PATH_STORE_VIEW)){
44
+ $this->store_id = Mage::getStoreConfig(Minematic_Connector_Model_Config::CONFIG_PATH_STORE_VIEW);
45
+ } else {
46
+ //Get Default Store ID for current Website.
47
+ $this->store_id = Mage::app()
48
+ ->getWebsite()
49
+ ->getDefaultGroup()
50
+ ->getDefaultStoreId();
51
+ }
52
+
53
+ //Get Website ID
54
+ $this->website_id = Mage::getModel('core/store')->load($this->store_id)->getWebsiteId();
55
+
56
+ //Validate variables
57
+ if(empty($this->store_id) || empty($this->website_id)){
58
+ throw new Exception("Store ID or Webstite variables are not initializated.");
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Check if data type is valid
64
+ * @param [type] $type [ALL, ITEMS, USERES, OTHERS]
65
+ * @return boolean
66
+ * @author edudeleon
67
+ * @date 2015-05-07
68
+ */
69
+ private function _valid_data_type($type=NULL){
70
+ if(!empty($type)){
71
+ if ($type == Minematic_Connector_Model_Config::DATA_TYPE_ALL ||
72
+ $type == Minematic_Connector_Model_Config::DATA_TYPE_ITEMS ||
73
+ $type == Minematic_Connector_Model_Config::DATA_TYPE_USERS ||
74
+ $type == Minematic_Connector_Model_Config::DATA_TYPE_EVENTS){
75
+
76
+ return TRUE;
77
+ } else {
78
+ return FALSE;
79
+ }
80
+ }
81
+
82
+ return TRUE;
83
+ }
84
+
85
+ /**
86
+ * Check if event type is valid
87
+ * @param [type] $event_type [ALL, PAID, OTHERS]
88
+ * @return boolean
89
+ * @author edudeleon
90
+ * @date 2015-05-10
91
+ */
92
+ private function _valid_event_type($event_type=NULL){
93
+ if(!empty($event_type)){
94
+ if ($event_type == Minematic_Connector_Model_Config::EVENT_TYPE_ALL ||
95
+ $event_type == Minematic_Connector_Model_Config::EVENT_TYPE_PAID ||
96
+ $event_type == Minematic_Connector_Model_Config::EVENT_TYPE_OTHERS){
97
+ return TRUE;
98
+ } else {
99
+ return FALSE;
100
+ }
101
+ }
102
+
103
+ return TRUE;
104
+ }
105
+
106
+ /**
107
+ * Checks if migration needs to be run for data_type specified
108
+ * @param $data_type [ITEMS, USERES, EVENTS]
109
+ * @return BOOLEAN
110
+ * @author edudeleon
111
+ * @date 2015-05-10
112
+ */
113
+ private function _run_migration($data_type){
114
+ $last_sync_datetime = TRUE;
115
+
116
+ // ITEMS
117
+ if($data_type == Minematic_Connector_Model_Config::DATA_TYPE_ITEMS){
118
+ $last_sync_datetime = $this->_get_connector_config_value(Minematic_Connector_Model_Config::ITEMS_LAST_SYNC_DATETIME);
119
+ }
120
+
121
+ // USERS
122
+ if($data_type == Minematic_Connector_Model_Config::DATA_TYPE_USERS){
123
+ $last_sync_datetime = $this->_get_connector_config_value(Minematic_Connector_Model_Config::USERS_LAST_SYNC_DATETIME);
124
+ }
125
+
126
+ // EVENTS
127
+ if($data_type == Minematic_Connector_Model_Config::DATA_TYPE_EVENTS){
128
+ $last_sync_datetime = $this->_get_connector_config_value(Minematic_Connector_Model_Config::EVENTS_LAST_SYNC_DATETIME);
129
+ }
130
+
131
+ // Return boolean
132
+ return $last_sync_datetime ? FALSE : TRUE;
133
+ }
134
+
135
+ /**
136
+ * Get summary data for items(products), users(customers) and events(orders)
137
+ * @param [type] $type [ALL, ITEMS, USERS, EVENTS]
138
+ * @return [type]
139
+ * @author edudeleon
140
+ * @date 2015-05-07
141
+ */
142
+ public function get_summary_data($type=null){
143
+ //Verify if type is valid
144
+ if(!$this->_valid_data_type($type)){
145
+ throw new Exception("Invalid type parameter");
146
+ }
147
+
148
+ //IF type is not set, get summary for all resources
149
+ if(empty($type)){
150
+ $type = Minematic_Connector_Model_Config::DATA_TYPE_ALL;
151
+ }
152
+
153
+ //Get time zone set in Magento
154
+ $magento_timezone = new DateTimeZone(Mage::getStoreConfig('general/locale/timezone'));
155
+
156
+ //Get time zone offset for GMT
157
+ $date_time = new DateTime('now', $magento_timezone);
158
+ $gmt_offest = 'GMT '. $date_time->format('O');
159
+
160
+ //Init summary array
161
+ $summary = array(
162
+ 'CURDATE' => time(),
163
+ 'TIMEZONE' => $gmt_offest,
164
+ );
165
+
166
+ //Get summary data for items (products)
167
+ if ($type == Minematic_Connector_Model_Config::DATA_TYPE_ITEMS || $type == Minematic_Connector_Model_Config::DATA_TYPE_ALL){
168
+ try {
169
+ $cpe_table = Mage::getSingleton('core/resource')->getTableName('catalog_product_entity');
170
+
171
+ $coreResource = Mage::getSingleton('core/resource');
172
+
173
+ $conn = $coreResource->getConnection('core_read');
174
+
175
+ //Preparing query
176
+ $sql = 'SELECT count(distinct entity_id) count, Month(`created_at`) as month, Year(`created_at`) as year
177
+ FROM '.$cpe_table .
178
+ ' GROUP BY Month(`created_at`), Year(created_at)
179
+ ORDER BY created_at ASC';
180
+
181
+ //Feth all items
182
+ $_products = $conn->fetchAll($sql);
183
+
184
+ //Preparing data
185
+ $products = array();
186
+ foreach ($_products as $_product) {
187
+ //Format month year
188
+ $month_year = str_pad($_product['month'], 2, "0", STR_PAD_LEFT).'-'.$_product['year'];
189
+ $products[$month_year] = $_product['count'];
190
+ }
191
+
192
+ //Adding item to summary array
193
+ $summary['ITEM'] = $products;
194
+ }
195
+ catch(Exception $e)
196
+ {
197
+ //Log exception in case something goes wrong
198
+ Mage::logException("Exception while querying the database for product data " . $e->getMessage());
199
+
200
+ }
201
+ }
202
+
203
+ //Get summary data for users (customers)
204
+ if ($type == Minematic_Connector_Model_Config::DATA_TYPE_USERS || $type == Minematic_Connector_Model_Config::DATA_TYPE_ALL){
205
+ try {
206
+ $ce_table = Mage::getSingleton('core/resource')->getTableName('customer_entity');
207
+
208
+ $coreResource = Mage::getSingleton('core/resource');
209
+
210
+ $conn = $coreResource->getConnection('core_read');
211
+
212
+ //Preparing query
213
+ $sql = 'SELECT count(distinct entity_id) count, Month(`created_at`) as month, Year(`created_at`) as year
214
+ FROM '.$ce_table .
215
+ ' GROUP BY Month(`created_at`), Year(created_at)
216
+ ORDER BY created_at ASC';
217
+
218
+ //Fetch data
219
+ $_customers = $conn->fetchAll($sql);
220
+
221
+ //Preparing data
222
+ $customers = array();
223
+ foreach ($_customers as $_customer) {
224
+ //Format month year
225
+ $month_year = str_pad($_customer['month'], 2, "0", STR_PAD_LEFT).'-'.$_customer['year'];
226
+ $customers[$month_year] = $_customer['count'];
227
+ }
228
+
229
+ //Adding item to summary array
230
+ $summary['USER'] = $customers;
231
+ }
232
+ catch(Exception $e)
233
+ {
234
+ //Log exception in case something goes wrong
235
+ Mage::logException("Exception while querying the database for user data " . $e->getMessage());
236
+ }
237
+ }
238
+
239
+ //Get summary data for events
240
+ if ($type == Minematic_Connector_Model_Config::DATA_TYPE_EVENTS || $type == Minematic_Connector_Model_Config::DATA_TYPE_ALL)
241
+ {
242
+ try {
243
+ $sfo_table = Mage::getSingleton('core/resource')->getTableName('sales_flat_order');
244
+
245
+ $coreResource = Mage::getSingleton('core/resource');
246
+
247
+ $conn = $coreResource->getConnection('core_read');
248
+
249
+ //Preparing query
250
+ $sql = 'SELECT count(distinct entity_id) count, Month(`created_at`) as month, Year(`created_at`) as year
251
+ FROM '.$sfo_table .
252
+ ' GROUP BY Month(`created_at`), Year(created_at)
253
+ ORDER BY created_at ASC';
254
+
255
+ $_events = $conn->fetchAll($sql);
256
+
257
+ //Preparing data
258
+ $events = array();
259
+ foreach ($_events as $_event) {
260
+ //Format month year
261
+ $month_year = str_pad($_event['month'], 2, "0", STR_PAD_LEFT).'-'.$_event['year'];
262
+ $events[$month_year] = $_event['count'];
263
+ }
264
+
265
+ //Adding item to summary array
266
+ $summary['EVENT'] = $events;
267
+ }
268
+ catch(Exception $e)
269
+ {
270
+ //Log exception in case something goes wrong
271
+ Mage::logException("Exception while querying the database for events data " . $e->getMessage());
272
+ }
273
+ }
274
+
275
+ //Return summay data
276
+ return $summary;
277
+ }
278
+
279
+ /**
280
+ * Method used to sync all data between Magento and Minematic
281
+ * Called by Module Observer based on Cron Task configurations
282
+ * @return [type]
283
+ * @author edudeleon
284
+ * @date 2015-05-11
285
+ */
286
+ public function sync_data($sync_type, $data_type=NULL){
287
+ //Verify if module is enabled (just in case). If module is not enabled, Magento won't never come here..
288
+ if(!Mage::helper('connector')->isEnabled()) {
289
+
290
+ //Throw Exception
291
+ throw new Exception("Minematic Module is disabled but Cron Jobs are still running. Disable Module in System > Configuration > Advanced > Advanced OR edit Minematic_Connect.xml in app/etc/modules/.");
292
+ }
293
+
294
+ //Set last_sync_datetime
295
+ $last_sync_datetime = date('Y-m-d H:i:s');
296
+
297
+ /* SYNCING ITEMS */
298
+ try {
299
+ //Get information about the last synchronization process
300
+ $items_last_sync_datetime = $this->_get_connector_config_value(Minematic_Connector_Model_Config::ITEMS_LAST_SYNC_DATETIME);
301
+ $items_last_sync_datetime = $items_last_sync_datetime ? strtotime($items_last_sync_datetime) : NULL; //Convert to timestamp
302
+
303
+ //Call ITEMS sync method
304
+ $this->sync_items_data($sync_type, $items_last_sync_datetime, NULL, NULL, $last_sync_datetime);
305
+
306
+ //If something goes wrong, catch the exception, log it and continue the synchronization
307
+ } catch (Exception $e) {
308
+ // Log exception
309
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), $sync_type, "ERROR");
310
+ }
311
+
312
+
313
+ /* SYNCING USERS */
314
+ try {
315
+ //Get information about the last synchronization process
316
+ $users_last_sync_datetime = $this->_get_connector_config_value(Minematic_Connector_Model_Config::USERS_LAST_SYNC_DATETIME);
317
+ $users_last_sync_datetime = $users_last_sync_datetime ? strtotime($users_last_sync_datetime) : NULL; //Convert to timestamp
318
+
319
+ //Call USERS sync method
320
+ $this->sync_users_data($sync_type, $users_last_sync_datetime, NULL, $last_sync_datetime);
321
+
322
+ } catch (Exception $e) {
323
+ // Log exception
324
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), $sync_type, "ERROR");
325
+ }
326
+
327
+ /* SYNCING EVENTS */
328
+ try {
329
+ //Get information about the last synchronization process
330
+ $events_last_sync_datetime = $this->_get_connector_config_value(Minematic_Connector_Model_Config::EVENTS_LAST_SYNC_DATETIME);
331
+ $events_last_sync_datetime = $events_last_sync_datetime ? strtotime($events_last_sync_datetime) : 978310861; //(Set date 2001-01-01 01:01:01 for migration)
332
+
333
+ //Call EVENTS sync method
334
+ $this->sync_events_data($sync_type, Minematic_Connector_Model_Config::EVENT_TYPE_ALL, $events_last_sync_datetime, NULL, $last_sync_datetime);
335
+
336
+ } catch (Exception $e) {
337
+ // Log exception
338
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), $sync_type, "ERROR");
339
+ }
340
+
341
+ }
342
+
343
+ /**
344
+ * Method used to sync Items Data
345
+ * Filter by Store ID
346
+ * @param [type] $sync_type Specified the type of synchronization ['magento', 'minematic'].
347
+ * @param [type] $date_from Filter Date From (Unix TimeStamp)
348
+ * @param [type] $date_to Filter Date To (Unix TimeStamp)
349
+ * @param [type] $limit Number of elements to send in one request. Default value is set in config file.
350
+ * @param [type] $last_sync_datetime Optional last sync datetime
351
+ * @return [type]
352
+ * @author edudeleon
353
+ * @date 2015-05-08
354
+ */
355
+ public function sync_items_data($sync_type, $date_from=NULL, $date_to=NULL, $limit=NULL, $last_sync_datetime=NULL){
356
+ //Check if migration needs to be run for ITEMS data
357
+ if($this->_run_migration(Minematic_Connector_Model_Config::DATA_TYPE_ITEMS)){
358
+
359
+ // Logging migration mode msg
360
+ Mage::helper('connector')->logSyncProcess("[ITEMS DATA] Request receieved in Migration Mode", $sync_type);
361
+
362
+ } else {
363
+
364
+ // Logging normal sync mode
365
+ $log_msg = "[ITEMS DATA] Request receieved in Normal Mode. Since Parameter '$date_from' = '" .date('Y-m-d H:i:s', $date_from). "'";
366
+ Mage::helper('connector')->logSyncProcess($log_msg, $sync_type);
367
+
368
+ //Security layer (date_from is mandatory if migration has run before)
369
+ if(empty($date_from)){
370
+ throw new Exception("Migration has run before for ITEMS data. Parameter 'since/data_from' is mandatory.");
371
+ }
372
+ }
373
+
374
+ //Set last sync datetime
375
+ $last_sync_datetime = $last_sync_datetime ? $last_sync_datetime : date('Y-m-d H:i:s');
376
+
377
+ //Prepare products collection
378
+ $productsCollection = Mage::getModel('catalog/product')->getCollection()
379
+ ->addAttributeToSelect(array('id'))
380
+ ->setStoreId($this->store_id); //Adding store ID filter (Language filter)
381
+
382
+ //Adding filters by date
383
+ if(!empty($date_from)){
384
+ //format date
385
+ $date_from = date('Y-m-d H:i:s', $date_from);
386
+ $productsCollection->addAttributeToFilter('updated_at', array('gteq' => $date_from)); //grether or equal than
387
+ }
388
+
389
+ if(!empty($date_to)){
390
+ //format date
391
+ $date_to = date('Y-m-d H:i:s', $date_to);
392
+ $productsCollection->addAttributeToFilter('updated_at', array('lt' => $date_to)); //less than
393
+ }
394
+
395
+ //If limit is not set, get value from config model
396
+ if(empty($limit)){
397
+ $limit = Minematic_Connector_Model_Config::SYNC_LIMIT;
398
+ }
399
+
400
+ //Adding fliter by status
401
+ $productsCollection->addAttributeToFilter('status', array('eq' => Mage_Catalog_Model_Product_Status::STATUS_ENABLED));
402
+
403
+ //Prepare Pagination
404
+ $productsCollection->setPageSize($limit);
405
+
406
+ //Set current and total pages variables
407
+ $currentPage = 1;
408
+ $pages = $productsCollection->getLastPageNumber();
409
+
410
+ //Define base url for images
411
+ $imageBaseUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product';
412
+
413
+ //Load products
414
+ $total_items = 0;
415
+ do {
416
+ //Get collection by current page
417
+ $productsCollection->setCurPage($currentPage);
418
+ $productsCollection->load();
419
+
420
+ $items_data = array();
421
+ foreach ($productsCollection as $product) {
422
+ //Load product data
423
+ $_product = Mage::getModel('catalog/product')->load($product->getId());
424
+
425
+ //Prepare Image URL
426
+ $iurl = '';
427
+ $tmpUrl = $imageBaseUrl . $_product->getImage();
428
+
429
+ //Validate Image
430
+ if($this->_validateProductImage($_product->getImage())) {
431
+ $iurl = $tmpUrl;
432
+ } else if($this->_validateProductImage($_product->getSmallImage())) {
433
+ $iurl = $_product->getSmallImage();
434
+ }
435
+
436
+ //Get product attributes
437
+ $sku = $_product->getId();
438
+ $pname = $_product->getName();
439
+ $purl = $_product->getProductUrl();
440
+
441
+ //Get product Stock Flag
442
+ $stock_item = Mage::getModel('cataloginventory/stock_item')->loadByProduct($_product);
443
+ $inStock = $stock_item->getIsInStock();
444
+ $stock_qty = $stock_item->getQty();
445
+
446
+ //Verify if add product to result
447
+ if (!empty($sku) && !empty($pname) && !empty($purl) && !empty($iurl)){
448
+ //Getting Product tags
449
+ $tags_array = array();
450
+ $tags = htmlspecialchars($_product->getMetaKeyword());
451
+ if (!empty($tags)){
452
+ $tags_array = split(',', $tags);
453
+ }
454
+
455
+ //Getting product categories
456
+ $category_ids = $_product->getCategoryIds();
457
+ if (is_array($category_ids)) {
458
+ foreach ($category_ids as $category_id) {
459
+ $category = Mage::getModel('catalog/category')->load($category_id);
460
+ array_push($tags_array, $category->getName());
461
+ }
462
+ }
463
+
464
+ //Adding data
465
+ $item_data = array (
466
+ 'id' => $_product->getId(),
467
+ 'name' => str_replace(",", " ", $_product->getName()),
468
+ 'image_url' => $iurl,
469
+ 'page_url' => $_product->getProductUrl(),
470
+ 'active' => TRUE, //Status = enabled
471
+ 'available' => $inStock ? 'Y' : 'N',
472
+ 'tags' => $tags_array,
473
+ 'amount' => $_product->getPrice(),
474
+ 'discount_amount' => $_product->getFinalPrice(),
475
+ 'quantity' => (int)$stock_qty,
476
+ );
477
+
478
+ //Get additional fields from Admin Panel
479
+ $additional_fields = $this->get_additional_fields(Minematic_Connector_Model_Config::DATA_TYPE_ITEMS);
480
+ foreach ($additional_fields as $field_name => $get_method) {
481
+ $item_data[$field_name] = $_product->$get_method();
482
+ }
483
+
484
+ //Adding elements
485
+ $items_data[] = $item_data;
486
+
487
+ //items count
488
+ $total_items++;
489
+ }
490
+ }
491
+
492
+
493
+ //Push data to Minematic. Array size is equal to Page_Size/Limit
494
+ if(!empty($items_data)){
495
+
496
+ Mage::helper('connector')->pushData('items', $items_data);
497
+
498
+ //$this->emulate_pushData("ITEMS", $items_data, $sync_type); //Remove this line for production
499
+
500
+ }
501
+
502
+ //Set pagination for next page
503
+ $currentPage++;
504
+
505
+ //clear collection and free memory
506
+ $productsCollection->clear();
507
+
508
+ } while ($currentPage <= $pages);
509
+
510
+ //Set sync result messages (Variables are retrieved when method is called from Frontend Controller)
511
+ if($total_items > 0){
512
+ $this->_result_sync_message = 'Successfully loaded ' . $total_items . ' products';
513
+ $this->_result_sync_http_code_response = 200;
514
+ } else {
515
+ $this->_result_sync_message = 'No products Found';
516
+ $this->_result_sync_http_code_response = 201;
517
+ }
518
+
519
+ // Logging sync summary for ITEMS
520
+ Mage::helper('connector')->logSyncProcess("[ITEMS DATA] Total Items synchronized ($total_items).", $sync_type);
521
+
522
+ //Update data about last synchronzation process
523
+ $this->_update_last_sync_data(Minematic_Connector_Model_Config::DATA_TYPE_ITEMS, $sync_type, $last_sync_datetime);
524
+ }
525
+
526
+ /**
527
+ * Method used to sync users data
528
+ * @param [type] $sync_type Specified the type of synchronization ['magento', 'minematic'].
529
+ * @param [type] $date_from Filter Date From (Unix TimeStamp)
530
+ * @param [type] $limit Number of elements to send in one request. Default value is set in config file.
531
+ * @param [type] $last_sync_datetime Optional last sync datetime
532
+ * @return [type]
533
+ * @author edudeleon
534
+ * @date 2015-05-09
535
+ */
536
+ public function sync_users_data($sync_type, $date_from=NULL, $limit=NULL, $last_sync_datetime=NULL){
537
+ //Check if migration needs to be run for USERS data
538
+ if($this->_run_migration(Minematic_Connector_Model_Config::DATA_TYPE_USERS)){
539
+
540
+ // Logging migration mode msg
541
+ Mage::helper('connector')->logSyncProcess("[USERES DATA] Request receieved in Migration Mode", $sync_type);
542
+
543
+ } else {
544
+
545
+ // Logging normal sync mode
546
+ $log_msg = "[USERS DATA] Request receieved in Normal Mode. Since Parameter '$date_from' = '" .date('Y-m-d H:i:s', $date_from). "'";
547
+ Mage::helper('connector')->logSyncProcess($log_msg, $sync_type);
548
+
549
+ //Security layer (date_from is mandatory if migration has run before)
550
+ if(empty($date_from)){
551
+ throw new Exception("Migration has run before for USERS data. Parameter 'since/data_from' is mandatory.");
552
+ }
553
+ }
554
+
555
+ //Set sync datetime
556
+ $last_sync_datetime = $last_sync_datetime ? $last_sync_datetime : date('Y-m-d H:i:s');
557
+
558
+ //Prepare customers collection
559
+ $customersCollection = Mage::getModel('customer/customer')->getCollection()
560
+ ->addAttributeToSelect('*')
561
+ ->addAttributeToFilter('store_id', array('eq' => $this->store_id)); //Filter by store Id
562
+
563
+ //Adding filters by date_from
564
+ if(!empty($date_from)){
565
+
566
+ //format date
567
+ $date_from = date('Y-m-d H:i:s', $date_from);
568
+ $customersCollection->addAttributeToFilter('updated_at', array('gteq' => $date_from)); //grether or equal than
569
+
570
+ }
571
+
572
+ //If limit is not set, get value from config model
573
+ if(empty($limit)){
574
+ $limit = Minematic_Connector_Model_Config::SYNC_LIMIT;
575
+ }
576
+
577
+ //Prepare Pagination
578
+ $customersCollection->setPageSize($limit);
579
+
580
+ //Set current and total pages variables
581
+ $currentPage = 1;
582
+ $pages = $customersCollection->getLastPageNumber();
583
+
584
+ //Load customers
585
+ $total_users = 0;
586
+ do {
587
+ $customersCollection->setCurPage($currentPage);
588
+ $customersCollection->load();
589
+
590
+ $customers_data = array();
591
+ foreach ($customersCollection as $customer) {
592
+ $id = $customer->getId();
593
+ $email = $customer->getEmail();
594
+
595
+ if (!empty($id) && !empty($email)){
596
+ $customer_data = array(
597
+ 'id' => $id,
598
+ 'email' => $email,
599
+ 'first_name' => $customer->getFirstname(),
600
+ 'last_name' => $customer->getLastname(),
601
+ //'reward_points' => '', not avaialable fro Magento CE
602
+ //'credit_balnce' => '', not available
603
+ 'active' => TRUE, //Default active
604
+ );
605
+
606
+ //Get additional fields from Admin Panel
607
+ $additional_fields = $this->get_additional_fields(Minematic_Connector_Model_Config::DATA_TYPE_USERS);
608
+ foreach ($additional_fields as $field_name => $get_method) {
609
+ $customer_data[$field_name] = $customer->$get_method();
610
+ }
611
+
612
+ //Adding elements
613
+ $customers_data[] = $customer_data;
614
+
615
+ //total count
616
+ $total_users++;
617
+ }
618
+ }
619
+
620
+ //Push data to Minematic. Array size is equal to Page_Size/Limit
621
+ if(!empty($customers_data)){
622
+
623
+ Mage::helper('connector')->pushData('users', $customers_data);
624
+
625
+ //$this->emulate_pushData("USERS", $customers_data, $sync_type); //Remove this line for production
626
+ }
627
+
628
+ //Set pagination for next page
629
+ $currentPage++;
630
+
631
+ //clear collection and free memory
632
+ $customersCollection->clear();
633
+ } while ($currentPage <= $pages);
634
+
635
+ //Set sync result messages (Variables are retrieved when method is called from Frontend Controller)
636
+ if($total_users > 0){
637
+ $this->_result_sync_message = 'Successfully loaded ' . $total_users . ' users';
638
+ $this->_result_sync_http_code_response = 200;
639
+ } else {
640
+ $this->_result_sync_message = 'No users Found';
641
+ $this->_result_sync_http_code_response = 201;
642
+ }
643
+
644
+ // Logging sync summary for ITEMS
645
+ Mage::helper('connector')->logSyncProcess("[USERS DATA] Total Users synchronized ($total_users).", $sync_type);
646
+
647
+ //Update data about last synchronzation process
648
+ $this->_update_last_sync_data(Minematic_Connector_Model_Config::DATA_TYPE_USERS, $sync_type, $last_sync_datetime);
649
+
650
+ }
651
+
652
+ /**
653
+ * Method used to sync events data
654
+ * @param [type] $sync_type Specified the type of synchronization ['magento', 'minematic'].
655
+ * @param [type] $event_type Event type [ALL, PAID, OTHERS]
656
+ * @param [type] $date_from Filter Date From (Unix TimeStamp)
657
+ * @param [type] $last_sync_datetime Optional last sync datetime
658
+ * @return [type]
659
+ * @author edudeleon
660
+ * @date 2015-05-10
661
+ */
662
+ public function sync_events_data($sync_type, $event_type=NULL, $date_from=NULL, $limit=NULL, $last_sync_datetime=NULL){
663
+ //TESTING
664
+ //$date_from=time()-60; //978310861
665
+
666
+ //Check if migration needs to be run for EVENTS data
667
+ if($this->_run_migration(Minematic_Connector_Model_Config::DATA_TYPE_EVENTS)){
668
+
669
+ // Log migration mode
670
+ Mage::helper('connector')->logSyncProcess("[EVENTS DATA] Request receieved in Migration Mode", $sync_type);
671
+
672
+ } else {
673
+
674
+ // Logging normal sync mode
675
+ $log_msg = "[EVENTS DATA] Request receieved in Normal Mode. Since Parameter '$date_from' = '" .date('Y-m-d H:i:s', $date_from). "'";
676
+ Mage::helper('connector')->logSyncProcess($log_msg, $sync_type);
677
+
678
+ }
679
+
680
+ //Security layer (date_from is mandatory for migration and normal mode)
681
+ if(empty($date_from)){
682
+ throw new Exception("Parameter 'since/data_from' is mandatory for Migration Mode and Normal Mode.");
683
+ }
684
+
685
+ //Set sync datetime
686
+ $last_sync_datetime = $last_sync_datetime ? $last_sync_datetime : date('Y-m-d H:i:s');
687
+
688
+ //Check if event type is set
689
+ if(!empty($event_type)){
690
+ //Validate event type
691
+ if(!$this->_valid_event_type($event_type)){
692
+ throw new Exception("Event Type Not Valid");
693
+ }
694
+
695
+ } else {
696
+ //Set event type to ALL
697
+ $event_type = Minematic_Connector_Model_Config::EVENT_TYPE_ALL;
698
+ }
699
+
700
+ //Check If limit is set, if not, get value from config model
701
+ if(empty($limit)){
702
+ $limit = Minematic_Connector_Model_Config::SYNC_LIMIT;
703
+ }
704
+
705
+ $this->total_events = 0;
706
+
707
+ //Sync "PAID" events
708
+ if($event_type == Minematic_Connector_Model_Config::EVENT_TYPE_PAID || $event_type == Minematic_Connector_Model_Config::EVENT_TYPE_ALL){
709
+ //Syncing ORDERS and PAID ORDERS events
710
+ $this->_sync_paid_events($date_from, $limit, $sync_type);
711
+ }
712
+
713
+ //Sync "OTHERS" events
714
+ if($event_type == Minematic_Connector_Model_Config::EVENT_TYPE_OTHERS || $event_type == Minematic_Connector_Model_Config::EVENT_TYPE_ALL){
715
+ //Syncing OTHER Events
716
+ $this->_sync_other_events($date_from, $limit, $sync_type);
717
+ }
718
+
719
+ //Set sync result messages (Variables are retrieved when method is called from Frontend Controller)
720
+ if($this->total_events > 0){
721
+ $this->_result_sync_message = 'Successfully loaded ' . $this->total_events . ' events';
722
+ $this->_result_sync_http_code_response = 200;
723
+ } else {
724
+ $this->_result_sync_message = 'No events Found';
725
+ $this->_result_sync_http_code_response = 201;
726
+ }
727
+
728
+ // Logging sync summary for EVENTS
729
+ Mage::helper('connector')->logSyncProcess("[EVENTS DATA] Total Events synchronized (". $this->total_events. ").", $sync_type);
730
+
731
+ //Update data about last synchronzation process
732
+ $this->_update_last_sync_data(Minematic_Connector_Model_Config::DATA_TYPE_EVENTS, $sync_type, $last_sync_datetime);
733
+
734
+ }
735
+
736
+ /**
737
+ * Sync orders and paid orders events [ORDER, ORDER]
738
+ * @param [type] $date_from
739
+ * @param [type] $limit
740
+ * @param [type] $sync_type
741
+ * @return [type]
742
+ * @author edudeleon
743
+ * @date 2015-05-14
744
+ */
745
+ private function _sync_paid_events($date_from, $limit, $sync_type=NULL){
746
+ //Set tables prefix
747
+ $tbl_prefix = Mage::getConfig()->getTablePrefix();
748
+
749
+ //Format date
750
+ if(!empty($date_from)){
751
+ $date_from = date('Y-m-d H:i:s', $date_from);
752
+ }
753
+
754
+ /**
755
+ * ORDERS LIST
756
+ */
757
+
758
+ //Get all ORDERS where status is different from "canceled" and "customer_id" field is set
759
+ $ordersCollection = Mage::getModel('sales/order')->getCollection()
760
+ ->addFieldToSelect('updated_at')
761
+ ->addAttributeToFilter('status', array('nin' => array('canceled','complete')))
762
+ ->addFieldToFilter('product_id', array('gt' => 0))
763
+ ->addFieldToFilter('customer_id', array('gt' => 0))
764
+ ->addFieldToFilter('main_table.store_id', array('eq' => $this->store_id)); //Filter by store Id
765
+
766
+
767
+ //Join "sales_falt_order" table with "sales_flat_order_item" table
768
+ $ordersCollection->getSelect()->join(
769
+ array('sales_flat_order_item_alias'=> $tbl_prefix.'sales_flat_order_item'), $tbl_prefix.'sales_flat_order_item_alias.order_id = main_table.entity_id', array("product_id" => "sales_flat_order_item_alias.product_id")
770
+ );
771
+
772
+ //Join "sales_flat_order" table with "customer_entity" table
773
+ $ordersCollection->getSelect()->join(
774
+ array('customer_alias'=> $tbl_prefix.'customer_entity'), $tbl_prefix.'customer_alias.entity_id = main_table.customer_id', array("customer_id" => "main_table.customer_id")
775
+ );
776
+
777
+ //Adding filters by date_from
778
+ if(!empty($date_from)){
779
+ $ordersCollection->addFieldToFilter('main_table.updated_at', array('gteq' => $date_from)); //grether or equal than
780
+ }
781
+
782
+ //Prepare Pagination
783
+ $ordersCollection->setPageSize($limit);
784
+
785
+ //Set current and total pages variables
786
+ $currentPageOrders = 1;
787
+ $orderTotalPages = $ordersCollection->getLastPageNumber();
788
+
789
+ //Load ORDERS
790
+ do {
791
+ $ordersCollection->setCurPage($currentPageOrders);
792
+ $ordersCollection->load();
793
+ $orders_data = array();
794
+ foreach ($ordersCollection as $order) {
795
+
796
+ $order_data = array(
797
+ 'type' => "ORDER",
798
+ 'user_id' => $order->getCustomerId(),
799
+ 'item_id' => $order->getProductId(),
800
+ 'datetime' => strtotime($order->getUpdatedAt()),
801
+ );
802
+
803
+ //Adding orders
804
+ $orders_data[] = $order_data;
805
+
806
+ $this->total_events++;
807
+ }
808
+
809
+ //Push data to Minematic by chunks
810
+ if(!empty($orders_data)){
811
+ Mage::helper('connector')->pushData('events', $orders_data);
812
+
813
+ //$this->emulate_pushData("EVENTS", $orders_data, $sync_type); //Remove this line for production
814
+ }
815
+
816
+ //Set pagination for next page
817
+ $currentPageOrders++;
818
+
819
+ //clear collection and free memory
820
+ $ordersCollection->clear();
821
+ } while ($currentPageOrders <= $orderTotalPages);
822
+
823
+
824
+ /**
825
+ * PAID ORDERS
826
+ */
827
+
828
+ //Get all PAID orders where status is "complete" and "customer_id" field is set
829
+ $paidOrdersCollection = Mage::getModel('sales/order')->getCollection()
830
+ ->addFieldToSelect('updated_at')
831
+ ->addFieldToFilter('status', array('eq' => 'complete'))
832
+ ->addFieldToFilter('product_id', array('gt' => 0))
833
+ ->addFieldToFilter('customer_id', array('gt' => 0))
834
+ ->addFieldToFilter('main_table.store_id', array('eq' => $this->store_id)); //Filter by store Id
835
+
836
+ //Join "sales_falt_order" table with "sales_flat_order_item" table
837
+ $paidOrdersCollection->getSelect()->join(
838
+ array('sales_flat_order_item_alias'=> $tbl_prefix.'sales_flat_order_item'), $tbl_prefix.'sales_flat_order_item_alias.order_id = main_table.entity_id', array("product_id" => "sales_flat_order_item_alias.product_id")
839
+ );
840
+
841
+ //Join "sales_flat_order" table with "customer_entity" table
842
+ $paidOrdersCollection->getSelect()->join(
843
+ array('customer_alias'=> $tbl_prefix.'customer_entity'), $tbl_prefix.'customer_alias.entity_id = main_table.customer_id', array("customer_id" => "main_table.customer_id")
844
+ );
845
+
846
+ //Adding filters by date_from
847
+ if(!empty($date_from)){
848
+ $paidOrdersCollection->addFieldToFilter('main_table.updated_at', array('gteq' => $date_from)); //grether or equal than
849
+ }
850
+
851
+ //Prepare Pagination
852
+ $paidOrdersCollection->setPageSize($limit);
853
+
854
+ //Set current and total pages variables
855
+ $currentPagePaidOrders = 1;
856
+ $paidOrdersTotalPages = $paidOrdersCollection->getLastPageNumber();
857
+
858
+ //Load PAID orders
859
+ do {
860
+ $paidOrdersCollection->setCurPage($currentPagePaidOrders);
861
+ $paidOrdersCollection->load();
862
+ $paid_orders_data = array();
863
+ foreach ($paidOrdersCollection as $paid_order) {
864
+
865
+ $paid_order_data = array(
866
+ 'type' => "PAID",
867
+ 'user_id' => $paid_order->getCustomerId(),
868
+ 'item_id' => $paid_order->getProductId(),
869
+ 'datetime' => strtotime($paid_order->getUpdatedAt()),
870
+ );
871
+
872
+ //Adding paid orders
873
+ $paid_orders_data[] = $paid_order_data;
874
+
875
+ $this->total_events++;
876
+ }
877
+
878
+ //Push data to Minematic by chunks
879
+ if(!empty($paid_orders_data)){
880
+ Mage::helper('connector')->pushData('events', $paid_orders_data);
881
+
882
+ //$this->emulate_pushData("EVENTS", $paid_orders_data, $sync_type); //Remove this line for production
883
+ }
884
+
885
+ //Set pagination for next page
886
+ $currentPagePaidOrders++;
887
+
888
+ //clear collection and free memory
889
+ $paidOrdersCollection->clear();
890
+ } while ($currentPagePaidOrders <= $paidOrdersTotalPages);
891
+ }
892
+
893
+ /**
894
+ * Sync other events [CART, LIKE, SHARE]
895
+ * @param [type] $date_from
896
+ * @param [type] $limit
897
+ * @param [type] $sync_type
898
+ * @return [type]
899
+ * @author edudeleon
900
+ * @date 2015-05-10
901
+ */
902
+ private function _sync_other_events($date_from, $limit, $sync_type=NULL){
903
+ //Prepare report events collection
904
+ $eventsCollection = Mage::getModel('reports/event')->getCollection();
905
+
906
+ //Filter by store Id
907
+ $eventsCollection->addFieldToFilter('main_table.store_id', array('eq' => $this->store_id));
908
+
909
+ //Set tables prefix
910
+ $tbl_prefix = Mage::getConfig()->getTablePrefix();
911
+
912
+ //Join "report_event" table with "report_event_types" table
913
+ $eventsCollection->getSelect()->join(
914
+ array('report_types_alias'=> $tbl_prefix.'report_event_types'), $tbl_prefix.'report_types_alias.event_type_id = main_table.event_type_id'
915
+ );
916
+
917
+ //Join "report_event" table with "customer_entity" table
918
+ $eventsCollection->getSelect()->join(
919
+ array('customer_alias'=> $tbl_prefix.'customer_entity'), $tbl_prefix.'customer_alias.entity_id = main_table.subject_id'
920
+ );
921
+
922
+ //Adding Filters (OR)
923
+ $eventsCollection->addFieldToFilter(array('main_table.event_type_id', 'main_table.event_type_id', 'main_table.event_type_id'),
924
+ array( Mage_Reports_Model_Event::EVENT_PRODUCT_TO_CART,
925
+ Mage_Reports_Model_Event::EVENT_PRODUCT_TO_WISHLIST,
926
+ Mage_Reports_Model_Event::EVENT_WISHLIST_SHARE,
927
+ )
928
+ );
929
+
930
+ //Adding filters by date_from
931
+ if(!empty($date_from)){
932
+ //format date
933
+ $date_from = date('Y-m-d H:i:s', $date_from);
934
+ $eventsCollection->addFieldToFilter('logged_at', array('gteq' => $date_from)); //grether or equal than
935
+ }
936
+
937
+ //Prepare Pagination
938
+ $eventsCollection->setPageSize($limit);
939
+
940
+ //Set current and total pages variables
941
+ $currentPage = 1;
942
+ $pages = $eventsCollection->getLastPageNumber();
943
+
944
+ //Load events
945
+ do {
946
+ $eventsCollection->setCurPage($currentPage);
947
+ $eventsCollection->load();
948
+ $events_data = array();
949
+ foreach ($eventsCollection as $event) {
950
+
951
+ $event_data = array(
952
+ 'type' => $this->_get_event_type_name($event->getEventTypeId()),
953
+ 'user_id' => $event->getSubjectId(),
954
+ 'item_id' => $event->getObjectId(),
955
+ 'datetime' => strtotime($event->getLoggedAt()),
956
+ );
957
+
958
+ //Get additional fields from Admin Panel
959
+ $additional_fields = $this->get_additional_fields(Minematic_Connector_Model_Config::DATA_TYPE_EVENTS);
960
+ foreach ($additional_fields as $field_name => $get_method) {
961
+ $event_data[$field_name] = $event->$get_method();
962
+ }
963
+
964
+ //Adding events
965
+ $events_data[] = $event_data;
966
+
967
+ //Increment count
968
+ $this->total_events++;
969
+ }
970
+
971
+ //Push data to Minematic by chunks
972
+ if(!empty($events_data)){
973
+
974
+ Mage::helper('connector')->pushData('events', $events_data);
975
+
976
+ //$this->emulate_pushData("EVENTS", $events_data, $sync_type); //Remove this line for production
977
+
978
+ }
979
+
980
+ //Set pagination for next page
981
+ $currentPage++;
982
+
983
+ //clear collection and free memory
984
+ $eventsCollection->clear();
985
+ } while ($currentPage <= $pages);
986
+
987
+ }
988
+
989
+ /**
990
+ * Get event type name by event type ID
991
+ * @param [type] $event_type_id
992
+ * @return [type]
993
+ * @author edudeleon
994
+ * @date 2015-05-10
995
+ */
996
+ private function _get_event_type_name($event_type_id){
997
+ switch ($event_type_id) {
998
+ case Mage_Reports_Model_Event::EVENT_PRODUCT_VIEW:
999
+ $event_name = "VIEW";
1000
+ break;
1001
+
1002
+ case Mage_Reports_Model_Event::EVENT_PRODUCT_SEND:
1003
+ $event_name = "SEND";
1004
+ break;
1005
+
1006
+ case Mage_Reports_Model_Event::EVENT_PRODUCT_COMPARE:
1007
+ $event_name = "COMPARE";
1008
+ break;
1009
+
1010
+ case Mage_Reports_Model_Event::EVENT_PRODUCT_TO_CART:
1011
+ $event_name = "CART";
1012
+ break;
1013
+
1014
+ case Mage_Reports_Model_Event::EVENT_PRODUCT_TO_WISHLIST:
1015
+ $event_name = "LIKE";
1016
+ break;
1017
+
1018
+ case Mage_Reports_Model_Event::EVENT_WISHLIST_SHARE:
1019
+ $event_name = "SHARE";
1020
+ break;
1021
+
1022
+ default:
1023
+ $event_name = "NOT_DEFINED";
1024
+ break;
1025
+ }
1026
+ return $event_name;
1027
+ }
1028
+
1029
+ /**
1030
+ * Method used to update last synchronzation data by data type
1031
+ * @param [type] $data_type [ITEMS, USERS, EVENTS]
1032
+ * @param [type] $sync_type [minematic, magento]
1033
+ * @param [type] $last_sync_datetime
1034
+ * @return [type]
1035
+ * @author edudeleon
1036
+ * @date 2015-05-11
1037
+ */
1038
+ private function _update_last_sync_data($data_type, $sync_type, $last_sync_datetime){
1039
+ //Update last sync type and datetime for ITEMS
1040
+ if($data_type == Minematic_Connector_Model_Config::DATA_TYPE_ITEMS){
1041
+ $this->_update_connector_config_value(Minematic_Connector_Model_Config::ITEMS_LAST_SYNC_TYPE, $sync_type);
1042
+ $this->_update_connector_config_value(Minematic_Connector_Model_Config::ITEMS_LAST_SYNC_DATETIME, $last_sync_datetime);
1043
+ }
1044
+
1045
+ //Update last sync type and datetime for USERS
1046
+ if($data_type == Minematic_Connector_Model_Config::DATA_TYPE_USERS){
1047
+ $this->_update_connector_config_value(Minematic_Connector_Model_Config::USERS_LAST_SYNC_TYPE, $sync_type);
1048
+ $this->_update_connector_config_value(Minematic_Connector_Model_Config::USERS_LAST_SYNC_DATETIME, $last_sync_datetime);
1049
+ }
1050
+
1051
+ //Update last sync type and datetime for EVENTS
1052
+ if($data_type == Minematic_Connector_Model_Config::DATA_TYPE_EVENTS){
1053
+ $this->_update_connector_config_value(Minematic_Connector_Model_Config::EVENTS_LAST_SYNC_TYPE, $sync_type);
1054
+ $this->_update_connector_config_value(Minematic_Connector_Model_Config::EVENTS_LAST_SYNC_DATETIME, $last_sync_datetime);
1055
+ }
1056
+ }
1057
+
1058
+ /**
1059
+ * Update config value
1060
+ * @param [type] $config_name
1061
+ * @param [type] $config_value
1062
+ * @return [type]
1063
+ * @author edudeleon
1064
+ * @date 2015-05-10
1065
+ */
1066
+ private function _update_connector_config_value($config_name, $config_value){
1067
+ try {
1068
+ /**
1069
+ * Get the resource model
1070
+ */
1071
+ $resource = Mage::getSingleton('core/resource');
1072
+
1073
+ /**
1074
+ * Retrieve the write connection
1075
+ */
1076
+ $writeConnection = $resource->getConnection('core_write');
1077
+
1078
+ /**
1079
+ * Retrieve our table name
1080
+ */
1081
+ $table = $resource->getTableName('minematic_config');
1082
+
1083
+ //Update register
1084
+ $query = "UPDATE {$table} SET value = '{$config_value}' WHERE name = '"
1085
+ . $config_name ."'";
1086
+
1087
+ //Execute the query
1088
+ $writeConnection->query($query);
1089
+
1090
+ return;
1091
+
1092
+ } catch (Exception $e) {
1093
+ //Log Exception Message
1094
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), "DATABASE", "ERROR");
1095
+ }
1096
+ }
1097
+
1098
+ /**
1099
+ * Retrieve config value by config name
1100
+ * @param [type] $config_name
1101
+ * @return [type]
1102
+ * @author edudeleon
1103
+ * @date 2015-05-11
1104
+ */
1105
+ private function _get_connector_config_value($config_name){
1106
+ try {
1107
+ /**
1108
+ * Get the resource model
1109
+ */
1110
+ $resource = Mage::getSingleton('core/resource');
1111
+
1112
+ /**
1113
+ * Retrieve the write connection
1114
+ */
1115
+ $readConnection = $resource->getConnection('core_read');
1116
+
1117
+ /**
1118
+ * Retrieve our table name
1119
+ */
1120
+ $table = $resource->getTableName('minematic_config');
1121
+
1122
+ //Update register
1123
+ $query = "SELECT value FROM " . $table . " WHERE name = '"
1124
+ . $config_name ."'";
1125
+
1126
+ //Execute the query
1127
+ $config_value = $readConnection->fetchOne($query);
1128
+
1129
+ return $config_value ? $config_value : FALSE;
1130
+
1131
+ } catch (Exception $e) {
1132
+ //Log Exception Message
1133
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), "DATABASE", "ERROR");
1134
+ }
1135
+
1136
+ return FALSE;
1137
+ }
1138
+
1139
+ /**
1140
+ * Get additional fields and respective getMethods() from Admin Panel by Data Type
1141
+ * @param [type] $type
1142
+ * @param [type] $store_id
1143
+ * @return [type]
1144
+ * @author edudeleon
1145
+ * @date 2015-05-11
1146
+ */
1147
+ private function get_additional_fields($type, $store_id=NULL){
1148
+ //Get additional fields
1149
+ switch ($type) {
1150
+ case Minematic_Connector_Model_Config::DATA_TYPE_ITEMS:
1151
+ $custom_fields = Mage::getStoreConfig(Minematic_Connector_Model_Config::ADDITIONAL_ITEM_FIELDS, $store_id);
1152
+ break;
1153
+
1154
+ case Minematic_Connector_Model_Config::DATA_TYPE_USERS:
1155
+ $custom_fields = Mage::getStoreConfig(Minematic_Connector_Model_Config::ADDITIONAL_USER_FIELDS, $store_id);
1156
+ break;
1157
+
1158
+ case Minematic_Connector_Model_Config::DATA_TYPE_EVENTS:
1159
+ $custom_fields = Mage::getStoreConfig(Minematic_Connector_Model_Config::ADDITIONAL_EVENT_FIELDS, $store_id);
1160
+ break;
1161
+
1162
+ default:
1163
+ $custom_fields = "";
1164
+ break;
1165
+ }
1166
+
1167
+ $additional_fields = array();
1168
+
1169
+ //Prepare field names and get methods
1170
+ if($custom_fields){
1171
+ $custom_field_names = explode(',', $custom_fields);
1172
+
1173
+ //Get field names
1174
+ foreach($custom_field_names as $field_name){
1175
+ //Prepare field_name
1176
+ $field_name = trim($field_name);
1177
+
1178
+ //Prepare Get method name
1179
+ $name_parts = explode('_', $field_name);
1180
+ $get_method = "get";
1181
+ foreach ($name_parts as $name_part) {
1182
+ $get_method .= ucfirst(strtolower($name_part));
1183
+ }
1184
+
1185
+ $additional_fields[$field_name] = $get_method;
1186
+ }
1187
+ }
1188
+
1189
+ //Return array of fields
1190
+ return $additional_fields;
1191
+ }
1192
+
1193
+ /**
1194
+ * Validate product image
1195
+ * @param [type] $image
1196
+ * @return [type]
1197
+ * @author minematic
1198
+ * @date 2015-05-08
1199
+ */
1200
+ private static function _validateProductImage($image) {
1201
+ if(empty($image)) {
1202
+ return false;
1203
+ }
1204
+
1205
+ if('no_selection' == $image) {
1206
+ return false;
1207
+ }
1208
+
1209
+ return true;
1210
+ }
1211
+
1212
+ /**
1213
+ * Return variable $_result_sync_message value
1214
+ * @return [type]
1215
+ * @author edudeleon
1216
+ * @date 2015-05-11
1217
+ */
1218
+ public function get_result_sync_message(){
1219
+ return $this->_result_sync_message;
1220
+ }
1221
+
1222
+ /**
1223
+ * Return variable _result_sync_http_code_response value
1224
+ * @return [type]
1225
+ * @author edudeleon
1226
+ * @date 2015-05-11
1227
+ */
1228
+ public function get_result_sync_http_code_response(){
1229
+ return $this->_result_sync_http_code_response;
1230
+ }
1231
+
1232
+ /**
1233
+ * Method that helps the debuggin of pushing data to Minematic
1234
+ * Data is logged in files
1235
+ * @param [type] $data_type [ITEMS, USERS, EVENTS]
1236
+ * @param [type] $data
1237
+ * @param [type] $sync_type
1238
+ * @return [type]
1239
+ * @author edudeleon
1240
+ * @date 2015-05-14
1241
+ */
1242
+ private function emulate_pushData($data_type, $data, $sync_type=NULL){
1243
+ if(empty($sync_type)){
1244
+ $sync_type="not_specified";
1245
+ }
1246
+ // Log name
1247
+ $log_filename = $sync_type."_mode_data_pushed_".date('Y-m-d').".log";
1248
+
1249
+ //Format data
1250
+ foreach($data as $data_element){
1251
+ //Get data_element
1252
+
1253
+ $log_line = "{";
1254
+ $i = 1;
1255
+ foreach ($data_element as $k => $value) {
1256
+ if($i != count($data_element)){
1257
+ $log_line .= $k.": ".$value.", ";
1258
+ } else {
1259
+ $log_line .= $k.": ".$value;
1260
+ }
1261
+ $i++;
1262
+ }
1263
+
1264
+ $log_line .= "}";
1265
+
1266
+ Mage::log(" [ $data_type ] :: " . $log_line, null, $log_filename);
1267
+ }
1268
+ }
1269
+
1270
+
1271
+ }
app/code/community/Minematic/Connector/Model/System/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Model/System/Config/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Model/System/Config/Backend/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/Model/System/Config/Backend/Cron.php ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+
3
+ /**
4
+ * Class that saves the correct cron expression from select option in Admin Panel
5
+ */
6
+ class Minematic_Connector_Model_System_Config_Backend_Cron extends Mage_Core_Model_Config_Data
7
+ {
8
+
9
+ /**
10
+ * Save the cron expression in core_config table
11
+ * @return [type]
12
+ * @author edudeleon
13
+ * @date 2015-05-12
14
+ */
15
+ protected function _afterSave()
16
+ {
17
+ //Get cron interval (hours)
18
+ $cron_interval_hours = $this->getData('groups/general/fields/cron_interval/value');
19
+
20
+ //Prepare cron expression (Run every N hours)
21
+ $cron_expression = "0 */".(int)$cron_interval_hours. " * * *";
22
+
23
+ try {
24
+ Mage::getModel('core/config_data')
25
+ ->load(Minematic_Connector_Model_Config::CRON_EXPRESSION_PATH, 'path')
26
+ ->setValue($cron_expression)
27
+ ->setPath(Minematic_Connector_Model_Config::CRON_EXPRESSION_PATH)
28
+ ->save();
29
+ }
30
+ catch (Exception $e) {
31
+ throw new Exception(Mage::helper('cron')->__('Unable to save the cron expression.'));
32
+ }
33
+ }
34
+ }
app/code/community/Minematic/Connector/controllers/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/controllers/MinematicController.php ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ class Minematic_Connector_MinematicController extends Mage_Core_Controller_Front_Action
3
+ {
4
+ /**
5
+ * Method used to verify the module status and security parameters
6
+ * @param boolean $ping_action
7
+ * @return [type]
8
+ * @author edudeleon
9
+ * @date 2015-05-10
10
+ */
11
+ private function _init($ping_action = false){
12
+ //Check if module is enabled
13
+ if(!Mage::helper('connector')->isEnabled()) {
14
+ $this->_set_header_response('error', 'Minematic module is not enabled', 400);
15
+ return false;
16
+ }
17
+
18
+ //Get credentials
19
+ $api_key = $this->getRequest()->getHeader(Mage::helper('connector')->getAPIKeyHeaderField());
20
+ $client_id = $this->getRequest()->getHeader(Mage::helper('connector')->getAPIClientIDHeaderField());
21
+
22
+ //Validate credentials
23
+ if (Mage::helper('connector')->valid_credentials($api_key, $client_id)){
24
+ //If ping action, set header response
25
+ if ($ping_action) {
26
+ //Set header respoonse
27
+ $this->_set_header_response('message', 'Ping Successfull', 200);
28
+ }
29
+
30
+ return true;
31
+
32
+ } else {
33
+
34
+ //Set header response for invalid credentials
35
+ $this->_set_header_response('error', 'Invalid API Key or Client Id.', 400);
36
+ return false;
37
+ }
38
+
39
+ return true;
40
+ }
41
+
42
+ /**
43
+ * Method used to set header responses
44
+ * @param [type] $response_type ['message', 'error']
45
+ * @param [type] $message
46
+ * @param [type] $http_code
47
+ * @author edudeleon
48
+ * @date 2015-05-10
49
+ */
50
+ private function _set_header_response($response_type, $message, $http_code){
51
+ //Prepare Json Message
52
+ $jsonData = Mage::helper('connector')->setReturnMessage($response_type, $message);
53
+
54
+ $this->getResponse()->setHeader('Content-type', 'application/json');
55
+ $this->getResponse()->setHttpResponseCode($http_code);
56
+ $this->getResponse()->setBody($jsonData);
57
+ }
58
+
59
+ /**
60
+ * Method used to check store status (ping)
61
+ * @return [type]
62
+ * @author edudeleon
63
+ * @date 2015-05-10
64
+ */
65
+ public function pingAction(){
66
+ //Call init method to verify module status and security parameters
67
+ $this->_init(true);
68
+
69
+ return;
70
+ }
71
+
72
+ /**
73
+ * Method used to get store summary data
74
+ * @return [type]
75
+ * @author edudeleon
76
+ * @date 2015-05-10
77
+ */
78
+ public function summaryAction(){
79
+ //Call init method to verify module status and security parameters
80
+ if(!$this->_init()){
81
+ return;
82
+ }
83
+
84
+ //Get Post Parameters
85
+ $type = $this->getRequest()->getPost('type');
86
+
87
+ //Get summary data from model
88
+ try {
89
+ $summary_data = Mage::getModel('connector/synchronization')->get_summary_data($type);
90
+ } catch (Exception $e) {
91
+ //Set error response
92
+ $this->_set_header_response('error', $e->getMessage(), 400);
93
+ return;
94
+ }
95
+
96
+ //Set response
97
+ $this->_set_header_response('summary', $summary_data, 200);
98
+ return;
99
+ }
100
+
101
+ /**
102
+ * Method used to items pull data manually through URL (i.e. http://www.storename.com/connector/minematic/items)
103
+ * @return [type]
104
+ * @author edudeleon
105
+ * @date 2015-05-05
106
+ */
107
+ public function itemsAction(){
108
+ //Call init method to verify module status and security parameters
109
+ if(!$this->_init()){
110
+ return;
111
+ }
112
+
113
+ //Get post parameters
114
+ $since = $this->getRequest()->getPost('since');
115
+ $till = $this->getRequest()->getPost('till');
116
+ $limit = $this->getRequest()->getPost('limit');
117
+
118
+ try {
119
+ //Intiantate sync model
120
+ $sync_model = Mage::getModel('connector/synchronization');
121
+
122
+ //Sync Items
123
+ $sync_model->sync_items_data(Minematic_Connector_Model_Config::SYNC_TYPE_MINEMATIC_SIDE, $since, $till, $limit);
124
+
125
+ //Get result sync messagae
126
+ $result_sync_message = $sync_model->get_result_sync_message();
127
+ $result_sync_http_code_response = $sync_model->get_result_sync_http_code_response();
128
+
129
+ //Set header response
130
+ $this->_set_header_response('success', $result_sync_message, $result_sync_http_code_response);
131
+ return;
132
+
133
+ } catch (Exception $e) {
134
+ //Log Error
135
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), Minematic_Connector_Model_Config::SYNC_TYPE_MINEMATIC_SIDE, "ERROR");
136
+
137
+ //Set error response
138
+ $this->_set_header_response('error', $e->getMessage(), 400);
139
+ }
140
+
141
+ return;
142
+ }
143
+
144
+ /**
145
+ * Method used to pull users data manually through URL (i.e. http://www.storename.kcom/connector/minematic/users)
146
+ * @return [type]
147
+ * @author edudeleon
148
+ * @date 2015-05-10
149
+ */
150
+ public function usersAction(){
151
+ //Call init method to verify module status and security parameters
152
+ if(!$this->_init()){
153
+ return;
154
+ }
155
+
156
+ //Get post parameters
157
+ $since = $this->getRequest()->getPost('since');
158
+ $limit = $this->getRequest()->getPost('limit');
159
+
160
+ try {
161
+ //Intiantate sync model
162
+ $sync_model = Mage::getModel('connector/synchronization');
163
+
164
+ //Sync users
165
+ $sync_model->sync_users_data(Minematic_Connector_Model_Config::SYNC_TYPE_MINEMATIC_SIDE, $since, $limit);
166
+
167
+ //Get result sync messagae
168
+ $result_sync_message = $sync_model->get_result_sync_message();
169
+ $result_sync_http_code_response = $sync_model->get_result_sync_http_code_response();
170
+
171
+ //Set header response
172
+ $this->_set_header_response('success', $result_sync_message, $result_sync_http_code_response);
173
+ return;
174
+
175
+ } catch (Exception $e) {
176
+ //Log Error
177
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), Minematic_Connector_Model_Config::SYNC_TYPE_MINEMATIC_SIDE, "ERROR");
178
+
179
+ //Set error response
180
+ $this->_set_header_response('error', $e->getMessage(), 400);
181
+ }
182
+
183
+ return;
184
+ }
185
+
186
+ /**
187
+ * Method used to pull events data manually through URL (i.e. http://www.storename.com/connector/minematic/events)
188
+ * @return [type]
189
+ * @author edudeleon
190
+ * @date 2015-05-10
191
+ */
192
+ public function eventsAction(){
193
+ //Call init method to verify module status and security parameters
194
+ if(!$this->_init()){
195
+ return;
196
+ }
197
+
198
+ //Get Post parameters
199
+ $type = $this->getRequest()->getPost('type');
200
+ $since = $this->getRequest()->getPost('since');
201
+ $limit = $this->getRequest()->getPost('limit');
202
+
203
+ try {
204
+ //Intiantate sync model
205
+ $sync_model = Mage::getModel('connector/synchronization');
206
+
207
+ //Sync events
208
+ $sync_model->sync_events_data(Minematic_Connector_Model_Config::SYNC_TYPE_MINEMATIC_SIDE, $type, $since, $limit);
209
+
210
+ //Get result sync messagae
211
+ $result_sync_message = $sync_model->get_result_sync_message();
212
+ $result_sync_http_code_response = $sync_model->get_result_sync_http_code_response();
213
+
214
+ //Set header response
215
+ $this->_set_header_response('success', $result_sync_message, $result_sync_http_code_response);
216
+ return;
217
+
218
+ } catch (Exception $e) {
219
+ //Log Error
220
+ Mage::helper('connector')->logSyncProcess($e->getMessage(), Minematic_Connector_Model_Config::SYNC_TYPE_MINEMATIC_SIDE, "ERROR");
221
+
222
+ //Set error response
223
+ $this->_set_header_response('error', $e->getMessage(), 400);
224
+ }
225
+
226
+ return;
227
+ }
228
+
229
+
230
+ }
app/code/community/Minematic/Connector/etc/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/etc/config.xml ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0" ?>
2
+ <!-- Root node for Magento configuration files -->
3
+ <config>
4
+ <!-- modules node provides basic information about the module -->
5
+ <modules>
6
+ <!-- This node's name has to be the same as module's full name including namespace -->
7
+ <Minematic_Connector>
8
+ <!-- Current version of module -->
9
+ <version>1.0.0</version>
10
+ </Minematic_Connector>
11
+ </modules>
12
+
13
+ <frontend>
14
+ <!-- Controller route -->
15
+ <routers>
16
+ <connector>
17
+ <use>standard</use>
18
+ <args>
19
+ <module>Minematic_Connector</module>
20
+ <frontName>connector</frontName>
21
+ </args>
22
+ </connector>
23
+ </routers>
24
+
25
+ <!-- Layout -->
26
+ <layout>
27
+ <updates>
28
+ <minematic_connector module="Minematic_Connector">
29
+ <file>minematic_connector.xml</file>
30
+ </minematic_connector>
31
+ </updates>
32
+ </layout>
33
+
34
+ </frontend>
35
+
36
+ <!-- Global Section -->
37
+ <global>
38
+ <!-- Models -->
39
+ <models>
40
+ <connector>
41
+ <class>Minematic_Connector_Model</class> <!-- Model class files -->
42
+ <resourceModel>connector_mysql4</resourceModel> <!--Resource model -->
43
+ </connector>
44
+ <connector_mysql4>
45
+ <class>Minematic_Connector_Model_Mysql4</class>
46
+ <entities>
47
+ <connector>
48
+ <table>minematic_config</table> <!-- Db table name -->
49
+ </connector>
50
+ </entities>
51
+ </connector_mysql4>
52
+ </models>
53
+
54
+ <!-- Resources / Needed for installtion/update scirpts-->
55
+ <resources>
56
+ <connector_setup> <!-- Setup directory -->
57
+ <setup>
58
+ <module>Minematic_Connector</module>
59
+ </setup>
60
+ <connection>
61
+ <use>core_setup</use>
62
+ </connection>
63
+ </connector_setup>
64
+
65
+ <connector_write>
66
+ <connection>
67
+ <use>core_write</use>
68
+ </connection>
69
+ </connector_write>
70
+
71
+ <connector_read>
72
+ <connection>
73
+ <use>core_read</use>
74
+ </connection>
75
+ </connector_read>
76
+ </resources>
77
+
78
+ <!-- Helpers -->
79
+ <helpers>
80
+ <connector>
81
+ <class>Minematic_Connector_Helper</class>
82
+ </connector>
83
+ </helpers>
84
+
85
+ <!-- Blocks -->
86
+ <blocks>
87
+ <connector>
88
+ <class>Minematic_Connector_Block</class>
89
+ </connector>
90
+ </blocks>
91
+
92
+ </global>
93
+
94
+ <!-- Setting up cronjobs -->
95
+ <crontab>
96
+ <jobs>
97
+ <!-- Default config comes from core_config_data, path: "crontab/jobs/minematic_sync_data/schedule/cron_expr" -->
98
+ <minematic_sync_data>
99
+ <!-- <schedule><cron_expr>0 */2 * * *</cron_expr></schedule> -->
100
+ <run><model>connector/observer::run_sync_process</model></run>
101
+ </minematic_sync_data>
102
+ </jobs>
103
+ </crontab>
104
+
105
+ <adminhtml>
106
+ <acl>
107
+ <resources>
108
+ <all>
109
+ <title>Allow Everything</title>
110
+ </all>
111
+ <admin>
112
+ <children>
113
+ <system>
114
+ <children>
115
+ <config>
116
+ <children>
117
+ <minematic_settings>
118
+ <title>Minematic</title>
119
+ </minematic_settings>
120
+ </children>
121
+ </config>
122
+ </children>
123
+ </system>
124
+ </children>
125
+ </admin>
126
+ </resources>
127
+ </acl>
128
+ </adminhtml>
129
+
130
+ <!-- Default values form Module -->
131
+ <default>
132
+ <minematic_settings>
133
+ <general>
134
+ <cron_interval>2</cron_interval> <!-- Default value every 2 hours. If changed, update mysql install script -->
135
+ </general>
136
+ </minematic_settings>
137
+ </default>
138
+
139
+ </config>
app/code/community/Minematic/Connector/etc/system.xml ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <tabs>
4
+ <minematic_config translate="label" module="connector">
5
+ <label>Minematic</label>
6
+ <sort_order>99999</sort_order>
7
+ </minematic_config>
8
+ </tabs>
9
+ <sections>
10
+
11
+ <minematic_settings translate="label" module="connector" >
12
+ <label>Settings</label>
13
+ <tab>minematic_config</tab>
14
+ <frontend_type>text</frontend_type>
15
+ <sort_order>9999</sort_order>
16
+ <show_in_default>1</show_in_default>
17
+ <show_in_website>1</show_in_website>
18
+ <show_in_store>1</show_in_store>
19
+ <groups>
20
+ <general translate="label">
21
+ <label>Configurations</label>
22
+ <frontend_type>text</frontend_type>
23
+ <sort_order>100</sort_order>
24
+ <show_in_default>1</show_in_default>
25
+ <show_in_website>1</show_in_website>
26
+ <show_in_store>1</show_in_store>
27
+ <fields>
28
+
29
+ <enabled translate="label">
30
+ <label>Module Enabled</label>
31
+ <frontend_type>select</frontend_type>
32
+ <source_model>adminhtml/system_config_source_yesno</source_model>
33
+ <sort_order>10</sort_order>
34
+ <show_in_default>1</show_in_default>
35
+ <show_in_website>1</show_in_website>
36
+ <show_in_store>1</show_in_store>
37
+ <comment>Minematic Module Enabled?</comment>
38
+ </enabled>
39
+
40
+ <clientid translate="label">
41
+ <label>Minematic Client ID</label>
42
+ <frontend_type>text</frontend_type>
43
+ <sort_order>20</sort_order>
44
+ <show_in_default>1</show_in_default>
45
+ <show_in_website>1</show_in_website>
46
+ <show_in_store>1</show_in_store>
47
+ <comment>Client Id. You can find this in <![CDATA[<a href="https://www.minematic.com/app/" target="_blank">Minematic</a>]]> web app.</comment>
48
+ </clientid>
49
+
50
+ <apikey translate="label">
51
+ <label>Minematic API Key</label>
52
+ <frontend_type>text</frontend_type>
53
+ <sort_order>30</sort_order>
54
+ <show_in_default>1</show_in_default>
55
+ <show_in_website>1</show_in_website>
56
+ <show_in_store>1</show_in_store>
57
+ <comment>API Key. You can find this in <![CDATA[<a href="https://www.minematic.com/app/" target="_blank">Minematic</a>]]> web app.</comment>
58
+ </apikey>
59
+
60
+ <javascript_code translate="label">
61
+ <label>Minematic Javascript Code</label>
62
+ <frontend_type>text</frontend_type>
63
+ <sort_order>33</sort_order>
64
+ <show_in_default>1</show_in_default>
65
+ <show_in_website>1</show_in_website>
66
+ <show_in_store>1</show_in_store>
67
+ <comment>Minematic Javascript Code. You can find this in <![CDATA[<a href="https://www.minematic.com/app/" target="_blank">Minematic</a>]]> web app.</comment>
68
+ </javascript_code>
69
+
70
+ <!-- Dropdown options to run module scheduled tasks -->
71
+ <cron_interval translate="label">
72
+ <label>Cron Interval</label>
73
+ <frontend_type>select</frontend_type>
74
+ <source_model>connector/config_crondropdown</source_model>
75
+ <backend_model>connector/system_config_backend_cron</backend_model> <!-- Save cron expression in core_config_data -->
76
+ <sort_order>35</sort_order>
77
+ <show_in_default>1</show_in_default>
78
+ <show_in_website>1</show_in_website>
79
+ <show_in_store>1</show_in_store>
80
+ <comment>Select the time interval you wish the module to run the scheduled tasks</comment>
81
+ </cron_interval>
82
+
83
+ <!-- Additional Product Fields Input Text -->
84
+ <product_fields translate="label">
85
+ <label>Optional Product Fields</label>
86
+ <frontend_type>text</frontend_type>
87
+ <sort_order>40</sort_order>
88
+ <show_in_default>1</show_in_default>
89
+ <show_in_website>1</show_in_website>
90
+ <show_in_store>1</show_in_store>
91
+ <comment>Insert additional product fields that you want to send to Minematic. Separate fields by commas (,) </comment>
92
+ </product_fields>
93
+
94
+ <!-- Additional Customer Fields Input Text -->
95
+ <customer_fields translate="label">
96
+ <label>Optional Customer Fields</label>
97
+ <frontend_type>text</frontend_type>
98
+ <sort_order>50</sort_order>
99
+ <show_in_default>1</show_in_default>
100
+ <show_in_website>1</show_in_website>
101
+ <show_in_store>1</show_in_store>
102
+ <comment>Insert additional customer fields that you want to send to Minematic. Separate fields by commas (,) </comment>
103
+ </customer_fields>
104
+
105
+ <!-- Additional Event Fields Input Text -->
106
+ <event_fields translate="label">
107
+ <label>Optional Event Fields</label>
108
+ <frontend_type>text</frontend_type>
109
+ <sort_order>60</sort_order>
110
+ <show_in_default>1</show_in_default>
111
+ <show_in_website>1</show_in_website>
112
+ <show_in_store>1</show_in_store>
113
+ <comment>Insert additional event fields that you want to send to Minematic. Separate fields by commas (,) </comment>
114
+ </event_fields>
115
+
116
+ <!-- Dropdown option with store views -->
117
+ <store_view translate="label">
118
+ <label>Store View</label>
119
+ <frontend_type>select</frontend_type>
120
+ <source_model>connector/config_storeviewsdropdown</source_model>
121
+ <sort_order>70</sort_order>
122
+ <show_in_default>1</show_in_default>
123
+ <show_in_website>1</show_in_website>
124
+ <show_in_store>1</show_in_store>
125
+ <comment>Select your store view</comment>
126
+ </store_view>
127
+
128
+ </fields>
129
+ </general>
130
+ </groups>
131
+ </minematic_settings>
132
+ </sections>
133
+ </config>
app/code/community/Minematic/Connector/sql/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/sql/connector_setup/.DS_Store ADDED
Binary file
app/code/community/Minematic/Connector/sql/connector_setup/mysql4-install-0.1.0.php ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php
2
+ // Script used to create minematc table
3
+
4
+ $installer = $this;
5
+ $installer->startSetup();
6
+
7
+ try {
8
+
9
+ //Drop 'minematic_config' table in case it exists
10
+ $installer->run("
11
+ DROP TABLE IF EXISTS {$this->getTable('minematic_config')};
12
+ ");
13
+
14
+ // Create table statment
15
+ $configTableName = $this->getTable('minematic_config');
16
+ $sql = "CREATE TABLE IF NOT EXISTS $configTableName (
17
+ `name` varchar(128) NOT NULL,
18
+ `value` varchar(255) NOT NULL,
19
+ PRIMARY KEY (`name`)
20
+ );
21
+
22
+ INSERT IGNORE INTO $configTableName VALUES('" . Minematic_Connector_Model_Config::ITEMS_LAST_SYNC_DATETIME . "', '');
23
+ INSERT IGNORE INTO $configTableName VALUES('" . Minematic_Connector_Model_Config::ITEMS_LAST_SYNC_TYPE . "', '');
24
+ INSERT IGNORE INTO $configTableName VALUES('" . Minematic_Connector_Model_Config::USERS_LAST_SYNC_DATETIME . "', '');
25
+ INSERT IGNORE INTO $configTableName VALUES('" . Minematic_Connector_Model_Config::USERS_LAST_SYNC_TYPE . "', '');
26
+ INSERT IGNORE INTO $configTableName VALUES('" . Minematic_Connector_Model_Config::EVENTS_LAST_SYNC_DATETIME . "', '');
27
+ INSERT IGNORE INTO $configTableName VALUES('" . Minematic_Connector_Model_Config::EVENTS_LAST_SYNC_TYPE . "', '');
28
+ ";
29
+
30
+ //Create table
31
+ $installer->run($sql);
32
+
33
+ //Insert default value for cron expression (run every 2 hours)
34
+ $installer->run("INSERT IGNORE INTO {$this->getTable('core/config_data')} VALUES('" . Minematic_Connector_Model_Config::CRON_EXPRESSION_PATH . "', '0 */2 * * *');");
35
+
36
+ } catch (Exception $e) {
37
+ Mage::logException($e);
38
+ }
39
+
40
+ $installer->endSetup();
app/design/frontend/base/default/layout/minematic_connector.xml ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <layout version="1.0.0">
3
+ <default>
4
+ <reference name="head">
5
+ <block type="core/template" name="header_snippet" as="headerSnippet" template="minematic_connector/header_snippet.phtml"/>
6
+ </reference>
7
+ </default>
8
+ </layout>
app/design/frontend/base/default/template/minematic_connector/header_snippet.phtml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?php if(Mage::helper('connector')->isEnabled()){ //Verify module status
2
+ $development_mode = "false"; // Edit to "false" when using in production
3
+ ?>
4
+
5
+ <?php $javascript_code = Mage::helper('connector')->getJavascriptCode(); ?>
6
+
7
+ <script type="text/javascript">
8
+ //<![CDATA[
9
+ var _mm = _mm || [];
10
+ (function() {
11
+ var a,b,c;a = function(f) { return function() {_mm.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track","addItems"]; for(c=0;c<b.length;c++){_mm[b[c]]=a(b[c])};
12
+ var t = document.createElement('script'),s = document.getElementsByTagName('script')[0]; t.async = true;t.id = 'mm-tracker';
13
+ t.setAttribute('install-code', '<?php echo $javascript_code; ?>'); t.setAttribute('development', <?php echo $development_mode; ?>);
14
+ t.src = 'https://s3-ap-southeast-1.amazonaws.com/asset.minematic.com/js/mm-track.min.js';s.parentNode.insertBefore(t, s);
15
+ })();
16
+ //]]>
17
+ </script>
18
+
19
+ <?php
20
+ if(Mage::getSingleton('customer/session')->isLoggedIn()){
21
+ // Load the customer's data
22
+ $customer = Mage::getSingleton('customer/session')->getCustomer();
23
+ // Getting data
24
+ $customer_id = $customer->getId();
25
+ ?>
26
+
27
+ <script type="text/javascript">
28
+ _mm.identify({id: '<?php echo $customer_id; ?>' });
29
+ </script>
30
+
31
+ <?php } ?>
32
+
33
+
34
+ <?php
35
+ if($this->getRequest()->getControllerName()=='product'){
36
+ //Get product data
37
+ $productObject = Mage::registry('current_product');
38
+ $product_id = $productObject->getId();
39
+ ?>
40
+
41
+ <script type="text/javascript">
42
+ _mm.track('VIEW', {id:'<?php echo $product_id; ?>'});
43
+ </script>
44
+
45
+ <?php } ?>
46
+
47
+ <?php } //Closing IF that validates module status?>
app/etc/modules/Minematic_Connector.xml ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <config>
3
+ <!-- the same block we have in module's config.xml -->
4
+ <modules>
5
+ <!-- This node's name has to be the same as module's full name including namespace -->
6
+ <Minematic_Connector>
7
+ <!-- flag indicating weather module is active or not -->
8
+ <active>true</active>
9
+ <!-- code pool -->
10
+ <codePool>community</codePool>
11
+ </Minematic_Connector>
12
+ </modules>
13
+ </config>
package.xml ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <?xml version="1.0"?>
2
+ <package>
3
+ <name>Minematic_Connector</name>
4
+ <version>1.0.0</version>
5
+ <stability>stable</stability>
6
+ <license>Open Software License (OSL)</license>
7
+ <channel>community</channel>
8
+ <extends/>
9
+ <summary>Minematic Connector collects products, customers and events data for the store and sends it to Minematic data collection API for analysis and marketing.</summary>
10
+ <description>This module collects information about products, customers and events (e.g. ADD TO CART, PRODUCT PAGE VIEW, ADD TO WISHLIST, SHARE) and transfers the information to Minematic data collection API for data analysis and marketing.</description>
11
+ <notes>First release version</notes>
12
+ <authors><author><name>Minematic</name><user>minematic</user><email>magento@minematic.com</email></author></authors>
13
+ <date>2015-05-26</date>
14
+ <time>12:50:06</time>
15
+ <contents><target name="magecommunity"><dir name="Minematic"><dir name="Connector"><dir name="Block"><file name="Connector.php" hash="8735289b0f9388955dda56de863cc7f0"/></dir><dir name="Helper"><file name="Data.php" hash="a008a987b46c28f46bf7de02dc7a5936"/><dir name="push_api"><file name="MinematicClient.php" hash="2466f46c03b4fc352e700c6ff287df46"/><file name=".DS_Store" hash="11d4264a26b39c74a6176b3feb5ddb56"/></dir><file name=".DS_Store" hash="166fc3c278a952701e9d4897bfbec1dc"/></dir><dir name="Model"><dir name="Config"><file name="CronDropdown.php" hash="fc52a230acf46a26e273ce001dc83391"/><file name="StoreViewsDropdown.php" hash="a88bbd250318f758430ab0f4425c72e3"/></dir><file name="Config.php" hash="fde17e756d5ebd6df6040bc874a42c46"/><file name="Observer.php" hash="27495887bfe154b51d9f11d8cd240286"/><file name="Synchronization.php" hash="3c6d6baca4bdd115131a5837bd54965a"/><dir name="System"><dir name="Config"><dir name="Backend"><file name="Cron.php" hash="52e119425813d464474474c15036375f"/><file name=".DS_Store" hash="194577a7e20bdcc7afbb718f502c134c"/></dir><file name=".DS_Store" hash="164f4d8848918d06a0b1de4041fdadd6"/></dir><file name=".DS_Store" hash="1a138f3b020c526173b9b06a9a2717df"/></dir><file name=".DS_Store" hash="245aa1be2b4f14ef749681c504db8590"/></dir><dir name="controllers"><file name="MinematicController.php" hash="d579d4533a39629ede1549d15e728fa6"/><file name=".DS_Store" hash="a1ddf4e9ec2bec74d4ae1ce8b742675d"/></dir><dir name="etc"><file name="config.xml" hash="02c893b821f614e805a68a233cee6ad4"/><file name="system.xml" hash="4e6616f879f2826de2cd99e189faef4c"/><file name=".DS_Store" hash="d5c9ef4cc8915721d89f14aff358e204"/></dir><dir name="sql"><dir name="connector_setup"><file name="mysql4-install-0.1.0.php" hash="6082551b6be34602284903c95beea1c5"/><file name=".DS_Store" hash="194577a7e20bdcc7afbb718f502c134c"/></dir><file name=".DS_Store" hash="e0ff3a55f14b180fe579834f1fd8d0e8"/></dir><file name=".DS_Store" hash="d4537f8cbf61ef83e95726abf22f1d09"/></dir><file name=".DS_Store" hash="326cb448044ba8acb73c993a1cdcb370"/></dir></target><target name="magedesign"><dir name="frontend"><dir name="base"><dir name="default"><dir name="layout"><file name="minematic_connector.xml" hash="ceae04cb1965c10562a4227be9eede40"/></dir><dir name="template"><dir name="minematic_connector"><file name="header_snippet.phtml" hash="1a972999363492611d3096aa1772cc44"/></dir></dir></dir></dir></dir></target><target name="mageetc"><dir name="modules"><file name="Minematic_Connector.xml" hash="78b1da5a65d9074dce12bc4d51fdb011"/></dir></target></contents>
16
+ <compatible/>
17
+ <dependencies><required><php><min>5.4.0</min><max>6.0.0</max></php></required></dependencies>
18
+ </package>