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