Completed
Push — master ( 8c4385...b55fd8 )
by Vitaly
07:46
created

Application::prepare()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
c 3
b 1
f 0
dl 0
loc 24
rs 8.9713
cc 2
eloc 14
nc 2
nop 0
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 samsonframework\core\RequestInterface;
14
use samsonframework\core\ResourcesInterface;
15
use samsonframework\core\SystemInterface;
16
use samsonphp\event\Event;
17
use samsonframework\orm\QueryInterface;
18
use samson\social\email\Email;
19
use samson\core\Core;
20
21
/**
22
 * Generic class for user sign in
23
 * @author Olexandr Nazarenko <[email protected]>
24
 * @copyright 2014 SamsonOS
25
 */
26
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...
27
{
28
    /** @var string Identifier */
29
    public $id = 'signin';
30
31
    /** @var Email Pointer to social email module */
32
    protected $social;
33
34
    /** @var QueryInterface Database query instance */
35
    protected $query;
36
37
    /** @var RequestInterface Request instance */
38
    protected $request;
39
40
    public function authorize($cms)
41
    {
42
        if ($cms->isCMS()) {
43
            if ( ! $this->social->authorized()) {
44
                if ( ! $this->social->cookieVerification()) {
45
                    if ( ! $this->request->is('signin')) {
46
                        $this->request->redirect('/'.$cms->baseUrl.'/signin');
47
                    }
48
                } else {
49
                    $this->request->redirect('/'.$cms->baseUrl.'/signin');
50
                }
51
            } else {
52
                if ($this->request->is('signin')) {
53
                    $this->request->redirect('/'.$cms->baseUrl);
54
                }
55
            }
56
        }
57
    }
58
59
    public function init(array $params = array())
60
    {
61
        $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...
62
        // Old applications main page rendering
63
        Event::subscribe(\samsoncms\cms\Application::EVENT_IS_CMS, array($this, 'authorize'));
64
65
        // Call parent initialization
66
        return parent::init($params);
67
    }
68
69
    /**
70
     * Application constructor.
71
     *
72
     * @param string $path
73
     * @param ResourcesInterface $resources
74
     * @param SystemInterface $system
75
     */
76
    public function  __construct($path, ResourcesInterface $resources, SystemInterface $system)
0 ignored issues
show
Coding Style introduced by
Expected "function abc(...)"; found "function abc(...)"
Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 2 found
Loading history...
77
    {
78
        // Inject dependencies
79
        $this->social  = m('socialemail');
0 ignored issues
show
Documentation Bug introduced by
It seems like m('socialemail') can also be of type object<samson\core\Module>. However, the property $social is declared as type object<samson\social\email\Email>. 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...
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...
80
        $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...
81
        $this->query   = new dbQuery();
82
83
        parent::__construct($path, $resources, $system);
84
    }
85
86
    //[PHPCOMPRESSOR(remove,start)]
87
    /** Module preparation */
88
    public function prepare()
89
    {
90
        // Create default user for first logins
91
        $adminUser        = '[email protected]';
92
        $hashedEmailValue = $this->social->hash($adminUser);
93
94
        /** @var \samson\activerecord\user $admin Try to find generic user */
95
        $admin = $this->query
96
            ->entity($this->social->dbTable)
97
            ->where($this->social->dbEmailField, $adminUser)
98
            ->first();
99
100
        // Create user record if missing
101
        if ( ! isset($admin)) {
102
            $admin = new $this->social->dbTable();
103
        }
104
105
        // Fill in user credentials according to config
106
        $admin[$this->social->dbEmailField]        = $adminUser;
107
        $admin[$this->social->dbHashEmailField]    = $hashedEmailValue;
108
        $admin[$this->social->dbHashPasswordField] = $hashedEmailValue;
109
        $admin->group_id = 1;
110
        $admin->save();
111
    }
112
    //[PHPCOMPRESSOR(remove,end)]
113
114
    /** Check the user's authorization */
115
    public function __HANDLER()
116
    {
117
        $this->authorize($this->social);
118
    }
119
120
    /** Main sign in template */
121
    public function __base()
122
    {
123
        // Change template
124
        $this->system->template('www/signin/signin_template.vphp');
125
126
        // Render template with sign in form
127
        $this->html($this->view('www/signin/signin_form.vphp')->output())
128
             ->title(t('Авторизация', true));
129
    }
130
131
    /** User asynchronous sign in */
132
    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...
133
    {
134
        $user  = null;
135
        $error = '';
136
137
        if (isset($_POST['email']) && isset($_POST['password'])) {
138
            $email    = $this->social->hash($_POST['email']);
139
            $password = $this->social->hash($_POST['password']);
140
            $remember = isset($_POST['remember']) ? true : false;
141
142
            /** @var EmailStatus Perform email authorization */
143
            $auth = $this->social->authorizeWithEmail($email, $password, $remember, $user);
144
145
            if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
146
                // Fire login success event
147
                Event::fire('samson.cms.signin.login', array(&$user));
148
149
                return array('status' => '1');
150
            } else {
151
                $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...
152
                               ->errorClass('errorAuth')
153
                               ->userEmail("{$_POST['email']}")
154
                               ->focus('autofocus')
155
                               ->output();
156
157
                return array('status' => '0', 'html' => $error);
158
            }
159
        } else {
160
            $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...
161
162
            return array('status' => '0', 'html' => $error);
163
        }
164
    }
