master
ブランチ master
LittleBeast / src / Std / Lib / Logs.php
5.4 KB、154行 生 Blame 履歴
1<?php
2/*************************************************************
3# 076 License
4
5Copyright (c) テクニカル諏訪子
6
7Permission is hereby granted to any person obtaining a copy of the software
8Little Beast (the "Software") to use, modify, merge, copy, publish, distribute,
9sublicense, and/or sell copies of the Software, subject to the following conditions:
10
11 1. **Origin Attribution**:
12 - You must not misrepresent the origin of the Software; you must not claim
13 you created the original Software.
14 - If the Software is used in a product, you must either:
15 a. Provide clear attribution in the product's documentation, user interface,
16 or other visible areas, **OR**
17 b. Pay the original developers a fee they specify in writing.
18 2. **Usage Restriction**:
19 - The Software, or any derivative works, dependencies, or libraries
20 incorporating it, must not be used for censorship or to suppress freedom of
21 speech, expression, or creativity. Prohibited uses include, but are not
22 limited to:
23 - Censorship of so-called "hate speech", visuals, non-mainstream opinions,
24 ideas, or objective reality.
25 - Tools or systems designed to restrict access to information or
26 artistic works.
27 3. **Notice Preservation**:
28 - This license and the above copyright notice must remain intact in all copies
29 of the source code.
30
31THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
32INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
33PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
34HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
35CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
36OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 */
38namespace Std\Lib;
39
40/**
41 * ログのファイル(log/、logger()が書く)を読む・消す(管理画面用)
42 *
43 * $logs = new Logs();
44 * foreach ($logs->list() as $f) echo $f['name'], ' ', $f['size'], "\n";
45 * $tail = $logs->tail('db_log.txt', 100, 'エラー');
46 */
47class Logs {
48 private string $dir;
49
50 /**
51 * @param string|null $dir ログのディレクトリ(既定はROOT/log、テスト用)
52 */
53 public function __construct(?string $dir = null) {
54 $this->dir = rtrim($dir ?? ROOT.'/log', '/\\');
55 }
56
57 public function dir(): string {
58 return $this->dir;
59 }
60
61 /**
62 * ログのファイルの一覧(ディレクトリが無ければ空)
63 *
64 * @return array name、size、mtime(名前の順)
65 */
66 public function list(): array {
67 $out = [];
68 foreach (@scandir($this->dir) ?: [] as $f) {
69 $p = $this->path($f);
70 if ($p === null) continue;
71 $out[] = ['name' => $f, 'size' => (int)filesize($p), 'mtime' => (int)filemtime($p)];
72 }
73 return $out;
74 }
75
76 /**
77 * ログのファイルのパス(ディレクトリの中の普通のファイルだけ)
78 *
79 * @param string $name ファイル名
80 * @return string|null 無い・不正な名前ならnull
81 */
82 public function path(string $name): ?string {
83 if (!preg_match('/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,200}$/', $name) || str_contains($name, '..')) return null;
84 $p = $this->dir.'/'.$name;
85 return is_file($p) && !is_link($p) ? $p : null;
86 }
87
88 /**
89 * 最後の行(新しい順ではなく、ファイルの順)
90 *
91 * @param string $name ファイル名
92 * @param int $lines 行数
93 * @param string $search 含む行だけ(大文字・小文字を区別しない、空なら全部)
94 * @return array|null lines(行の配列)、more(前にもっと有るか)。ファイルが無ければnull
95 */
96 public function tail(string $name, int $lines = 200, string $search = ''): ?array {
97 $p = $this->path($name);
98 if ($p === null) return null;
99 $lines = max(1, min($lines, 10000));
100 $fh = @fopen($p, 'rb');
101 if (!$fh) return null;
102 try {
103 if ($search !== '') {
104 // 検索は全部を読む(一致した最後の行だけ残す)
105 $out = [];
106 $more = false;
107 while (($l = fgets($fh)) !== false) {
108 $l = rtrim($l, "\r\n");
109 if (mb_stripos($l, $search, 0, 'UTF-8') === false) continue;
110 $out[] = $l;
111 if (count($out) > $lines) {
112 array_shift($out);
113 $more = true;
114 }
115 }
116 return ['lines' => $out, 'more' => $more];
117 }
118 // 後ろから読む
119 $size = (int)fstat($fh)['size'];
120 $pos = $size;
121 $buf = '';
122 $chunk = 65536;
123 while ($pos > 0 && substr_count($buf, "\n") <= $lines) {
124 $n = min($chunk, $pos);
125 $pos -= $n;
126 fseek($fh, $pos);
127 $buf = (string)fread($fh, $n).$buf;
128 }
129 $all = explode("\n", rtrim($buf, "\n"));
130 if ($buf === '') $all = [];
131 $more = $pos > 0 || count($all) > $lines;
132 if (count($all) > $lines) $all = array_slice($all, -$lines);
133 return ['lines' => array_map(fn($l) => rtrim($l, "\r"), $all), 'more' => $more];
134 } finally {
135 fclose($fh);
136 }
137 }
138
139 /**
140 * ログを空にする
141 */
142 public function clear(string $name): bool {
143 $p = $this->path($name);
144 return $p !== null && @file_put_contents($p, '', LOCK_EX) !== false;
145 }
146
147 /**
148 * ログのファイルを消す
149 */
150 public function delete(string $name): bool {
151 $p = $this->path($name);
152 return $p !== null && @unlink($p);
153 }
154}