Completed
Push — master ( 83a775...704a0b )
by Nikita
04:15
created

Application::getModuleList()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 13
rs 9.2
cc 4
eloc 8
nc 4
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: nazarenko
5
 * Date: 20.10.2014
6
 * Time: 11:43
7
 */
8
namespace samsoncms\app\signin;
9
10
use samson\activerecord\dbQuery;
11
use samson\cms\CMS;
12
use samson\social\email\EmailStatus;
13
use samsoncms\api\generated\UserQuery;
14
use samsonframework\core\RequestInterface;
15
use samsonframework\core\ResourcesInterface;
16
use samsonframework\core\SystemInterface;
17
use samsonphp\event\Event;
18
use samsonframework\orm\QueryInterface;
19
use samson\social\email\Email;
20
use samson\core\Core;
21
use samsonphp\compressor\Compressor;
22
23
/**
24
 * Generic class for user sign in
25
 * @author Olexandr Nazarenko <[email protected]>
26
 * @copyright 2014 SamsonOS
27
 */
28
class Application extends \samson\core\CompressableExternalModule
0 ignored issues
show
Deprecated Code introduced by
The class samson\core\CompressableExternalModule has been deprecated with message: Just implement samsonframework\core\CompressInterface

This class, trait or interface has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the type will be removed from the class and what other constant to use instead.

Loading history...
29
{
30
    /** @var string Identifier */
31
    public $id = 'signin';
32
33
    /** @var Email Pointer to social email module */
34
    protected $social;
35
36
    /** @var QueryInterface Database query instance */
37
    protected $query;
38
39
    /** @var RequestInterface Request instance */
40
    protected $request;
41
42
    public function authorize($cms)
43
    {
44
        if ($cms->isCMS()) {
45
            if (!$this->social->authorized()) {
46
                if (!$this->social->cookieVerification()) {
47
                    if (!$this->request->is('signin')) {
48
                        $this->request->redirect('/' . $cms->baseUrl . '/signin');
49
                    }
50
                } else {
51
                    $this->request->redirect('/' . $cms->baseUrl . '/signin');
52
                }
53
            } else {
54
                if ($this->request->is('signin')) {
55
                    $this->request->redirect('/' . $cms->baseUrl);
56
                }
57
            }
58
        }
59
    }
60
61
    public function init(array $params = array())
62
    {
63
        $this->request = url();
0 ignored issues
show
Documentation Bug introduced by
It seems like url() of type object<samson\core\URL> is incompatible with the declared type object<samsonframework\core\RequestInterface> of property $request.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
64
        // Old applications main page rendering
65
        Event::subscribe(\samsoncms\cms\Application::EVENT_IS_CMS, array($this, 'authorize'));
66
        
67
        Event::subscribe(Compressor::E_CREATE_MODULE_LIST, array($this, 'getModuleList'));
68
69
        // Call parent initialization
70
        return parent::init($params);
71
    }
72
    
73
    public function getModuleList(& $moduleListArray)
74
    {
75
        $moduleList = array();
76
        foreach ($this->system->module_stack as $id => $module) {
0 ignored issues
show
Bug introduced by
Accessing module_stack on the interface samsonframework\core\SystemInterface suggest that you code against a concrete implementation. How about adding an instanceof check?

If you access a property on an interface, you most likely code against a concrete implementation of the interface.

Available Fixes

  1. Adding an additional type check:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeInterface $object) {
        if ($object instanceof SomeClass) {
            $a = $object->a;
        }
    }
    
  2. Changing the type hint:

    interface SomeInterface { }
    class SomeClass implements SomeInterface {
        public $a;
    }
    
    function someFunction(SomeClass $object) {
        $a = $object->a;
    }
    
Loading history...
77
            if (isset($module->composerParameters['composerName'])) {
78
                if (in_array($module->composerParameters['composerName'], $this->composerParameters['required'])) {
79
                    $moduleList[$id] = $module;
80
                }
81
            }
82
        }
83
        $moduleList[$this->id] = $this;
84
        $moduleListArray[$this->path().'www/signin/signin_template.vphp'] = $moduleList;
85
    }
