Completed
Push — development ( c8f467...de45b7 )
by Andrij
10:53
created

Mailer::ajaxSubmit()   C

Complexity

Conditions 9
Paths 7

Size

Total Lines 52
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 0
Metric Value
cc 9
eloc 32
c 6
b 1
f 0
nc 7
nop 0
dl 0
loc 52
rs 6.5703

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
if (!defined('BASEPATH')) {
4
    exit('No direct script access allowed');
5
}
6
7
/**
8
 * Image CMS
9
 *
10
 * Класс отображения страниц по ID.
11
 */
12
class Mailer extends MY_Controller
13
{
0 ignored issues
show
introduced by
Opening brace of a class must be on the same line as the definition
Loading history...
14
15
    public $settings = [];
16
17
    public function __construct() {
18
        parent::__construct();
19
20
        $this->load->module('core');
21
        $lang = new MY_Lang();
22
        $lang->load('mailer');
23
    }
24
25
    /**
26
     * Подписка пользователей.
27
     */
28
    public function index() {
29
30
        $this->load->library('form_validation');
31
        $this->form_validation->set_rules('user_email', lang('Your e-mail', 'mailer'), 'required|trim|valid_email');
32
33
        if ($this->form_validation->run($this) == FALSE) {
34
35
            echo $errors = validation_errors();
36
37
            redirect('/mailer/error/');
38
        } else {
39
40
            $query = $this->db->get_where('mail', ['email' => $this->input->post('user_email')]);
41
            $row = $query->row();
42
43
            if (!empty($row) && $this->input->post('add_user_mail') != 1) {
44
                redirect('/mailer/already/');
45
                exit;
46
            } elseif (empty($row) && $this->input->post('add_user_mail') == 1) {
47
                redirect('/mailer/no/');
48
                exit;
49
            }
50
51
            if ($this->input->post('add_user_mail') == 2) {
52
53
                $date = date('U');
54
                $email = $this->input->post('user_email');
55
56
                if ($this->dx_auth->get_user_email() != $email) {
57
                    if (!$this->dx_auth->is_email_available($email)) {
58
                        redirect(site_url('/mailer/error/'));
59
                        exit;
60
                    }
61
                }
62
63
                $data = [
64
                         'email' => $email,
65
                         'date'  => $date,
66
                        ];
67
68
                $this->db->insert('mail', $data);
69
70
                $this->registerUserByEmail($email);
71
72
                $this->template->add_array(
73
                    ['email' => $query]
74
                );
75
76
                redirect('/mailer/success/');
77
            } else {
78
                $this->db->delete('mail', ['email' => $this->input->post('user_email')]);
79
                redirect('/mailer/cancel/');
80
            }
81
        }
82
    }
83
84
    public function ajaxSubmit() {
85
86
        $this->load->library('form_validation');
87
        $this->form_validation->set_rules('user_email', lang('Your e-mail', 'mailer'), 'required|trim|valid_email');
88
89
        if ($this->form_validation->run($this) == FALSE) {
90
            CMSFactory\assetManager::create()->setData(
91
                [
92
                 'mailer_errors' => validation_errors(),
93
                ]
94
            );
95
            CMSFactory\assetManager::create()->render('error', true);
96
        } else {
97
98
            $query = $this->db->get_where('mail', ['email' => $this->input->post('user_email')]);
99
            $row = $query->row();
100
101
            if (!empty($row) && $this->input->post('add_user_mail') != 1) {
102
                CMSFactory\assetManager::create()->render('already', true);
103
                exit;
104
            } elseif (empty($row) && $this->input->post('add_user_mail') == 1) {
105
                CMSFactory\assetManager::create()->render('no', true);
106
                exit;
107
            }
108
109
            if ($this->input->post('add_user_mail') == 2) {
110
                $email = $this->input->post('user_email');
111
112
                $date = date('U');
113
                $data = [
114
                         'email' => $email,
115
                         'date'  => $date,
116
                        ];
117
118
                $this->db->insert('mail', $data);
119
120
                if ($this->dx_auth->get_user_email() != $email) {
121
                    if ($this->dx_auth->is_email_available($email)) {
122
                        $this->registerUserByEmail($email);
123
                    }
124
                }
125
126
                CMSFactory\assetManager::create()->setData(
127
                    ['email' => $query]
128
                );
129
                CMSFactory\assetManager::create()->render('success', true);
130
            } else {
131
                $this->db->delete('mail', ['email' => $this->input->post('user_email')]);
132
                CMSFactory\assetManager::create()->render('cancel', true);
133
            }
134
        }
135
    }
136
137
    /**
138
     * Register subscribed user by email
139
     * @param string $email - user email
140
     * @return false|null
141
     */
142
    private function registerUserByEmail($email) {
143
        if (!$email) {
144
            return FALSE;
145
        }
146
147
        $username = array_shift(explode('@', $email));
0 ignored issues
show
Bug introduced by
explode('@', $email) cannot be passed to array_shift() as the parameter $array expects a reference.
Loading history...
148
        $password = random_string('alnum', 8);
149
        $key = random_string('alnum', 5);
150
        $this->dx_auth->register($username, $password, $email, '', $key);
151
    }
152
153
    public function getForm() {
154
        return $this->fetch_tpl('form');
155
    }
156
157
    public function success() {
158
        $this->show_tpl('success');
159
    }
160
161
    public function already() {
162
        $this->show_tpl('already');
163
    }
164
165
    public function cancel() {
166
        $this->show_tpl('cancel');
167
    }
168
169
    public function no() {
170
        $this->show_tpl('no');
171
    }
172
173
    public function error() {
174
        $this->show_tpl('error');
175
    }
176
177
    /**
178
     * Загрузка настроек модуля
179
     */
180
    private function load_settings() {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
181
        $this->db->limit(1);
182
        $this->db->where('name', 'page_id');
183
        $query = $this->db->get('components');
184
185
        if ($query->num_rows() == 1) {
186
            $settings = $query->row_array();
187
            $this->settings = unserialize($settings['settings']);
188
        }
189
    }
190
191
    /**
192
     * Функция будет вызвана при установке модуля из панели управления
193
     */
194
    public function _install() {
195
        if ($this->dx_auth->is_admin() == FALSE) {
196
            exit;
197
        }
198
        //Create Table MAIL
199
        $sql = 'CREATE TABLE IF NOT EXISTS `mail` (
200
                    `id` int(11) NOT NULL AUTO_INCREMENT,
201
                    `email` varchar(255) DEFAULT NULL,
202
                    `date` int(15) DEFAULT NULL,
203
                    PRIMARY KEY (`id`)
204
                    ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;';
205
206
        $this->db->query($sql);
207
208
        // Включаем доступ к модулю по URL
209
        $this->db->limit(1);
210
        $this->db->where('name', 'mailer');
211
        $this->db->update('components', ['enabled' => 1]);
212
    }
213
214
    public function _deinstall() {
215
        if ($this->dx_auth->is_admin() == FALSE) {
216
            exit;
217
        }
218
        //Delete Table MAIL
219
        $sql = 'DROP TABLE `mail`;';
220
221
        $this->db->query($sql);
222
223
        //$this->load->model('install')->deinstall();
224
    }
225
226
    /**
227
     * Display template file
228
     */
229
    private function display_tpl($file = '') {
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
230
        $this->template->show('file:' . $this->searchTpl($file));
231
    }
232
233
    /**
234
     * Display template file
235
     */
236
    private function show_tpl($file = '') {
237
        $this->template->show('file:' . $this->searchTpl($file));
238
    }
239
240
    /**
241
     * Fetch template file
242
     */
243
    private function fetch_tpl($file = '') {
244
        return $this->template->fetch('file:' . $this->searchTpl($file . '.tpl'));
245
    }
246
247
    protected function searchTpl($file = '') {
248
        $templateModulePath = TEMPLATES_PATH
249
            . template_manager\classes\TemplateManager::getInstance()->getCurentTemplate()->name
250
            . '/mailer/';
251
        if (file_exists($templateModulePath . $file) || file_exists($templateModulePath . $file . '.tpl')) {
252
            return $templateModulePath . $file;
253
        }
254
        return realpath(__DIR__) . '/templates/public/' . $file;
255
    }
256
257
}
258
259
/* End of file mailer.php */