Monitor.php 7.16 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 2/10/18
 * Time: 3:14 PM
 *
 * See: doc/THUMBNAIL.md
 */

Marc Egger's avatar
Marc Egger committed
11
namespace IMATHUZH\Qfq\Core\Report;
12

Marc Egger's avatar
Marc Egger committed
13
 
14
use IMATHUZH\Qfq\Core\Helper\Path;
Marc Egger's avatar
Marc Egger committed
15
16
17
use IMATHUZH\Qfq\Core\Store\Session;
use IMATHUZH\Qfq\Core\Store\Store;
use IMATHUZH\Qfq\Core\Helper\Support;
18
19
20
21
22
23
24
25
26
27
28
29

/**
 * Class Thumbnail
 * @package qfq
 */
class Monitor {

    /**
     * @var Store
     */
    private $store = null;

Carsten  Rose's avatar
Carsten Rose committed
30
31
32
33
34
    /**
     * @var Session
     */
    private $session = null;

35
36
    /**
     * @param bool|false $phpUnit
Marc Egger's avatar
Marc Egger committed
37
38
39
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
40
41
     */
    public function __construct($phpUnit = false) {
42
43

        #TODO: rewrite $phpUnit to: "if (!defined('PHPUNIT_QFQ')) {...}"
44
        $this->store = Store::getInstance();
Carsten  Rose's avatar
Carsten Rose committed
45
        $this->session = Session::getInstance($phpUnit);
46
47
48
49
    }

    /**
     * Renders some JS to monitor a file on the server.
Carsten  Rose's avatar
Carsten Rose committed
50
51
     * Report: $str: 'file:typo3conf/sql.log|tail:1000|append:1|interval:1000|htmlId:monitor1'
     * Fetch: download.php?s=<sip> with sip: file=<filename>&tail=<number of lines>
52
     *
53
     * @param array $vars
54
     * @return string
Marc Egger's avatar
Marc Egger committed
55
56
57
     * @throws \CodeException
     * @throws \UserFormException
     * @throws \UserReportException
58
     */
59
    public function process(array $vars) {
60

61
        if (empty($vars[TOKEN_L_FILE])) {
Marc Egger's avatar
Marc Egger committed
62
            throw new \UserReportException("Monitor: empty or missing parameter 'file'", ERROR_MISSING_PARAMETER_FILE);
63
64
65
        }

        // Set defaults
66
67
68
69
        Support::setIfNotSet($vars, TOKEN_L_TAIL, MONITOR_TAIL_DEFAULT);
        $isContinuous = Support::setIfNotSet($vars, TOKEN_L_APPEND, MONITOR_APPEND_DEFAULT) == MONITOR_MODE_APPEND_1 ? 'true' : 'false';
        $interval = Support::setIfNotSet($vars, TOKEN_L_INTERVAL, MONITOR_INTERVAL_DEFAULT);
        $htmlId = Support::setIfNotSet($vars, TOKEN_L_HTML_ID, MONITOR_HTML_ID_DEFAULT);
70
71

        // Setup query to generate SIP
Carsten  Rose's avatar
Carsten Rose committed
72
        $queryString = DOWNLOAD_MODE . '=' . DOWNLOAD_MODE_MONITOR .
73
74
75
            '&' . TOKEN_L_FILE . '=' . $vars[TOKEN_L_FILE] .
            '&' . TOKEN_L_TAIL . '=' . $vars[TOKEN_L_TAIL] .
            '&' . TOKEN_L_APPEND . '=' . $vars[TOKEN_L_APPEND];
Carsten  Rose's avatar
Carsten Rose committed
76
//        $url = store::getSipInstance()->queryStringToSip(API_DIR . '/' . API_DOWNLOAD_PHP . '?' . $queryString, RETURN_URL);
77
        $arr = store::getSipInstance()->queryStringToSip(Path::join(Path::JAVASCRIPT_TO_EXT, Path::EXT_TO_API, API_DOWNLOAD_PHP) . '?' . $queryString, RETURN_ARRAY);
Carsten  Rose's avatar
Carsten Rose committed
78
79
        $url = $arr[SIP_SIP_URL];

80
        // On page reload, take care to remove optional existing old seek position.
Carsten  Rose's avatar
Carsten Rose committed
81
82
        $key = $this->getSeekSessionKey($arr[CLIENT_SIP]);
        $this->session::unsetItem($key);
83

84
        $webworker = Path::urlExt(Path::EXT_TO_JAVASCRIPT, 'GetFileContent.js');
85

86
87
88
89
        $code = <<<EOF
<script type="text/javascript">
    $(document).ready(function () {
        var getFile = new QfqNS.DisplayFile({
90
            webworker: "$webworker",
91
92
93
94
95
96
97
98
99
100
101
102
103
            filePath: "$url",
            interval: $interval,
            targetId: "$htmlId",
            isContinuous: $isContinuous
        });
        getFile.show();
    });
</script>
EOF;

        return $code;
    }

Carsten  Rose's avatar
Carsten Rose committed
104
105
106
107
108
    /**
     * @param $filepath
     * @param int $lines
     * @param $modeAppend
     * @return string
Marc Egger's avatar
Marc Egger committed
109
110
111
     * @throws \CodeException
     * @throws \DownloadException
     * @throws \UserFormException
Carsten  Rose's avatar
Carsten Rose committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
     */
    public function dump($filepath, $lines, $modeAppend) {

        // Retrieve always the last $lines
        if ($modeAppend == MONITOR_MODE_APPEND_0) {
            return $this->tailCustom($filepath, $lines);
        }

        // First call to this file in this session.
        $f = $this->open($filepath);

        // Check if there is already a seek position.
        $key = $this->getSeekSessionKey($this->store->getVar(SIP_SIP, STORE_SIP));
        $seek = $this->session::get($key);
        if ($seek === false) {

            // Get seek position EOF
            fseek($f, 0, SEEK_END);
            $seek = ftell($f);

            // Store the position in session.
            $this->session::set($key, $seek);

            // On initial call, get the specified last $lines.
            return $this->tailCustom($filepath, $lines, true, $f);
        }

        fseek($f, $seek, SEEK_SET);
        $output = fread($f, 8192);
        $this->session::set($key, ftell($f));

        return $output;
    }

