Fanplayr - Version 1.0.48

Version Notes

- optionally remove trailing slash from embed URL

Download this release

Release Info

Developer Magento Core Team
Extension Fanplayr
Version 1.0.48
Comparing to
See all releases


Version 1.0.48

Files changed (34) hide show
  1. app/code/community/Fanplayr/Socialcoupons/Block/Adminhtml/System/Config/Form/Field/Installhelper.php +441 -0
  2. app/code/community/Fanplayr/Socialcoupons/Model/CartObserver.php +89 -0
  3. app/code/community/Fanplayr/Socialcoupons/Model/EmbedObserver.php +637 -0
  4. app/code/community/Fanplayr/Socialcoupons/Model/OrderObserver.php +349 -0
  5. app/code/community/Fanplayr/Socialcoupons/controllers/AjaxController.php +116 -0
  6. app/code/community/Fanplayr/Socialcoupons/controllers/CompyController.php +750 -0
  7. app/code/community/Fanplayr/Socialcoupons/controllers/CouponController.php +191 -0
  8. app/code/community/Fanplayr/Socialcoupons/controllers/IndexController.php +24 -0
  9. app/code/community/Fanplayr/Socialcoupons/etc/config.xml +178 -0
  10. app/code/community/Fanplayr/Socialcoupons/etc/system.xml +67 -0
  11. app/design/frontend/base/default/template/fanplayr/embed.phtml +122 -0
  12. app/design/frontend/base/default/template/fanplayr/embed_ajax.phtml +32 -0
  13. app/design/frontend/base/default/template/fanplayr/success.phtml +157 -0
  14. app/design/frontend/default/default/template/fanplayr/embed.phtml +122 -0
  15. app/design/frontend/default/default/template/fanplayr/embed_ajax.phtml +32 -0
  16. app/design/frontend/default/default/template/fanplayr/success.phtml +157 -0
  17. app/etc/modules/Fanplayr_Socialcoupons.xml +10 -0
  18. package.xml +18 -0
  19. skin/frontend/socialcoupons/fanplayr_join.html +42 -0
  20. skin/frontend/socialcoupons/fanplayr_socialcoupons.css +298 -0
  21. skin/frontend/socialcoupons/fanplayr_socialcoupons.js +591 -0
  22. skin/frontend/socialcoupons/fanplayr_socialcoupons.min.css +39 -0
  23. skin/frontend/socialcoupons/images/.picasa.ini +2 -0
  24. skin/frontend/socialcoupons/images/accept.png +0 -0
  25. skin/frontend/socialcoupons/images/activity.gif +0 -0
  26. skin/frontend/socialcoupons/images/disable.png +0 -0
  27. skin/frontend/socialcoupons/images/fanplayr_logo.png +0 -0
  28. skin/frontend/socialcoupons/images/genius_16.png +0 -0
  29. skin/frontend/socialcoupons/images/pencil.png +0 -0
  30. skin/frontend/socialcoupons/images/progress-loader.gif +0 -0
  31. skin/frontend/socialcoupons/images/sales_16.png +0 -0
  32. skin/frontend/socialcoupons/images/star_gold.png +0 -0
  33. skin/frontend/socialcoupons/images/warning.png +0 -0
  34. skin/frontend/socialcoupons/jquery-1.7.2.min.js +4 -0
