Completed
Push — development ( cfd391...deed4d )
by Andrij
12:03
created

ParentEmail::email_check()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 7

Duplication

Lines 14
Ratio 100 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 3
nop 1
dl 14
loc 14
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace cmsemail\classes;
4
5
use CI_DB_active_record;
6
use CI_Input;
7
use CI_URI;
8
use Cmsemail_model;
9
use CMSFactory\Events;
10
use DX_Auth;
11
use MY_Controller;
12
use MY_Lang;
13
14
/**
15
 * Image CMS
16
 * Module Wishlist
17
 * @property Cmsemail_model $cmsemail_model
18
 * @property DX_Auth $dx_auth
19
 * @property CI_URI $uri
20
 * @property CI_DB_active_record $db
21
 * @property CI_Input $input
22
 * @version 1.0 big start!
23
 */
24
class ParentEmail extends MY_Controller
25
{
26
27
    /**
28
     * List of accepted params
29
     * @var array
30
     */
31
    public $accepted_params = [
32
                               'name',
33
                               'from',
34
                               'from_email',
35
                               'theme',
36
                               'type',
37
                               'user_message',
38
                               'user_message_active',
39
                               'admin_message',
40
                               'admin_message_active',
41
                               'admin_email',
42
                               'description',
43
                              ];
44
45
    /**
46
     * Attachment file
47
     * @var string
48
     */
49
    protected $attachment;
50
51
    /**
52
     * Array of data
53
     * @var array
54
     */
55
    public $data_model = [];
56
57
    /**
58
     * Array of errors
59
     * @var array
60
     */
61
    public $errors = [];
62
63
    /**
64
     * Email sender name
65
     * @var string
66
     */
67
    protected $from;
68
69
    /**
70
     * Email sender email address
71
     * @var string
72
     */
73
    protected $from_email;
74
75
    /**
76
     * Server path to Sendmail
77
     * @var string
78
     */
79
    protected $mailpath;
80
81
    /**
82
     * Email message
83
     * @var string
84
     */
85
    protected $message;
86
87
    /**
88
     * Mail port
89
     * @var int
90
     */
91
    protected $port;
92
93
    /**
94
     * Mail protocol
95
     * @var string
96
     */
97
    protected $protocol;
98
99
    /**
100
     * Receiver email
101
     * @var string
102
     */
103
    protected $send_to;
104
105
    /**
106
     * Email theme
107
     * @var string
108
     */
109
    protected $theme;
110
111
    /**
112
     * Mail content type
113
     * @var string
114
     */
115
    protected $type;
116
117
    public function __construct() {
118
        parent::__construct();
119
        $this->load->model('../' . getModContDirName('cmsemail') . '/cmsemail/models/cmsemail_model');
120
        (new MY_Lang())->load('cmsemail');
121
    }
122
123
    /**
124
     * @param int $template_id
125
     * @param string $variable
126
     * @param string $variableValue
127
     * @param string $locale
128
     * @return object
129
     */
130
    public function addVariable($template_id, $variable, $variableValue, $locale) {
131
        return $this->cmsemail_model->addVariable($template_id, $variable, $variableValue, $locale);
132
    }
133
134
    /**
135
     *
136
     * @param array $data keys from list:
137
     * 'name',
0 ignored issues
show
introduced by
Parameter comment must start with a capital letter
Loading history...
138
     * 'from',
139
     * 'from_email',
140
     * 'theme',
141
     * 'type',
142
     * 'user_message',
143
     * 'user_message_active',
144
     * 'admin_message',
145
     * 'admin_message_active',
146
     * 'admin_email',
147
     * 'description'
0 ignored issues
show
introduced by
Parameter comment must end with a full stop
Loading history...
148
     * @return boolean
149
     */
150
    public function create($data = []) {
151
        if ($this->input->post()) {
152
            $this->form_validation->set_rules('mail_name', lang('Template name', 'cmsemail'), 'required|alpha_dash');
153
            $this->form_validation->set_rules('from_email', lang('From email', 'cmsemail'), 'valid_email');
154
            $this->form_validation->set_rules('mail_theme', lang('Template theme', 'cmsemail'), 'required');
155
156
            if ($this->input->post('userMailTextRadio')) {
157
                $this->form_validation->set_rules('userMailText', lang('Template user mail', 'cmsemail'), 'required');
158
            }
159
160
            if ($this->input->post('adminMailTextRadio')) {
161
                $this->form_validation->set_rules('adminMailText', lang('Template admin mail', 'cmsemail'), 'required');
162
            }
163
164
            $this->form_validation->set_rules('admin_email', lang('Admin address', 'cmsemail'), 'valid_email');
165
166 View Code Duplication
            if ($this->form_validation->run($this) == FALSE) {
167
                $this->errors = validation_errors();
168
                return FALSE;
169
            } else {
170
                return TRUE;
171
            }
172 View Code Duplication
        } else {
173
            if (is_array($data) && !empty($data)) {
174
                foreach ($data as $key => $d) {
175
                    if (!in_array($key, $this->accepted_params)) {
176
                        unset($data[$key]);
177
                    }
178
                }
179
180
                $this->data_model = $data;
181
                return TRUE;
182
            } else {
183
                return FALSE;
184
            }
185
        }
186
    }
187
188
    /**
189
     * @param array $ids
190
     * @return bool
191
     */
192
    public function delete(array $ids) {
193
        return $this->cmsemail_model->deleteTemplateByID($ids);
194
    }
195
196
    /**
197
     * @param int $template_id
198
     * @param string $variable
199
     * @param string $locale
200
     * @return bool|object
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use object|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
201
     */
202
    public function deleteVariable($template_id, $variable, $locale) {
203
        return $this->cmsemail_model->deleteVariable($template_id, $variable, $locale);
204
    }
205
206
    /**
207
     *
208
     * @param integer $id ID of element
209
     * @param array $data keys from list:
210
     * 'name',
0 ignored issues
show
introduced by
Parameter comment must start with a capital letter
Loading history...
211
     * 'from',
212
     * 'from_email',
213
     * 'theme',
214
     * 'type',
215
     * 'user_message',
216
     * 'user_message_active',
217
     * 'admin_message',
218
     * 'admin_message_active',
219
     * 'admin_email',
220
     * 'description'
0 ignored issues
show
introduced by
Parameter comment must end with a full stop
Loading history...
221
     * @return boolean
222
     */
223
    public function edit($id, $data = []) {
224
        if ($this->input->post()) {
225
            $this->form_validation->set_rules('from_email', lang('From email', 'cmsemail'), 'valid_email');
226
            $this->form_validation->set_rules('mail_theme', lang('Template theme', 'cmsemail'), 'required');
227
228
            if ($this->input->post('userMailTextRadio')) {
229
                $this->form_validation->set_rules('userMailText', lang('Template user mail', 'cmsemail'), 'required');
230
            }
231
232
            if ($this->input->post('adminMailTextRadio')) {
233
                $this->form_validation->set_rules('adminMailText', lang('Template admin mail', 'cmsemail'), 'required');
234
            }
235
236
            $this->form_validation->set_rules('admin_email', lang('Admin address', 'cmsemail'), 'trim|callback_email_check');
237
238 View Code Duplication
            if ($this->form_validation->run($this) == FALSE) {
239
                $this->errors = validation_errors();
240
                return FALSE;
241
            } else {
242
                return TRUE;
243
            }
244 View Code Duplication
        } else {
245
            if (is_array($data) && !empty($data)) {
246
                foreach ($data as $key => $d) {
247
                    if (!in_array($key, $this->accepted_params)) {
248
                        unset($data[$key]);
249
                    }
250
                }
251
252
                $this->data_model = $data;
253
                return TRUE;
254
            } else {
255
                return FALSE;
256
            }
257
        }
258
    }
259
260
    /**
261
     * @param $emails
0 ignored issues
show
introduced by
Missing parameter type
Loading history...
262
     *
263
     * @return bool
264
     */
265 View Code Duplication
    public function email_check($emails) {
266
267
        $emails = str_replace(' ', '', $emails);
268
269
        foreach (explode(',', $emails) as $e) {
270
            if (!filter_var($e, FILTER_VALIDATE_EMAIL)) {
271
                $this->form_validation->set_message('email_check', lang('Field', 'cmsemail') . ' %s ' . lang('Must contain valid email', 'cmsemail'));
272
273
                return false;
274
            }
275
        }
276
277
        return TRUE;
278
    }
279
280
    /**
281
     * @return array|string
282
     */
283
    public function getAllTemplates() {
284
        return $this->cmsemail_model->getAllTemplates();
285
    }
286
287
    /**
288
     * @param bool|string $locale
289
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be array|null|string? Also, consider making the array more specific, something like array<String>, or String[].

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

If the return type contains the type array, this check recommends the use of a more specific type like String[] or array<String>.

Loading history...
290
     */
291
    public function getSettings($locale = FALSE) {
292
        return $this->cmsemail_model->getSettings($locale);
293
    }
294
295
    /**
296
     * @param int $id
297
     * @param string $locale
298
     * @return mixed
299
     */
300
    public function getTemplateById($id, $locale) {
301
        return $this->cmsemail_model->getTemplateById($id, $locale);
302
    }
303
304
    /**
305
     * @param string $template_id
306
     * @param string $locale
307
     * @return bool|mixed
308
     */
309
    public function getTemplateVariables($template_id, $locale) {
310
        return $this->cmsemail_model->getTemplateVariables($template_id, $locale);
311
    }
312
313
    /**
314
     * test mail sending
315
     *
316
     * @param array $config cohfiguration options for sending email:
317
     * 'protocol',
0 ignored issues
show
introduced by
Parameter comment must start with a capital letter
Loading history...
318
     * 'smtp_port',
319
     * 'type',
320
     * 'mailpath'
0 ignored issues
show
introduced by
Parameter comment must end with a full stop
Loading history...
321
     */
322
    public function mailTest($config) {
323
        $this->load->library('email');
324
        $this->email->clear();
325
326
        $this->_set_config($config);
327
        $this->email->initialize($config);
328
329
        $this->email->from($this->from_email, $this->from);
330
        $this->email->to($this->send_to);
331
        $this->email->subject($this->theme);
332
        $this->email->message(lang('Check email sending', 'cmsemail'));
333
334
        $this->email->send();
335
336
        echo $this->email->print_debugger();
337
    }
338
339
    /**
340
     * send email
341
     *
342
     * @param string $send_to - recepient email
343
     * @param string $pattern_name - email patern  name
344
     * @param array $variables - variables to raplase in message:
345
     *   $variables = array('$user$' => 'UserName')
0 ignored issues
show
introduced by
Parameter comment must end with a full stop
Loading history...
346
     * @param bool|string $attachment
347
     * @return bool
348
     */
349
    public function sendEmail($send_to, $pattern_name, $variables, $attachment = FALSE) {
350
        //loading CodeIgniter Email library
351
        $this->load->library('email');
352
        $locale = MY_Controller::getCurrentLocale();
353
354
        //Getting settings
355
        $pattern_settings = $this->cmsemail_model->getPaternSettings($pattern_name);
356
        $default_settings = $this->cmsemail_model->getSettings($locale);
357
358
        //Prepare settings into correct array for initialize library
359
        if ($pattern_settings) {
360
            foreach ($pattern_settings as $key => $value) {
0 ignored issues
show
Bug introduced by
The expression $pattern_settings of type string is not traversable.
Loading history...
361
                if (!$value) {
362
                    if ($default_settings[$key]) {
363
                        $pattern_settings[$key] = $default_settings[$key];
364
                    }
365
                }
366
            }
367
        }
368
        $default_settings['type'] = strtolower($pattern_settings['type']);
369
        $pattern_settings['protocol'] = $default_settings['protocol'];
370
        if (strtolower($default_settings['protocol']) == strtolower('SMTP')) {
371
            $pattern_settings['smtp_port'] = $default_settings['port'];
372
            $pattern_settings['smtp_host'] = $default_settings['smtp_host'];
373
            $pattern_settings['smtp_user'] = $default_settings['smtp_user'];
374
            $pattern_settings['smtp_pass'] = $default_settings['smtp_pass'];
375
            $pattern_settings['smtp_crypto'] = $default_settings['encryption'];
376
            $this->email->set_newline("\r\n");
377
        }
378
379
        //Initializing library settings
380
        $this->_set_config($pattern_settings);
381
382
        //Sending user email if active in options
383
        if ($pattern_settings['user_message_active']) {
384
            $this->from_email = $pattern_settings['from_email'];
385
            $this->from = $pattern_settings['from'];
386
            $this->send_to = $send_to;
387
            $this->theme = $pattern_settings['theme'];
388
            $this->message = $this->replaceVariables($pattern_settings['user_message'], $variables);
389
390 View Code Duplication
            if (!$this->_sendEmail()) {
391
                $this->errors[] = lang('User message doesnt send', 'cmsemail');
392
            } else {
393
                //Registering event is success
394
                Events::create()->registerEvent(
395
                    [
396
                     'from'       => $this->from,
397
                     'from_email' => $this->from_email,
398
                     'send_to'    => $this->send_to,
399
                     'theme'      => $this->theme,
400
                     'message'    => $this->message,
401
                    ],
402
                    'ParentEmail:userSend'
403
                );
404
                Events::runFactory();
405
            }
406
        }
407
        //Sending administrator email if active in options
408
        if ($pattern_settings['admin_message_active']) {
409
            $this->from_email = $pattern_settings['from_email'];
410
            $this->from = $pattern_settings['from'];
411
412
            if ($pattern_settings['admin_email']) {
413
                $this->send_to = $pattern_settings['admin_email'];
414
            } else {
415
                $this->send_to = $default_settings['admin_email'];
416
            }
417
418
            $this->theme = $pattern_settings['theme'];
419
            $this->message = $this->replaceVariables($pattern_settings['admin_message'], $variables);
420
            $this->attachment = $attachment;
0 ignored issues
show
Documentation Bug introduced by
It seems like $attachment can also be of type boolean. However, the property $attachment is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
421
422 View Code Duplication
            if (!$this->_sendEmail()) {
423
                $this->errors[] = lang('User message doesnt send', 'cmsemail');
424
            } else {
425
                //Registering event is success
426
                Events::create()->registerEvent(
427
                    [
428
                     'from'       => $this->from,
429
                     'from_email' => $this->from_email,
430
                     'send_to'    => $this->send_to,
431
                     'theme'      => $this->theme,
432
                     'message'    => $this->message,
433
                    ],
434
                    'ParentEmail:adminSend'
435
                );
436
                Events::runFactory();
437
            }
438
        }
439
440
        //Returning status
441
        return $this->errors ? FALSE : TRUE;
442
    }
443
444
    /**
445
     * set email config
446
     *
447
     * @param array $settings
448
     */
449
    private function _set_config($settings) {
450
        $config['protocol'] = $settings['protocol'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$config was never initialized. Although not strictly required by PHP, it is generally a good practice to add $config = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
451
        if (strtolower($settings['protocol']) == strtolower('SMTP')) {
452
            $config['protocol'] = strtolower($settings['protocol']);
453
            $config['smtp_port'] = $settings['smtp_port'];
454
            $config['smtp_host'] = $settings['smtp_host'];
455
            $config['smtp_user'] = $settings['smtp_user'];
456
            $config['smtp_pass'] = $settings['smtp_pass'];
457
            $config['smtp_crypto'] = $settings['smtp_crypto'];
458
        }
459
460
        $config['mailtype'] = strtolower($settings['type']);
461
        $config['mailpath'] = $settings['mailpath'];
462
463
        return $this->email->initialize($config);
464
    }
465
466
    /**
467
     * replace variables in patern and wrap it
468
     *
469
     * @param array $variables
470
     * @param string $pattern
0 ignored issues
show
introduced by
Doc comment for parameter $pattern does not match actual variable name <undefined>
Loading history...
471
     * @return string
472
     */
473
    public function replaceVariables($pattern, $variables) {
474
        foreach ($variables as $variable => $replace_value) {
475
            $pattern = str_replace('$' . $variable . '$', $replace_value, $pattern);
476
        }
477
478
        $wrapper = $this->cmsemail_model->getWraper();
479
480
        if ($wrapper) {
481
            $pattern = str_replace('$content', $pattern, $wrapper);
482
        }
483
        return $pattern;
484
    }
485
486
    /**
487
     * send email
488
     *
489
     * @return bool
490
     */
491
    private function _sendEmail() {
492
        $this->email->from($this->from_email, $this->from);
493
        $this->email->to($this->send_to);
494
        $this->email->subject($this->theme);
495
        $this->email->message($this->message);
496
497
        if ($this->attachment && file_exists($this->attachment)) {
498
            $this->email->attach($this->attachment);
499
        }
500
501
        return $this->email->send();
502
    }
503
504
    /**
505
     * @param array $settings
506
     * @return bool
0 ignored issues
show
Documentation introduced by
Should the return type not be boolean|null?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
507
     */
508
    public function setSettings($settings) {
509
        return $this->cmsemail_model->setSettings($settings);
510
    }
511
512
    /**
513
     * @param int $template_id
514
     * @param string $variable
515
     * @param string $variableNewValue
516
     * @param string $oldVariable
517
     * @param string $locale
518
     * @return bool|object
0 ignored issues
show
Documentation introduced by
Consider making the return type a bit more specific; maybe use object|false.

This check looks for the generic type array as a return type and suggests a more specific type. This type is inferred from the actual code.

Loading history...
519
     */
520
    public function updateVariable($template_id, $variable, $variableNewValue, $oldVariable, $locale) {
521
        return $this->cmsemail_model->updateVariable($template_id, $variable, $variableNewValue, $oldVariable, $locale);
522
    }
523
524
}