Completed
Push — master ( a505a0...5d1dca )
by Fèvre
20s
created

SessionsActivityComponent::startup()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 29
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 29
rs 8.8571
cc 3
eloc 18
nc 3
nop 1
1
<?php
2
namespace App\Controller\Component;
3
4
use App\Model\Entity\User;
5
use Cake\Controller\Component;
6
use Cake\Event\Event;
7
use Cake\I18n\Time;
8
use Cake\ORM\Entity;
9
use Cake\ORM\TableRegistry;
10
11
class SessionsActivityComponent extends Component
12
{
13
14
    /**
15
     * Request object
16
     *
17
     * @var \Cake\Network\Request
18
     */
19
    protected $_request;
20
21
    /**
22
     * Instance of the Session object
23
     *
24
     * @return void
25
     */
26
    protected $_session;
27
28
    /**
29
     * Initialize properties.
30
     *
31
     * @param array $config The config data.
32
     * @return void
33
     */
34
    public function initialize(array $config)
35
    {
36
        $controller = $this->_registry->getController();
37
        $this->_request = $controller->request;
38
        $this->_session = $controller->request->session();
39
    }
40
41
    /**
42
     * Startup event to trace the user on the website.
43
     *
44
     * @param Event $event The event that was fired.
45
     *
46
     * @return void
47
     */
48
    public function startup(Event $event)
0 ignored issues
show
Unused Code introduced by
The parameter $event 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...
49
    {
50
        if (empty($this->_session->id())) {
51
            $this->_session->start();
52
53
            return;
54
        }
55
        $sessions = TableRegistry::get('Sessions');
56
57
        $prefix = isset($this->_request['prefix']) ? $this->_request['prefix'] . '/' : '';
58
        $controller = $prefix . $this->_request['controller'];
59
        $action = $this->_request['action'];
60
        $params = serialize($this->_request->pass);
61
        $expires = time() + ini_get('session.gc_maxlifetime');
62
63
        //@codingStandardsIgnoreStart
64
        $user_id = $this->_session->read('Auth.User.id');
65
        $user_agent = $this->_request->env('HTTP_USER_AGENT');
66
        $user_ip = $this->_request->clientIp();
67
        $full_url = $this->_request->url;
68
        //@codingStandardIgnoreEnd
69
70
        $modified = new Time();
71
72
        $record = compact('controller', 'action', 'params', 'expires', 'user_id', 'user_agent', 'user_ip', 'full_url', 'modified');
73
74
        $record[$sessions->primaryKey()] = $this->_session->id();
75
        $sessions->save(new Entity($record));
76
    }
77
78
    /**
79
     * Get the list of the users online.
80
     *
81
     * @return array
82
     */
83
    public function getOnlineUsers()
84
    {
85
        $sessions = TableRegistry::get('Sessions');
86
87
        $output = [
88
            'guests' => 0,
89
            'members' => 0,
90
        ];
91
92
        $records = $sessions
93
            ->find('expires')
94
            ->contain([
95
                'Users' => function ($q) {
96
                    return $q->select([
97
                        'id',
98
                        'username'
99
                    ]);
100
                },
101
                'Users.Groups' => function ($q) {
102
                    return $q->select(['css', 'is_member']);
103
                },
104
            ])
105
            ->select(['Sessions.user_id', 'Sessions.expires'])
106
            ->group('Sessions.user_id')
107
            ->toArray();
108
109
        foreach ($records as $key => $record) {
110
            if (is_null($record->user_id)) {
111
                $output['guests']++;
112
113
                unset($records[$key]);
114
                continue;
115
            } else {
116
                $output['members']++;
117
            }
118
        }
119
120
        //Total visitors.
121
        $output['total'] = $output['guests'] + $output['members'];
122
123
        //Visitor records.
124
        $output['records'] = $records;
125
126
        return $output;
127
    }
128
129
    /**
130
     * Determine if the given user is online or offline.
131
     *
132
     * @param App\Model\Entity\User $user The user to check.
133
     *
134
     * @return bool
135
     */
136
    public function getOnlineStatus(User $user)
137
    {
138
        $sessions = TableRegistry::get('Sessions');
139
        $online = $sessions
140
            ->find('expires')
141
            ->select(['Sessions.expires', 'Sessions.user_id'])
142
            ->where([
143
                'Sessions.user_id' => $user->id
0 ignored issues
show
Documentation introduced by
The property id does not exist on object<App\Model\Entity\User>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
144
            ])
145
            ->first();
146
147
        if (!empty($online)) {
148
            return true;
149
        }
150
151
        return false;
152
    }
153
154
    /**
155
     * Get all the sessions online for the given user.
156
     *
157
     * @param int $user The user id.
158
     *
159
     * @return false|array
160
     */
161
    public function getOnlineSessionsForUser($user)
162
    {
163
        if (empty($user) || is_null($user)) {
164
            return false;
165
        }
166
167
        $this->Sessions = TableRegistry::get('Sessions');
0 ignored issues
show
Bug introduced by
The property Sessions does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
168
169
        $sessions = $this->Sessions
170
            ->find('expires')
171
            ->where([
172
                'Sessions.user_id' => $user
173
            ])
174
            ->toArray();
175
176
        return $sessions;
177
    }
178
179
}
180