86
87
    /**
88
     * Application constructor.
89
     *
90
     * @param string $path
91
     * @param ResourcesInterface $resources
92
     * @param SystemInterface $system
93
     */
94
    public function __construct($path, ResourcesInterface $resources, SystemInterface $system)
95
    {
96
        parent::__construct($path, $resources, $system);
97
98
        // Inject dependencies
99
        $this->social = $this->system->module('socialemail');
100
        $this->request = $this->system->module('samsonosphp_url');
101
        $this->query = new dbQuery();
102
    }
103
104
    //[PHPCOMPRESSOR(remove,start)]
105
    /** Module preparation */
106
    public function prepare()
107
    {
108
        // Create default user for first logins
109
        $adminUser = '[email protected]';
110
        $hashedEmailValue = $this->social->hash($adminUser);
111
112
        /** @var \samsoncms\api\generated\User $admin Try to find generic user */
113
        $admin = $this->query
114
            ->entity($this->social->dbTable)
115
            ->where($this->social->dbEmailField, $adminUser)
116
            ->first();
117
118
        // Create user record if missing
119
        if (!isset($admin)) {
120
            $admin = new $this->social->dbTable();
121
        }
122
123
        // Fill in user credentials according to config
124
        $admin[$this->social->dbEmailField] = $adminUser;
125
        $admin[$this->social->dbHashEmailField] = $hashedEmailValue;
126
        $admin[$this->social->dbHashPasswordField] = $hashedEmailValue;
127
        $admin->fName = 'admin';
128
        $admin->sName = '';
129
        $admin->tName = '';
130
        $admin->groupId = 1;
131
        $admin->system = 1;
132
        $admin->created = date('Y-m-d H:i:s');
133
        $admin->active = 1;
134
        $admin->save();
135
    }
136
    //[PHPCOMPRESSOR(remove,end)]
137
138
    /** Check the user's authorization */
139
    public function __HANDLER()
140
    {
141
        $this->authorize($this->social);
142
    }
143
144
    /** Main sign in template */
145
    public function __base()
146
    {
147
        // Change template
148
        $this->system->template('www/signin/signin_template.vphp');
149
150
        // Render template with sign in form
151
        $this->html($this->view('www/signin/signin_form.vphp')->output())
152
            ->title(t('Авторизация', true));
153
    }
154
155
    /** User asynchronous sign in */
156
    public function __async_login()
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_login" is not in camel caps format
Loading history...
157
    {
158
        $user = null;
159
        $error = '';
160
161
        if (isset($_POST['email']) && isset($_POST['password'])) {
162
            $email = $this->social->hash($_POST['email']);
163
            $password = $this->social->hash($_POST['password']);
164
            $remember = isset($_POST['remember']) ? true : false;
165
166
            /** @var EmailStatus Perform email authorization */
167
            $auth = $this->social->authorizeWithEmail($email, $password, $remember, $user);
168
169
            if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
170
                // Fire login success event
171
                Event::fire('samson.cms.signin.login', array(&$user));
172
173
                return array('status' => '1');
174
            } else {
175
                $error .= $this->view('www/signin/signin_form.vphp')
0 ignored issues
show
Documentation Bug introduced by
The method errorClass does not exist on object<samsoncms\app\signin\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
176
                    ->errorClass('errorAuth')
177
                    ->userEmail("{$_POST['email']}")
178
                    ->focus('autofocus')
179
                    ->output();
180
181
                return array('status' => '0', 'html' => $error);
182
            }
183
        } else {
184
            $error .= $this->view('www/signin/signin_form')->errorClass('errorAuth')->output();
0 ignored issues
show
Documentation Bug introduced by
The method errorClass does not exist on object<samsoncms\app\signin\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
185
186
            return array('status' => '0', 'html' => $error);
187
        }
188
    }
189
190
    /** User logout */
191
    public function __logout()
192
    {
193
        $this->social->deauthorize();
194
195
        // Fire logout event
196
        Event::fire('samson.cms.signin.logout');
197
198
        $this->request->redirect('cms/signin');
199
    }