165
166
    /** User logout */
167
    public function __logout()
168
    {
169
        $this->social->deauthorize();
170
171
        // Fire logout event
172
        Event::fire('samson.cms.signin.logout');
173
174
        $this->request->redirect('cms/signin');
175
    }
176
177
    /** Sending email with the correct address */
178
    public function __mail()
179
    {
180
        if (isset($_POST['email'])) {
181
            /** @var \samson\activerecord\user $user */
182
            $user   = null;
183
            $result = '';
184
            if ($this->query->entity('user')->where('email', $_POST['email'])->first($user)) {
185
                $user->confirmed = $this->social->hash(generate_password(20) . time());
0 ignored issues
show
Bug introduced by
Accessing confirmed on the interface samsonframework\orm\RecordInterface 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...
186
                $user->save();
187
                $message = $this->view('www/signin/email/pass_recovery')->code($user->confirmed)->output();
0 ignored issues
show
Bug introduced by
Accessing confirmed on the interface samsonframework\orm\RecordInterface 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...
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...
188
189
                mail_send($user->Email, '[email protected]', $message, t('Восстановление пароля!', true), 'SamsonCMS');
0 ignored issues
show
Bug introduced by
Accessing Email on the interface samsonframework\orm\RecordInterface 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...
190
191
                $result .= $this->view('www/signin/pass_recovery_mailsend')->output();
192
                $this->system->template('www/signin/signin_template.vphp');
193
                $this->html($result)->title(t('Восстановление пароля', true));
194
            } else {
195
                $this->request->redirect();
196
            }
197
        } else {
198
            $this->request->redirect();
199
        }
200
    }
201
202
    /**
203
     * New password form.
204
     *
205
     * @param string $code Code password recovery
206
     *
207
     * @return bool
208
     */
209
    public function __confirm($code)
210
    {
211
        if ($this->query->entity('user')->where($this->social->dbConfirmField, $code)->first()) {
212
            $this->system->template('www/signin/signin_template.vphp');
213
            $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...
214
                 ->title(t('Восстановление пароля', true));
215
        } else {
216
            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...
217
        }
218
    }
219
220
    /**
221
     * Setting new password and sign in
222
     *
223
     * @param string $code Code password recovery
224
     */
225
    public function __recovery($code)
226
    {
227
        if (isset($_POST['password']) && isset($_POST['confirm_password'])
228
            && $_POST['password'] == $_POST['confirm_password']
229
        ) {
230
            /** @var \samson\activerecord\user $user */
231
            $user = null;
232
            if ($this->query->where('confirmed', $code)->first($user)) {
233
                $user->confirmed    = 1;
0 ignored issues
show
Bug introduced by
Accessing confirmed on the interface samsonframework\orm\RecordInterface 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...
234
                $user->md5_password = md5($_POST['password']);
0 ignored issues
show
Bug introduced by
Accessing md5_password on the interface samsonframework\orm\RecordInterface 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...
235
                $user->Password     = $_POST['password'];
0 ignored issues
show
Bug introduced by
Accessing Password on the interface samsonframework\orm\RecordInterface 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...
236
                $user->save();
237
238
                $auth = $this->social->authorizeWithEmail($user->md5_email, $user->md5_password, $user);
0 ignored issues
show
Bug introduced by
Accessing md5_email on the interface samsonframework\orm\RecordInterface 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...
Bug introduced by
Accessing md5_password on the interface samsonframework\orm\RecordInterface 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...
Documentation introduced by
$user is of type object<samsonframework\orm\RecordInterface>, but the function expects a boolean|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
239
                if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
240
                    $this->request->redirect();
241
                }
242
            }
243
        } else {
244
            $result = '';
245
            $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...
246
                          ->message(t('Вы ввели некорректный пароль либо пароли не совпадают', true))
247
                          ->output();
248
            $this->system->template('www/signin/signin_template.vphp');
249
            $this->html($result)->title(t('Ошибка восстановление пароля', true));
250
        }
251
    }
252
}
253