forked from mautic/mautic-joomla
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mautic.php
396 lines (344 loc) · 10.7 KB
/
mautic.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
<?php
/**
* Mautic-Joomla plugin
* @author Mautic
* @copyright Copyright (C) 2014 Mautic All Rights Reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* Website http://www.mautic.org
*/
// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
jimport('joomla.plugin.plugin');
jimport('joomla.log.log');
require_once __DIR__ . '/mauticApiHelper.php';
/**
*
* @package Joomla
* @subpackage System.Mautic
*/
class plgSystemMautic extends JPlugin
{
/**
* mauticApiHelper
*/
protected $apiHelper;
/**
* Object Constructor.
*
* @access public
* @param object The object to observe -- event dispatcher.
* @param object The configuration object for the plugin.
* @return void
* @since 1.0
*/
function __construct(&$subject, $config)
{
parent::__construct($subject, $config);
// Define the logger.
JLog::addLogger(array('text_file' => 'plg_mautic.php'), JLog::ALL, array('plg_mautic'));
}
/**
* This event is triggered after the framework has loaded and the application initialise method has been called.
*
* @return void
*/
public function onAfterDispatch()
{
$app = JFactory::getApplication();
$document = JFactory::getDocument();
$input = $app->input;
// Check to make sure we are loading an HTML view and there is a main component area
if ($document->getType() !== 'html' || $input->get('tmpl', '', 'cmd') === 'component' || $app->isAdmin())
{
return true;
}
// Get additional data to send
$attrs = array();
$attrs['title'] = $document->title;
$attrs['language'] = $document->language;
$attrs['referrer'] = isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : JUri::current();
$attrs['url'] = JURI::getInstance()->toString();
$user = JFactory::getUser();
// Get info about the user if logged in
if (!$user->guest)
{
$attrs['email'] = $user->email;
$name = explode(' ', $user->name);
if (isset($name[0]))
{
$attrs['firstname'] = $name[0];
}
if (isset($name[count($name) - 1]))
{
$attrs['lastname'] = $name[count($name) - 1];
}
}
$encodedAttrs = urlencode(base64_encode(serialize($attrs)));
$buffer = $document->getBuffer('component');
$image = '<img style="display:none" src="' . trim($this->params->get('base_url'), ' \t\n\r\0\x0B/') . '/mtracking.gif?d=' . $encodedAttrs . '" alt="mautic is open source marketing automation" />';
$buffer .= $image;
$document->setBuffer($buffer, 'component');
return true;
}
/**
* Insert form script to the content
*
* @param string The context of the content being passed to the plugin.
* @param object The article object. Note $article->text is also available
* @param object The article params
* @param integer The 'page' number
*/
public function onContentPrepare($context, &$article, &$params, $page = 0)
{
$app = JFactory::getApplication();
$document = JFactory::getDocument();
$input = $app->input;
// Check to make sure we are loading an HTML view and there is a main component area and content is not being indexed
if ($document->getType() !== 'html'
|| $input->get('tmpl', '', 'cmd') === 'component'
|| $app->isAdmin()
|| $context == 'com_finder.indexer')
{
return true;
}
// simple performance check to determine whether bot should process further
if (strpos($article->text, '{mauticform') === false)
{
return true;
}
// expression to search for (positions)
$regex = '/{mauticform\s+(.*?)}/i';
// Find all instances of plugin and put in $matches for githubrepo
// $matches[0] is full pattern match, $matches[1] is the repo declaration
preg_match_all($regex, $article->text, $matches, PREG_SET_ORDER);
if ($matches && isset($matches[0]))
{
foreach ($matches as $match)
{
if (isset($match[1]))
{
$formId = (int) $match[1];
$formTag = '<script type="text/javascript" src="' . trim($this->params->get('base_url'), ' \t\n\r\0\x0B/') . '/form/generate.js?id=' . $formId . '"></script>';
$article->text = str_replace($match[0], $formTag, $article->text);
}
}
}
}
/**
* Mautic API call
*/
public function onAfterRoute()
{
$user = JFactory::getUser();
$app = JFactory::getApplication();
$input = $app->input;
$isRoot = true; // $user->authorise('core.admin');
if ($input->get('plugin') == 'mautic')
{
$lang = JFactory::getLanguage();
$lang->load('plg_system_mautic', JPATH_ADMINISTRATOR);
if ($isRoot)
{
if ($input->get('authorize', false, 'BOOLEAN'))
{
$this->authorize($input->get('reauthorize', false, 'BOOLEAN'));
}
if ($input->get('reauthorize', false, 'BOOLEAN'))
{
$this->authorize(true);
}
if ($input->get('reset', false, 'BOOLEAN'))
{
$this->resetAccessToken();
}
}
else
{
$app->enqueueMessage(JText::_('PLG_MAUTIC_ERROR_ONLY_ADMIN_CAN_AUTHORIZE'), 'warning');
$this->log(JText::_('PLG_MAUTIC_ERROR_ONLY_ADMIN_CAN_AUTHORIZE'), JLog::ERROR);
}
}
if (($input->get('oauth_token') && $input->get('oauth_verifier'))
|| ($input->get('state') && $input->get('code')))
{
$this->authorize($input->get('reauthorize', false, 'BOOLEAN'));
}
}
/**
* Reset Access token so the plugin could authorize again
*
* @return void
*/
public function resetAccessToken()
{
$app = JFactory::getApplication();
$apiHelper = $this->getMauticApiHelper();
$table = $apiHelper->getTable();
$this->params->set('access_token', '');
$this->params->set('access_token_secret', '');
$this->params->set('access_token_expires', '');
$table->set('params', $this->params->toString());
$table->store();
$app->enqueueMessage(JText::_('PLG_MAUTIC_RESET_SUCCESSFUL'));
$this->log(JText::_('PLG_MAUTIC_RESET_SUCCESSFUL'), JLog::INFO);
$app->redirect(JRoute::_('index.php?option=com_plugins&view=plugin&layout=edit&extension_id=' . $table->get('extension_id'), false));
}
/**
* Create sanitized Mautic Base URL without the slash at the end.
*
* @return string
*/
public function getMauticApiHelper()
{
if ($this->apiHelper)
{
return $this->apiHelper;
}
$this->apiHelper = new mauticApiHelper;
return $this->apiHelper;
}
/**
* Get Table instance of this plugin
*
* @return JTableExtension
*/
public function authorize($reauthorize = false)
{
$app = JFactory::getApplication();
$apiHelper = $this->getMauticApiHelper();
$mauticBaseUrl = $apiHelper->getMauticBaseUrl();
$auth = $apiHelper->getMauticAuth($reauthorize);
$table = $apiHelper->getTable();
$lang = JFactory::getLanguage();
$message = '';
$lang->load('plg_system_mautic', JPATH_ADMINISTRATOR);
$this->log('Authorize method called.', JLog::INFO);
try
{
if ($auth->validateAccessToken())
{
if ($auth->accessTokenUpdated())
{
$accessTokenData = new JRegistry($auth->getAccessTokenData());
$this->log('authorize::accessTokenData: ' . var_export($accessTokenData, true), JLog::INFO);
$this->params->merge($accessTokenData);
$table = $apiHelper->getTable();
$table->set('params', $this->params->toString());
$table->store();
$extraWord = $reauthorize ? 'PLG_MAUTIC_REAUTHORIZED' : 'PLG_MAUTIC_AUTHORIZED';
$message = JText::sprintf('PLG_MAUTIC_REAUTHORIZE_SUCCESS', JText::_($extraWord));
$this->log($message, JLog::INFO);
}
else
{
$message = JText::_('PLG_MAUTIC_REAUTHORIZE_NOT_NEEDED');
$this->log(JText::_('PLG_MAUTIC_REAUTHORIZE_NOT_NEEDED'), JLog::INFO);
}
}
else
{
$message = JText::_('PLG_MAUTIC_ACCESS_TOKEN_NOT_VALID');
$this->log(JText::_('PLG_MAUTIC_ACCESS_TOKEN_NOT_VALID'), JLog::ERROR);
}
}
catch (Exception $e)
{
$message = $e->getMessage();
$this->log($e->getMessage(), JLog::ERROR);
}
$app->redirect(JURI::base() . 'administrator/index.php?option=com_plugins&view=plugin&layout=edit&extension_id=' . $table->get('extension_id'), $message);
}
/**
* Create new lead on Joomla user registration
*
* For debug is better to switch function to:
* public function onUserBeforeSave($success, $isNew, $user)
*
* @param array $user array with user information
* @param boolean $isNew whether the user is new
* @param boolean $success whether the user was saved successfully
* @param string $msg error message
*/
public function onUserAfterSave($user, $isNew, $success, $msg = '')
{
$this->log('onUserAfterSave method called.', JLog::INFO);
$this->log('onUserAfterSave::isNew: ' . var_export($isNew, true), JLog::INFO);
$this->log('onUserAfterSave::success: ' . var_export($success, true), JLog::INFO);
$this->log('onUserAfterSave::send_registered: ' . var_export($this->params->get('send_registered'), true), JLog::INFO);
if ($isNew && $success && $this->params->get('send_registered') == 1)
{
$this->log('onUserAfterSave: Send the user to Mautic.', JLog::INFO);
try
{
$apiHelper = $this->getMauticApiHelper();
$mauticBaseUrl = $apiHelper->getMauticBaseUrl();
$auth = $apiHelper->getMauticAuth();
$leadApi = \Mautic\MauticApi::getContext("leads", $auth, $mauticBaseUrl . '/api/');
$ip = $this->getUserIP();
$name = explode(' ', $user['name']);
$mauticUser = array(
'ipAddress' => $ip,
'firstname' => isset($name[0]) ? $name[0] : '',
'lastname' => isset($name[1]) ? $name[1] : '',
'email' => $user['email'],
);
$this->log('onUserAfterSave::mauticUser: ' . var_export($mauticUser, true), JLog::INFO);
$result = $leadApi->create($mauticUser);
if (isset($result['error']))
{
$this->log('onUserAfterSave::leadApi::create - response: ' . $result['error']['code'] . ": " . $result['error']['message'], JLog::ERROR);
}
elseif (!empty($result['lead']['id']))
{
$this->log('onUserAfterSave: Mautic lead was successfully created with ID ' . $result['lead']['id'], JLog::INFO);
}
else
{
$this->log('onUserAfterSave: Mautic lead was NOT successfully created. ' . var_export($result, true), JLog::ERROR);
}
}
catch (Exception $e)
{
$this->log($e->getMessage(), JLog::ERROR);
}
}
else
{
$this->log('onUserAfterSave: Do not send the user to Mautic.', JLog::INFO);
}
}
/**
* Try to guess the real user IP address
*
* @return string
*/
public function getUserIP()
{
$ip = '';
if (!empty($_SERVER['HTTP_CLIENT_IP']))
{
$ip = $_SERVER['HTTP_CLIENT_IP'];
}
elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
{
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
}
elseif (!empty($_SERVER['REMOTE_ADDR']))
{
$ip = $_SERVER['REMOTE_ADDR'];
}
return $ip;
}
/**
* Log helper function
*
* @return string
*/
public function log($msg, $type)
{
if ($this->params->get('log_on', 1) == 1)
{
JLog::add($msg, $type, 'plg_mautic');
}
}
}