Completed
Push — master ( 13d43e...43caeb )
by
unknown
11:00
created

Application::test()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 1
nc 1
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 samson\url\URL;
14
use samsoncms\api\generated\UserQuery;
15
use samsonframework\container\definition\analyzer\annotation\annotation\InjectService;
16
use samsonframework\containerannotation\InjectArgument;
17
use samsonframework\core\RequestInterface;
18
use samsonframework\core\ResourcesInterface;
19
use samsonframework\core\SystemInterface;
20
use samsonphp\event\Event;
21
use samsonframework\orm\QueryInterface;
22
use samson\social\email\Email;
23
use samson\core\Core;
24
use samsonphp\compressor\Compressor;
25
26
/**
27
 * Generic class for user sign in
28
 * @author Olexandr Nazarenko <[email protected]>
29
 * @copyright 2014 SamsonOS
30
 */
31
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...
32
{
33
    /** @var string Identifier */
34
    public $id = 'signin';
35
36
    /** @var Email Pointer to social email module */
37
    protected $social;
38
39
    /** @var QueryInterface Database query instance */
40
    protected $query;
41
42
    /** @var RequestInterface Request instance */
43
    protected $request;
44
45
    public function authorize($cms)
46
    {
47
        if ($cms->isCMS()) {
48
            if (!$this->social->authorized()) {
49
                if (!$this->social->cookieVerification()) {
50
                    if (!$this->request->is('signin')) {
51
                        $this->request->redirect('/' . $cms->baseUrl . '/signin');
52
                    }
53
                } else {
54
                    $this->request->redirect('/' . $cms->baseUrl . '/signin');
55
                }
56
            } else {
57
                if ($this->request->is('signin')) {
58
                    $this->request->redirect('/' . $cms->baseUrl);
59
                }
60
            }
61
        }
62
    }
63
64
    /**
65
     * @InjectService(core="core")
66
     */
67
    public function test($core)
0 ignored issues
show
Unused Code introduced by
The parameter $core is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
68
    {
69
70
    }
71
72
    public function init(array $params = array())
73
    {
74
        $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...
75
        // Old applications main page rendering
76
        Event::subscribe(\samsoncms\cms\Application::EVENT_IS_CMS, array($this, 'authorize'));
77
        
78
        Event::subscribe(Compressor::E_CREATE_MODULE_LIST, array($this, 'getModuleList'));
79
80
        // Call parent initialization
81
        return parent::init($params);
82
    }
83
    
84
    public function getModuleList(& $moduleListArray)
85
    {
86
        $moduleList = array();
87
        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...
88
            if (isset($module->composerParameters['composerName'])) {
89
                if (in_array($module->composerParameters['composerName'], $this->composerParameters['required'])) {
90
                    $moduleList[$id] = $module;
91
                }
92
            }
93
        }
94
        $moduleList[$this->id] = $this;
95
        $moduleListArray[$this->path().'www/signin/signin_template.vphp'] = $moduleList;
96
    }
97
98
    /**
99
     * Application constructor.
100
     *
101
     * @param string $path
102
     * @param ResourcesInterface $resources
103
     * @param SystemInterface $system
104
     *
105
     * @ InjectArgument(socialEmail="samson\social\email\Email")
106
     * @ InjectArgument(request="samson\url\URL")
107
     * @ InjectArgument(queryInterface="samsonframework\orm\QueryInterface")
108
     *
109
     * @ InjectArgument(resources="samsonframework\core\ResourcesInterface")
110
     * @ InjectArgument(system="samsonframework\core\SystemInterface")
111
     */
112
    public function __construct($path, Email $socialEmail, URL $request, QueryInterface $queryInterface, ResourcesInterface $resources, SystemInterface $system)
113
    {
114
        parent::__construct(realpath(__DIR__ . '/../'), $resources, $system);
115
116
        // Inject dependencies
117
//        $this->social = $this->system->module('socialemail');
118
//        $this->request = $this->system->module('samsonos_php_url');
119
//        $this->query = new dbQuery();
120
        $this->social = $socialEmail;
121
        $this->request = $request;
122
        $this->query = $queryInterface;
123
    }
124
125
    //[PHPCOMPRESSOR(remove,start)]
126
    /** Module preparation */
127
    public function prepare()
128
    {
129
        // Create default user for first logins
130
        $adminUser = '[email protected]';
131
        $hashedEmailValue = $this->social->hash($adminUser);
132
133
        /** @var \samsoncms\api\generated\User $admin Try to find generic user */
134
        $admin = $this->query
135
            ->entity($this->social->dbTable)
136
            ->where($this->social->dbEmailField, $adminUser)
137
            ->first();
138
139
        // Create user record if missing
140
        if (!isset($admin)) {
141
            $admin = new $this->social->dbTable($this->system->getContainer()->get('database'));
142
        }
143
144
        // Fill in user credentials according to config
145
        $admin[$this->social->dbEmailField] = $adminUser;
146
        $admin[$this->social->dbHashEmailField] = $hashedEmailValue;
147
        $admin[$this->social->dbHashPasswordField] = $hashedEmailValue;
148
        $admin->fName = 'admin';
149
        $admin->sName = '';
150
        $admin->tName = '';
151
        $admin->groupId = 1;
152
        $admin->system = 1;
153
        $admin->created = date('Y-m-d H:i:s');
154
        $admin->active = 1;
155
        $admin->save();
156
    }