    /**
     * @param $sip
     * @return string
     */
    private function getSeekSessionKey($sip){
        return MONITOR_SESSION_FILE_SEEK . '-' . $sip;
    }

    /**
     * @param string $filepath
     * @param string $mode
     * @return bool|resource
Marc Egger's avatar
Marc Egger committed
158
     * @throws \DownloadException
Carsten  Rose's avatar
Carsten Rose committed
159
160
161
162
163
164
     */
    private function open($filepath, $mode = 'rb') {

        // Open file
        $f = @fopen($filepath, $mode);
        if ($f === false) {
165
166
167
            $err = error_get_last();
            $msg = $err['message'] ?? '';
            throw new \DownloadException ("Error open '" . $filepath . "': " . $msg, ERROR_IO_FILE_NOT_FOUND);
Carsten  Rose's avatar
Carsten Rose committed
168
169
170
171
172
173
        }

        return $f;
    }


174
175
176
177
178
    /**
     * Slightly modified version of http://www.geekality.net/2011/05/28/php-tail-tackling-large-files/
     * @author Torleif Berger, Lorenzo Stanco
     * @link http://stackoverflow.com/a/15025877/995958
     * @license http://creativecommons.org/licenses/by/3.0/
Carsten  Rose's avatar
Carsten Rose committed
179
180
181
182
     *
     * @param string $filepath
     * @param int $lines
     * @param bool $adaptive
183
     * @param null $f
Carsten  Rose's avatar
Carsten Rose committed
184
     * @return string
Marc Egger's avatar
Marc Egger committed
185
     * @throws \DownloadException
186
     */
Carsten  Rose's avatar
Carsten Rose committed
187
    private function tailCustom($filepath, $lines = 1, $adaptive = true, $f = null) {
188
189

        // Open file
Carsten  Rose's avatar
Carsten Rose committed
190
191
192
        if ($f === null) {
            $f = $this->open($filepath);
        }
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243

        // Sets buffer size, according to the number of lines to retrieve.
        // This gives a performance boost when reading a few lines from the file.
        if (!$adaptive) $buffer = 4096;
        else $buffer = ($lines < 2 ? 64 : ($lines < 10 ? 512 : 4096));

        // Jump to last character
        fseek($f, -1, SEEK_END);

        // Read it and adjust line number if necessary
        // (Otherwise the result would be wrong if file doesn't end with a blank line)
        if (fread($f, 1) != "\n") $lines -= 1;

        // Start reading
        $output = '';
        $chunk = '';

        // While we would like more
        while (ftell($f) > 0 && $lines >= 0) {

            // Figure out how far back we should jump
            $seek = min(ftell($f), $buffer);

            // Do the jump (backwards, relative to where we are)
            fseek($f, -$seek, SEEK_CUR);

            // Read a chunk and prepend it to our output
            $output = ($chunk = fread($f, $seek)) . $output;

            // Jump back to where we started reading
            fseek($f, -mb_strlen($chunk, '8bit'), SEEK_CUR);

            // Decrease our line counter
            $lines -= substr_count($chunk, "\n");

        }

        // While we have too many lines
        // (Because of buffer size we might have read too many)
        while ($lines++ < 0) {

            // Find first newline and remove all text before that
            $output = substr($output, strpos($output, "\n") + 1);

        }

        // Close file and return
        fclose($f);
        return trim($output);
    }
}