app/code/community/Fanplayr/Socialcoupons/Block/Adminhtml/System/Config/Form/Field/Installhelper.php ADDED
@@ -0,0 +1,441 @@
1
+ <?php
2
+
3
+ class Fanplayr_Socialcoupons_Block_Adminhtml_System_Config_Form_Field_Installhelper extends Mage_Adminhtml_Block_System_Config_Form_Field
4
+ {
5
+ protected function _getElementHtml(Varien_Data_Form_Element_Abstract $element)
6
+ {
7
+
8
+ // ------------------------------------------------------------------------
9
+ // get local details
10
+ $secret = Mage::getStoreConfig('fanplayrsocialcoupons/config/secret');
11
+ $secretInner = Mage::getStoreConfig('fanplayrsocialcoupons/config/secret_inner');
12
+ $accKey = Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key');
13
+ $shopId = Mage::getStoreConfig('fanplayrsocialcoupons/config/shop_id');
14
+
15
+ if (empty($secret)) {
16
+ $secret = md5(uniqid("Things are fine, seriously. I love this!", true));
17
+ $this->updateConfig('fanplayrsocialcoupons/config/secret', $secret);
18
+ }
19
+ if (empty($secretInner)) {
20
+ $secretInner = md5(uniqid("And other things are great ...", true));
21
+ $this->updateConfig('fanplayrsocialcoupons/config/secret_inner', $secretInner);
22
+ }
23
+
24
+ // default some others
25
+ $prefix = Mage::getStoreConfig('fanplayrsocialcoupons/config/dep_prefix');
26
+ if (empty($prefix)) {
27
+ $this->updateConfig('fanplayrsocialcoupons/config/dep_prefix', 'F2P9P31R_');
28
+ }
29
+
30
+ // setup vars in case we need 'em
31
+ // ------------------------------------------------------------------------
32
+ // get current admin user info
33
+ $userId = Mage::getSingleton('admin/session')->getUser()->getId();
34
+ $user = Mage::getModel('admin/user')->load($userId);
35
+ $userData = $user->getData();
36
+
37
+ // get details to send along ...
38
+ $firstname = array_key_exists('firstname', $userData) ? $userData['firstname'] : '';
39
+ $lastname = array_key_exists('lastname', $userData) ? $userData['lastname'] : '';
40
+ $email = array_key_exists('email', $userData) ? $userData['email'] : '';
41
+ $shopUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
42
+
43
+ $customShopUrl = Mage::getStoreConfig('fanplayrsocialcoupons/config/custom_url');
44
+ $customShopUrlUsed = true;
45
+ if (empty($customShopUrl)) {
46
+ $customShopUrlUsed = false;
47
+ $customShopUrl = $shopUrl;
48
+ }
49
+ $shopUrl = $customShopUrl;
50
+
51
+ $customEmbedUrl = Mage::getStoreConfig('fanplayrsocialcoupons/config/custom_embed_url');
52
+
53
+ $shopName = Mage::getStoreConfig('general/store_information/name');
54
+ $shopPhone = Mage::getStoreConfig('general/store_information/phone');
55
+ $shopAddress = Mage::getStoreConfig('general/store_information/address');
56
+ $shopCountry = Mage::getStoreConfig('general/country/default');
57
+ $shopTz = Mage::getStoreConfig('general/locale/timezone');
58
+
59
+ $adminUrlFull = Mage::helper('adminhtml')->getUrl('/');
60
+ $adminUrl = substr($adminUrlFull, 0, strpos($adminUrlFull, 'index/index'));
61
+
62
+ // add index.php to shop URL, just in case they don't have URL rewriting ong
63
+ if (!$customShopUrlUsed){
64
+ if (!strpos($shopUrl, 'index.php/'))
65
+ $shopUrl .= 'index.php/';
66
+ }
67
+
68
+ $logoSrc = 'http://localhost/magento/skin/frontend/default/default/' . Mage::getStoreConfig('design/header/logo_src');
69
+ $skinDir = Mage::getBaseUrl('skin').'frontend/socialcoupons';
70
+
71
+ $queryString = 'secret=' . urlencode($secret);
72
+ $queryString .= '&email=' . urlencode($email);
73
+ $queryString .= '&name=' . urlencode($firstname . ' ' . $lastname);
74
+ $queryString .= '&shopUrl=' . urlencode($shopUrl);
75
+ $queryString .= '&shopName=' . urlencode($shopName);
76
+ $queryString .= '&adminUrl=' . urlencode($adminUrl);
77
+
78
+ $queryString .= '&phone=' . urlencode($shopPhone);
79
+ //$queryString .= '&address=' . urlencode($shopAddress);
80
+ $queryString .= '&address=';
81
+ $queryString .= '&country=' . urlencode($shopCountry);
82
+ $queryString .= '&tz=' . urlencode($shopTz);
83
+
84
+ $queryString .= '&authUser=' . urlencode(array_key_exists('PHP_AUTH_USER', $_SERVER) ? $_SERVER['PHP_AUTH_USER'] : '');
85
+ $queryString .= '&authPass=' . urlencode(array_key_exists('PHP_AUTH_PW', $_SERVER) ? $_SERVER['PHP_AUTH_PW'] : '');
86
+
87
+ // setup our general always needed HTML
88
+ // ------------------------------------------------------------------------
89
+ $mageVersion = Mage::getVersion();
90
+
91
+ $gamafiedKeys = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/widget_keys'));
92
+ $sntKeys = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/widget_keys_genius'));
93
+ $disableOnUrls = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/disable_on_urls'));
94
+
95
+ $depPrefix = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/dep_prefix'));
96
+ $depRoutes = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/dep_extra_rewrite_routes'));
97
+ $gtmContainerId = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/gtm_container_id'));
98
+ $trailingSlash = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/trailing_slash'));
99
+
100
+ // have to use this variable for backwards compatability ...
101
+ $currentEmbedType = htmlspecialchars(Mage::getStoreConfig('fanplayrsocialcoupons/config/wait_for_onload'));
102
+ if (!$currentEmbedType) $currentEmbedType = '0';
103
+ $embedOptions = '';
104
+ $embedOptions .= '<option value="0"'.($currentEmbedType=='0'||!$currentEmbedType?' selected':'').'>Defered Script: Normal</option>';
105
+ $embedOptions .= '<option value="1"'.($currentEmbedType=='1'?' selected':'').'>Defered Script: Lazy Loading</option>';
106
+ $embedOptions .= '<option value="2"'.($currentEmbedType=='2'?' selected':'').'>Tag Management System (User Only)</option>';
107
+ $embedOptions .= '<option value="3"'.($currentEmbedType=='3'?' selected':'').'>Tag Management System (User &amp; Order)</option>';
108
+ $embedOptions .= '<option value="4"'.($currentEmbedType=='4'?' selected':'').'>Direct Embed</option>';
109
+ $embedOptions .= '<option value="5"'.($currentEmbedType=='5'?' selected':'').'>Direct Embed: Lazy Loading</option>';
110
+ $embedOptions .= '<option value="6"'.($currentEmbedType=='6'?' selected':'').'>Google Tag Manager</option>';
111
+ $embedOptions .= '<option value="6"'.($currentEmbedType=='7'?' selected':'').'>Google Tag Manager (Universal Analytics Enhanced Ecommerce)</option>';
112
+
113
+ $currentLayoutHookHome = Mage::getStoreConfig('fanplayrsocialcoupons/config/layout_hook_home');
114
+ if (!$currentLayoutHookHome) $currentLayoutHookHome = 'content';
115
+ $layoutHooksHome = '';
116
+ $layoutHooksHome .= '<option value="content"'.($currentLayoutHookHome=='content'?' selected':'').'>content</option>';
117
+ $layoutHooksHome .= '<option value="footer.before"'.($currentLayoutHookHome=='footer.before'?' selected':'').'>footer.before</option>';
118
+ $layoutHooksHome .= '<option value="before_body_end"'.($currentLayoutHookHome=='before_body_end'?' selected':'').'>before_body_end</option>';
119
+
120
+ $currentLayoutHook = Mage::getStoreConfig('fanplayrsocialcoupons/config/layout_hook');
121
+ if (!$currentLayoutHook) $currentLayoutHook = 'content';
122
+ $layoutHooks = '';
123
+ $layoutHooks .= '<option value="content"'.($currentLayoutHook=='content'?' selected':'').'>content</option>';
124
+ $layoutHooks .= '<option value="footer.before"'.($currentLayoutHook=='footer.before'?' selected':'').'>footer.before</option>';
125
+ $layoutHooks .= '<option value="before_body_end"'.($currentLayoutHook=='before_body_end'?' selected':'').'>before_body_end</option>';
126
+
127
+ $currentLayoutHookOrder = Mage::getStoreConfig('fanplayrsocialcoupons/config/layout_hook_order');
128
+ if (!$currentLayoutHookOrder) $currentLayoutHookOrder = 'content';
129
+ $layoutHooksOrder = '';
130
+ $layoutHooksOrder .= '<option value="content"'.($currentLayoutHookOrder=='content'?' selected':'').'>content</option>';
131
+ $layoutHooksOrder .= '<option value="footer.before"'.($currentLayoutHookOrder=='footer.before'?' selected':'').'>footer.before</option>';
132
+ $layoutHooksOrder .= '<option value="before_body_end"'.($currentLayoutHookOrder=='before_body_end'?' selected':'').'>before_body_end</option>';
133
+
134
+ $customShopUrlEdit = (empty($accKey) && empty($customShopUrl)) ? $shopUrl : $customShopUrl;
135
+
136
+ // ------------------------------------------------------------------------
137
+ // check that all themes have FP templates!
138
+
139
+ // we may need to add Fanplayr templates to other directories
140
+ // is this just for default though?
141
+ $templatesWithNoFanplayr = array();
142
+
143
+ foreach(array(getcwd().'/app/design/frontend/default/', getcwd().'/app/design/frontend/enterprise/') as $path) {
144
+ $dir = opendir($path);
145
+ while($d = readdir($dir)){
146
+ if (is_dir($path . $d) && $d != '.' && $d != '..') {
147
+ if (is_dir($path . $d . '/template') && !is_dir($path . $d . '/template/fanplayr')){
148
+ array_push($templatesWithNoFanplayr, $d);
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ // ------------------------------------------------------------------------
155
+
156
+ $generalHtml = <<<EOT
157
+ <script>
158
+ var c = document.createElement("link");
159
+ c.setAttribute("rel", "stylesheet");
160
+ c.setAttribute("type", "text/css");
161
+ c.setAttribute("href", '{$skinDir}/fanplayr_socialcoupons.css');
162
+ document.getElementsByTagName("head")[0].appendChild(c);
163
+ </script>
164
+ <script type="text/javascript" src="{$skinDir}/jquery-1.7.2.min.js"></script>
165
+ <script type="text/javascript" src="{$skinDir}/fanplayr_socialcoupons.js"></script>
166
+ <script>
167
+ $.noConflict()(function($) {
168
+ // remove unneeded TDs, we want all the space!
169
+ // hope this is OK with the "Magento Way"?
170
+ // v1.4.1 and above
171
+
172
+ $('#row_fanplayrsocialcoupons_config_installed td:eq(0)').remove();
173
+ $('#row_fanplayrsocialcoupons_config_installed td.scope-label').remove();
174
+ //$('#row_fanplayrsocialcoupons_config_installed td:eq(2)').remove();
175
+ //$('#row_fanplayrsocialcoupons_config_installed td').css('width', 'auto');
176
+
177
+ if ("{$mageVersion}" == "1.4.0"){
178
+ // for v1.4.0
179
+ $('#fanplayrsocialcoupons_config td:eq(0)').remove();
180
+ $('#fanplayrsocialcoupons_config td:eq(1)').remove();
181
+ $('#fanplayrsocialcoupons_config td:eq(1)').remove();
182
+ $('#fanplayrsocialcoupons_config td').css('width', 'auto');
183
+ }
184
+
185
+ var fieldSet = fanplayrJQuery('#fanplayrsocialcoupons_config-head');
186
+ if (!fieldSet.hasClass('open')) {
187
+ // open it automatically !
188
+ try {
189
+ var a = fieldSet.attr('onclick');
190
+ eval(a.substr(0, a.indexOf('return')));
191
+ }catch(e){}
192
+ }
193
+
194
+ // set up some vars we need
195
+ Fanplayr.configAccKey = "{$accKey}";
196
+ Fanplayr.configSecret = "{$secret}";
197
+ Fanplayr.configSecretInner = "{$secretInner}";
198
+ Fanplayr.configShopId = "{$shopId}";
199
+ Fanplayr.configShopUrl = "{$shopUrl}";
200
+ });
201
+ </script>
202
+ <div id="fanplayrsocialcoupons-console" style="display:none;">
203
+ <div>
204
+ <p>Please be very careful when editing these values manually. Not for the faint of heart.</p>
205
+ <p>Disable on URLs: please provide a comma separated list of URLs on which to disable Fanplayr. By default Fanplayr is disabled for URLs containing "/checkout/onepage/" and "/checkout/multishipping/".</p>
206
+ <p>Embed Type: Do not use "Direct Embed" if you are using a Full Page Cache.</p>
207
+ </div>
208
+ <table>
209
+ <tr><td><label></label></td><td></td></tr>
210
+ <tr><td><label>Custom URL</label></td><td><input type="text" id="fanplayrsocialcoupons-console-url" name="fanplayrsocialcoupons-console-url" value="{$customShopUrlEdit}" /></td></tr>
211
+ <tr><td><label>Account Key</label></td><td><input type="text" id="fanplayrsocialcoupons-console-acckey" name="fanplayrsocialcoupons-console-acckey" value="{$accKey}" /></td></tr>
212
+ <tr><td><label>Secret</label></td><td><input type="text" id="fanplayrsocialcoupons-console-secret" name="fanplayrsocialcoupons-console-secret" value="{$secret}" /></td></tr>
213
+ <tr><td><label>Shop ID</label></td><td><input type="text" id="fanplayrsocialcoupons-console-shopid" name="fanplayrsocialcoupons-console-shopid" value="{$shopId}" /></td></tr>
214
+ <tr><td><label>Gamafied</label></td><td><input type="text" id="fanplayrsocialcoupons-console-gamafied" name="fanplayrsocialcoupons-console-gamafied" value="{$gamafiedKeys}" /></td></tr>
215
+ <tr><td><label>S &amp; T</label></td><td><input type="text" id="fanplayrsocialcoupons-console-snt" name="fanplayrsocialcoupons-console-snt" value="{$sntKeys}" /></td></tr>
216
+ <tr><td><label>Disable on URLs</label></td><td><input type="text" id="fanplayrsocialcoupons-console-disableonurls" name="fanplayrsocialcoupons-console-disableonurls" value="{$disableOnUrls}" /></td></tr>
217
+ <tr><td><label>Embed Type</label></td><td><select size="1" id="fanplayrsocialcoupons-console-embedtype" name="fanplayrsocialcoupons-console-embedtype">{$embedOptions}</select></td></tr>
218
+ <tr><td><label>Layout Hook (User: Home)</label></td><td><select size="1" id="fanplayrsocialcoupons-console-layouthookhome" name="fanplayrsocialcoupons-console-layouthookhome">{$layoutHooksHome}</select></td></tr>
219
+ <tr><td><label>Layout Hook (User: Other)</label></td><td><select size="1" id="fanplayrsocialcoupons-console-layouthook" name="fanplayrsocialcoupons-console-layouthook">{$layoutHooks}</select></td></tr>
220
+ <tr><td><label>Layout Hook (Order)</label></td><td><select size="1" id="fanplayrsocialcoupons-console-layouthookorder" name="fanplayrsocialcoupons-console-layouthookorder">{$layoutHooksOrder}</select></td></tr>
221
+ <tr><td colspan="2"><small>Please note this may cause problems on multi-site if you use different "websites".</small></td></tr>
222
+ <tr><td><label>Custom Embed URL</label></td><td><input type="text" id="fanplayrsocialcoupons-console-customembedurl" name="fanplayrsocialcoupons-console-customembedurl" value="{$customEmbedUrl}" /></td></tr>
223
+
224
+ <tr><td colspan="2"><b>Deputization</b></td></tr>
225
+ <tr><td><label>Prefix</label></td><td><input type="text" id="fanplayrsocialcoupons-console-depprefix" name="fanplayrsocialcoupons-console-depprefix" value="{$depPrefix}" /></td></tr>
226
+ <tr><td><label>Extra Routes</label></td><td><input type="text" id="fanplayrsocialcoupons-console-deproutes" name="fanplayrsocialcoupons-console-deproutes" value="{$depRoutes}" /></td></tr>
227
+ <tr><td><label>GTM Container Public ID</label></td><td><input type="text" id="fanplayrsocialcoupons-console-gtmcontainerid" name="fanplayrsocialcoupons-console-gtmcontainerid" value="{$gtmContainerId}" /></td></tr>
228
+ <tr><td><label>Trailing Slash (0 == no)</label></td><td><input type="text" id="fanplayrsocialcoupons-console-trailingslash" name="fanplayrsocialcoupons-console-trailingslash" value="{$trailingSlash}" /></td></tr>
229
+
230
+ <tr><td colspan="2"><a href="#" id="fanplayrsocialcoupons-console-save" onclick="Fanplayr.console.save(); return false;">Save</a> <a href="#" id="fanplayrsocialcoupons-console-hide" onclick="Fanplayr.console.hide(); return false;">Hide</a></td></tr>
231
+ </table>
232
+ <div id="fanplayrsocialcoupons-console-saving" style="display: none;"><b>Please be patient, saving ...</b></div>
233
+ </div>
234
+ EOT;
235
+ if (array_key_exists('fanplayrsocialcoupons-console-display', $_COOKIE) && $_COOKIE['fanplayrsocialcoupons-console-display'] == 'show') {
236
+ $generalHtml .= <<< EOT
237
+ <script>
238
+ document.getElementById('fanplayrsocialcoupons-console').style.display = 'block';
239
+ </script>
240
+ EOT;
241
+ }
242
+
243
+ // actual logic time !
244
+ // ------------------------------------------------------------------------
245
+
246
+ // the HTML to output to the admin control
247
+ $ouputHtml = '';
248
+
249
+ if (empty($secret) || empty($accKey) || empty($shopId)) {
250
+
251
+ // our install HTML
252
+ $installHtml = <<<EOT
253
+ <script>
254
+ fanplayrJQuery().ready(function() {
255
+ var $ = fanplayrJQuery;
256
+ var fanplayrInstallModal = new FanplayrModal('fanplayr_install_modal');
257
+ $('#fanplayr-install-button').on('click', function(e) {
258
+ e.preventDefault();
259
+ fanplayrInstallModal.load('{$skinDir}/fanplayr_join.html?{$queryString}');
260
+ });
261
+ });
262
+ </script>
263
+ <div id="fanplayr-install-wrapper">
264
+ <p>
265
+ <img src="{$skinDir}/images/fanplayr_logo.png" width="200" height="65" alt="Fanplayr Logo" title="Fanplayr" />
266
+ </p>
267
+ <div id="fanplayr-install-description">
268
+ <p>Welcome to Fanplayr, the leader in targeted conversions.</p>
269
+ <p>Click on the button below to get started by linking your Fanplayr account to your Magento Store. If you don't have an account yet you will have a chance to create one. Easy!</p>
270
+ </div>
271
+ <a href="#" id="fanplayr-install-button"><div class="fanplayr-icon fanplayr-add"></div>Link to Fanplayr</a>
272
+ </div>
273
+ EOT;
274
+ $outputHtml = $installHtml;
275
+ } else {
276
+ $errorGettingInstallData = false;
277
+ try {
278
+ $m = json_decode($this->httpGetContent('http://my.fanplayr.com/api.magentoCheckInstall/', array(
279
+ 'acc_key' => $accKey,
280
+ 'shop_id' => $shopId,
281
+ 'secret' => $secret,
282
+ 'version' => $this->getExtensionVersion()
283
+ )));
284
+ }catch (Exception $e) {
285
+ $errorGettingInstallData = true;
286
+ }
287
+ if (!$m) $errorGettingInstallData = true;
288
+
289
+ // just give 'em an error
290
+ if ($errorGettingInstallData) {
291
+ $outputHtml = 'Sorry, there was an error getting information about your installation. Please refresh to try again.';
292
+ }else{
293
+ // the server said there was an error
294
+ if ($m->error) {
295
+ $outputHtml = 'ERROR: ' . $m->message . ' - This may be due to a wrongly linked account. To unlink your account and try again <a href="#" onclick="Fanplayr.unlink();">click here</a>.';
296
+ // all is good, let's continue!
297
+ }else{
298
+
299
+ // if it's a new version warn 'em!
300
+ $newVersionWarningHtml = '';
301
+
302
+ if ($m->newVersion) {
303
+ $newVersionWarningHtml = $m->newVersion;
304
+ }
305
+
306
+ try {
307
+ $campData = addslashes($this->httpGetContent('http://my.fanplayr.com/api.magentoGetCampaigns/all/1/', array(
308
+ 'acc_key' => $accKey,
309
+ 'shop_id' => $shopId,
310
+ 'secret' => $secret,
311
+ 'version' => $this->getExtensionVersion()
312
+ )));
313
+ } catch (Exception $e) {
314
+ $campData = '';
315
+ }
316
+
317
+ $outputHtml = '';
318
+
319
+ if ($newVersionWarningHtml){
320
+ $outputHtml .= '<div id="fanplayr-new-version">' . $newVersionWarningHtml . '</div>';
321
+ }else {
322
+ $outputHtml .= '';
323
+ }
324
+
325
+ $outputHtml .= "<script> fanplayrCampData = null; try { fanplayrCampData = ";
326
+ $outputHtml .= $campData == '' ? 'null;' : 'fanplayrJQuery.parseJSON("'.$campData.'");';
327
+ $outputHtml .= "} catch(e){} </script>";
328
+
329
+ if (count($templatesWithNoFanplayr)) {
330
+ $outputHtml .= '<div id="fanplayr-template-warning"><span>'.count($templatesWithNoFanplayr).'</span> Magento templates do not include Fanplayr templates. This could cause Fanplayr to incorrectly track visitors on some or all pages. Please click the "Add Templates" button below.<br /><br />Optionally, you can do this manually by copying the Fanplayr templates from /app/design/frontend/base/default/template/fanplayr into the Magento templates in question.';
331
+ $outputHtml .= '<br /><br /><button onclick="Fanplayr.addTemplates(); return false;" id="fanplayr-template-warning-add" title="Add Templates" type="button" class="scalable save"><span>Add Templates</span></button>';
332
+ $outputHtml .= '</div>';
333
+ }
334
+
335
+ $outputHtml .= <<<EOT
336
+ <script>
337
+ fanplayrJQuery().ready(function() {
338
+ var $ = fanplayrJQuery;
339
+
340
+ $('#fanplayr-none-wrapper, #fanplayr-draft-wrapper, #fanplayr-head-wrapper').css('display','none');
341
+
342
+ Fanplayr.fillCampaignList($('#fanplayr-campaign-list'), fanplayrCampData);
343
+
344
+ if (Fanplayr.hasDraftCampaigns || Fanplayr.hasPublishedCampaigns || Fanplayr.hasRunningCampaigns) {
345
+ if (Fanplayr.hasPublishedCampaigns || Fanplayr.hasRunningCampaigns) {
346
+ $('#fanplayr-head-wrapper').css('display', 'block');
347
+ }else {
348
+ $('#fanplayr-draft-wrapper').css('display', 'block');
349
+ }
350
+ }
351
+ });
352
+ function refreshPage() {
353
+ window.location.reload();
354
+ }
355
+ </script>
356
+
357
+ <div id="fanplayr-none-wrapper">
358
+ <p>
359
+ <img src="{$skinDir}/images/fanplayr_logo.png" width="200" height="65" alt="Fanplayr Logo" title="Fanplayr" />
360
+ </p>
361
+ <div id="fanplayr-none-description">
362
+ <p>Your Store has been linked to Fanplayr, but you still need to create a campaign. Click below to get started.</p>
363
+ <p>You will have to <a href="#" onclick="refreshPage();">refresh</a> the page to see campaigns once you have created them.</p>
364
+ </div>
365
+ <a href="http://my.fanplayr.com/login/" id="fanplayr-start-button" target="_blank"><div class="fanplayr-icon fanplayr-icon-star"></div>Create a Fanplayr Campaign</a>
366
+ </div>
367
+ <script>
368
+ fanplayrJQuery().ready(function() {
369
+ if (fanplayrCampData == null || fanplayrCampData.campaigns.length == 0)
370
+ fanplayrJQuery('#fanplayr-none-wrapper').css('display', 'block');
371
+ });
372
+ </script>
373
+
374
+ <div id="fanplayr-draft-wrapper">
375
+ <p>
376
+ <img src="{$skinDir}/images/fanplayr_logo.png" width="200" height="65" alt="Fanplayr Logo" title="Fanplayr" />
377
+ </p>
378
+ <div id="fanplayr-draft-description">
379
+ <p>You've got a campaign but it's not quite ready to show on your store. Edit a current campaign, and once it's published you can show it on your Store.</p>
380
+ </div>
381
+ </div>
382
+
383
+ <div id="fanplayr-head-wrapper">
384
+ <p>
385
+ <img src="{$skinDir}/images/fanplayr_logo.png" width="200" height="65" alt="Fanplayr Logo" title="Fanplayr" />
386
+ </p>
387
+ <div id="fanplayr-head-description">
388
+ <p>Awesome. Looks like there's campaigns that can be running on the store!</p>
389
+ </div>
390
+ </div>
391
+
392
+ <table cellspacing="0" id="fanplayr-campaign-list"></table>
393
+ EOT;
394
+ }
395
+ }
396
+ }
397
+
398
+ //
399
+ // Return
400
+ return $generalHtml . $outputHtml;
401
+ }
402
+
403
+ // -------------------------------------------------------------------------
404
+ // helpers
405
+
406
+ private function getExtensionVersion()
407
+ {
408
+ return (string) Mage::getConfig()->getNode()->modules->Fanplayr_Socialcoupons->version;
409
+ }
410
+
411
+ // postVars as k/v array OR
412
+ private function httpGetContent($url, $vars = null)
413
+ {
414
+ $ch = curl_init();
415
+
416
+ curl_setopt($ch, CURLOPT_URL, $url);
417
+ curl_setopt($ch, CURLOPT_HEADER, 0);
418
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1) ;
419
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
420
+
421
+ if ($vars != null) {
422
+ // WTF ?
423
+ if (is_array($vars)) $vars = str_replace('&amp;', '&', http_build_query($vars));
424
+ //curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
425
+ //curl_setopt($ch, CURLOPT_POST, 1);
426
+ curl_setopt($ch, CURLOPT_URL, $url.'?'.$vars);
427
+ }
428
+
429
+ $r = curl_exec($ch);
430
+ curl_close($ch);
431
+
432
+ return $r;
433
+ }
434
+
435
+ public function updateConfig($key, $value)
436
+ {
437
+ Mage::getConfig()->saveConfig($key, $value);
438
+ Mage::getConfig()->reinit();
439
+ Mage::app()->reinitStores();
440
+ }
441
+ }
app/code/community/Fanplayr/Socialcoupons/Model/CartObserver.php ADDED
@@ -0,0 +1,89 @@
1
+ <?php
2
+ class Fanplayr_Socialcoupons_Model_CartObserver
3
+ {
4
+ public $hasSucceeded;
5
+
6
+ public function checkSavedCouponAction()
7
+ {
8
+ $couponCode = Mage::getSingleton('core/session')->getData('fanplayr_coupon');
9
+
10
+ if ($couponCode) {
11
+ $this->applyCoupon($couponCode);
12
+ if ($this->hasSucceeded) {
13
+ Mage::getSingleton('core/session')->setData('fanplayr_coupon', null);
14
+ }
15
+ }
16
+ }
17
+
18
+ public function applyCoupon($couponCode)
19
+ {
20
+ $itemInCart = true;
21
+ $this->hasSucceeded = true;
22
+
23
+ $quote = $this->getCurrentQuote();
24
+
25
+ if (!$quote->getItemsCount()) {
26
+ $itemInCart = false;
27
+ // store it for later use ...
28
+ $this->remember($couponCode);
29
+ $this->notice('There are currently no items in the shopping cart. We will try and apply your coupon code "' . $couponCode . '" once you have added some items to your cart.');
30
+ }
31
+
32
+ if ($itemInCart){
33
+
34
+ // ----------------------------------------
35
+ // check for deputized coupon and replace
36
+ $session = Mage::getSingleton("core/session");
37
+ $deputies = $session->getData("fanplayr_deputy_codes");
38
+ if (is_array($deputies) && array_key_exists($couponCode, $deputies)) {
39
+ // has to be done first so we get actual coupon
40
+ $session->setData('fanplayr_last_deputy_used', $couponCode);
41
+ $couponCode = array_key_exists($couponCode, $deputies) ? $deputies[$couponCode] : '';
42
+ }
43
+ try {
44
+ $quote->getShippingAddress()->setCollectShippingRates(true);
45
+ $quote->setCouponCode(strlen($couponCode) ? $couponCode : '')
46
+ ->collectTotals()
47
+ ->save();
48
+ } catch (Exception $e) {
49
+ $this->error('Cannot apply coupon code: ' . $e-> getMessage());
50
+ $this->hasSucceeded = false;
51
+ return;
52
+ }
53
+
54
+ if ($couponCode) {
55
+ if ($couponCode != $quote->getCouponCode()) {
56
+ $this->error('Coupon code is invalid');
57
+ $this->hasSucceeded = false;
58
+ return;
59
+ }
60
+ }
61
+
62
+ if ($this->hasSucceeded) {
63
+ $this->success('Your coupon has been applied.');
64
+ }
65
+ }
66
+ }
67
+
68
+ public function getCurrentQuote($quoteId)
69
+ {
70
+ return Mage::getSingleton('checkout/session')->getQuote();
71
+ }
72
+
73
+ // TODO: multilingual this
74
+ public function error($message)
75
+ {
76
+ Mage::getSingleton('core/session')->addError($message);
77
+ $this->hasSucceeded = false;
78
+ }
79
+
80
+ public function success($message)
81
+ {
82
+ Mage::getSingleton('core/session')->addSuccess($message);
83
+ }
84
+
85
+ public function notice($message)
86
+ {
87
+ Mage::getSingleton('core/session')->addNotice($message);
88
+ }
89
+ }
app/code/community/Fanplayr/Socialcoupons/Model/EmbedObserver.php ADDED
@@ -0,0 +1,637 @@
1
+ <?php
2
+ class Fanplayr_Socialcoupons_Model_EmbedObserver
3
+ {
4
+ public function getEmbedAction()
5
+ {
6
+ $r = Mage::app()->getRequest();
7
+ $pCnt = $r->getControllerName(); // onepage, multishipping, cart
8
+ $pAct = $r->getActionName(); // index
9
+ $pRte = $r->getRouteName(); // checkout
10
+ $pMod = $r->getModuleName(); // checkout
11
+
12
+ if ($pMod == 'admin')
13
+ return;
14
+
15
+ $_ac = Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key');
16
+ if (empty($_ac))
17
+ return;
18
+
19
+ $atPayment = $pMod == 'checkout' && $pCnt != 'cart';
20
+ $atCart = $pMod == 'checkout' && $pCnt == 'cart';
21
+
22
+ // AIT checkout compatability
23
+ $atCart = $pMod == 'aitcheckout'&& $pCnt == 'checkout';
24
+
25
+ // StreamCheckout
26
+ $atCart = $pRte == 'streamcheckout'&& $pMod == 'streamcheckout';
27
+
28
+ // DEPUTIES: if we have cookies set then reset it to 3 hours later
29
+ // so we don't forget
30
+ $cookie = Mage::getSingleton('core/cookie');
31
+ $d = $cookie->get('fanplayr_deputy_codes');
32
+ if ($d) $cookie->set('fanplayr_deputy_codes', $d, 10800, '/');
33
+
34
+ // v1.0.14: added this to allow disabling on specific URLs
35
+ $disableThisUrl = false;
36
+ $disabledUrlString = Mage::getStoreConfig('fanplayrsocialcoupons/config/disable_on_urls');
37
+ if (!empty($disabledUrlString)) {
38
+ $disabledUrls = explode(',', $disabledUrlString);
39
+ if (count($disabledUrls)) {
40
+ $currentUrl = Mage::helper('core/url')->getCurrentUrl();
41
+ foreach($disabledUrls as $url) {
42
+ $url = trim($url);
43
+ if (strstr($currentUrl, $url) !== false) {
44
+ $disableThisUrl = true;
45
+ break;
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ // don't show at payment, or custom disabled URLs
52
+ if (!$atPayment && !$disableThisUrl) {
53
+
54
+ $block = Mage::getSingleton('core/layout')->createBlock(
55
+ 'Mage_Core_Block_Template',
56
+ 'fanplayr_embed_block'
57
+ );
58
+
59
+
60
+ // this variable has changed from simply doing "wait for onload" to being for differnt types
61
+ // 0: Ajax: Normal
62
+ // 1: Ajax: Lazy load
63
+ // 2: TMS: User Only
64
+ // 3: TMS: User and Order
65
+ // 4: No Ajax: Normal
66
+ // 5: No Ajax: Lazy Load
67
+ // 6: Ajax: Normal, GTM
68
+ // 7: Ajax: Normal, GTM Extended
69
+ $embedType = intval(Mage::getStoreConfig('fanplayrsocialcoupons/config/wait_for_onload'));
70
+
71
+ $directEmbed = true;
72
+ // ajax embeds
73
+ if ($embedType >= 0 && $embedType <= 3 || $embedType == 6 || $embedType = 7) {
74
+ $directEmbed = false;
75
+ }
76
+
77
+ if ($directEmbed){
78
+ $block->setTemplate('fanplayr/embed.phtml');
79
+ }else{
80
+ $block->setTemplate('fanplayr/embed_ajax.phtml');
81
+ }
82
+
83
+ // enc data
84
+ $pageType = '';
85
+ $currentProduct = '';
86
+ $currentProductName = '';
87
+ $currentCategory = '';
88
+ $currentCategoryName = '';
89
+
90
+ $pageType = $this->getPageType();
91
+
92
+ if ($pageType == 'prod') {
93
+ // just in case we'll protect with @
94
+ @$cP = Mage::registry('current_product');
95
+ if ($cP){
96
+ $currentProduct = $cP->getId();
97
+ $currentProductName = $cP->getName();
98
+
99
+ $categories = $cP->getCategoryIds();
100
+ foreach($categories as $k => $_category_id){
101
+ $_category = Mage::getModel('catalog/category')->load($_category_id);
102
+ $currentCategory = $_category->getId();
103
+ $currentCategoryName = $_category->getName();
104
+ break;
105
+ }
106
+ }
107
+ } else if ($pageType == 'cat') {
108
+ // url for category ?
109
+ @$cC = Mage::registry('current_category');
110
+ if ($cC) {
111
+ $currentCategory = $cC->getId();
112
+ $currentCategoryName = $cC->getName();
113
+ }
114
+ }
115
+
116
+ // shop URL
117
+ $shopUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
118
+ if (!strpos($shopUrl, 'index.php/'))
119
+ $shopUrl .= 'index.php/';
120
+ $customEmbedUrl = trim(Mage::getStoreConfig('fanplayrsocialcoupons/config/custom_embed_url'));
121
+ if (!empty($customEmbedUrl)) $shopUrl = $customEmbedUrl;
122
+
123
+ $block->assign('shopUrl', $shopUrl);
124
+
125
+ if (!$directEmbed){
126
+ $block->assign('tt', $pageType);
127
+ $block->assign('tp', $currentProduct);
128
+ $block->assign('tc', $currentCategory);
129
+
130
+ $block->assign('tpn', $currentProductName);
131
+ $block->assign('tcn', $currentCategoryName);
132
+ }else {
133
+ // direct embed so we need to set some other things we'd normally set in AjaxController
134
+ // store session data in case the cookie is lost somehow
135
+ $sessionVars = $this->decodeSessionCookie('fanplayr_genius_session');
136
+ if ($sessionVars) {
137
+ $session = Mage::getModel('core/session');
138
+ if ($session){
139
+ if (array_key_exists('key', $sessionVars)) $session->setData('fanplayr_session_session_key',$sessionVars['key']);
140
+ if (array_key_exists('user', $sessionVars)) $session->setData('fanplayr_session_user_key', $sessionVars['user']);
141
+ }
142
+ }
143
+
144
+ $block->assign('widgetKeys', Mage::getStoreConfig('fanplayrsocialcoupons/config/widget_keys'));
145
+ $block->assign('widgetKeysGenius', Mage::getStoreConfig('fanplayrsocialcoupons/config/widget_keys_genius'));
146
+ $block->assign('accountKey', Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key'));
147
+
148
+ $block->assign('applyToCartUrl', $shopUrl . 'fanplayr/coupon/add/code/%c/');
149
+ $block->assign('depitizeUrl', $shopUrl . 'fanplayr/coupon/deputize/a/%a/d/%d/');
150
+
151
+ $block->assign('noTags', false);
152
+
153
+ $data = $this->getData(
154
+ ($pageType == 'cart'),
155
+ $pageType,
156
+ $currentProduct,
157
+ $currentCategory,
158
+ $currentProductName,
159
+ $currentCategoryName
160
+ );
161
+
162
+ $block->assign('data', $data);
163
+ }
164
+
165
+ $trailingSlash = Mage::getStoreConfig('fanplayrsocialcoupons/config/trailing_slash');
166
+ var_dump('xxxxxxxxxxxxxx');
167
+ var_dump($trailingSlash);
168
+ if ($trailingSlash == '0') {
169
+ $trailingSlash = '';
170
+ }else{
171
+ $trailingSlash = '/';
172
+ }
173
+ var_dump($trailingSlash);
174
+ $block->assign('embedType', $embedType);
175
+ $block->assign('trailingSlash', $trailingSlash);
176
+
177
+ $currentLayoutHook = Mage::getStoreConfig('fanplayrsocialcoupons/config/layout_hook' . ($pageType == 'home' ? '_home' : ''));
178
+ if (!$currentLayoutHook)
179
+ $currentLayoutHook = 'content';
180
+
181
+ $contentBlock = Mage::getSingleton('core/layout')->getBlock($currentLayoutHook);
182
+ if ($contentBlock) $contentBlock->insert($block);
183
+ }
184
+ }
185
+
186
+ public static function getData($atCart = null, $pageType = null, $currentProduct = null, $currentCategory = null, $currentProductName = null, $currentCategoryName = null)
187
+ {
188
+ $itemCount = 0;
189
+ $itemQty = 0;
190
+ $subtotal = 0;
191
+ $discount = 0;
192
+ $custEmail = '';
193
+ $custId = '';
194
+ $couponCode = '';
195
+ $currencyIso = '';
196
+ $custSegment = '';
197
+ $custGroup = '';
198
+
199
+ $products = array();
200
+ $productString = '';
201
+
202
+ // get the current customer
203
+ $customer = Mage::getSingleton('customer/session');
204
+ $custGroup = $customer->getCustomerGroupId();
205
+
206
+ $customerId = $customer->getCustomerId();
207
+ if (self::isMageEnterprise()){
208
+ $websiteId = Mage::app()->getStore()->getWebsiteId();
209
+ $segments = Mage::getModel('enterprise_customersegment/customer')->getCustomerSegmentIdsForWebsite($customerId,$websiteId);
210
+ $custSegment = implode(',', $segments);
211
+ }
212
+
213
+ // get cart data
214
+ $cartData = null;
215
+ $cartMod = Mage::getSingleton('checkout/session');
216
+
217
+ $mageV = Mage::getVersion();
218
+ $mageVa = explode('.', $mageV);
219
+
220
+ if ($cartMod) {
221
+ $quote = $cartMod->getQuote();
222
+ if ($quote) {
223
+
224
+ $session = Mage::getSingleton("core/session");
225
+
226
+ $updateProductDetails = $session->getData("fanplayr_update_product_details");
227
+ if ($updateProductDetails === true || $updateProductDetails === null) {
228
+
229
+ //Mage::log('Updating product details JSON');
230
+
231
+ $products = self::getProductsFromQuote($quote);
232
+
233
+ $productString = addslashes(json_encode($products));
234
+ $session->setData("fanplayr_product_cache", $productString);
235
+
236
+ $session->setData("fanplayr_update_product_details", false);
237
+ }else{
238
+ $productCache = $session->getData("fanplayr_product_cache");
239
+ if (strlen($productCache) > 0) {
240
+ $productString = $productCache;
241
+ }else{
242
+ // empty array JSON of products
243
+ $productString = "[]";
244
+ }
245
+ }
246
+
247
+ $cartData = $quote->getData();
248
+
249
+ $itemCount = array_key_exists('items_count', $cartData) ? $cartData['items_count'] : 0;
250
+ $itemQty = array_key_exists('items_qty', $cartData) ? $cartData['items_qty'] : 0;
251
+
252
+ $custEmail = array_key_exists('customer_email', $cartData) ? $cartData['customer_email'] : '';
253
+ $custId = array_key_exists('customer_id', $cartData) ? $cartData['customer_id'] : '';
254
+ $couponCode = array_key_exists('coupon_code', $cartData) ? $cartData['coupon_code'] : '';
255
+ $currencyIso = array_key_exists('quote_currency_code', $cartData) ? $cartData['quote_currency_code'] : '';
256
+
257
+ // before discount
258
+ $subtotal = array_key_exists('subtotal', $cartData) ? $cartData['subtotal'] : 0;
259
+ $discount = array_key_exists('subtotal_with_discount', $cartData) ? $subtotal - $cartData['subtotal_with_discount'] : 0;
260
+ // after discount, before shipping / tax
261
+ $total = array_key_exists('subtotal_with_discount', $cartData) ? $cartData['subtotal_with_discount'] : 0;
262
+ }
263
+ }
264
+
265
+ $storeCode = Mage::app()->getStore()->getCode();
266
+ $gtmContainerId = Mage::getStoreConfig('fanplayrsocialcoupons/config/gtm_container_id');
267
+
268
+ $data = array(
269
+ 'atCart' => $atCart,
270
+ 'lineItemCount' => (int)$itemCount,
271
+ 'numItems' => (int)$itemQty,
272
+ 'total' => (float)$total,
273
+ 'subTotal' => (float)$subtotal,
274
+ 'discount' => (float)$discount,
275
+ 'customerEmail' => $custEmail,
276
+ 'couponCode' => $couponCode,
277
+ 'currency' => $currencyIso,
278
+ 'customerId' => $custId,
279
+ 'customerSegment' => $custSegment,
280
+ 'customerGroup' => $custGroup,
281
+ 'pageType' => $pageType,
282
+ 'productId' => $currentProduct,
283
+ 'productName' => $currentProductName,
284
+ 'categoryId' => $currentCategory,
285
+ 'categoryName' => $currentCategoryName,
286
+ 'version' => 3,
287
+ 'shopType' => 'magento',
288
+ 'products' => $productString,
289
+ 'storeCode' => $storeCode,
290
+ 'gtmContainerId' => $gtmContainerId
291
+ );
292
+
293
+ return $data;
294
+ }
295
+
296
+ function getPageType()
297
+ {
298
+ // pageType, currentPRoduct, currentCategory
299
+ // tt: home, cart, page, srch, cat, prod, blog
300
+ $r = Mage::app()->getRequest();
301
+ $pCnt = $r->getControllerName();
302
+ $pAct = $r->getActionName();
303
+ $pRte = $r->getRouteName();
304
+ $pMod = $r->getModuleName();
305
+
306
+ // home
307
+ // index, index, cms, cms
308
+ if ($pCnt == 'index' && $pAct == 'index' && $pRte == 'cms') {
309
+ return 'home';
310
+ }
311
+
312
+ // product
313
+ // product, view, catalog, catalog
314
+ if ($pCnt == 'product') {
315
+ return 'prod';
316
+ }
317
+
318
+ // category
319
+ // category, view, catalog, catalog
320
+ if ($pCnt == 'category') {
321
+ return 'cat';
322
+ }
323
+
324
+ // search
325
+ // result, index, catalogsearch, catalogsearch
326
+ // advanced, index, catalogsearch, catalogsearch
327
+ // term, popular, catalogsearch, catalogsearch
328
+ // seo_sitemap, category, catalog, catalog
329
+ if ($pCnt == 'result' || $pCnt == 'advanced' || $pCnt == 'term' || $pCnt == 'seo_sitemap') {
330
+ return 'srch';
331
+ }
332
+
333
+ // cart
334
+ // cart, index, checkout, checkout
335
+ if ($pCnt == 'cart') {
336
+ return 'cart';
337
+ }
338
+
339
+ // blog (nah !)
340
+
341
+ // page
342
+ // page, view, cms, cms
343
+ // index, index, contacts, contacts
344
+ // guest, form, sales, sales
345
+ return 'page';
346
+ }
347
+
348
+ public static function isMageEnterprise() {
349
+ return Mage::getConfig ()->getModuleConfig ( 'Enterprise_Enterprise' ) && Mage::getConfig ()->getModuleConfig ( 'Enterprise_AdminGws' ) && Mage::getConfig ()->getModuleConfig ( 'Enterprise_Checkout' ) && Mage::getConfig ()->getModuleConfig ( 'Enterprise_Customer' );
350
+ }
351
+
352
+ public static function isMageProfessional() {
353
+ return Mage::getConfig ()->getModuleConfig ( 'Enterprise_Enterprise' ) && !Mage::getConfig ()->getModuleConfig ( 'Enterprise_AdminGws' ) && !Mage::getConfig ()->getModuleConfig ( 'Enterprise_Checkout' ) && !Mage::getConfig ()->getModuleConfig ( 'Enterprise_Customer' );
354
+ }
355
+
356
+ public static function isMageCommunity() {
357
+ return !self::isMageEnterprise() && !self::isMageProfessional();
358
+ }
359
+
360
+ // -------------------------------------------------------------------
361
+ // coupon deputization
362
+
363
+ // called before outpout, replaced coupons with deputized coupons
364
+ // called on http_response_send_before
365
+ //
366
+ public function deputizeReplaceAction($observer)
367
+ {
368
+ $response = $observer->getResponse();
369
+ if (!$response) return;
370
+
371
+ $session = Mage::getSingleton("core/session");
372
+ $lastDeputiesUsed = $session->getData("fanplayr_used_deputies");
373
+
374
+ // don't even bother to go further if we haven't used a deputized code
375
+ if (!is_array($lastDeputiesUsed)) {
376
+ return;
377
+ }
378
+
379
+ // ------------------------------------------------------
380
+ // only for pages we want
381
+ $r = Mage::app()->getRequest();
382
+ $pCnt = $r->getControllerName(); // onepage, multishipping, cart
383
+ $pAct = $r->getActionName(); // index
384
+ $pRte = $r->getRouteName(); // checkout
385
+ $pMod = $r->getModuleName(); // checkout
386
+
387
+ // full route
388
+ $route = $pCnt.'/'.$pAct.'/'.$pRte.'/'.$pMod;
389
+
390
+ $extraAllowedRoutes = array();
391
+ $depRoutes = Mage::getStoreConfig('fanplayrsocialcoupons/config/dep_extra_rewrite_routes');
392
+ // just in case we have problems here we don't want it to freak out
393
+ try {
394
+ $extraAllowedRoutes = array_merge($extraAllowedRoutes, explode(',', $depRoutes));
395
+ }catch (Exception $e) {
396
+ $extraAllowedRoutes = array();
397
+ }
398
+
399
+ // checkout pages, order view pages
400
+ if (
401
+ ($pMod == 'checkout' && $pAct != 'success')
402
+ || $route == 'order/view/sales/sales'
403
+ || $route == 'index/index/onestepcheckout/onestepcheckout' // osc
404
+ || $route == 'ajax/add_coupon/onestepcheckout/onestepcheckout' // osc
405
+ || $route == 'ajax/set_methods_separate/onestepcheckout/onestepcheckout' // osc
406
+ || $route == 'checkout/updateSteps/aitcheckout/aitcheckout' //AIT checkout
407
+ || $route == 'cart/couponPost/aitcheckout/aitcheckout' //AIT checkout
408
+ || $route == 'checkout/index/aitcheckout/aitcheckout' //AIT checkout
409
+ || $route == 'index/index/streamcheckout/streamcheckout' // StreamCheckout by Made People
410
+ || $route == 'index/saveAll/streamcheckout/streamcheckout' // StreamCheckout (AJAX)
411
+ || $route == 'index/applyCoupon/streamcheckout/streamcheckout' // StreamCheckout (Coupon)
412
+ || in_array($route, $extraAllowedRoutes)
413
+ ){
414
+ // do nothing
415
+ }else {
416
+ // yes I know this is a silly way to "else return"
417
+ // but it makes the above code cleaner
418
+ return;
419
+ }
420
+
421
+ // ------------------------------------------------------
422
+ // now we should be doing the deputization
423
+ // as we are only doing a simple search/replace this is
424
+ // why we REQUIRE a "prefix" as to not destroy any
425
+ // HTML tags etc
426
+
427
+ $deputies = $session->getData("fanplayr_deputy_codes");
428
+
429
+ // cookie fallback
430
+ if (!$deputies) {
431
+ $cookie = Mage::getSingleton('core/cookie');
432
+ $d = $cookie->get('fanplayr_deputy_codes');
433
+ if ($d) $deputies = (Array)json_decode($d);
434
+ }
435
+
436
+ $html = $response->getBody();
437
+
438
+ foreach($lastDeputiesUsed as $lastDeputyUsed){
439
+ if (is_array($deputies) && array_key_exists($lastDeputyUsed, $deputies)) {
440
+
441
+ // replace deputies
442
+ if (array_key_exists($lastDeputyUsed, $deputies))
443
+ $html = str_replace($deputies[$lastDeputyUsed], $lastDeputyUsed, $html);
444
+ }
445
+ }
446
+
447
+ $response->setBody($html);
448
+ }
449
+
450
+ // used when a user inputs a coupon,
451
+ // called on controller_action_predispatch
452
+ public function deputizeInputAction($observer)
453
+ {
454
+ $r = Mage::app()->getRequest();
455
+ $pCnt = $r->getControllerName(); // onepage, multishipping, cart
456
+ $pAct = $r->getActionName(); // index
457
+ $pRte = $r->getRouteName(); // checkout
458
+ $pMod = $r->getModuleName(); // checkout
459
+
460
+ $route = $pCnt . '/' . $pAct . '/' . $pRte . '/' . $pMod;
461
+
462
+ // which input do we use?
463
+ $inpVar = 'coupon_code';
464
+ $setPost = false;
465
+
466
+ // one step checkout
467
+ if ($route == 'ajax/add_coupon/onestepcheckout/onestepcheckout') {
468
+ $inpVar = 'code';
469
+ }
470
+
471
+ // amasty cancel
472
+ if ($route == 'checkout/cancelCoupon/amcoupons/amcoupons') {
473
+ $inpVar = 'amcoupon_code_cancel';
474
+ }
475
+
476
+ // AIT Checkout
477
+ if ($route == 'cart/couponPost/aitcheckout/aitcheckout') {
478
+ // it uses 'getPost' rather than 'getParam'
479
+ $setPost = true;
480
+ }
481
+
482
+ // StreamCheckout: uses POST
483
+ if ($route == 'index/applyCoupon/streamcheckout/streamcheckout') {
484
+ $setPost = true;
485
+ }
486
+
487
+ // special for StreamCheckout SaveOrder
488
+ if ($route == 'index/saveOrder/streamcheckout/streamcheckout') {
489
+ $setPost = true;
490
+ $inpVar = 'stream_coupon_code';
491
+ }
492
+
493
+ $depCoupon = Mage::app()->getRequest()->getParam($inpVar); // normal coupon
494
+ $disallowedPrefix = Mage::getStoreConfig('fanplayrsocialcoupons/config/dep_prefix');
495
+
496
+ // remove spaces
497
+ $depCoupon = trim($depCoupon);
498
+
499
+ // if someone enters the actual code, and it is a prefix code
500
+ // then set it to prefix with "..." on the end
501
+ if (strpos($depCoupon, $disallowedPrefix) === 0) {
502
+ Mage::app()->getRequest()->setParam($inpVar, $disallowedPrefix . '...');
503
+ if ($setPost) Mage::app()->getRequest()->setPost($inpVar, $disallowedPrefix . '...');
504
+ return;
505
+ }
506
+
507
+ $session = Mage::getSingleton("core/session");
508
+ $deputies = $session->getData("fanplayr_deputy_codes");
509
+
510
+ // cookie fallback
511
+ if (!$deputies) {
512
+ $cookie = Mage::getSingleton('core/cookie');
513
+ $d = $cookie->get('fanplayr_deputy_codes');
514
+ if ($d) $deputies = (Array)json_decode($d);
515
+ }
516
+
517
+ if (is_array($deputies) && array_key_exists($depCoupon, $deputies)) {
518
+ $actualCoupon = array_key_exists($depCoupon, $deputies) ? $deputies[$depCoupon] : '';
519
+
520
+ // must be set first to get actual coupon
521
+ // need to set as array, to support those horrible multi-coupon extensions
522
+ $sessionDeps = $session->getData('fanplayr_used_deputies');
523
+ if (!is_array($sessionDeps))
524
+ $sessionDeps = array();
525
+ // and only add it if it's not there so no duplicates
526
+ if (!in_array($depCoupon, $sessionDeps))
527
+ array_push($sessionDeps, $depCoupon);
528
+ $session->setData('fanplayr_used_deputies', $sessionDeps);
529
+
530
+ Mage::app()->getRequest()->setParam($inpVar, $actualCoupon);
531
+ if ($setPost) Mage::app()->getRequest()->setPost($inpVar, $actualCoupon);
532
+ }
533
+ }
534
+
535
+ // when adding a product we should refresh product info on next call
536
+ public function checkQuoteAddAction($observer)
537
+ {
538
+ $session = Mage::getSingleton("core/session");
539
+ $session->setData("fanplayr_update_product_details", true);
540
+ }
541
+
542
+ // when removing a product we should refresh product info on next call
543
+ public function checkQuoteRemoveAction($observer)
544
+ {
545
+ $session = Mage::getSingleton("core/session");
546
+ $session->setData("fanplayr_update_product_details", true);
547
+ }
548
+
549
+ // when updating a product we should refresh product info on next call
550
+ // we only do this for checkout 'updatePost' and 'delete' actions though
551
+ // update is called many many times for simple things like cart views
552
+ public function checkQuoteUpdateQtyAction($observer)
553
+ {
554
+ $r = Mage::app()->getRequest();
555
+ $pCnt = $r->getControllerName(); // onepage, multishipping, cart
556
+ $pAct = $r->getActionName(); // index
557
+ $pRte = $r->getRouteName(); // checkout
558
+ $pMod = $r->getModuleName(); // checkout
559
+
560
+ $route = "$pMod/$pRte/$pAct/$pCnt";
561
+ if ($route == "checkout/checkout/updatePost/cart"
562
+ || $route == "checkout/checkout/delete/cart") {
563
+ $session = Mage::getSingleton("core/session");
564
+ $session->setData("fanplayr_update_product_details", true);
565
+ }
566
+ }
567
+
568
+ // -------------------------------------------------------------------
569
+ // gets an array of all products from cart with needed details for tracking
570
+ // quite expensive so should only be called when it has changed
571
+
572
+ private static function getProductsFromQuote($quote)
573
+ {
574
+ $products = array();
575
+
576
+ foreach ($quote->getAllVisibleItems() as $item) {
577
+
578
+ if ($option = $item->getOptionByCode('simple_product')) {
579
+ $p = $option->getProduct();
580
+ } else {
581
+ $p = $item->getProduct();
582
+ }
583
+
584
+ // bug in Magento 1.5 and below?
585
+ // just make sure it doesn't break things!
586
+ $sku = '';
587
+ try { $sku = !$p ? '' : $p->getSku(); }catch(Exception $e){}
588
+
589
+ $products[] = array(
590
+ 'qty' => $item->getQty(),
591
+ 'price' => $item->getCalculationPrice(),
592
+ 'catName' => '',
593
+ 'id' => !$p ? '' : $p->getId(),
594
+ 'sku' => $sku,
595
+ 'name' => $item->getName(),
596
+ 'catId' => !$p ? '' : implode(',', $p->getCategoryIds())
597
+ );
598
+ }
599
+
600
+ return $products;
601
+ }
602
+
603
+ // -------------------------------------------------------------------
604
+ // decode session cookie
605
+
606
+ // in case sessions aren't being sent through correctly
607
+ // we will store this each hit, and then get it back later
608
+
609
+ private function decodeSessionCookie( $cookie_name )
610
+ {
611
+ if ( array_key_exists($cookie_name, $_COOKIE) && !empty($_COOKIE[$cookie_name]) ) {
612
+ $data = array();
613
+ $params = explode(';', $_COOKIE[$cookie_name]);
614
+
615
+ foreach ( $params as $param ) {
616
+ $parts = explode('=', $param);
617
+ if (count($parts) != 2)
618
+ continue;
619
+
620
+ $type = substr($parts[1], 0, 1);
621
+ $value = substr($parts[1], 1);
622
+
623
+ if ( empty($type) ) continue;
624
+
625
+ if ( $type === 'n' || $type === 'u' ) { $value = null; }
626
+ if ( $type === 'b' ) { $value = (intval($value, 10) !== 0); }
627
+ if ( $type === 'f' ) { $value = floatval($value); }
628
+ if ( $type === 's' ) { $value = urldecode($value); }
629
+
630
+ $data[urldecode($parts[0])] = $value;
631
+ }
632
+
633
+ return $data;
634
+ }
635
+ return null;
636
+ }
637
+ }
app/code/community/Fanplayr/Socialcoupons/Model/OrderObserver.php ADDED
@@ -0,0 +1,349 @@
1
+ <?php
2
+ class Fanplayr_Socialcoupons_Model_OrderObserver
3
+ {
4
+ // normal flow for single address orders
5
+ public function checkSuccessSingle($observer)
6
+ {
7
+ $this->afterSuccessfulOrder($observer->getData('order_ids'));
8
+ }
9
+
10
+ // normal flow for multi address orders
11
+ public function checkSuccessMulti($observer)
12
+ {
13
+ $this->afterSuccessfulOrder($observer->getData('order_ids'));
14
+ }
15
+
16
+ // normal flow fro multi or single address orders
17
+ // this is not the flow for external paypal payments and such
18
+ private function afterSuccessfulOrder($lastOrderId)
19
+ {
20
+ // only do embed (or even get data for it) if we have an account key - ie we are linked
21
+ $accountKey = Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key');
22
+ if (empty($accountKey))
23
+ return;
24
+
25
+ $errors = '';
26
+
27
+ $secret = Mage::getStoreConfig('fanplayrsocialcoupons/config/secret');
28
+
29
+ if (is_array($lastOrderId))
30
+ $lastOrderId = $lastOrderId[0];
31
+
32
+ // get the main order data, offloaded here as we also use this in the server-server route
33
+ $data = $this->getLastOrderInformation($lastOrderId);
34
+
35
+ // get session data if we can
36
+ $session = null;
37
+ $sessionKey = '';
38
+ $userKey = '';
39
+ try {
40
+ $session = Mage::getModel('core/session');
41
+ }catch(Exception $e){}
42
+
43
+ if ($session) {
44
+ $sessionKey = $session->getData('fanplayr_session_session_key');
45
+ $userKey = $session->getData('fanplayr_session_user_key');
46
+ }
47
+
48
+ $data = array_merge($data, array(
49
+ 'accountKey' => $accountKey,
50
+ 'shopType' => 'magento',
51
+ 'version' => 3,
52
+ 'sessionKey' => $sessionKey,
53
+ 'userKey' => $userKey,
54
+ 'errors' => $errors
55
+ ));
56
+
57
+ // add the embed type
58
+ // this variable has changed from simply doing "wait for onload" to being for differnt types
59
+ $data['embedType'] = intval(Mage::getStoreConfig('fanplayrsocialcoupons/config/wait_for_onload'));
60
+
61
+ // ------------------------------------------------------------------
62
+ // do the embed
63
+ // normaly in the content block, but may be changed
64
+
65
+ $block = Mage::getSingleton('core/layout')->createBlock(
66
+ 'Mage_Core_Block_Template',
67
+ 'fanplayr_embed_block',
68
+ array('template' => 'fanplayr/success.phtml')
69
+ )->assign('data', $data);
70
+
71
+ $currentLayoutHook = Mage::getStoreConfig('fanplayrsocialcoupons/config/layout_hook_order');
72
+ if (!$currentLayoutHook)
73
+ $currentLayoutHook = 'content';
74
+
75
+ $contentBlock = Mage::getSingleton('core/layout')->getBlock($currentLayoutHook);
76
+ if ($contentBlock) $contentBlock->insert($block);
77
+ }
78
+
79
+ // sales_order_place_after
80
+ public function serverToServerTrackingBeforePayment($ob)
81
+ {
82
+ $this->serverToServerTracking($ob->order);
83
+ }
84
+
85
+ // called on "sales_order_invoice_save_commit_after", after payment
86
+ public function serverToServerTrackingAfterPayment($ob)
87
+ {
88
+ $this->serverToServerTracking($ob->getEvent()->getInvoice()->getOrder());
89
+ }
90
+
91
+ // used for tracking payments that don't go through the normal flow
92
+ private function serverToServerTracking($order)
93
+ {
94
+ try {
95
+
96
+ $accountKey = Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key');
97
+ if (!$accountKey) return;
98
+
99
+ //$order = $ob->order;
100
+
101
+ $state = $order->getState();
102
+ $method = $order->getPayment()->getMethod();
103
+
104
+ // only paypal_standard supported ATM
105
+ if ($method == 'paypal_standard'){
106
+
107
+ $url = '';
108
+ $params = array();
109
+
110
+ // order created, let's tell Fanplayr to link details at a later time
111
+ if ($state == Mage_Sales_Model_Order::STATE_PENDING_PAYMENT) {
112
+
113
+ $url .= 'http://my.fanplayr.com/api.track.v1.ordercreated/';
114
+
115
+ // we will only have these on the before
116
+ // get session data if we can
117
+ $session = null;
118
+ $sessionKey = '';
119
+ $userKey = '';
120
+ try {
121
+ $session = Mage::getModel('core/session');
122
+ }catch(Exception $e){}
123
+ if ($session) {
124
+ $sessionKey = $session->getData('fanplayr_session_session_key');
125
+ $userKey = $session->getData('fanplayr_session_user_key');
126
+ }
127
+
128
+ $params['id'] = $order->getId();
129
+ $params['number'] = $order->getIncrementId(); // getNumber don't work here ...
130
+
131
+ $params['accountkey'] = $accountKey;
132
+ $params['sessionkey'] = $sessionKey;
133
+ $params['userkey'] = $userKey;
134
+
135
+ // log the order with Fanplayr
136
+ } else if ($state == Mage_Sales_Model_Order::STATE_PROCESSING) {
137
+
138
+ $url .= 'http://my.fanplayr.com/api.track.v1.orderpaid/';
139
+
140
+ // get order info
141
+ $data = $this->getLastOrderInformation($order->getId());
142
+
143
+ $params['domain'] = Mage::getUrl();
144
+ $params['shoptype'] = 'magento';
145
+
146
+ $params['id'] = $data['orderId'];
147
+ $params['number'] = $data['orderNumber'];
148
+
149
+ $params['email'] = $data['orderEmail'];
150
+ $params['date'] = $data['orderDate'];
151
+ $params['total'] = $data['total'];
152
+ $params['subTotal'] = $data['subTotal'];
153
+ $params['discountamount'] = $data['discount'];
154
+ $params['discountcode'] = $data['discountCode'];
155
+ $params['firstname'] = $data['firstName'];
156
+ $params['lastname'] = $data['lastName'];
157
+ $params['customeremail'] = $data['customerEmail'];
158
+ $params['customerid'] = $data['customerId'];
159
+ $params['shipping'] = $data['shipping'];
160
+ $params['tax'] = $data['tax'];
161
+ $params['products'] = json_encode($data['products']);
162
+
163
+ $params['accountkey'] = $accountKey;
164
+
165
+ // we don't have these afterwards but we should send through anyway
166
+ $params['sessionkey'] = '';
167
+ $params['userkey'] = '';
168
+ }
169
+
170
+ // now if we set a URL call it!
171
+ if ($url) {
172
+
173
+ $params = http_build_query($params);
174
+
175
+ $ch = curl_init();
176
+ curl_setopt($ch, CURLOPT_URL, $url);
177
+ curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
178
+ curl_setopt($ch, CURLOPT_POST, 1);
179
+ curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
180
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
181
+
182
+ // DEBUG
183
+ //Mage::log('PayPal Return, URL: ' . $url);
184
+ //Mage::log('PayPal Return, Params: ' . $params);
185
+ //Mage::log('PayPal Return, State (' . $state . '): ' . curl_exec($ch));
186
+ }
187
+ }
188
+
189
+ }catch(Exception $e) {
190
+ Mage::log('Fanplayr Exception. Save order for PayPal. ' . $e->message);
191
+ }
192
+ }
193
+
194
+ // ------------------------------------------------------------------------------------------------------
195
+ // utils / helpers
196
+
197
+ // gets the last order information
198
+ // needs an ID for later than 1.4, otherwise automatically gets it
199
+ // returns an array of data from the order
200
+ private function getLastOrderInformation($lastOrderId)
201
+ {
202
+ $mageV = Mage::getVersion();
203
+ $mageVa = explode('.', $mageV);
204
+
205
+ // community 1.4 and below
206
+ // enterprise 1.9 and below
207
+ $useOldVersion = false;
208
+ if ($this->isMageCommunity() && $mageVa[0] == '1' && intval($mageVa[1]) <= 4
209
+ || ($this->isMageEnterprise() || $this->isMageProfessional) && $mageVa[0] == '1' && intval($mageVa[1] <= 9)) {
210
+ $useOldVersion = true;
211
+ }
212
+
213
+ $products = array();
214
+
215
+ // have to get the last order in a stupid way for some reason for 1.4 ...
216
+ if ($useOldVersion) {
217
+
218
+ $lastOrderId = Mage::getSingleton('checkout/session')->getLastRealOrderId();
219
+
220
+ // seriosuly, why would THIS be the way to do it? fail!
221
+ $orderCollection = Mage::getModel('sales/order')->getCollection()
222
+ ->addFilter('increment_id', $lastOrderId)
223
+ ->setOrder('created_at', Varien_Data_Collection_Db::SORT_ORDER_DESC)
224
+ ;
225
+ $order = $orderCollection->getFirstItem();
226
+ $order->load($lastOrderId);
227
+
228
+ $orderId = $order->getId();
229
+ $orderNumber = $order->getRealOrderId();
230
+
231
+ $data = $order->getData();
232
+
233
+ // have to be careful here because some versions miss some variables ...
234
+ $orderEmail = array_key_exists('customer_email', $data) ? $data['customer_email'] : '';
235
+ $orderDate = array_key_exists('created_at', $data) ? $data['created_at'] : '';
236
+ $currency = array_key_exists('order_currency_code', $data) ? $data['order_currency_code'] : '';
237
+ $firstName = array_key_exists('customer_firstname', $data) ? $data['customer_firstname'] : '';
238
+ $lastName = array_key_exists('customer_lastname', $data) ? $data['customer_lastname'] : '';
239
+ $customerEmail = array_key_exists('customer_email', $data) ? $data['customer_email'] : '';
240
+ $customerId = array_key_exists('customer_id', $data) ? $data['customer_id'] : '';
241
+ $discountCode = array_key_exists('coupon_code', $data) ? $data['coupon_code'] : '';
242
+ if (!$discountCode) $discountCode = '';
243
+ $discountAmount = array_key_exists('discount_amount', $data) ? round($data['discount_amount'], 2) : 0;
244
+
245
+ $orderSubTotal = array_key_exists('subtotal', $data) ? round($data['subtotal'], 2) : 0;
246
+ $orderTotal = $orderSubTotal - abs($discountAmount);
247
+
248
+ $shipping = array_key_exists('shipping_amount', $data) ? round($data['shipping_amount'], 2) : 0;
249
+ $tax = array_key_exists('tax_amount', $data) ? round($data['tax_amount'], 2) : 0;
250
+
251
+ $products = $this->getProductsFromOrder($order);
252
+
253
+ } else {
254
+ $order = Mage::getModel('sales/order')->load($lastOrderId);
255
+
256
+ $orderId = $order->getId();
257
+ $orderNumber = $order->getRealOrderId();
258
+ $orderEmail = $order->getCustomerEmail();
259
+ $orderDate = $order->getCreatedAt();
260
+ $currency = $order->getOrderCurrencyCode();
261
+ $firstName = $order->getCustomerFirstname();
262
+ $lastName = $order->getCustomerLastname();
263
+ $customerEmail = $order->getCustomerEmail();
264
+ $customerId = $order->getCustomerId();
265
+ $discountCode = $order->getCouponCode();
266
+ if (!$discountCode) $discountCode = '';
267
+
268
+ $data = $order->getData();
269
+ $discountAmount = array_key_exists('base_discount_amount', $data) ? round($data['base_discount_amount'], 2) : 0;
270
+
271
+ $orderSubTotal = round($order->getBaseSubtotal(), 2);
272
+ $orderTotal = $orderSubTotal - abs($discountAmount);
273
+
274
+ $shipping = round($order->getShippingAmount(), 2);
275
+ $tax = round($order->getTaxAmount(), 2);
276
+
277
+ $products = $this->getProductsFromOrder($order);
278
+ }
279
+
280
+ $storeCode = Mage::app()->getStore()->getCode();
281
+ $gtmContainerId = Mage::getStoreConfig('fanplayrsocialcoupons/config/gtm_container_id');
282
+
283
+ return array(
284
+ 'orderId' => $orderId,
285
+ 'orderNumber' => $orderNumber,
286
+ 'orderDate' => $orderDate,
287
+ 'total' => (float)$orderTotal,
288
+ 'subTotal' => (float)$orderSubTotal,
289
+ 'discount' => (float)$discountAmount,
290
+ 'discountCode' => $discountCode,
291
+ 'currency' => $currency,
292
+ 'orderEmail' => $orderEmail,
293
+ 'firstName' => $firstName,
294
+ 'lastName' => $lastName,
295
+ 'customerEmail' => $customerEmail,
296
+ 'customerId' => $customerId,
297
+ 'shipping' => (float)$shipping,
298
+ 'tax' => (float)$tax,
299
+ 'products' => $products,
300
+ 'storeCode' => $storeCode,
301
+ 'gtmContainerId' => $gtmContainerId
302
+ );
303
+
304
+ }
305
+
306
+ // used to fill out the "products" data
307
+ // this will normally be printed later as a JSON, but this simply returns an array or arrays
308
+ // it is likely we will not get all the information
309
+ private function getProductsFromOrder($order)
310
+ {
311
+ $products = array();
312
+
313
+ $items = $order->getAllItems();
314
+
315
+ foreach ($items as $itemId => $item) {
316
+ if ($item->getQtyOrdered() > 0 && !$item->getParentItemId()){
317
+
318
+ // bug in Magento 1.5 and below?
319
+ // just make sure it doesn't break things!
320
+ $sku = '';
321
+ try { $sku = $item->getSku(); }catch(Exception $e){}
322
+
323
+ $products[] = array(
324
+ 'qty' => $item->getQtyOrdered(),
325
+ 'id' => $item->getProductId(),
326
+ 'sku' => $sku,
327
+ 'name' => $item->getName(),
328
+ 'price' => $item->getPrice(),
329
+ 'catId' => '',
330
+ 'catName' => ''
331
+ );
332
+ }
333
+ }
334
+
335
+ return $products;
336
+ }
337
+
338
+ public function isMageEnterprise() {
339
+ return Mage::getConfig ()->getModuleConfig ( 'Enterprise_Enterprise' ) && Mage::getConfig ()->getModuleConfig ( 'Enterprise_AdminGws' ) && Mage::getConfig ()->getModuleConfig ( 'Enterprise_Checkout' ) && Mage::getConfig ()->getModuleConfig ( 'Enterprise_Customer' );
340
+ }
341
+
342
+ public function isMageProfessional() {
343
+ return Mage::getConfig ()->getModuleConfig ( 'Enterprise_Enterprise' ) && !Mage::getConfig ()->getModuleConfig ( 'Enterprise_AdminGws' ) && !Mage::getConfig ()->getModuleConfig ( 'Enterprise_Checkout' ) && !Mage::getConfig ()->getModuleConfig ( 'Enterprise_Customer' );
344
+ }
345
+
346
+ public function isMageCommunity() {
347
+ return !$this->isMageEnterprise() && !$this->isMageProfessional();
348
+ }
349
+ }
app/code/community/Fanplayr/Socialcoupons/controllers/AjaxController.php ADDED
@@ -0,0 +1,116 @@
1
+ <?php
2
+ class Fanplayr_Socialcoupons_AjaxController extends Mage_Core_Controller_Front_Action
3
+ {
4
+ public function indexAction()
5
+ {
6
+ echo $this->jsonMessage(true, 'Please use a valid method.');
7
+ }
8
+
9
+ public function getEmbedJsAction()
10
+ {
11
+ // store session data in case the cookie is lost somehow
12
+ $sessionVars = $this->decodeSessionCookie('fanplayr_genius_session');
13
+ if ($sessionVars) {
14
+ $session = Mage::getModel('core/session');
15
+ if ($session){
16
+ if (array_key_exists('key', $sessionVars)) $session->setData('fanplayr_session_session_key',$sessionVars['key']);
17
+ if (array_key_exists('user', $sessionVars)) $session->setData('fanplayr_session_user_key', $sessionVars['user']);
18
+ }
19
+ }
20
+
21
+ // now do the rest ...
22
+ $p = $this->getRequest()->getParams();
23
+
24
+ $block = new Mage_Core_Block_Template();
25
+ $block->setTemplate('fanplayr/embed.phtml');
26
+
27
+ // shop URL
28
+ $shopUrl = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB);
29
+ if (!strpos($shopUrl, 'index.php/'))
30
+ $shopUrl .= 'index.php/';
31
+ $customEmbedUrl = trim(Mage::getStoreConfig('fanplayrsocialcoupons/config/custom_embed_url'));
32
+ if (!empty($customEmbedUrl)) $shopUrl = $customEmbedUrl;
33
+
34
+ $block->assign('widgetKeys', Mage::getStoreConfig('fanplayrsocialcoupons/config/widget_keys'));
35
+ $block->assign('widgetKeysGenius', Mage::getStoreConfig('fanplayrsocialcoupons/config/widget_keys_genius'));
36
+ $block->assign('accountKey', Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key'));
37
+
38
+ $block->assign('applyToCartUrl', $shopUrl . 'fanplayr/coupon/add/code/%c/');
39
+ $block->assign('depitizeUrl', $shopUrl . 'fanplayr/coupon/deputize/a/%a/d/%d/');
40
+
41
+ $block->assign('noTags', true);
42
+
43
+ // get data and add it ...
44
+ $data = Fanplayr_Socialcoupons_Model_EmbedObserver::getData(
45
+ array_key_exists('ac', $p) ? $p['ac'] == '1' : false,
46
+ array_key_exists('tt', $p) ? $p['tt'] : '',
47
+ array_key_exists('tp', $p) ? $p['tp'] : '',
48
+ array_key_exists('tc', $p) ? $p['tc'] : '',
49
+ array_key_exists('tpn', $p) ? $p['tpn'] : '',
50
+ array_key_exists('tcn', $p) ? $p['tcn'] : ''
51
+ );
52
+
53
+ $block->assign('data', $data);
54
+
55
+ $embedType = intval(Mage::getStoreConfig('fanplayrsocialcoupons/config/wait_for_onload'));
56
+ $block->assign('embedType', $embedType);
57
+
58
+ $this->getResponse()
59
+ ->clearHeaders()
60
+ ->setHeader('Cache-Control', 'no-cache, must-revalidate')
61
+ ->setHeader('Expires', 'Mon, 26 Jul 1997 05:00:00 GMT')
62
+ ->setHeader('Content-Type', 'text/javascript')
63
+ ->setBody($block->toHtml());
64
+ }
65
+
66
+ // -------------------------------------------------------------------
67
+ // decode session cookie
68
+
69
+ // in case sessions aren't being sent through correctly
70
+ // we will store this each hit, and then get it back later
71
+
72
+ private function decodeSessionCookie( $cookie_name )
73
+ {
74
+ if ( array_key_exists($cookie_name, $_COOKIE) && !empty($_COOKIE[$cookie_name]) ) {
75
+ $data = array();
76
+ $params = explode(';', $_COOKIE[$cookie_name]);
77
+
78
+ foreach ( $params as $param ) {
79
+ $parts = explode('=', $param);
80
+ if (count($parts) != 2)
81
+ continue;
82
+
83
+ $type = substr($parts[1], 0, 1);
84
+ $value = substr($parts[1], 1);
85
+
86
+ if ( empty($type) ) continue;
87
+
88
+ if ( $type === 'n' || $type === 'u' ) { $value = null; }
89
+ if ( $type === 'b' ) { $value = (intval($value, 10) !== 0); }
90
+ if ( $type === 'f' ) { $value = floatval($value); }
91
+ if ( $type === 's' ) { $value = urldecode($value); }
92
+
93
+ $data[urldecode($parts[0])] = $value;
94
+ }
95
+
96
+ return $data;
97
+ }
98
+ return null;
99
+ }
100
+
101
+ public function jsonMessage($isError, $message, $extras = array())
102
+ {
103
+ $extras['error'] = $isError;
104
+ $extras['message'] = $message;
105
+ $extras['version'] = $this->getExtensionVersion();
106
+ $extras['mage_version'] = Mage::getVersion();
107
+
108
+ return json_encode($extras);
109
+ }
110
+
111
+ private function getExtensionVersion()
112
+ {
113
+ return (string) Mage::getConfig()->getNode()->modules->Fanplayr_Socialcoupons->version;
114
+ }
115
+ }
116
+ ?>
app/code/community/Fanplayr/Socialcoupons/controllers/CompyController.php ADDED
@@ -0,0 +1,750 @@
1
+ <?php
2
+ class Fanplayr_Socialcoupons_CompyController extends Mage_Core_Controller_Front_Action
3
+ {
4
+ private $countryLookup;
5
+ private $shippingLookup;
6
+ private $paymentLookup;
7
+ private $regionLookup;
8
+
9
+ public function indexAction()
10
+ {
11
+ echo $this->jsonMessage(true, 'Please use a valid method.');
12
+ }
13
+
14
+ public function isPerm()
15
+ {
16
+ $p = $this->getRequest()->getParams();
17
+
18
+ // required input
19
+ $secret = array_key_exists('secret', $p) ? $p['secret'] : '';
20
+ $accKey = array_key_exists('acckey', $p) ? $p['acckey'] : '';
21
+
22
+ // error, needs more info
23
+ if (empty($secret) || empty($accKey)) {
24
+ echo $this->jsonMessage(true, "Error. Needs 'secret' and 'acckey'.");
25
+ return false;
26
+ }
27
+
28
+ $actualSecret = Mage::getStoreConfig('fanplayrsocialcoupons/config/secret');
29
+ $actualAccKey = Mage::getStoreConfig('fanplayrsocialcoupons/config/acc_key');
30
+
31
+ if ($actualSecret != $secret || $actualA