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