login/pass: error messages below page title
[minimedit.git] / article.inc.php
1 <?php
2 class ArchiveArticle
3 {
4         public $raw, $title, $body; # file contents
5         public $meta = [];  # head metadata properties
6         public $place = []; # template variables replaced in render()
7         public $api = FALSE; # requested programming interface
8
9         function __construct($path)
10         {
11                 $this->file = preg_replace('{^\.(?:/|$)}', '', $path);
12                 $this->link = preg_replace('{(?:(?:/|^)index)?\.html$}', '', $this->file);
13                 $this->raw($this->file);
14         }
15
16         function raw($page)
17         {
18                 if (!file_exists($page)) {
19                         return;
20                 }
21                 $this->raw = file_get_contents($page);
22
23                 if (preg_match_all('{
24                         \G <meta \s+ property="( [^"]+ )" \s+ content="( [^"]* )" > \s*
25                 }x', $this->raw, $meta)) {
26                         $matchlen = array_sum(array_map('strlen', $meta[0]));
27                         $this->raw = substr($this->raw, $matchlen); # delete matched contents
28                         $this->meta = array_combine($meta[1], $meta[2]); # [property => content]
29                 }
30
31                 // find significant contents
32                 $this->body = preg_replace('{<aside\b.*?</aside>}s', '', $this->raw);
33                 if (preg_match('{<h2>(.*?)</h2>\s*(.*)}s', $this->body, $titlematch)) {
34                         list (, $this->title, $this->body) = $titlematch;
35                 }
36
37                 return $this->raw;
38         }
39
40         function __get($col)
41         {
42                 return $this->$col = $this->$col();  # run method and cache
43         }
44
45         function handler()
46         {
47                 $path = $this->link;
48                 $this->path = '';
49                 $this->restricted = FALSE;
50                 while (TRUE) {
51                         if (file_exists("$path/.private") and !$this->restricted) {
52                                 $this->restricted = $path;
53                         }
54
55                         if (file_exists("$path/index.php")) {
56                                 return $path;
57                         }
58
59                         $up = strrpos($path, '/');
60                         $this->path = substr($path, $up) . $this->path;
61                         $path = substr($path, 0, $up);
62                         if ($up === FALSE) {
63                                 break;
64                         }
65                 }
66                 return;
67         }
68
69         function index($api = TRUE)
70         {
71                 $this->handler;
72                 if (empty($this->handler)) {
73                         return;
74                 }
75                 $this->api = $api;
76                 $Page = $this;
77                 global $User;
78                 return require "./{$this->handler}/index.php";
79         }
80
81         function restricted()
82         {
83                 $this->handler;
84                 return $this->restricted;
85         }
86
87         function safetitle()
88         {
89                 return trim($this->meta['og:title'] ?? strip_tags($this->title));
90         }
91         function name()
92         {
93                 return $this->safetitle ?: htmlspecialchars($this->link);
94         }
95
96         function last()
97         {
98                 return filemtime($this->file);
99         }
100         function lastiso()
101         {
102                 return date(DATE_ATOM, $this->last);
103         }
104
105         function dateparts()
106         {
107                 preg_match('< / (\d{4}) [/-] (\d{2}) (?:- (\d{2}) )? - >x', $this->file, $ymd);
108                 array_shift($ymd);
109                 return $ymd;
110         }
111         function dateiso()
112         {
113                 return implode('-', $this->dateparts()) . 'T12:00:00+02:00';
114         }
115
116         function story()
117         {
118                 if ( preg_match('{
119                         (?: < (?: p | figure [^>]* ) >\s* )+ (<img\ [^>]*>) | \n <hr\ />
120                 }x', $this->body, $img, PREG_OFFSET_CAPTURE) ) {
121                         # strip part after matching divider (image)
122                         if (isset($img[1])) {
123                                 $this->img = $img[1][0];
124                         }
125                         return substr($this->body, 0, $img[0][1]);
126                 }
127                 return $this->body;
128         }
129
130         function teaser()
131         {
132                 if ($override = @$this->meta['og:description']) {
133                         # prefer specific page description if found in metadata
134                         return $override;
135                 }
136
137                 # paragraph contents following the page header if any
138                 if (preg_match('{
139                         \G (?> \s+ | <div [^>]*> | \[\[[^]]*\]\] )* <p> \s* (.*?) </p>
140                 }sx', $this->body, $bodyp, 0)) {
141                         return $bodyp[1];
142                 }
143         }
144
145         function img()
146         {
147                 $this->img = NULL;
148                 $this->story;
149                 return $this->img;
150         }
151         function image()
152         {
153                 if ($override = @$this->meta['og:image']) {
154                         # prefer specific page image if found in metadata
155                         return $override;
156                 }
157
158                 if ( preg_match('/\bsrc="([^"]*)"/', $this->img, $src) ) {
159                         return $src[1];
160                 }
161         }
162         function thumb($size = '300x')
163         {
164                 if (!$this->image or $this->image[0] !== '/') return;
165                 if (preg_match('{^/thumb/\D}', $this->image)) {
166                         return ltrim($this->image, '/');
167                 }
168                 return preg_replace(
169                         ['{^(?:/thumb/[^/]*)?}', '/\.groot(?=\.\w+$)/', '/(?:\.jpg)?$/'],
170                         [      "thumb/$size",    '',                         '.jpg'    ],
171                         $this->image, 1
172                 );
173         }
174
175         function widget($name, $params = [])
176         {
177                 $path = stream_resolve_include_path("widget/$name.php");
178                 if (!file_exists($path)) {
179                         return '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
180                 }
181
182                 ob_start();
183                 $Page = clone $this;
184                 if (is_array($params)) {
185                         $Page->place += $params;
186                 }
187                 else {
188                         foreach (explode(' ', $params) as $param) {
189                                 if ($set = strpos($param, '=')) {
190                                         $Page->place[ substr($param, 0, $set) ] = urldecode(substr($param, $set + 1));
191                                 }
192                                 elseif (!empty($param)) {
193                                         $Page->place[] = $param;
194                                 }
195                         }
196                 }
197
198                 try {
199                         include "widget/$name.php";
200                         return ob_get_clean();
201                 }
202                 catch (Exception $e) {
203                         return sprintf('<strong class="warn">%s</strong>',
204                                 "fout in <em>$name</em>: {$e->getMessage()}"
205                         );
206                 }
207         }
208
209         function render()
210         {
211                 $doc = $this->raw;
212
213                 if (!empty($this->place['warn'])) {
214                         $warn = '<p class="warn">[[warn]]</p>';
215                         if ($offset = strpos($doc, '</h2>')) {
216                                 $doc = substr_replace($doc, "\n\n".$warn, $offset + 5, 0);
217                         }
218                         else {
219                                 $doc = $warn . "\n\n" . $doc;
220                         }
221                 }
222
223                 # keep either login or logout parts depending on user level
224                 global $User;
225                 $userexists = $User && property_exists($User, 'login') && $User->login;
226                 if (! ($userexists and !empty($this->editable)) ) {
227                         # remove matching elements until first corresponding closing tag
228                         $hideclass = $userexists ? 'logout' : 'login';
229                         $tagmatch = '<([a-z]+) class="'.$hideclass.'"[^>]*>';
230                         $doc = preg_replace("{\s*{$tagmatch}.*?</\\1>}s", '', $doc);
231                 }
232
233                 return preg_replace_callback(
234                         '{ \[\[ ([^] ]+) ([^]]*) \]\] }x',
235                         function ($sub) {
236                                 list ($placeholder, $name, $params) = $sub;
237                                 $html = $this->place[$name] ??
238                                         $this->widget($name, $params);
239                                 if (empty($html) or $html[0] != '<') {
240                                         $html = "<span>$html</span>";
241                                 }
242                                 $attr = sprintf(' data-dyn="%s"', is_numeric($name) ? '' : $name.$params);
243                                 # contents with identifier in first tag
244                                 return preg_replace( '/(?=>)/', $attr, $html, 1);
245                         },
246                         $doc
247                 );
248         }
249 }
250
251 class PageSearch
252 {
253         public $handlers = [];
254
255         function __construct($path = '.')
256         {
257                 $this->iterator = new RecursiveCallbackFilterIterator(
258                         new RecursiveDirectoryIterator($path),
259                         function ($current) {
260                                 if ($current->getFilename()[0] === '.') {
261                                         # skip hidden files and directories
262                                         return FALSE;
263                                 }
264                                 if (file_exists($current->getFilename() . '/index.php')) {
265                                         # contents better provided by handler code
266                                         $this->handlers[ $current->getPathname() ] = $current;
267                                         return FALSE;
268                                 }
269                                 if ($current->isLink()) {
270                                         # ignore symlinks, original contents only
271                                         return FALSE;
272                                 }
273                                 if ($current->isDir()) {
274                                         # traverse subdirectories unless untracked in any amount
275                                         return !file_exists("$current/.gitignore");
276                                 }
277                                 # match **/*.html
278                                 return preg_match('/(?<!\.inc)\.html$/', $current->getFilename());
279                         }
280                 );
281         }
282
283         function files()
284         {
285                 # order alphabetically by link
286                 $dir = [];
287                 foreach (new RecursiveIteratorIterator($this->iterator) as $name) {
288                         $article = new ArchiveArticle($name);
289                         $dir[$article->link] = $article;
290                 }
291                 ksort($dir);
292                 return $dir;
293         }
294 }