PluginProbe
AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress / 10.0.1
AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress v10.0.1
11.1.1 11.1.0 11.0.5 11.0.4 11.0.3 11.0.2 11.0.1 11.0.0 10.11.1 10.11.0 10.10.2 10.10.1 10.10.0 10.9.1 trunk 10.0.0 10.0.1 10.1.0 10.1.1 10.1.2 10.1.3 10.1.4 10.2.0 10.2.1 10.2.2 All 62 releases
acymailing / back / Helpers / MigrationHelper.php

MigrationHelper.php in AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress 10.0.1, at back/Helpers/MigrationHelper.php

1,459 lines 55.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 namespace AcyMailing\Helpers;
4
5 use AcyMailing\Classes\CampaignClass;
6 use AcyMailing\Classes\FieldClass;
7 use AcyMailing\Classes\FollowupClass;
8 use AcyMailing\Classes\ListClass;
9 use AcyMailing\Classes\MailboxClass;
10 use AcyMailing\Classes\MailClass;
11 use AcyMailing\Core\AcymObject;
12
13 class MigrationHelper extends AcymObject
14 {
15 private $errors = [];
16
17 private $result = [
18 'isOk' => true,
19 'errorInsert' => false,
20 'errorClean' => false,
21 'count' => 0,
22 ];
23
24 public function doConfigMigration()
25 {
26 $this->doElementMigration('config');
27
28 return $this->result;
29 }
30
31 public function doUsers_fieldsMigration()
32 {
33 $this->doElementMigration('users_fields');
34
35 return $this->result;
36 }
37
38 public function doMailStatsMigration()
39 {
40 $this->doElementMigration('MailStats');
41
42 return $this->result;
43 }
44
45 public function doMailhaslistsMigration()
46 {
47 $this->doElementMigration('MailHasLists');
48
49 return $this->result;
50 }
51
52 public function doTemplatesMigration()
53 {
54 $this->doElementMigration('templates');
55
56 return $this->result;
57 }
58
59 public function doMailsMigration()
60 {
61 $params = [];
62
63 $this->doElementMigration('mails', $params);
64
65 return $this->result;
66 }
67
68 public function doFieldsMigration()
69 {
70 $this->doElementMigration('fields');
71
72 return $this->result;
73 }
74
75 public function doListsMigration()
76 {
77
78 $this->doElementMigration('lists');
79
80 return $this->result;
81 }
82
83 public function doUsersMigration()
84 {
85
86 $this->doElementMigration('users');
87
88 return $this->result;
89 }
90
91 public function doSubscriptionsMigration()
92 {
93 $this->doElementMigration('subscriptions');
94
95 return $this->result;
96 }
97
98 public function doWelcomeunsubMigration()
99 {
100 $this->doElementMigration('Welcomeunsub');
101
102 return $this->result;
103 }
104
105 public function doBounceMigration()
106 {
107 $this->doElementMigration('bounce');
108
109 return $this->result;
110 }
111
112 public function doDistribMigration()
113 {
114 $this->doElementMigration('distrib');
115
116 return $this->result;
117 }
118
119 public function migrateConfig($params = [])
120 {
121 $fieldsMatchMailSettings = [
122 'add_names' => 'add_names',
123 'bounce_email' => 'bounce_email',
124 'charset' => 'charset',
125 'dkim' => 'dkim',
126 'dkim_domain' => 'dkim_domain',
127 'dkim_identity' => 'dkim_identity',
128 'dkim_passphrase' => 'dkim_passphrase',
129 'dkim_private' => 'dkim_private',
130 'dkim_public' => 'dkim_public',
131 'dkim_selector' => 'dkim_selector',
132 'elasticemail_password' => 'elasticemail_password',
133 'elasticemail_port' => 'elasticemail_port',
134 'elasticemail_username' => 'elasticemail_username',
135 'embed_files' => 'embed_files',
136 'embed_images' => 'embed_images',
137 'encoding_format' => 'encoding_format',
138 'from_email' => 'from_email',
139 'from_name' => 'from_name',
140 'mailer_method' => 'mailer_method',
141 'multiple_part' => 'multiple_part',
142 'reply_email' => 'replyto_email',
143 'reply_name' => 'replyto_name',
144 'sendmail_path' => 'sendmail_path',
145 'smtp_auth' => 'smtp_auth',
146 'smtp_host' => 'smtp_host',
147 'smtp_keepalive' => 'smtp_keepalive',
148 'smtp_password' => 'smtp_password',
149 'smtp_port' => 'smtp_port',
150 'smtp_secured' => 'smtp_secured',
151 'smtp_username' => 'smtp_username',
152 'special_chars' => 'special_chars',
153 ];
154
155 $fieldsMatchQueueProcess = [
156 'cron_frequency' => 'cron_frequency',
157 'cron_fromip' => 'cron_fromip',
158 'cron_last' => 'cron_last',
159 'cron_report' => 'cron_report',
160 'cron_savereport' => 'cron_savereport',
161 'cron_sendreport' => 'cron_sendreport',
162 'cron_sendto' => 'cron_sendto',
163 'queue_nbmail' => 'queue_nbmail',
164 'queue_nbmail_auto' => 'queue_nbmail_auto',
165 'queue_pause' => 'queue_pause',
166 'queue_try' => 'queue_try',
167 'queue_type' => 'queue_type',
168 ];
169
170 $fieldsMatchSubscription = [
171 'require_confirmation' => 'require_confirmation',
172 ];
173
174 $fieldsMatchSecurity = [
175 'allowedfiles' => 'allowed_files',
176 'email_checkdomain' => 'email_checkdomain',
177 'recaptcha_secretkey' => 'recaptcha_secretkey',
178 'recaptcha_sitekey' => 'recaptcha_sitekey',
179 'security_key' => 'security_key',
180 ];
181
182 $fieldsMatchNotUsed = [
183 'allow_visitor' => 'allow_visitor',
184 'confirm_redirect' => 'confirm_redirect',
185 'confirmation_message' => 'confirmation_message',
186 'cron_fullreport' => 'cron_fullreport',
187 'cron_next' => 'cron_next',
188 'css_backend' => 'css_backend',
189 'css_frontend' => 'css_frontend',
190 'forward' => 'forward',
191 'hostname' => 'hostname',
192 'notification_accept' => 'notification_accept',
193 'notification_confirm' => 'notification_confirm',
194 'notification_created' => 'notification_created',
195 'notification_refuse' => 'notification_refuse',
196 'notification_unsuball' => 'notification_unsuball',
197 'priority_followup' => 'priority_followup',
198 'priority_newsletter' => 'priority_newsletter',
199 'subscription_message' => 'subscription_message',
200 'unsub_message' => 'unsub_message',
201 'unsub_reasons' => 'unsub_reasons',
202 'unsub_redirect' => 'unsub_redirect',
203 'use_sef' => 'use_sef',
204 'welcome_message' => 'welcome_message',
205 'word_wrapping' => 'word_wrapping',
206 ];
207
208 $fieldsMatchBounce = [
209 'bounce_email' => 'bounce_email',
210 'bounce_server' => 'bounce_server',
211 'bounce_port' => 'bounce_port',
212 'bounce_connection' => 'bounce_connection',
213 'bounce_secured' => 'bounce_secured',
214 'bounce_certif' => 'bounce_certif',
215 'bounce_username' => 'bounce_username',
216 'bounce_password' => 'bounce_password',
217 'bounce_timeout' => 'bounce_timeout',
218 'bounce_max' => 'bounce_max',
219 'auto_bounce' => 'auto_bounce',
220 'auto_bounce_frequency' => 'auto_bounce_frequency',
221 'bounce_action_lists_maxtry' => 'bounce_action_lists_maxtry',
222 ];
223
224 $fieldsMatch = array_merge(
225 $fieldsMatchMailSettings,
226 $fieldsMatchQueueProcess,
227 $fieldsMatchSubscription,
228 $fieldsMatchSecurity,
229 $fieldsMatchNotUsed,
230 $fieldsMatchBounce
231 );
232
233 $dataPrevious = acym_loadObjectList(
234 'SELECT `namekey`, `value`
235 FROM #__acymailing_config
236 WHERE `namekey` IN ("'.implode('","', array_keys($fieldsMatch)).'")
237 LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls'])
238 );
239
240 if (empty($dataPrevious)) {
241 return true;
242 }
243
244 $valuesToInsert = [];
245
246 foreach ($dataPrevious as $value) {
247 if (empty($fieldsMatch[$value->namekey])) {
248 continue;
249 }
250
251 $value->namekey = $fieldsMatch[$value->namekey];
252
253 switch ($value->namekey) {
254 case 'queue_type':
255 switch ($value->value) {
256 case 'onlyauto':
257 $value->value = 'auto';
258 break;
259 case 'auto':
260 $value->value = 'automan';
261 break;
262 }
263 break;
264
265 case 'mailer_method':
266 $sending_platform = $value->value == 'smtp' || $value->value === 'elasticemail' ? 'external' : 'server';
267 $valuesToInsert[] = '("sending_platform",'.acym_escapeDB($sending_platform).')';
268 break;
269 }
270
271 $valuesToInsert[] = '('.acym_escapeDB($value->namekey).','.acym_escapeDB($value->value).')';
272 }
273
274 $query = 'REPLACE INTO #__acym_configuration VALUES '.implode(',', $valuesToInsert).';';
275
276 return $this->_insertQuery($query);
277 }
278
279 private function _insertQuery($queryInsert, $result = 0)
280 {
281 try {
282 $resultQuery = acym_query($queryInsert);
283 } catch (\Exception $e) {
284 $this->errors[] = $e->getMessage();
285
286 return false;
287 }
288
289 if ($resultQuery === null) {
290 $this->errors[] = acym_getDBError();
291
292 return false;
293 } else {
294 $result += $resultQuery;
295 }
296
297 return $result;
298 }
299
300 public function migrateTemplates($params = [])
301 {
302 $mailClass = new MailClass();
303 $result = 0;
304
305 $queryGetTemplates = 'SELECT `tempid`, `name`, `body`, `styles`, `subject`, `stylesheet`, `fromname`, `fromemail`, `replyname`, `replyemail` FROM #__acymailing_template LIMIT '.intval(
306 $params['currentElement']
307 ).', '.intval($params['insertPerCalls']);
308
309 $templates = acym_loadObjectList($queryGetTemplates);
310 if (empty($templates)) return true;
311
312 $valuesToInsert = [];
313
314 $templates = $mailClass->encode($templates);
315
316 foreach ($templates as $oneTemplate) {
317 $oneTemplateStyles = unserialize($oneTemplate->styles);
318
319 foreach ($oneTemplateStyles as $key => $value) {
320 if (strpos($key, 'tag_') !== false) {
321 $tag = str_replace('tag_', '', $key);
322 $styleDeclaration = $tag.'{'.$value.'}';
323 } elseif (strpos($key, 'color_bg') !== false) {
324 $styleDeclaration = '';
325 } else {
326 $styleDeclaration = '.'.$key.'{'.$value.'}';
327 }
328
329 $oneTemplate->stylesheet .= $styleDeclaration;
330 }
331
332 $valuesToInsert[] = '('.implode(
333 ', ',
334 [
335 acym_escapeDB(empty($oneTemplate->name) ? acym_translation('ACYM_MIGRATED_TEMPLATE').' '.time() : $oneTemplate->name),
336 acym_escapeDB(acym_date('now', 'Y-m-d H:i:s', false)),
337 '0',
338 acym_escapeDB(MailClass::TYPE_TEMPLATE),
339 acym_escapeDB(empty($oneTemplate->body) ? '' : $oneTemplate->body),
340 acym_escapeDB($oneTemplate->subject),
341 acym_escapeDB($oneTemplate->fromname),
342 acym_escapeDB($oneTemplate->fromemail),
343 acym_escapeDB($oneTemplate->replyname),
344 acym_escapeDB($oneTemplate->replyemail),
345 acym_escapeDB($oneTemplate->stylesheet),
346 intval(acym_currentUserId()),
347 ]
348 ).')';
349 }
350
351 if (empty($valuesToInsert)) {
352 return true;
353 }
354
355 $queryInsert = 'INSERT INTO #__acym_mail (`name`, `creation_date`, `drag_editor`, `type`, `body`, `subject`, `from_name`, `from_email`, `reply_to_name`, `reply_to_email`, `stylesheet`, `creator_id`) VALUES '.implode(
356 ',',
357 $valuesToInsert
358 ).';';
359
360 return $this->_insertQuery($queryInsert, $result);
361 }
362
363 public function migrateUsers_fields($params = [])
364 {
365 $fieldsV5InDB = acym_loadObjectList(
366 'SELECT `namekey`, `type`
367 FROM #__acymailing_fields
368 WHERE `namekey` NOT IN ("name", "email", "html")
369 AND `type` NOT IN ("customtext", "category", "gravatar")',
370 'namekey'
371 );
372
373 if (empty($fieldsV5InDB)) return true;
374
375 $columnUserTable = acym_getColumns('acymailing_subscriber', false);
376
377 $fieldsV5 = [];
378
379 foreach ($fieldsV5InDB as $key => $field) {
380 if (in_array($key, $columnUserTable)) {
381 $fieldsV5[$key] = $field;
382 }
383 }
384
385 if (empty($fieldsV5)) return true;
386
387 $fieldsKeyV5 = array_keys($fieldsV5);
388
389 $whereUserField = '`'.implode('` IS NOT NULL OR `', $fieldsKeyV5);
390 if (!empty($fieldsKeyV5)) {
391 $whereUserField .= '` IS NOT NULL';
392 }
393
394 $query = 'SELECT `subid`, `'.implode('`, `', $fieldsKeyV5).'` FROM #__acymailing_subscriber WHERE '.$whereUserField.' LIMIT '.intval($params['currentElement']).', '.intval(
395 $params['insertPerCalls']
396 );
397 $usersFieldsValuesV5 = acym_loadObjectList($query);
398
399 $fieldImported = acym_loadObjectList('SELECT `id`, `namekey`, `option`, `type` FROM #__acym_field WHERE `namekey` IN ("'.implode('", "', $fieldsKeyV5).'")', 'namekey');
400
401 $valuesToInsert = [];
402
403 foreach ($fieldsKeyV5 as $fieldKey) {
404 foreach ($usersFieldsValuesV5 as $user) {
405 if ('date' == $fieldImported[$fieldKey]->type) {
406 $user->$fieldKey = preg_replace('@[^0-9]@', '/', $user->$fieldKey);
407 }
408
409 if ('birthday' == $fieldsV5[$fieldKey]->type && !empty($user->$fieldKey)) {
410 if (!is_array($fieldImported[$fieldKey]->option)) {
411 $fieldImported[$fieldKey]->option = json_decode($fieldImported[$fieldKey]->option, true);
412 }
413
414 if (!empty($fieldImported[$fieldKey]->option['format'])) {
415 $birthdayValue = explode('/', $user->$fieldKey);
416 $positions = [
417 '0' => strpos($fieldImported[$fieldKey]->option['format'], '%y'),
418 '1' => strpos($fieldImported[$fieldKey]->option['format'], '%m'),
419 '2' => strpos($fieldImported[$fieldKey]->option['format'], '%d'),
420 ];
421 asort($positions);
422 $final = [];
423 foreach ($positions as $key => $value) {
424 $final[] = $birthdayValue[$key];
425 }
426 $user->$fieldKey = implode('/', $final);
427 }
428 }
429
430 if ('phone' == $fieldImported[$fieldKey]->type) {
431 $user->$fieldKey = str_replace('+', '', $user->$fieldKey);
432 }
433
434 if (strlen($user->$fieldKey) === 0 || ($fieldImported[$fieldKey]->type === 'phone' && $user->$fieldKey === ',')) {
435 continue;
436 }
437
438 $valuesToInsert[] = '('.intval($user->subid).', '.acym_escapeDB($user->$fieldKey).', '.intval($fieldImported[$fieldKey]->id).')';
439 }
440 }
441
442 if (empty($valuesToInsert)) return true;
443
444 return acym_query('INSERT IGNORE INTO #__acym_user_has_field (`user_id`, `value`, `field_id`) VALUES '.implode(', ', $valuesToInsert));
445 }
446
447 public function migrateFields($params = [])
448 {
449
450 $fieldClass = new FieldClass();
451
452 $columnConnection = [
453 'namekey' => 'namekey',
454 'fieldname' => 'name',
455 'published' => 'active',
456 'options' => 'option',
457 'listing' => 'backend_listing',
458 'backend' => 'backend_edition',
459 'default' => 'default_value',
460 'type' => 'type',
461 'value' => 'value',
462 'ordering' => 'ordering',
463 'required' => 'required',
464 ];
465
466 $optionConnection = [
467 'errormessage' => 'error_message',
468 'checkcontent' => 'authorized_content',
469 'errormessagecheckcontent' => 'error_message_invalid',
470 'cols' => 'columns',
471 'fieldcatclass' => 'css_class',
472 'format' => 'format',
473 'size' => 'size',
474 'rows' => 'rows',
475 'customtext' => 'custom_text',
476 ];
477
478 $databaseConnection = [
479 'dbName' => 'database',
480 'tableName' => 'table',
481 'valueFromDb' => 'value',
482 'titleFromDb' => 'title',
483 'whereCond' => 'where',
484 'whereOperator' => 'where_sign',
485 'whereValue' => 'where_value',
486 'orderField' => 'order_by',
487 'orderValue' => 'sort_order',
488 ];
489
490 $typeConnection = [
491 'text' => 'text',
492 'textarea' => 'textarea',
493 'radio' => 'radio',
494 'checkbox' => 'checkbox',
495 'singledropdown' => 'single_dropdown',
496 'multipledropdown' => 'multiple_dropdown',
497 'date' => 'date',
498 'birthday' => 'date',
499 'file' => 'file',
500 'phone' => 'phone',
501 'customtext' => 'custom_text',
502 ];
503
504 $fieldsFromV5 = acym_loadObjectList(
505 'SELECT * FROM #__acymailing_fields WHERE `namekey` NOT IN ("name", "email", "html") AND `type` NOT IN ("gravatar", "category") LIMIT '.intval(
506 $params['currentElement']
507 ).', '.intval($params['insertPerCalls'])
508 );
509
510 $insertedFields = [];
511
512 foreach ($fieldsFromV5 as $oneField) {
513 $newField = new \stdClass();
514 foreach ($oneField as $key => $value) {
515 if (!array_key_exists($key, $columnConnection)) continue;
516 if ('type' == $columnConnection[$key]) {
517 $value = $typeConnection[$value];
518 }
519 if ('default_value' == $columnConnection[$key] && in_array($oneField->type, ['date', 'birthday'])) {
520 $value = preg_replace('@[^0-9]@', '/', $value);
521 }
522 if ('value' == $columnConnection[$key]) {
523 $allValues = explode("\n", $value);
524 $returnedValues = [];
525 foreach ($allValues as $id => $oneVal) {
526 $line = explode('::', trim($oneVal));
527 if (empty($line[1])) continue;
528 $var = empty($line[0]) ? '' : $line[0];
529 $val = empty($line[1]) ? '' : $line[1];
530
531 $obj = new \stdClass();
532 $obj->value = $var;
533 $obj->title = $val;
534 if (!empty($line[2])) {
535 $obj->disabled = 'y';
536 } else {
537 $obj->disabled = 'n';
538 }
539 $returnedValues[] = $obj;
540 }
541 $value = json_encode($returnedValues);
542 }
543 if ('option' == $columnConnection[$key]) {
544 $options = unserialize($value);
545 if (empty($options)) {
546 continue;
547 }
548 $newOption = new \stdClass();
549 foreach ($options as $keyOption => $option) {
550 if (!array_key_exists($keyOption, $optionConnection)) continue;
551 if ('authorized_content' == $optionConnection[$keyOption]) {
552 $option = [
553 $option,
554 'regex' => $options['regexp'],
555 ];
556 }
557 if (in_array($oneField->type, ['date', 'birthday']) && 'format' == $keyOption) {
558 if (empty($option)) {
559 $option = '%d%m%y';
560 } else {
561 $option = strtolower($option);
562 $position = [
563 '%y' => strpos($option, '%y'),
564 '%m' => strpos($option, '%m'),
565 '%d' => strpos($option, '%d'),
566 ];
567 asort($position);
568 $option = implode('', array_keys($position));
569 }
570 }
571 $optionName = $optionConnection[$keyOption];
572 $newOption->$optionName = $option;
573 }
574 $newOption->fieldDB = [];
575 foreach ($databaseConnection as $keyOldDatabase => $keyNewDatabase) {
576 if (!array_key_exists($keyOldDatabase, $options)) {
577 $newOption->fieldDB[$keyNewDatabase] = '';
578 continue;
579 }
580 if ('database' == $keyNewDatabase && 'current' == $options[$keyOldDatabase]) $options[$keyOldDatabase] = acym_loadResult('SELECT DATABASE();');
581 $newOption->fieldDB[$keyNewDatabase] = $options[$keyOldDatabase];
582 }
583 $newOption->fieldDB = json_encode($newOption->fieldDB);
584 $value = json_encode($newOption);
585 }
586 $column = $columnConnection[$key];
587 $newField->$column = $value;
588 }
589 $insertedFields[] = $fieldClass->save($newField);
590 }
591
592 return count($insertedFields);
593 }
594
595 public function migrateMails($params = [])
596 {
597 $queryGetMails = 'SELECT mail.`mailid`,
598 mail.`created`,
599 mail.`type`,
600 mail.`body`,
601 mail.`subject`,
602 mail.`fromname`,
603 mail.`fromemail`,
604 mail.`replyname`,
605 mail.`replyemail`,
606 mail.`bccaddresses`,
607 mail.`tempid`,
608 mail.`senddate`,
609 mail.`published`,
610 mail.`attach`,
611 mail.userid,
612 template.`stylesheet`,
613 template.`styles`
614 FROM #__acymailing_mail mail
615 LEFT JOIN #__acymailing_template template
616 ON mail.tempid = template.tempid
617 LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls']);
618
619 $mails = acym_loadObjectList($queryGetMails);
620
621 if (empty($mails)) return true;
622
623 $mailsToInsert = [];
624 $campaignsToInsert = [];
625 $followupsToInsert = [];
626 $followupsCreated = [];
627 $followupClass = new FollowupClass();
628
629 foreach ($mails as $oneMail) {
630 if (empty($oneMail->mailid)) {
631 continue;
632 }
633
634 switch ($oneMail->type) {
635 case 'welcome':
636 $mailType = MailClass::TYPE_WELCOME;
637 break;
638 case 'unsub':
639 $mailType = MailClass::TYPE_UNSUBSCRIBE;
640 break;
641 case 'followup':
642 $mailType = MailClass::TYPE_FOLLOWUP;
643 break;
644 case 'news':
645 $mailType = MailClass::TYPE_STANDARD;
646 break;
647 default:
648 $mailType = 'invalid';
649 break;
650 }
651
652 if ($mailType === 'invalid') {
653 continue;
654 }
655
656 $mailStylesheet = $oneMail->stylesheet;
657
658 $templateStyles = unserialize($oneMail->styles);
659
660 if ($templateStyles !== false) {
661 foreach ($templateStyles as $key => $value) {
662 if (strpos($key, 'tag_') !== false) {
663 $tag = str_replace('tag_', '', $key);
664 $styleDeclaration = $tag.'{'.$value.'}';
665 } elseif (strpos($key, 'color_bg') !== false) {
666 $styleDeclaration = '';
667 } else {
668 $styleDeclaration = '.'.$key.'{'.$value.'}';
669 }
670 $mailStylesheet .= $styleDeclaration;
671 }
672 }
673
674 $subject = acym_utf8Encode(substr($oneMail->subject, 0, 255));
675
676 $mail = [
677 'id' => intval($oneMail->mailid),
678 'name' => acym_escapeDB($subject),
679 'creation_date' => acym_escapeDB(acym_date(empty($oneMail->created) ? 'now' : $oneMail->created, 'Y-m-d H:i:s')),
680 'drag_editor' => 0,
681 'type' => acym_escapeDB($mailType),
682 'body' => acym_escapeDB(acym_utf8Encode($oneMail->body)),
683 'subject' => acym_escapeDB($subject),
684 'from_name' => acym_escapeDB($oneMail->fromname),
685 'from_email' => acym_escapeDB($oneMail->fromemail),
686 'reply_to_name' => acym_escapeDB($oneMail->replyname),
687 'reply_to_email' => acym_escapeDB($oneMail->replyemail),
688 'bcc' => acym_escapeDB($oneMail->bccaddresses),
689 'stylesheet' => acym_escapeDB($mailStylesheet),
690 'creator_id' => empty($oneMail->userid) ? acym_currentUserId() : intval($oneMail->userid),
691 'attachments' => [],
692 ];
693
694 if (!empty($oneMail->attach)) {
695 $attachments = unserialize($oneMail->attach);
696 foreach ($attachments as $oneAttachment) {
697 $fileName = substr($oneAttachment->filename, strrpos($oneAttachment->filename, DS));
698 $uploadFolder = str_replace(['/', '\\'], DS, acym_getFilesFolder());
699 $v7Location = $uploadFolder.$fileName;
700
701 $v5Path = acym_cleanPath(ACYM_ROOT.DS.$oneAttachment->filename);
702 if (!file_exists($v5Path)) continue;
703
704 $v7Path = acym_cleanPath(ACYM_ROOT.DS.$v7Location);
705 if (!file_exists($v7Path)) {
706 acym_copyFile($v5Path, $v7Path);
707 }
708
709 $mail['attachments'][] = (object)[
710 'filename' => $v7Location,
711 'size' => $oneAttachment->size,
712 ];
713 }
714 }
715 $mail['attachments'] = acym_escapeDB(json_encode($mail['attachments']));
716
717 if ($mailType === MailClass::TYPE_STANDARD) {
718 $stats = acym_loadResult('SELECT COUNT(mailid) FROM #__acymailing_stats WHERE mailid = '.intval($oneMail->mailid));
719 $isSent = !empty($stats);
720
721 $sendingType = intval(!$isSent && ($oneMail->senddate > time()));
722 $campaign = [
723 'sending_date' => empty($oneMail->senddate) ? 'NULL' : acym_escapeDB(acym_date($oneMail->senddate, 'Y-m-d H:i:s')),
724 'draft' => intval(!$isSent),
725 'active' => empty($oneMail->published) ? 0 : intval($oneMail->published),
726 'mail_id' => intval($oneMail->mailid),
727 'sending_type' => acym_escapeDB(0 === $sendingType ? CampaignClass::SENDING_TYPE_NOW : CampaignClass::SENDING_TYPE_SCHEDULED),
728 'sent' => intval($isSent),
729 'sending_params' => acym_escapeDB('[]'),
730 ];
731 $campaignsToInsert[] = '('.implode(', ', $campaign).')';
732 }
733
734 if ($mailType === MailClass::TYPE_FOLLOWUP) {
735 $v5Campaign = acym_loadObject(
736 'SELECT l.listid, l.published, l.name
737 FROM #__acymailing_listmail AS lm
738 JOIN #__acymailing_list AS l ON l.listid = lm.listid
739 WHERE mailid = '.intval($oneMail->mailid)
740 );
741
742 if (empty($followupsCreated[$v5Campaign->listid])) {
743 $followupListIds = acym_loadResultArray('SELECT listid FROM #__acymailing_listcampaign WHERE campaignid = '.intval($v5Campaign->listid));
744 $followupCampaign = new \stdClass();
745 $followupCampaign->name = $v5Campaign->name;
746 $followupCampaign->display_name = $v5Campaign->name;
747 $followupCampaign->creation_date = acym_date('now', 'Y-m-d H:i:s');
748 $followupCampaign->trigger = 'user_subscribe';
749 $followupCampaign->condition = [
750 'lists_status' => 'is',
751 'lists' => $followupListIds,
752 'segments_status' => '',
753 ];
754 $followupCampaign->active = $v5Campaign->published;
755 $followupCampaign->send_once = 1;
756 $followupCampaign->list_id = $v5Campaign->listid;
757
758 $followupsCreated[$v5Campaign->listid] = $followupClass->save($followupCampaign);
759 }
760
761 $delay = $oneMail->senddate;
762 if (empty($delay)) {
763 $unit = 60;
764 } elseif ($delay % 2628000 === 0) {
765 $unit = 2628000;
766 } elseif ($delay % 604800 === 0) {
767 $unit = 604800;
768 } elseif ($delay % 86400 === 0) {
769 $unit = 86400;
770 } elseif ($delay % 3600 === 0) {
771 $unit = 3600;
772 } else {
773 $unit = 60;
774 }
775 $delay = $delay / $unit;
776
777 $followup = [
778 'mail_id' => intval($oneMail->mailid),
779 'followup_id' => intval($followupsCreated[$v5Campaign->listid]),
780 'delay' => intval($delay),
781 'delay_unit' => intval($unit),
782 ];
783
784 $followupsToInsert[] = '('.implode(', ', $followup).')';
785 }
786
787 $mailsToInsert[] = '('.implode(', ', $mail).')';
788 }
789
790 if (empty($mailsToInsert)) {
791 return true;
792 }
793
794 $queryMailsInsert = 'INSERT INTO #__acym_mail ('.implode(', ', array_keys($mail)).') VALUES '.implode(',', $mailsToInsert).';';
795 $resultMail = $this->_insertQuery($queryMailsInsert);
796 if ($resultMail === false) {
797 return false;
798 }
799
800 if (!empty($campaignsToInsert)) {
801 $queryCampaignInsert = 'INSERT IGNORE INTO #__acym_campaign ('.implode(', ', array_keys($campaign)).') VALUES '.implode(',', $campaignsToInsert).';';
802 if ($this->_insertQuery($queryCampaignInsert) === false) {
803 return false;
804 }
805 }
806
807 if (!empty($followupsToInsert)) {
808 $queryInsert = 'INSERT IGNORE INTO #__acym_followup_has_mail ('.implode(', ', array_keys($followup)).') VALUES '.implode(',', $followupsToInsert).';';
809 if ($this->_insertQuery($queryInsert) === false) {
810 return false;
811 }
812 }
813
814 return $resultMail;
815 }
816
817 public function migrateLists($params = [])
818 {
819 $lists = acym_loadObjectList(
820 'SELECT `listid`, `name`, `published`, `visible`, `color`, `userid`, `type`, `description`, `access_manage`
821 FROM #__acymailing_list
822 LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls'])
823 );
824
825 $listsToInsert = [];
826
827 $siteUserGroupIds = array_keys(acym_getGroups());
828
829 foreach ($lists as $oneList) {
830 $access = '';
831 if ($oneList->access_manage === 'all') {
832 $access = ','.implode(',', $siteUserGroupIds).',';
833 } elseif ($oneList->access_manage !== 'none') {
834 $access = $oneList->access_manage;
835 }
836
837 $list = [
838 'id' => intval($oneList->listid),
839 'name' => acym_escapeDB($oneList->name),
840 'active' => $oneList->type === 'campaign' ? 1 : (empty($oneList->published) ? 0 : 1),
841 'visible' => acym_escapeDB($oneList->visible),
842 'clean' => 0,
843 'color' => acym_escapeDB($oneList->color),
844 'creation_date' => acym_escapeDB(acym_date('now', 'Y-m-d H:i:s')),
845 'cms_user_id' => empty($oneList->userid) ? acym_currentUserId() : intval($oneList->userid),
846 'description' => acym_escapeDB($oneList->description),
847 'type' => acym_escapeDB($oneList->type === 'campaign' ? ListClass::LIST_TYPE_FOLLOWUP : ListClass::LIST_TYPE_STANDARD),
848 'access' => acym_escapeDB($access),
849 ];
850
851 $listsToInsert[] = '('.implode(', ', $list).')';
852 }
853
854 if (empty($listsToInsert)) {
855 return true;
856 }
857
858 $queryInsert = 'INSERT INTO #__acym_list ('.implode(', ', array_keys($list)).') VALUES '.implode(',', $listsToInsert).';';
859
860 return $this->_insertQuery($queryInsert, 0);
861 }
862
863 public function migrateUsers($params = [])
864 {
865 $result = 0;
866
867 $queryGetUsers = 'SELECT `subid`, `name`, `email`, `created`, `enabled`, `userid`, `source`, `confirmed`, `key` FROM #__acymailing_subscriber LIMIT '.intval(
868 $params['currentElement']
869 ).', '.intval($params['insertPerCalls']);
870
871 $users = acym_loadObjectList($queryGetUsers, 'subid');
872
873 $usersToInsert = [];
874
875 foreach ($users as $oneUser) {
876 if (empty($oneUser->subid)) {
877 continue;
878 }
879
880 $user = [
881 'id' => intval($oneUser->subid),
882 'name' => acym_escapeDB($oneUser->name),
883 'email' => acym_escapeDB($oneUser->email),
884 'creation_date' => acym_escapeDB(empty($oneUser->created) ? acym_date('now', 'Y-m-d H:i:s') : acym_date($oneUser->created, 'Y-m-d H:i:s')),
885 'active' => acym_escapeDB($oneUser->enabled),
886 'cms_id' => intval($oneUser->userid),
887 'source' => acym_escapeDB($oneUser->source),
888 'confirmed' => acym_escapeDB($oneUser->confirmed),
889 'key' => acym_escapeDB($oneUser->key),
890 ];
891
892 $usersToInsert[] = '('.implode(', ', $user).')';
893 }
894
895 if (empty($usersToInsert)) {
896 return true;
897 }
898
899 $queryInsert = 'INSERT INTO #__acym_user (`id`, `name`, `email`, `creation_date`, `active`, `cms_id`, `source`, `confirmed`, `key`) VALUES '.implode(
900 ', ',
901 $usersToInsert
902 ).';';
903
904 return $this->_insertQuery($queryInsert, $result);
905 }
906
907 public function migrateBounce($params = [])
908 {
909 $rules = acym_loadObjectList('SELECT * FROM #__acymailing_rules LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls']));
910
911 if (empty($rules)) return true;
912
913 $keys = [
914 'ACY_RULE_ACTION' => 'ACYM_ACTION_REQUIRED',
915 'ACY_RULE_ACKNOWLEDGE_BODY' => 'ACYM_ACKNOWLEDGMENT_RECEIPT_BODY',
916 'ACY_RULE_ACKNOWLEDGE' => 'ACYM_ACKNOWLEDGMENT_RECEIPT_SUBJECT',
917 'ACY_RULE_LOOP_BODY' => 'ACYM_FEEDBACK_LOOP_BODY',
918 'ACY_RULE_LOOP' => 'ACYM_FEEDBACK_LOOP',
919 'ACY_RULE_FULL' => 'ACYM_MAILBOX_FULL',
920 'ACY_RULE_GOOGLE' => 'ACYM_BLOCKED_GOOGLE_GROUPS',
921 'ACY_RULE_EXIST1' => 'ACYM_MAILBOX_DOESNT_EXIST_1',
922 'ACY_RULE_FILTERED' => 'ACYM_MESSAGE_BLOCKED_RECIPIENTS',
923 'ACY_RULE_EXIST2' => 'ACYM_MAILBOX_DOESNT_EXIST_2',
924 'ACY_RULE_DOMAIN' => 'ACYM_DOMAIN_NOT_EXIST',
925 'ACY_RULE_TEMPORAR' => 'ACYM_TEMPORARY_FAILURES',
926 'ACY_RULE_PERMANENT' => 'ACYM_FAILED_PERM',
927 'ACY_RULE_FINAL' => 'ACYM_FINAL_RULE',
928 ];
929
930 $migratedRules = [];
931 foreach ($rules as $oneRule) {
932
933 $actionUser = unserialize($oneRule->action_user);
934 $actionMessage = unserialize($oneRule->action_message);
935
936 $actionsOnUsers = [];
937 if (!empty($actionUser['unsub'])) $actionsOnUsers[] = 'unsubscribe_user';
938 if (!empty($actionUser['sub']) && !empty($actionUser['subscribeto'])) {
939 $actionsOnUsers[] = 'subscribe_user';
940 $actionsOnUsers['subscribe_user_list'] = $actionUser['subscribeto'];
941 }
942 if (!empty($actionUser['block'])) $actionsOnUsers[] = 'block_user';
943 if (!empty($actionUser['delete'])) $actionsOnUsers[] = 'delete_user';
944 if (!empty($actionUser['emptyq'])) $actionsOnUsers[] = 'empty_queue_user';
945
946
947 $actionsOnEmail = [];
948 if (!empty($actionMessage['save'])) $actionsOnEmail[] = 'save_message';
949 if (!empty($actionMessage['delete'])) $actionsOnEmail[] = 'delete_message';
950 if (!empty($actionMessage['forwardto'])) {
951 $actionsOnEmail[] = 'forward_message';
952 $actionsOnEmail['forward_to'] = $actionMessage['forwardto'];
953 }
954
955 $rule = [
956 'id' => intval($oneRule->ruleid),
957 'name' => acym_escapeDB(str_replace(array_keys($keys), $keys, $oneRule->name)),
958 'active' => intval($oneRule->published),
959 'ordering' => intval($oneRule->ordering),
960 'regex' => acym_escapeDB($oneRule->regex),
961 'executed_on' => acym_escapeDB(json_encode(array_keys(unserialize($oneRule->executed_on)))),
962 'execute_action_after' => empty($actionUser['min']) ? 0 : intval($actionUser['min']),
963 'increment_stats' => empty($actionUser['stats']) ? 0 : intval($actionUser['stats']),
964 'action_user' => acym_escapeDB(json_encode($actionsOnUsers)),
965 'action_message' => acym_escapeDB(json_encode($actionsOnEmail)),
966 ];
967
968 $migratedRules[] = '('.implode(', ', $rule).')';
969 }
970
971 if (empty($migratedRules)) return true;
972
973 $queryInsert = 'INSERT INTO #__acym_rule (`id`, `name`, `active`, `ordering`, `regex`, `executed_on`, `execute_action_after`, `increment_stats`, `action_user`, `action_message`) VALUES '.implode(
974 ', ',
975 $migratedRules
976 );
977
978 try {
979 return acym_query($queryInsert);
980 } catch (\Exception $e) {
981 $this->errors[] = $e->getMessage();
982
983 return false;
984 }
985 }
986
987 public function migrateDistrib($params = [])
988 {
989 $distributionLists = acym_loadObjectList(
990 'SELECT *
991 FROM #__acymailing_action
992 LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls'])
993 );
994
995 if (empty($distributionLists)) {
996 return true;
997 }
998
999 $mailboxClass = new MailboxClass();
1000 $listClass = new ListClass();
1001 $standardLists = array_column($listClass->getAllWithoutManagement(), 'id');;
1002 $groups = acym_getGroups();
1003 foreach ($distributionLists as $oneDistributionList) {
1004 $mailboxAction = new \stdClass();
1005 $mailboxAction->name = $oneDistributionList->name;
1006 $mailboxAction->active = $oneDistributionList->published;
1007 $mailboxAction->frequency = $oneDistributionList->frequency;
1008 $mailboxAction->description = $oneDistributionList->description;
1009
1010 $mailboxAction->server = $oneDistributionList->server;
1011 $mailboxAction->username = $oneDistributionList->username;
1012 $mailboxAction->password = $oneDistributionList->password;
1013 $mailboxAction->connection_method = $oneDistributionList->connection_method;
1014 $mailboxAction->secure_method = $oneDistributionList->secure_method;
1015 $mailboxAction->port = $oneDistributionList->port;
1016 $mailboxAction->self_signed = $oneDistributionList->self_signed;
1017
1018 $mailboxAction->delete_wrong_emails = $oneDistributionList->delete_wrong_emails;
1019
1020 $oneDistributionList->conditions = json_decode($oneDistributionList->conditions, true);
1021 $mailboxAction->conditions = [
1022 'sender' => '',
1023 'specific' => '',
1024 'groups' => [],
1025 'lists' => [],
1026 'subject' => '',
1027 'subject_text' => '',
1028 'subject_regex' => '',
1029 ];
1030
1031 if ($oneDistributionList->conditions['sender'] === 'specific') {
1032 $mailboxAction->conditions['sender'] = 'specific';
1033 $mailboxAction->conditions['specific'] = $oneDistributionList->conditions['specific'];
1034 } elseif ($oneDistributionList->conditions['sender'] === 'group') {
1035 $mailboxAction->conditions['sender'] = 'groups';
1036 if ($oneDistributionList->conditions['group'] === 'all') {
1037 $mailboxAction->conditions['groups'] = array_keys($groups);
1038 } else {
1039 $mailboxAction->conditions['groups'] = $oneDistributionList->conditions['group'];
1040 }
1041 } elseif ($oneDistributionList->conditions['sender'] === 'list') {
1042 $mailboxAction->conditions['sender'] = 'lists';
1043 if ($oneDistributionList->conditions['listids'] === 'All') {
1044 $mailboxAction->conditions['lists'] = $standardLists;
1045 } else {
1046 $mailboxAction->conditions['lists'] = is_array($oneDistributionList->conditions['listids']) ? $oneDistributionList->conditions['listids']
1047 : [$oneDistributionList->conditions['listids']];
1048 }
1049 }
1050
1051 if ($oneDistributionList->conditions['subject'] !== 'all') {
1052 $mailboxAction->conditions['subject'] = $oneDistributionList->conditions['subject'];
1053 $mailboxAction->conditions['subject_text'] = $oneDistributionList->conditions['subjectvalue'];
1054 }
1055
1056 $mailboxAction->conditions['subject_remove'] = $oneDistributionList->conditions['removeSubject'];
1057
1058
1059 $oneDistributionList->actions = json_decode($oneDistributionList->actions, true);
1060 $mailboxAction->actions = [];
1061
1062 foreach ($oneDistributionList->actions as $oneAction) {
1063 if ($oneAction['type'] === 'forward') {
1064 $mailboxAction->actions[] = [
1065 'forward_specific' => [
1066 'addresses' => $oneAction['forward'],
1067 'template_id' => $oneAction['template'],
1068 ],
1069 ];
1070 } elseif ($oneAction['type'] === 'forwardlist') {
1071 $mailboxAction->actions[] = [
1072 'forward_list' => [
1073 'list_id' => $oneAction['list'],
1074 'template_id' => $oneAction['template'],
1075 ],
1076 ];
1077 } elseif ($oneAction['type'] === 'subscribe') {
1078 $mailboxAction->actions[] = [
1079 'acy_list_subscribe' => [
1080 'list_id' => $oneAction['list'],
1081 ],
1082 ];
1083 } elseif ($oneAction['type'] === 'unsubscribe') {
1084 $mailboxAction->actions[] = [
1085 'acy_list_unsubscribe' => [
1086 'list_id' => $oneAction['list'],
1087 ],
1088 ];
1089 }
1090 }
1091
1092 $mailboxAction->conditions = json_encode($mailboxAction->conditions);
1093 $mailboxAction->actions = json_encode($mailboxAction->actions);
1094
1095 $mailboxAction->senderfrom = $oneDistributionList->senderfrom;
1096 $mailboxAction->senderto = $oneDistributionList->senderto;
1097
1098 $mailboxClass->save($mailboxAction);
1099 }
1100
1101 return true;
1102 }
1103
1104 public function migrateSubscriptions($params = [])
1105 {
1106 $result = 0;
1107
1108 $queryGetSubscriptions = 'SELECT `listid`, `subid`, `subdate`, `unsubdate`, `status` FROM #__acymailing_listsub LIMIT '.intval($params['currentElement']).', '.intval(
1109 $params['insertPerCalls']
1110 );
1111
1112 $subscriptions = acym_loadObjectList($queryGetSubscriptions);
1113
1114 if (empty($subscriptions)) return true;
1115
1116 $subscriptionsToInsert = [];
1117
1118 foreach ($subscriptions as $oneSubscription) {
1119 if (empty($oneSubscription->subid) || empty($oneSubscription->listid)) {
1120 continue;
1121 }
1122
1123 if ($oneSubscription->status == 2) $oneSubscription->status = 1;
1124
1125 $subscription = [
1126 'user_id' => acym_escapeDB($oneSubscription->subid),
1127 'list_id' => acym_escapeDB($oneSubscription->listid),
1128 'status' => acym_escapeDB($oneSubscription->status == -1 ? 0 : $oneSubscription->status),
1129 'subscription_date' => empty($oneSubscription->subdate) ? 'NULL' : acym_escapeDB(acym_date($oneSubscription->subdate, 'Y-m-d H:i:s')),
1130 'unsubscribe_date' => empty($oneSubscription->unsubdate) ? 'NULL' : acym_escapeDB(acym_date($oneSubscription->unsubdate, 'Y-m-d H:i:s')),
1131 ];
1132
1133 $subscriptionsToInsert[] = '('.implode(', ', $subscription).')';
1134 }
1135
1136 if (empty($subscriptionsToInsert)) {
1137 return true;
1138 }
1139
1140 $queryInsert = 'INSERT IGNORE INTO #__acym_user_has_list (`user_id`, `list_id`, `status`, `subscription_date`, `unsubscribe_date`) VALUES '.implode(
1141 ', ',
1142 $subscriptionsToInsert
1143 ).';';
1144
1145 return $this->_insertQuery($queryInsert, $result);
1146 }
1147
1148 public function migrateMailHasLists($params = [])
1149 {
1150 $result = 0;
1151
1152 $queryGetMailHasLists = 'SELECT listmail.`mailid`, listmail.`listid`
1153 FROM #__acymailing_listmail AS listmail
1154 JOIN #__acymailing_mail AS mail ON mail.`mailid` = listmail.`mailid`
1155 WHERE mail.`type` IN ("news", "unsub", "welcome", "followup")
1156 LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls']);
1157
1158 $mailHasLists = acym_loadObjectList($queryGetMailHasLists);
1159 if (empty($mailHasLists)) return true;
1160
1161 $mailHasListsToInsert = [];
1162
1163 foreach ($mailHasLists as $oneMailHasLists) {
1164 if (empty($oneMailHasLists->mailid) || empty($oneMailHasLists->listid)) {
1165 continue;
1166 }
1167
1168 $mailHasListsToInsert[] = '('.intval($oneMailHasLists->mailid).', '.intval($oneMailHasLists->listid).')';
1169 }
1170
1171 if (empty($mailHasListsToInsert)) {
1172 return true;
1173 }
1174
1175 $queryInsert = 'INSERT IGNORE INTO #__acym_mail_has_list (`mail_id`, `list_id`) VALUES '.implode(',', $mailHasListsToInsert).';';
1176
1177 return $this->_insertQuery($queryInsert, $result);
1178 }
1179
1180 public function migrateMailStats($params = [])
1181 {
1182 $result = 0;
1183
1184 $queryGetStats = 'SELECT `mailid`, `senthtml`, `senttext`, `senddate`, `fail`, `openunique`, `opentotal` FROM #__acymailing_stats LIMIT '.intval(
1185 $params['currentElement']
1186 ).', '.intval($params['insertPerCalls']);
1187
1188 $stats = acym_loadObjectList($queryGetStats);
1189 if (empty($stats)) return true;
1190
1191
1192 $statsToInsert = [];
1193
1194 $allMails = acym_loadResultArray('SELECT id FROM #__acym_mail');
1195
1196 foreach ($stats as $oneStat) {
1197 if (empty($oneStat->mailid) || !in_array($oneStat->mailid, $allMails)) {
1198 continue;
1199 }
1200
1201 $totalSent = intval($oneStat->senthtml) + intval($oneStat->senttext);
1202 $stat = [
1203 'mail_id' => acym_escapeDB($oneStat->mailid),
1204 'total_subscribers' => acym_escapeDB($totalSent + $oneStat->fail),
1205 'sent' => acym_escapeDB($totalSent),
1206 'send_date' => empty($oneStat->senddate) ? 'NULL' : acym_escapeDB(acym_date($oneStat->senddate, 'Y-m-d H:i:s')),
1207 'fail' => acym_escapeDB($oneStat->fail),
1208 'open_unique' => intval($oneStat->openunique),
1209 'open_total' => intval($oneStat->opentotal),
1210 ];
1211 $statsToInsert[] = '('.implode(', ', $stat).')';
1212 }
1213
1214 if (empty($statsToInsert)) {
1215 return true;
1216 }
1217
1218 $queryInsert = 'INSERT IGNORE INTO #__acym_mail_stat (`mail_id`, `total_subscribers`, `sent`, `send_date`, `fail`, `open_unique`, `open_total`) VALUES '.implode(
1219 ',',
1220 $statsToInsert
1221 ).';';
1222
1223 return $this->_insertQuery($queryInsert, $result);
1224 }
1225
1226 public function migrateWelcomeunsub($params = [])
1227 {
1228 $result = 0;
1229
1230 $queryGetIds = 'SELECT `listid`, `welmailid`, `unsubmailid` FROM #__acymailing_list LIMIT '.intval($params['currentElement']).', '.intval($params['insertPerCalls']);
1231
1232 $ids = acym_loadObjectList($queryGetIds);
1233
1234 if (empty($ids)) return true;
1235
1236 $idsToInsert = [];
1237
1238 foreach ($ids as $oneId) {
1239 if (empty($oneId->listid) || (empty($oneId->welmailid) && empty($oneId->unsubmailid))) {
1240 continue;
1241 }
1242
1243 $welId = empty($oneId->welmailid) ? 'NULL' : intval($oneId->welmailid);
1244 $unsId = empty($oneId->unsubmailid) ? 'NULL' : intval($oneId->unsubmailid);
1245
1246 $id = [
1247 'id' => intval($oneId->listid),
1248 'welcome_id' => $welId,
1249 'unsubscribe_id' => $unsId,
1250 ];
1251
1252 $idsToInsert[] = '('.implode(', ', $id).')';
1253 }
1254
1255 if (empty($idsToInsert)) {
1256 return true;
1257 }
1258
1259 $queryInsert = 'INSERT IGNORE INTO #__acym_list(`id`, `welcome_id`, `unsubscribe_id`) VALUES '.implode(
1260 ',',
1261 $idsToInsert
1262 ).' ON DUPLICATE KEY UPDATE `welcome_id` = VALUES(`welcome_id`), `unsubscribe_id` = VALUES(`unsubscribe_id`)';
1263
1264 return $this->_insertQuery($queryInsert, $result);
1265 }
1266
1267
1268 private function cleanFieldsTable()
1269 {
1270 $queryClean = [
1271 'DELETE FROM #__acym_user_has_field',
1272 'DELETE FROM #__acym_field WHERE `id` NOT IN (1,2)',
1273 ];
1274
1275 return $this->_finalizeClean($queryClean);
1276 }
1277
1278 private function cleanUsers_fieldsTable()
1279 {
1280 return true;
1281 }
1282
1283 private function _finalizeClean($queryClean)
1284 {
1285 $hasError = false;
1286
1287 foreach ($queryClean as $oneQuery) {
1288 try {
1289 $res = acym_query($oneQuery);
1290 } catch (\Exception $e) {
1291 $res = null;
1292 }
1293 if ($res === null) {
1294 $this->errors[] = isset($e) ? $e->getMessage() : acym_getDBError();
1295 $hasError = true;
1296 break;
1297 }
1298 }
1299
1300 return !$hasError;
1301 }
1302
1303 private function cleanMailsTable()
1304 {
1305 $queryClean = [
1306 'UPDATE #__acym_list SET `unsubscribe_id` = NULL',
1307 'UPDATE #__acym_list SET `welcome_id` = NULL',
1308 'UPDATE #__acym_mail SET `parent_id` = NULL',
1309 'DELETE FROM #__acym_mail_archive',
1310 'DELETE FROM #__acym_followup_has_mail',
1311 'DELETE FROM #__acym_followup',
1312 'DELETE FROM #__acym_tag WHERE `type` = "mail"',
1313 'DELETE FROM #__acym_mail_override',
1314 'DELETE FROM #__acym_campaign WHERE `mail_id` IS NOT NULL',
1315 'DELETE FROM #__acym_campaign',
1316 'DELETE FROM #__acym_queue',
1317 'DELETE FROM #__acym_mail_has_list',
1318 'DELETE FROM #__acym_user_stat',
1319 'DELETE FROM #__acym_url_click',
1320 'DELETE FROM #__acym_mail_stat',
1321 'DELETE FROM #__acym_mail',
1322 ];
1323
1324 return $this->_finalizeClean($queryClean);
1325 }
1326
1327 private function cleanListsTable()
1328 {
1329 $queryClean = [
1330 'UPDATE #__acym_followup SET `list_id` = NULL',
1331 'DELETE FROM #__acym_tag WHERE `type` = "list"',
1332 'DELETE FROM #__acym_mail_has_list',
1333 'DELETE FROM #__acym_user_has_list',
1334 'DELETE FROM #__acym_list',
1335 ];
1336
1337 return $this->_finalizeClean($queryClean);
1338 }
1339
1340 private function cleanUsersTable()
1341 {
1342 $queryClean = [
1343 'DELETE FROM `#__acym_user_has_field`',
1344 'DELETE FROM `#__acym_user_has_list`',
1345 'DELETE FROM `#__acym_queue`',
1346 'DELETE FROM `#__acym_user`',
1347 ];
1348
1349 return $this->_finalizeClean($queryClean);
1350 }
1351
1352 private function cleanBounceTable()
1353 {
1354 $queryClean = [
1355 'DELETE FROM `#__acym_rule`',
1356 ];
1357
1358 return $this->_finalizeClean($queryClean);
1359 }
1360
1361 private function cleanDistribTable()
1362 {
1363 $queryClean = [
1364 'DELETE FROM `#__acym_mailbox_action`',
1365 ];
1366
1367 return $this->_finalizeClean($queryClean);
1368 }
1369
1370 public function doElementMigration($elementName, $params = [])
1371 {
1372 $functionName = 'migrate'.ucfirst($elementName);
1373 $params['currentElement'] = acym_getVar('int', 'currentElement');
1374 $params['insertPerCalls'] = acym_getVar('int', 'insertPerCalls');
1375
1376 if (empty($params)) {
1377 $nbInsert = $this->$functionName();
1378 } else {
1379 $nbInsert = $this->$functionName($params);
1380 }
1381
1382 if ($nbInsert !== false) {
1383 $this->result[$elementName] = $nbInsert;
1384
1385 return true;
1386 } else {
1387 $this->result[$elementName] = false;
1388 $this->result['isOk'] = false;
1389 $this->result['errorInsert'] = true;
1390 $this->result['errors'] = $this->errors;
1391
1392 return false;
1393 }
1394 }
1395
1396 private function doCleanTable($tableName)
1397 {
1398 $functionName = 'clean'.ucfirst($tableName).'Table';
1399
1400 if (method_exists($this, $functionName) && !$this->$functionName()) {
1401 $this->result['isOk'] = false;
1402 $this->result['errorClean'] = true;
1403 $this->result['errors'] = $this->errors;
1404 }
1405
1406 return $this->result;
1407 }
1408
1409 public function preMigration($element)
1410 {
1411 $connection = [
1412 'config' => ['table' => 'config', 'where' => ''],
1413 'templates' => ['table' => 'template', 'where' => ''],
1414 'mails' => ['table' => 'mail', 'where' => ''],
1415 'lists' => ['table' => 'list', 'where' => ''],
1416 'users' => ['table' => 'subscriber', 'where' => ''],
1417 'bounce' => ['table' => 'rules', 'where' => ''],
1418 'distrib' => ['table' => 'action', 'where' => ''],
1419 'subscriptions' => ['table' => 'listsub', 'where' => ''],
1420 'mailhaslists' => ['table' => 'listmail', 'where' => ''],
1421 'mailstats' => ['table' => 'stats', 'where' => ''],
1422 'welcomeunsub' => ['table' => 'list', 'where' => 'unsubmailid IS NOT NULL OR welmailid IS NOT NULL'],
1423 'users_fields' => ['table' => 'subscriber'],
1424 'fields' => ['table' => 'fields', 'where' => 'namekey NOT IN (\'name\', \'html\', \'email\')'],
1425 ];
1426
1427 $this->doCleanTable($element);
1428
1429 if ('users_fields' === $element) {
1430 $fields = acym_loadResultArray(
1431 'SELECT namekey FROM #__acymailing_fields WHERE `namekey` NOT IN ("name", "email", "html") AND `type` NOT IN ("customtext", "category", "gravatar")'
1432 );
1433 $columnUserTable = acym_getColumns('acymailing_subscriber', false);
1434
1435 $fieldToCheck = [];
1436
1437 foreach ($fields as $key => $field) {
1438 if (in_array($field, $columnUserTable)) {
1439 $fieldToCheck[$key] = '`'.$field.'`';
1440 }
1441 }
1442
1443 $connection[$element]['where'] = implode(' IS NOT NULL OR ', $fieldToCheck);
1444 if (!empty($fieldToCheck)) {
1445 $connection[$element]['where'] .= ' IS NOT NULL;';
1446 }
1447 }
1448
1449 $query = 'SELECT COUNT(*) FROM #__acymailing_'.$connection[$element]['table'];
1450 if (!empty($connection[$element]['where'])) {
1451 $query .= ' WHERE '.$connection[$element]['where'];
1452 }
1453
1454 $this->result['count'] = acym_loadResult($query);
1455
1456 return $this->result;
1457 }
1458 }
1459