200
201
    /** Sending email with the correct address */
202
    public function __mail()
203
    {
204
        if (isset($_POST['email'])) {
205
            /** @var \samson\activerecord\user $user */
206
            $user = null;
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
207
            $result = '';
208
209
            if (!empty($user = (new UserQuery())->email($_POST['email'])->first())) {
210
                $user->confirmed = $this->social->hash(generate_password(20) . time());
211
                $user->save();
212
213
                $message = $this->view('www/signin/email/pass_recovery')->code($user->confirmed)->output();
0 ignored issues
show
Documentation Bug introduced by
The method code does not exist on object<samsoncms\app\signin\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
214
                mail_send($user->email, '[email protected]', $message, t('Восстановление пароля!', true), 'SamsonCMS');
215
216
                $result .= $this->view('www/signin/pass_recovery_mailsend')->output();
217
                $this->system->template('www/signin/signin_template.vphp');
218
                $this->html($result)->title(t('Восстановление пароля', true));
219
            } else {
220
                $this->request->redirect();
221
            }
222
        } else {
223
            $this->request->redirect();
224
        }
225
    }
226
227
    /**
228
     * New password form.
229
     *
230
     * @param string $code Code password recovery
231
     *
232
     * @return bool
233
     */
234
    public function __confirm($code)
235
    {
236
        $code = substr($code, 0, 32);
237
        $rights = (new UserQuery())->confirmed($code)->first();
238
239
        if (!empty($rights)) {
240
            $this->system->template('www/signin/signin_template.vphp');
241
            $this->html($this->view('www/signin/new_pass_form')->code($code)->output())
0 ignored issues
show
Documentation Bug introduced by
The method code does not exist on object<samsoncms\app\signin\Application>? Since you implemented __call, maybe consider adding a @method annotation.

If you implement __call and you know which methods are available, you can improve IDE auto-completion and static analysis by adding a @method annotation to the class.

This is often the case, when __call is implemented by a parent class and only the child class knows which methods exist:

class ParentClass {
    private $data = array();

    public function __call($method, array $args) {
        if (0 === strpos($method, 'get')) {
            return $this->data[strtolower(substr($method, 3))];
        }

        throw new \LogicException(sprintf('Unsupported method: %s', $method));
    }
}

/**
 * If this class knows which fields exist, you can specify the methods here:
 *
 * @method string getName()
 */
class SomeClass extends ParentClass { }
Loading history...
242
                ->title(t('Восстановление пароля', true));
243
        } else {
244
            return A_FAILED;
0 ignored issues
show
Deprecated Code introduced by
The constant A_FAILED has been deprecated with message: Действие контроллера НЕ выполнено

This class constant has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the constant will be removed from the class and what other constant to use instead.

Loading history...
245
        }
246
    }
247
248
    /**
249
     * Setting new password and sign in
250
     *
251
     * @param string $code Code password recovery
252
     */
253
    public function __recovery($code)
254
    {
255
        if (isset($_POST['password']) && isset($_POST['confirm_password'])
256
            && $_POST['password'] == $_POST['confirm_password']
257
        ) {
258
            /** @var \samson\activerecord\user $user */
259
            $user = null;
0 ignored issues
show
Unused Code introduced by
$user is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
260
            if (!empty($user = (new UserQuery())->confirmed($code)->first())) {
261
                $user->confirmed = 1;
262
                $user->md5_password = md5($_POST['password']);
263
                $user->hash_password = md5($_POST['password']);
264
                $user->save();
265
266
                $auth = $this->social->authorizeWithEmail($user->md5_email, $user->md5_password, $user);
267
                if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
268
                    $this->request->redirect();
269
                }
270
            }
271
        } else {
272
            $result = '';
273
            $result .= m()->view('www/signin/pass_error')
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
274
                ->message(t('Вы ввели некорректный пароль либо пароли не совпадают', true))
275
                ->output();
276
            $this->system->template('www/signin/signin_template.vphp');
277
            $this->html($result)->title(t('Ошибка восстановление пароля', true));
278
        }
279
    }
280
}
281