157
    //[PHPCOMPRESSOR(remove,end)]
158
159
    /** Check the user's authorization */
160
    public function __HANDLER()
161
    {
162
        $this->authorize($this->social);
163
    }
164
165
    /** Main sign in template */
166
    public function __base()
167
    {
168
        // Change template
169
        $this->system->template('www/signin/signin_template.vphp');
170
171
        // Render template with sign in form
172
        $this->html($this->view('www/signin/signin_form')->output())
173
            ->title(t('Авторизация', true));
174
    }
175
176
    /** User asynchronous sign in */
177
    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...
178
    {
179
        $user = null;
180
        $error = '';
181
182
        if (isset($_POST['email']) && isset($_POST['password'])) {
183
            $email = $this->social->hash($_POST['email']);
184
            $password = $this->social->hash($_POST['password']);
185
            $remember = isset($_POST['remember']) ? true : false;
186
187
            /** @var EmailStatus Perform email authorization */
188
            $auth = $this->social->authorizeWithEmail($email, $password, $remember, $user);
189
190
            if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
191
                // Fire login success event
192
                Event::fire('samson.cms.signin.login', array(&$user));
193
194
                return array('status' => '1');
195
            } else {
196
                $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...
197
                    ->errorClass('errorAuth')
198
                    ->userEmail("{$_POST['email']}")
199
                    ->focus('autofocus')
200
                    ->output();
201
202
                return array('status' => '0', 'html' => $error);
203
            }
204
        } else {
205
            $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...
206
207
            return array('status' => '0', 'html' => $error);
208
        }
209
    }
210
211
    /** User logout */
212
    public function __logout()
213
    {
214
        $this->social->deauthorize();
215
216
        // Fire logout event
217
        Event::fire('samson.cms.signin.logout');
218
219
        $this->request->redirect('cms/signin');
220
    }
221
222
    /** Sending email with the correct address */
223
    public function __mail()
224
    {
225
        if (isset($_POST['email'])) {
226
            /** @var \samson\activerecord\user $user */
227
            $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...
228
            $result = '';
229
230
            if (!empty($user = (new UserQuery())->email($_POST['email'])->first())) {
231
                $user->confirmed = $this->social->hash(generate_password(20) . time());
232
                $user->save();
233
234
                $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...
235
                mail_send($user->email, '[email protected]', $message, t('Восстановление пароля!', true), 'SamsonCMS');
236
237
                $result .= $this->view('www/signin/pass_recovery_mailsend')->output();
238
                $this->system->template('www/signin/signin_template.vphp');
239
                $this->html($result)->title(t('Восстановление пароля', true));
240
            } else {
241
                $this->request->redirect();
242
            }
243
        } else {
244
            $this->request->redirect();
245
        }
246
    }
247
248
    /**
249
     * New password form.
250
     *
251
     * @param string $code Code password recovery
252
     *
253
     * @return bool
254
     */
255
    public function __confirm($code)
256
    {
257
        $code = substr($code, 0, 32);
258
        $rights = (new UserQuery())->confirmed($code)->first();
259
260
        if (!empty($rights)) {
261
            $this->system->template('www/signin/signin_template.vphp');
262
            $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...
263
                ->title(t('Восстановление пароля', true));
264
        } else {
265
            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...
266
        }
267
    }
268
269
    /**
270
     * Setting new password and sign in
271
     *
272
     * @param string $code Code password recovery
273
     */
274
    public function __recovery($code)
275
    {
276
        if (isset($_POST['password']) && isset($_POST['confirm_password'])
277
            && $_POST['password'] == $_POST['confirm_password']
278
        ) {
279
            /** @var \samson\activerecord\user $user */
280
            $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...
281
            if (!empty($user = (new UserQuery())->confirmed($code)->first())) {
282
                $user->confirmed = 1;
283
                $user->md5_password = md5($_POST['password']);
284
                $user->hash_password = md5($_POST['password']);
285
                $user->save();
286
287
                $auth = $this->social->authorizeWithEmail($user->md5_email, $user->md5_password, $user);
288
                if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
289
                    $this->request->redirect();
290
                }
291
            }
292
        } else {
293
            $result = '';
294
            $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...
295
                ->message(t('Вы ввели некорректный пароль либо пароли не совпадают', true))
296
                ->output();
297
            $this->system->template('www/signin/signin_template.vphp');
298
            $this->html($result)->title(t('Ошибка восстановление пароля', true));
299
        }
300
    }
301
}
302