Completed
Push — master ( 6bb16a...109b91 )
by Vitaly
08:29 queued 03:01
created

Application::__mail()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 24
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 1 Features 2
Metric Value
c 6
b 1
f 2
dl 0
loc 24
rs 8.9713
cc 3
eloc 16
nc 3
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 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
22
/**
23
 * Generic class for user sign in
24
 * @author Olexandr Nazarenko <[email protected]>
25
 * @copyright 2014 SamsonOS
26
 */
27
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...
28
{
29
    /** @var string Identifier */
30
    public $id = 'signin';
31
32
    /** @var Email Pointer to social email module */
33
    protected $social;
34
35
    /** @var QueryInterface Database query instance */
36
    protected $query;
37
38
    /** @var RequestInterface Request instance */
39
    protected $request;
40
41
    public function authorize($cms)
42
    {
43
        if ($cms->isCMS()) {
44
            if ( ! $this->social->authorized()) {
45
                if ( ! $this->social->cookieVerification()) {
46
                    if ( ! $this->request->is('signin')) {
47
                        $this->request->redirect('/'.$cms->baseUrl.'/signin');
48
                    }
49
                } else {
50
                    $this->request->redirect('/'.$cms->baseUrl.'/signin');
51
                }
52
            } else {
53
                if ($this->request->is('signin')) {
54
                    $this->request->redirect('/'.$cms->baseUrl);
55
                }
56
            }
57
        }
58
    }
59
60
    public function init(array $params = array())
61
    {
62
        $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...
63
        // Old applications main page rendering
64
        Event::subscribe(\samsoncms\cms\Application::EVENT_IS_CMS, array($this, 'authorize'));
65
66
        //[PHPCOMPRESSOR(remove,start)]
67
68
        $moduleList = array();
69
        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...
70
        {
71
            if(isset($module->composerParameters['composerName'])) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
72
                if (in_array($module->composerParameters['composerName'], $this->composerParameters['required'])){
73
                    $moduleList[$id] = $module;
74
                }
75
            }
76
        }
77
        $moduleList[$this->id] = $this;
78
79
        // Generate resources for new module
80
        $this->system->module('resourcer')->generateResources($moduleList, $this->path() . 'www/signin/signin_template.vphp');
81
        //[PHPCOMPRESSOR(remove,end)]
82
83
        // Call parent initialization
84
        return parent::init($params);
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)
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...
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 \samson\activerecord\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->group_id = 1;
128
        $admin->created = date('Y-m-d H:i:s');
129
        $admin->active = 1;
130
        $admin->save();
131
    }
132
    //[PHPCOMPRESSOR(remove,end)]
133
134
    /** Check the user's authorization */
135
    public function __HANDLER()
136
    {
137
        $this->authorize($this->social);
138
    }
139
140
    /** Main sign in template */
141
    public function __base()
142
    {
143
        // Change template
144
        $this->system->template('www/signin/signin_template.vphp');
145
146
        // Render template with sign in form
147
        $this->html($this->view('www/signin/signin_form.vphp')->output())
148
             ->title(t('Авторизация', true));
149
    }
150
151
    /** User asynchronous sign in */
152
    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...
153
    {
154
        $user  = null;
155
        $error = '';
156
157
        if (isset($_POST['email']) && isset($_POST['password'])) {
158
            $email    = $this->social->hash($_POST['email']);
159
            $password = $this->social->hash($_POST['password']);
160
            $remember = isset($_POST['remember']) ? true : false;
161
162
            /** @var EmailStatus Perform email authorization */
163
            $auth = $this->social->authorizeWithEmail($email, $password, $remember, $user);
164
165
            if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
166
                // Fire login success event
167
                Event::fire('samson.cms.signin.login', array(&$user));
168
169
                return array('status' => '1');
170
            } else {
171
                $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...
172
                               ->errorClass('errorAuth')
173
                               ->userEmail("{$_POST['email']}")
174
                               ->focus('autofocus')
175
                               ->output();
176
177
                return array('status' => '0', 'html' => $error);
178
            }
179
        } else {
180
            $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...
181
182
            return array('status' => '0', 'html' => $error);
183
        }
184
    }
185
186
    /** User logout */
187
    public function __logout()
188
    {
189
        $this->social->deauthorize();
190
191
        // Fire logout event
192
        Event::fire('samson.cms.signin.logout');
193
194
        $this->request->redirect('cms/signin');
195
    }
196
197
    /** Sending email with the correct address */
198
    public function __mail()
199
    {
200
        if (isset($_POST['email'])) {
201
            /** @var \samson\activerecord\user $user */
202
            $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...
203
            $result = '';
204
205
            if (!empty($user = (new UserQuery())->email($_POST['email'])->first())) {
206
                $user->confirmed = $this->social->hash(generate_password(20) . time());
207
                $user->save();
208
209
                $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...
210
                mail_send($user->email, '[email protected]', $message, t('Восстановление пароля!', true), 'SamsonCMS');
211
212
                $result .= $this->view('www/signin/pass_recovery_mailsend')->output();
213
                $this->system->template('www/signin/signin_template.vphp');
214
                $this->html($result)->title(t('Восстановление пароля', true));
215
            } else {
216
                $this->request->redirect();
217
            }
218
        } else {
219
            $this->request->redirect();
220
        }
221
    }
222
223
    /**
224
     * New password form.
225
     *
226
     * @param string $code Code password recovery
227
     *
228
     * @return bool
229
     */
230
    public function __confirm($code)
231
    {
232
        $rights = (new UserQuery())->hashConfirm($code)->first();
233
      
234
        if (!empty($rights)) {
235
            //$this->system->template('www/signin/signin_template.vphp');
236
            $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...
237
                ->title(t('Восстановление пароля', true));
238
        } else {
239
            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...
240
        }
241
    }
242
243
    /**
244
     * Setting new password and sign in
245
     *
246
     * @param string $code Code password recovery
247
     */
248
    public function __recovery($code)
249
    {
250
        if (isset($_POST['password']) && isset($_POST['confirm_password'])
251
            && $_POST['password'] == $_POST['confirm_password']
252
        ) {
253
            /** @var \samson\activerecord\user $user */
254
            $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...
255
            if (!empty($user = (new UserQuery())->hashConfirm($code)->first())) {
256
                $user->confirmed = 1;
257
                $user->md5_password = md5($_POST['password']);
258
                $user->hash_password = md5($_POST['password']);
259
                $user->save();
260
261
                $auth = $this->social->authorizeWithEmail($user->md5_email, $user->md5_password, $user);
262
                if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
263
                    $this->request->redirect();
264
                }
265
            }
266
        } else {
267
            $result = '';
268
            $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...
269
                ->message(t('Вы ввели некорректный пароль либо пароли не совпадают', true))
270
                ->output();
271
            $this->system->template('www/signin/signin_template.vphp');
272
            $this->html($result)->title(t('Ошибка восстановление пароля', true));
273
        }
274
    }
275
}
276