xref: /plugin/statistics/Logger.php (revision 41d1fffc4a3b58bed7f96d983ba8317fe9e225a5)
1762f4807SAndreas Gohr<?php
2762f4807SAndreas Gohr
3762f4807SAndreas Gohrnamespace dokuwiki\plugin\statistics;
4762f4807SAndreas Gohr
5*41d1fffcSAndreas Gohr/**
6*41d1fffcSAndreas Gohr * Exception thrown when logging should be ignored
7*41d1fffcSAndreas Gohr */
8*41d1fffcSAndreas Gohrclass IgnoreException extends \RuntimeException
9*41d1fffcSAndreas Gohr{
10*41d1fffcSAndreas Gohr}
11*41d1fffcSAndreas Gohr
12762f4807SAndreas Gohruse DeviceDetector\DeviceDetector;
13762f4807SAndreas Gohruse DeviceDetector\Parser\Client\Browser;
14762f4807SAndreas Gohruse DeviceDetector\Parser\Device\AbstractDeviceParser;
15762f4807SAndreas Gohruse DeviceDetector\Parser\OperatingSystem;
16762f4807SAndreas Gohruse dokuwiki\HTTP\DokuHTTPClient;
17*41d1fffcSAndreas Gohruse dokuwiki\Input\Input;
18762f4807SAndreas Gohruse dokuwiki\plugin\sqlite\SQLiteDB;
19762f4807SAndreas Gohruse helper_plugin_popularity;
20762f4807SAndreas Gohruse helper_plugin_statistics;
21762f4807SAndreas Gohr
22762f4807SAndreas Gohrclass Logger
23762f4807SAndreas Gohr{
24762f4807SAndreas Gohr    /** @var helper_plugin_statistics The statistics helper plugin instance */
25762f4807SAndreas Gohr    protected helper_plugin_statistics $hlp;
26762f4807SAndreas Gohr
27762f4807SAndreas Gohr    /** @var SQLiteDB The SQLite database instance */
28762f4807SAndreas Gohr    protected SQLiteDB $db;
29762f4807SAndreas Gohr
30762f4807SAndreas Gohr    /** @var string The full user agent string */
31762f4807SAndreas Gohr    protected string $uaAgent;
32762f4807SAndreas Gohr
33762f4807SAndreas Gohr    /** @var string The type of user agent (browser, robot, feedreader) */
34762f4807SAndreas Gohr    protected string $uaType = 'browser';
35762f4807SAndreas Gohr
36762f4807SAndreas Gohr    /** @var string The browser/client name */
37762f4807SAndreas Gohr    protected string $uaName;
38762f4807SAndreas Gohr
39762f4807SAndreas Gohr    /** @var string The browser/client version */
40762f4807SAndreas Gohr    protected string $uaVersion;
41762f4807SAndreas Gohr
42762f4807SAndreas Gohr    /** @var string The operating system/platform */
43762f4807SAndreas Gohr    protected string $uaPlatform;
44762f4807SAndreas Gohr
454a163f50SAndreas Gohr    /** @var string|null The user name, if available */
464a163f50SAndreas Gohr    protected ?string $user = null;
474a163f50SAndreas Gohr
48762f4807SAndreas Gohr    /** @var string The unique user identifier */
49762f4807SAndreas Gohr    protected string $uid;
50762f4807SAndreas Gohr
514a163f50SAndreas Gohr    /** @var string The session identifier */
524a163f50SAndreas Gohr    protected string $session;
534a163f50SAndreas Gohr
544a163f50SAndreas Gohr    /** @var int|null The ID of the main access log entry if any */
554a163f50SAndreas Gohr    protected ?int $hit = null;
564a163f50SAndreas Gohr
57c7cad24dSAndreas Gohr    /** @var DokuHTTPClient|null The HTTP client instance for testing */
58c7cad24dSAndreas Gohr    protected ?DokuHTTPClient $httpClient = null;
59c7cad24dSAndreas Gohr
604a163f50SAndreas Gohr    // region lifecycle
61762f4807SAndreas Gohr
62762f4807SAndreas Gohr    /**
63762f4807SAndreas Gohr     * Constructor
64762f4807SAndreas Gohr     *
65762f4807SAndreas Gohr     * Parses browser info and set internal vars
66762f4807SAndreas Gohr     */
67c7cad24dSAndreas Gohr    public function __construct(helper_plugin_statistics $hlp, ?DokuHTTPClient $httpClient = null)
68762f4807SAndreas Gohr    {
69*41d1fffcSAndreas Gohr        /** @var Input $INPUT */
70762f4807SAndreas Gohr        global $INPUT;
71762f4807SAndreas Gohr
72762f4807SAndreas Gohr        $this->hlp = $hlp;
73762f4807SAndreas Gohr        $this->db = $this->hlp->getDB();
74c7cad24dSAndreas Gohr        $this->httpClient = $httpClient;
75762f4807SAndreas Gohr
764a163f50SAndreas Gohr        // FIXME if we already have a session, we should not re-parse the user agent
77762f4807SAndreas Gohr
784a163f50SAndreas Gohr        $ua = trim($INPUT->server->str('HTTP_USER_AGENT'));
79762f4807SAndreas Gohr        AbstractDeviceParser::setVersionTruncation(AbstractDeviceParser::VERSION_TRUNCATION_MAJOR);
80762f4807SAndreas Gohr        $dd = new DeviceDetector($ua); // FIXME we could use client hints, but need to add headers
81762f4807SAndreas Gohr        $dd->discardBotInformation();
82762f4807SAndreas Gohr        $dd->parse();
83762f4807SAndreas Gohr
8400f786d8SAndreas Gohr        if ($dd->isFeedReader()) {
8500f786d8SAndreas Gohr            $this->uaType = 'feedreader';
8600f786d8SAndreas Gohr        } elseif ($dd->isBot()) {
87762f4807SAndreas Gohr            $this->uaType = 'robot';
88762f4807SAndreas Gohr            // for now ignore bots
89c5d2f052SAndreas Gohr            throw new IgnoreException('Bot detected, not logging');
90762f4807SAndreas Gohr        }
91762f4807SAndreas Gohr
92762f4807SAndreas Gohr        $this->uaAgent = $ua;
9305786d83SAndreas Gohr        $this->uaName = Browser::getBrowserFamily($dd->getClient('name')) ?: 'Unknown';
9400f786d8SAndreas Gohr        $this->uaVersion = $dd->getClient('version') ?: '0';
9505786d83SAndreas Gohr        $this->uaPlatform = OperatingSystem::getOsFamily($dd->getOs('name')) ?: 'Unknown';
96762f4807SAndreas Gohr        $this->uid = $this->getUID();
974a163f50SAndreas Gohr        $this->session = $this->getSession();
98*41d1fffcSAndreas Gohr        $this->user = $INPUT->server->str('REMOTE_USER', null, true);
99762f4807SAndreas Gohr    }
100762f4807SAndreas Gohr
101762f4807SAndreas Gohr    /**
102762f4807SAndreas Gohr     * Should be called before logging
103762f4807SAndreas Gohr     *
1044a163f50SAndreas Gohr     * This starts a transaction, so all logging is done in one go. It also logs the user and session data.
105762f4807SAndreas Gohr     */
106762f4807SAndreas Gohr    public function begin(): void
107762f4807SAndreas Gohr    {
108762f4807SAndreas Gohr        $this->hlp->getDB()->getPdo()->beginTransaction();
1094a163f50SAndreas Gohr
1104a163f50SAndreas Gohr        $this->logUser();
1114a163f50SAndreas Gohr        $this->logGroups();
1124a163f50SAndreas Gohr        $this->logDomain();
1134a163f50SAndreas Gohr        $this->logSession();
114762f4807SAndreas Gohr    }
115762f4807SAndreas Gohr
116762f4807SAndreas Gohr    /**
117762f4807SAndreas Gohr     * Should be called after logging
118762f4807SAndreas Gohr     *
119762f4807SAndreas Gohr     * This commits the transaction started in begin()
120762f4807SAndreas Gohr     */
121762f4807SAndreas Gohr    public function end(): void
122762f4807SAndreas Gohr    {
123762f4807SAndreas Gohr        $this->hlp->getDB()->getPdo()->commit();
124762f4807SAndreas Gohr    }
125762f4807SAndreas Gohr
1264a163f50SAndreas Gohr    // endregion
1274a163f50SAndreas Gohr    // region data gathering
1284a163f50SAndreas Gohr
129762f4807SAndreas Gohr    /**
130762f4807SAndreas Gohr     * Get the unique user ID
131762f4807SAndreas Gohr     *
13204928db4SAndreas Gohr     * The user ID is stored in the user preferences and should stay there forever.
133762f4807SAndreas Gohr     * @return string The unique user identifier
134762f4807SAndreas Gohr     */
135762f4807SAndreas Gohr    protected function getUID(): string
136762f4807SAndreas Gohr    {
13704928db4SAndreas Gohr        if(!isset($_SESSION[DOKU_COOKIE]['statistics']['uid'])) {
13804928db4SAndreas Gohr            // when there is no session UID set, we assume this was deliberate and we simply abort all logging
13904928db4SAndreas Gohr            // @todo we may later make UID generation optional
14004928db4SAndreas Gohr            throw new IgnoreException('No user ID found');
14104928db4SAndreas Gohr        }
142762f4807SAndreas Gohr
14304928db4SAndreas Gohr        return $_SESSION[DOKU_COOKIE]['statistics']['uid'];
144762f4807SAndreas Gohr    }
145762f4807SAndreas Gohr
146762f4807SAndreas Gohr    /**
147762f4807SAndreas Gohr     * Return the user's session ID
148762f4807SAndreas Gohr     *
149762f4807SAndreas Gohr     * @return string The session identifier
150762f4807SAndreas Gohr     */
151762f4807SAndreas Gohr    protected function getSession(): string
152762f4807SAndreas Gohr    {
15304928db4SAndreas Gohr        if(!isset($_SESSION[DOKU_COOKIE]['statistics']['id'])) {
15404928db4SAndreas Gohr            // when there is no session ID set, we assume this was deliberate and we simply abort all logging
15504928db4SAndreas Gohr            throw new IgnoreException('No session ID found');
15604928db4SAndreas Gohr        }
157762f4807SAndreas Gohr
15804928db4SAndreas Gohr        return $_SESSION[DOKU_COOKIE]['statistics']['id'];
159762f4807SAndreas Gohr    }
160762f4807SAndreas Gohr
1614a163f50SAndreas Gohr    // endregion
1624a163f50SAndreas Gohr    // region automatic logging
163762f4807SAndreas Gohr
1644a163f50SAndreas Gohr    /**
1654a163f50SAndreas Gohr     * Log the user was seen
1664a163f50SAndreas Gohr     */
1674a163f50SAndreas Gohr    protected function logUser(): void
1684a163f50SAndreas Gohr    {
1694a163f50SAndreas Gohr        if (!$this->user) return;
170762f4807SAndreas Gohr
171762f4807SAndreas Gohr        $this->db->exec(
1724a163f50SAndreas Gohr            'INSERT INTO users (user, dt)
1734a163f50SAndreas Gohr                  VALUES (?, CURRENT_TIMESTAMP)
1744a163f50SAndreas Gohr            ON CONFLICT (user) DO UPDATE SET
1754a163f50SAndreas Gohr                         dt = CURRENT_TIMESTAMP
1764a163f50SAndreas Gohr                   WHERE excluded.user = users.user
1774a163f50SAndreas Gohr            ',
1784a163f50SAndreas Gohr            $this->user
1794a163f50SAndreas Gohr        );
1804a163f50SAndreas Gohr
1814a163f50SAndreas Gohr    }
1824a163f50SAndreas Gohr
1834a163f50SAndreas Gohr    /**
1844a163f50SAndreas Gohr     * Log the session and user agent information
1854a163f50SAndreas Gohr     */
1864a163f50SAndreas Gohr    protected function logSession(): void
1874a163f50SAndreas Gohr    {
1884a163f50SAndreas Gohr        $this->db->exec(
1894a163f50SAndreas Gohr            'INSERT INTO sessions (session, dt, end, uid, user, ua, ua_info, ua_type, ua_ver, os)
1904a163f50SAndreas Gohr                  VALUES (?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ?, ?, ?, ?, ?, ?, ?)
1914a163f50SAndreas Gohr             ON CONFLICT (session) DO UPDATE SET
192*41d1fffcSAndreas Gohr                         end = CURRENT_TIMESTAMP,
193*41d1fffcSAndreas Gohr                         user = excluded.user,
194*41d1fffcSAndreas Gohr                         uid = excluded.uid
1954a163f50SAndreas Gohr                   WHERE excluded.session = sessions.session
1964a163f50SAndreas Gohr             ',
1974a163f50SAndreas Gohr            $this->session,
1984a163f50SAndreas Gohr            $this->uid,
1994a163f50SAndreas Gohr            $this->user,
2004a163f50SAndreas Gohr            $this->uaAgent,
2014a163f50SAndreas Gohr            $this->uaName,
2024a163f50SAndreas Gohr            $this->uaType,
2034a163f50SAndreas Gohr            $this->uaVersion,
2044a163f50SAndreas Gohr            $this->uaPlatform
205762f4807SAndreas Gohr        );
206762f4807SAndreas Gohr    }
207762f4807SAndreas Gohr
208762f4807SAndreas Gohr    /**
2094a163f50SAndreas Gohr     * Log all groups for the user
210762f4807SAndreas Gohr     *
2114a163f50SAndreas Gohr     * @todo maybe this should be done only once per session?
212762f4807SAndreas Gohr     */
2134a163f50SAndreas Gohr    protected function logGroups(): void
214762f4807SAndreas Gohr    {
2154a163f50SAndreas Gohr        global $USERINFO;
216762f4807SAndreas Gohr
2174a163f50SAndreas Gohr        if (!$this->user) return;
2184a163f50SAndreas Gohr        if (!isset($USERINFO['grps'])) return;
2194a163f50SAndreas Gohr        if (!is_array($USERINFO['grps'])) return;
2204a163f50SAndreas Gohr        $groups = $USERINFO['grps'];
221fced2f86SAnna Dabrowska
2224a163f50SAndreas Gohr        $this->db->exec('DELETE FROM groups WHERE user = ?', $this->user);
223762f4807SAndreas Gohr
224*41d1fffcSAndreas Gohr        if( empty($groups)) {
225*41d1fffcSAndreas Gohr            return;
226*41d1fffcSAndreas Gohr        }
227*41d1fffcSAndreas Gohr
22802aa9b73SAndreas Gohr        $placeholders = implode(',', array_fill(0, count($groups), '(?, ?)'));
229762f4807SAndreas Gohr        $params = [];
2304a163f50SAndreas Gohr        $sql = "INSERT INTO groups (`user`, `group`) VALUES $placeholders";
231762f4807SAndreas Gohr        foreach ($groups as $group) {
2324a163f50SAndreas Gohr            $params[] = $this->user;
233762f4807SAndreas Gohr            $params[] = $group;
234762f4807SAndreas Gohr        }
235762f4807SAndreas Gohr        $this->db->exec($sql, $params);
236762f4807SAndreas Gohr    }
237762f4807SAndreas Gohr
238762f4807SAndreas Gohr    /**
2394a163f50SAndreas Gohr     * Log email domain
2400b8b7abaSAnna Dabrowska     *
2414a163f50SAndreas Gohr     * @todo maybe this should be done only once per session?
2420b8b7abaSAnna Dabrowska     */
2434a163f50SAndreas Gohr    protected function logDomain(): void
2440b8b7abaSAnna Dabrowska    {
2454a163f50SAndreas Gohr        global $USERINFO;
2464a163f50SAndreas Gohr        if (!$this->user) return;
2474a163f50SAndreas Gohr        if (!isset($USERINFO['mail'])) return;
2484a163f50SAndreas Gohr        $mail = $USERINFO['mail'];
2490b8b7abaSAnna Dabrowska
2500b8b7abaSAnna Dabrowska        $pos = strrpos($mail, '@');
2510b8b7abaSAnna Dabrowska        if (!$pos) return;
2520b8b7abaSAnna Dabrowska        $domain = substr($mail, $pos + 1);
2530b8b7abaSAnna Dabrowska        if (empty($domain)) return;
2540b8b7abaSAnna Dabrowska
2554a163f50SAndreas Gohr        $sql = 'UPDATE users SET domain = ? WHERE user = ?';
2564a163f50SAndreas Gohr        $this->db->exec($sql, [$domain, $this->user]);
2570b8b7abaSAnna Dabrowska    }
2580b8b7abaSAnna Dabrowska
2594a163f50SAndreas Gohr    // endregion
2604a163f50SAndreas Gohr    // region internal loggers called by the dispatchers
2614a163f50SAndreas Gohr
2620b8b7abaSAnna Dabrowska    /**
2634a163f50SAndreas Gohr     * Log the given referer URL
264762f4807SAndreas Gohr     *
2654a163f50SAndreas Gohr     * @param $referer
2664a163f50SAndreas Gohr     * @return int|null The referer ID or null if no referer was given
267762f4807SAndreas Gohr     */
2684a163f50SAndreas Gohr    public function logReferer($referer): ?int
269762f4807SAndreas Gohr    {
2704a163f50SAndreas Gohr        if (!$referer) return null;
271762f4807SAndreas Gohr
2724a163f50SAndreas Gohr        // FIXME we could check against a blacklist here
273762f4807SAndreas Gohr
2744a163f50SAndreas Gohr        $se = new SearchEngines($referer);
275*41d1fffcSAndreas Gohr        $engine = $se->getEngine();
276762f4807SAndreas Gohr
277*41d1fffcSAndreas Gohr        $sql = 'INSERT OR IGNORE INTO referers (url, engine, dt) VALUES (?, ?, CURRENT_TIMESTAMP)';
278*41d1fffcSAndreas Gohr        return $this->db->exec($sql, [$referer, $engine]); // returns ID even if the insert was ignored
279762f4807SAndreas Gohr    }
280762f4807SAndreas Gohr
281762f4807SAndreas Gohr    /**
282762f4807SAndreas Gohr     * Resolve IP to country/city and store in database
283762f4807SAndreas Gohr     *
2844a163f50SAndreas Gohr     * @return string The IP address as stored
285762f4807SAndreas Gohr     */
2864a163f50SAndreas Gohr    public function logIp(): string
287762f4807SAndreas Gohr    {
2884a163f50SAndreas Gohr        $ip = clientIP(true);
2894a163f50SAndreas Gohr        $hash = $ip; // @todo we could anonymize here
2904a163f50SAndreas Gohr
291762f4807SAndreas Gohr        // check if IP already known and up-to-date
292762f4807SAndreas Gohr        $result = $this->db->queryValue(
293762f4807SAndreas Gohr            "SELECT ip
294762f4807SAndreas Gohr             FROM   iplocation
295762f4807SAndreas Gohr             WHERE  ip = ?
296762f4807SAndreas Gohr               AND  lastupd > date('now', '-30 days')",
2974a163f50SAndreas Gohr            $hash
298762f4807SAndreas Gohr        );
2994a163f50SAndreas Gohr        if ($result) return $hash; // already known and up-to-date
300762f4807SAndreas Gohr
301c7cad24dSAndreas Gohr        $http = $this->httpClient ?: new DokuHTTPClient();
3024a163f50SAndreas Gohr        $http->timeout = 7;
303762f4807SAndreas Gohr        $json = $http->get('http://ip-api.com/json/' . $ip); // yes, it's HTTP only
304762f4807SAndreas Gohr
3054a163f50SAndreas Gohr        if (!$json) {
3064a163f50SAndreas Gohr            \dokuwiki\Logger::error('Statistics Plugin - Failed talk to ip-api.com.');
3074a163f50SAndreas Gohr            return $hash;
3084a163f50SAndreas Gohr        }
309762f4807SAndreas Gohr        try {
310762f4807SAndreas Gohr            $data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
311762f4807SAndreas Gohr        } catch (\JsonException $e) {
3124a163f50SAndreas Gohr            \dokuwiki\Logger::error('Statistics Plugin - Failed to decode JSON from ip-api.com.', $e);
3134a163f50SAndreas Gohr            return $hash;
314762f4807SAndreas Gohr        }
31502aa9b73SAndreas Gohr        if (!isset($data['status'])) {
31602aa9b73SAndreas Gohr            \dokuwiki\Logger::error('Statistics Plugin - Invalid ip-api.com result' . $ip, $data);
3174a163f50SAndreas Gohr            return $hash;
318*41d1fffcSAndreas Gohr        }
31902aa9b73SAndreas Gohr
32002aa9b73SAndreas Gohr        // we do not check for 'success' status here. when the API can't resolve the IP we still log it
32102aa9b73SAndreas Gohr        // without location data, so we won't re-query it in the next 30 days.
322762f4807SAndreas Gohr
3234a163f50SAndreas Gohr        $host = gethostbyaddr($ip); // @todo if we anonymize the IP, we should not do this
324762f4807SAndreas Gohr        $this->db->exec(
325762f4807SAndreas Gohr            'INSERT OR REPLACE INTO iplocation (
326762f4807SAndreas Gohr                    ip, country, code, city, host, lastupd
327762f4807SAndreas Gohr                 ) VALUES (
328762f4807SAndreas Gohr                    ?, ?, ?, ?, ?, CURRENT_TIMESTAMP
329762f4807SAndreas Gohr                 )',
3304a163f50SAndreas Gohr            $hash,
33102aa9b73SAndreas Gohr            $data['country'] ?? '',
33202aa9b73SAndreas Gohr            $data['countryCode'] ?? '',
33302aa9b73SAndreas Gohr            $data['city'] ?? '',
3342adee4c6SAndreas Gohr            $host
335762f4807SAndreas Gohr        );
3364a163f50SAndreas Gohr
3374a163f50SAndreas Gohr        return $hash;
3384a163f50SAndreas Gohr    }
3394a163f50SAndreas Gohr
3404a163f50SAndreas Gohr    // endregion
3414a163f50SAndreas Gohr    // region log dispatchers
3424a163f50SAndreas Gohr
3434a163f50SAndreas Gohr    public function logPageView(): void
3444a163f50SAndreas Gohr    {
3454a163f50SAndreas Gohr        global $INPUT;
3464a163f50SAndreas Gohr
3474a163f50SAndreas Gohr        if (!$INPUT->str('p')) return;
3484a163f50SAndreas Gohr
3494a163f50SAndreas Gohr
3504a163f50SAndreas Gohr        $referer = $INPUT->filter('trim')->str('r');
3514a163f50SAndreas Gohr        $ip = $this->logIp(); // resolve the IP address
3524a163f50SAndreas Gohr
3534a163f50SAndreas Gohr        $data = [
3544a163f50SAndreas Gohr            'page' => $INPUT->filter('cleanID')->str('p'),
3554a163f50SAndreas Gohr            'ip' => $ip,
3564a163f50SAndreas Gohr            'ref_id' => $this->logReferer($referer),
3574a163f50SAndreas Gohr            'sx' => $INPUT->int('sx'),
3584a163f50SAndreas Gohr            'sy' => $INPUT->int('sy'),
3594a163f50SAndreas Gohr            'vx' => $INPUT->int('vx'),
3604a163f50SAndreas Gohr            'vy' => $INPUT->int('vy'),
3614a163f50SAndreas Gohr            'session' => $this->session,
3624a163f50SAndreas Gohr        ];
3634a163f50SAndreas Gohr
3644a163f50SAndreas Gohr        $this->db->exec('
3654a163f50SAndreas Gohr        INSERT INTO pageviews (
3664a163f50SAndreas Gohr            dt, page, ip, ref_id, screen_x, screen_y, view_x, view_y, session
3674a163f50SAndreas Gohr        ) VALUES (
3684a163f50SAndreas Gohr            CURRENT_TIMESTAMP, :page, :ip, :ref_id, :sx, :sy, :vx, :vy, :session
3694a163f50SAndreas Gohr        )
3704a163f50SAndreas Gohr        ',
3714a163f50SAndreas Gohr            $data
3724a163f50SAndreas Gohr        );
373762f4807SAndreas Gohr    }
374762f4807SAndreas Gohr
375762f4807SAndreas Gohr    /**
376762f4807SAndreas Gohr     * Log a click on an external link
377762f4807SAndreas Gohr     *
378762f4807SAndreas Gohr     * Called from log.php
379762f4807SAndreas Gohr     */
380762f4807SAndreas Gohr    public function logOutgoing(): void
381762f4807SAndreas Gohr    {
382762f4807SAndreas Gohr        global $INPUT;
383762f4807SAndreas Gohr
384762f4807SAndreas Gohr        if (!$INPUT->str('ol')) return;
385762f4807SAndreas Gohr
3864a163f50SAndreas Gohr        $link = $INPUT->filter('trim')->str('ol');
3874a163f50SAndreas Gohr        $session = $this->session;
3884a163f50SAndreas Gohr        $page = $INPUT->filter('cleanID')->str('p');
389762f4807SAndreas Gohr
390762f4807SAndreas Gohr        $this->db->exec(
391762f4807SAndreas Gohr            'INSERT INTO outlinks (
3924a163f50SAndreas Gohr                dt, session, page, link
393762f4807SAndreas Gohr             ) VALUES (
394*41d1fffcSAndreas Gohr                CURRENT_TIMESTAMP, ?, ?, ?
395762f4807SAndreas Gohr             )',
3962adee4c6SAndreas Gohr            $session,
3972adee4c6SAndreas Gohr            $page,
3982adee4c6SAndreas Gohr            $link
399762f4807SAndreas Gohr        );
400762f4807SAndreas Gohr    }
401762f4807SAndreas Gohr
402762f4807SAndreas Gohr    /**
403762f4807SAndreas Gohr     * Log access to a media file
404762f4807SAndreas Gohr     *
405762f4807SAndreas Gohr     * Called from action.php
406762f4807SAndreas Gohr     *
407762f4807SAndreas Gohr     * @param string $media The media ID
408762f4807SAndreas Gohr     * @param string $mime The media's mime type
409762f4807SAndreas Gohr     * @param bool $inline Is this displayed inline?
410762f4807SAndreas Gohr     * @param int $size Size of the media file
411762f4807SAndreas Gohr     */
412762f4807SAndreas Gohr    public function logMedia(string $media, string $mime, bool $inline, int $size): void
413762f4807SAndreas Gohr    {
414762f4807SAndreas Gohr        [$mime1, $mime2] = explode('/', strtolower($mime));
415762f4807SAndreas Gohr        $inline = $inline ? 1 : 0;
416762f4807SAndreas Gohr
417762f4807SAndreas Gohr
4184a163f50SAndreas Gohr        $data = [
4194a163f50SAndreas Gohr            'media' => cleanID($media),
4204a163f50SAndreas Gohr            'ip' => $this->logIp(), // resolve the IP address
4214a163f50SAndreas Gohr            'session' => $this->session,
4224a163f50SAndreas Gohr            'size' => $size,
4234a163f50SAndreas Gohr            'mime1' => $mime1,
4244a163f50SAndreas Gohr            'mime2' => $mime2,
4254a163f50SAndreas Gohr            'inline' => $inline,
4264a163f50SAndreas Gohr        ];
4274a163f50SAndreas Gohr
4284a163f50SAndreas Gohr        $this->db->exec('
4294a163f50SAndreas Gohr                INSERT INTO media ( dt, media, ip, session, size, mime1, mime2, inline )
4304a163f50SAndreas Gohr                     VALUES (CURRENT_TIMESTAMP, :media, :ip, :session, :size, :mime1, :mime2, :inline)
4314a163f50SAndreas Gohr            ',
4324a163f50SAndreas Gohr            $data
433762f4807SAndreas Gohr        );
434762f4807SAndreas Gohr    }
435762f4807SAndreas Gohr
436762f4807SAndreas Gohr    /**
437762f4807SAndreas Gohr     * Log page edits
438762f4807SAndreas Gohr     *
4394a163f50SAndreas Gohr     * called from action.php
4404a163f50SAndreas Gohr     *
441762f4807SAndreas Gohr     * @param string $page The page that was edited
442762f4807SAndreas Gohr     * @param string $type The type of edit (create, edit, etc.)
443762f4807SAndreas Gohr     */
444762f4807SAndreas Gohr    public function logEdit(string $page, string $type): void
445762f4807SAndreas Gohr    {
4464a163f50SAndreas Gohr        $data = [
4474a163f50SAndreas Gohr            'page' => cleanID($page),
4484a163f50SAndreas Gohr            'type' => $type,
4494a163f50SAndreas Gohr            'ip' => $this->logIp(), // resolve the IP address
4504a163f50SAndreas Gohr            'session' => $this->session
4514a163f50SAndreas Gohr        ];
452762f4807SAndreas Gohr
453*41d1fffcSAndreas Gohr        $this->db->exec(
454762f4807SAndreas Gohr            'INSERT INTO edits (
4554a163f50SAndreas Gohr                dt, page, type, ip, session
456762f4807SAndreas Gohr             ) VALUES (
4574a163f50SAndreas Gohr                CURRENT_TIMESTAMP, :page, :type, :ip, :session
458762f4807SAndreas Gohr             )',
4594a163f50SAndreas Gohr            $data
460762f4807SAndreas Gohr        );
461762f4807SAndreas Gohr    }
462762f4807SAndreas Gohr
463762f4807SAndreas Gohr    /**
464762f4807SAndreas Gohr     * Log login/logoffs and user creations
465762f4807SAndreas Gohr     *
466af93d154SAndreas Gohr     * @param string $type The type of login event (login, logout, create, failed)
467af93d154SAndreas Gohr     * @param string $user The username
468762f4807SAndreas Gohr     */
469762f4807SAndreas Gohr    public function logLogin(string $type, string $user = ''): void
470762f4807SAndreas Gohr    {
471762f4807SAndreas Gohr        global $INPUT;
472762f4807SAndreas Gohr
473762f4807SAndreas Gohr        if (!$user) $user = $INPUT->server->str('REMOTE_USER');
474762f4807SAndreas Gohr
475762f4807SAndreas Gohr        $ip = clientIP(true);
476762f4807SAndreas Gohr
477762f4807SAndreas Gohr        $this->db->exec(
478762f4807SAndreas Gohr            'INSERT INTO logins (
479af93d154SAndreas Gohr                dt, ip, user, type
480762f4807SAndreas Gohr             ) VALUES (
481af93d154SAndreas Gohr                CURRENT_TIMESTAMP, ?, ?, ?
482762f4807SAndreas Gohr             )',
4832adee4c6SAndreas Gohr            $ip,
4842adee4c6SAndreas Gohr            $user,
485af93d154SAndreas Gohr            $type
486762f4807SAndreas Gohr        );
487762f4807SAndreas Gohr    }
488762f4807SAndreas Gohr
489762f4807SAndreas Gohr    /**
49002aa9b73SAndreas Gohr     * Log search data to the search related tables
49102aa9b73SAndreas Gohr     *
49202aa9b73SAndreas Gohr     * @param string $query The search query
49302aa9b73SAndreas Gohr     * @param string[] $words The query split into words
49402aa9b73SAndreas Gohr     */
49502aa9b73SAndreas Gohr    public function logSearch(string $query, array $words): void
49602aa9b73SAndreas Gohr    {
49702aa9b73SAndreas Gohr        if (!$query) return;
49802aa9b73SAndreas Gohr
49902aa9b73SAndreas Gohr        $sid = $this->db->exec(
50002aa9b73SAndreas Gohr            'INSERT INTO search (dt, ip, session, query) VALUES (CURRENT_TIMESTAMP, ?, ? , ?)',
50102aa9b73SAndreas Gohr            $this->logIp(), // resolve the IP address
50202aa9b73SAndreas Gohr            $this->session,
50302aa9b73SAndreas Gohr            $query,
50402aa9b73SAndreas Gohr        );
50502aa9b73SAndreas Gohr
50602aa9b73SAndreas Gohr        foreach ($words as $word) {
50702aa9b73SAndreas Gohr            if (!$word) continue;
50802aa9b73SAndreas Gohr            $this->db->exec(
50902aa9b73SAndreas Gohr                'INSERT INTO searchwords (sid, word) VALUES (?, ?)',
51002aa9b73SAndreas Gohr                $sid,
51102aa9b73SAndreas Gohr                $word
51202aa9b73SAndreas Gohr            );
51302aa9b73SAndreas Gohr        }
51402aa9b73SAndreas Gohr    }
51502aa9b73SAndreas Gohr
51602aa9b73SAndreas Gohr    /**
517762f4807SAndreas Gohr     * Log the current page count and size as today's history entry
518762f4807SAndreas Gohr     */
519762f4807SAndreas Gohr    public function logHistoryPages(): void
520762f4807SAndreas Gohr    {
521762f4807SAndreas Gohr        global $conf;
522762f4807SAndreas Gohr
523762f4807SAndreas Gohr        // use the popularity plugin's search method to find the wanted data
524762f4807SAndreas Gohr        /** @var helper_plugin_popularity $pop */
525762f4807SAndreas Gohr        $pop = plugin_load('helper', 'popularity');
526b188870fSAndreas Gohr        $list = $this->initEmptySearchList();
527762f4807SAndreas Gohr        search($list, $conf['datadir'], [$pop, 'searchCountCallback'], ['all' => false], '');
528762f4807SAndreas Gohr        $page_count = $list['file_count'];
529762f4807SAndreas Gohr        $page_size = $list['file_size'];
530762f4807SAndreas Gohr
531762f4807SAndreas Gohr        $this->db->exec(
532762f4807SAndreas Gohr            'INSERT OR REPLACE INTO history (
533762f4807SAndreas Gohr                info, value, dt
534762f4807SAndreas Gohr             ) VALUES (
535483101d3SAndreas Gohr                ?, ?, CURRENT_TIMESTAMP
536762f4807SAndreas Gohr             )',
5372adee4c6SAndreas Gohr            'page_count',
5382adee4c6SAndreas Gohr            $page_count
539762f4807SAndreas Gohr        );
540762f4807SAndreas Gohr        $this->db->exec(
541762f4807SAndreas Gohr            'INSERT OR REPLACE INTO history (
542762f4807SAndreas Gohr                info, value, dt
543762f4807SAndreas Gohr             ) VALUES (
544483101d3SAndreas Gohr                ?, ?, CURRENT_TIMESTAMP
545762f4807SAndreas Gohr             )',
5462adee4c6SAndreas Gohr            'page_size',
5472adee4c6SAndreas Gohr            $page_size
548762f4807SAndreas Gohr        );
549762f4807SAndreas Gohr    }
550762f4807SAndreas Gohr
551762f4807SAndreas Gohr    /**
552762f4807SAndreas Gohr     * Log the current media count and size as today's history entry
553762f4807SAndreas Gohr     */
554762f4807SAndreas Gohr    public function logHistoryMedia(): void
555762f4807SAndreas Gohr    {
556762f4807SAndreas Gohr        global $conf;
557762f4807SAndreas Gohr
558762f4807SAndreas Gohr        // use the popularity plugin's search method to find the wanted data
559762f4807SAndreas Gohr        /** @var helper_plugin_popularity $pop */
560762f4807SAndreas Gohr        $pop = plugin_load('helper', 'popularity');
561b188870fSAndreas Gohr        $list = $this->initEmptySearchList();
562762f4807SAndreas Gohr        search($list, $conf['mediadir'], [$pop, 'searchCountCallback'], ['all' => true], '');
563762f4807SAndreas Gohr        $media_count = $list['file_count'];
564762f4807SAndreas Gohr        $media_size = $list['file_size'];
565762f4807SAndreas Gohr
566762f4807SAndreas Gohr        $this->db->exec(
567762f4807SAndreas Gohr            'INSERT OR REPLACE INTO history (
568762f4807SAndreas Gohr                info, value, dt
569762f4807SAndreas Gohr             ) VALUES (
570483101d3SAndreas Gohr                ?, ?, CURRENT_TIMESTAMP
571762f4807SAndreas Gohr             )',
5722adee4c6SAndreas Gohr            'media_count',
5732adee4c6SAndreas Gohr            $media_count
574762f4807SAndreas Gohr        );
575762f4807SAndreas Gohr        $this->db->exec(
576762f4807SAndreas Gohr            'INSERT OR REPLACE INTO history (
577762f4807SAndreas Gohr                info, value, dt
578762f4807SAndreas Gohr             ) VALUES (
579483101d3SAndreas Gohr                ?, ?, CURRENT_TIMESTAMP
580762f4807SAndreas Gohr             )',
5812adee4c6SAndreas Gohr            'media_size',
5822adee4c6SAndreas Gohr            $media_size
583762f4807SAndreas Gohr        );
584762f4807SAndreas Gohr    }
585b188870fSAndreas Gohr
5864a163f50SAndreas Gohr    // endregion
5874a163f50SAndreas Gohr
588b188870fSAndreas Gohr    /**
589b188870fSAndreas Gohr     * @todo can be dropped in favor of helper_plugin_popularity::initEmptySearchList() once it's public
590b188870fSAndreas Gohr     * @return array
591b188870fSAndreas Gohr     */
592b188870fSAndreas Gohr    protected function initEmptySearchList()
593b188870fSAndreas Gohr    {
594b188870fSAndreas Gohr        return array_fill_keys([
595b188870fSAndreas Gohr            'file_count',
596b188870fSAndreas Gohr            'file_size',
597b188870fSAndreas Gohr            'file_max',
598b188870fSAndreas Gohr            'file_min',
599b188870fSAndreas Gohr            'dir_count',
600b188870fSAndreas Gohr            'dir_nest',
601b188870fSAndreas Gohr            'file_oldest'
602b188870fSAndreas Gohr        ], 0);
603b188870fSAndreas Gohr    }
604762f4807SAndreas Gohr}
605