PluginProbe
AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress / 10.2.2
AcyMailing – An Ultimate Newsletter Plugin and Marketing Automation Solution for WordPress v10.2.2
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.2.2, at back/Helpers/MigrationHelper.php

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