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

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