page: store placeholder values in $Page object
[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         public $place = []; # template variables replaced in render()
22
23         function __construct($path)
24         {
25                 $this->page = preg_replace('{^\.(?:/|$)}', '', $path);
26                 $this->link = preg_replace('{(?:(?:/|^)index)?\.html$}', '', $this->page);
27                 $this->raw($this->page);
28         }
29
30         function raw($page)
31         {
32                 if (!file_exists($page)) {
33                         return;
34                 }
35                 $this->raw = file_get_contents($page);
36
37                 if (preg_match_all('{
38                         \G <meta \s+ property="( [^"]+ )" \s+ content="( [^"]* )" > \s*
39                 }x', $this->raw, $meta)) {
40                         $matchlen = array_sum(array_map('strlen', $meta[0]));
41                         $this->raw = substr($this->raw, $matchlen); # delete matched contents
42                         $this->meta = array_combine($meta[1], $meta[2]); # [property => content]
43                 }
44
45                 // find significant contents
46                 $this->body = preg_replace('{<aside\b.*?</aside>}s', '', $this->raw);
47                 if (preg_match('{<h2>(.*?)</h2>\s*(.*)}s', $this->body, $titlematch)) {
48                         list (, $this->title, $this->body) = $titlematch;
49                 }
50
51                 return $this->raw;
52         }
53
54         function __get($col)
55         {
56                 return $this->$col = $this->$col();  # run method and cache
57         }
58
59         function handler()
60         {
61                 $path = $this->link;
62                 $this->path = '';
63                 $this->restricted = FALSE;
64                 while (TRUE) {
65                         if (file_exists("$path/.private")) {
66                                 $this->restricted = $path;
67                         }
68
69                         if (file_exists("$path/index.php")) {
70                                 return $path;
71                         }
72
73                         $up = strrpos($path, '/');
74                         $this->path = substr($path, $up) . $this->path;
75                         $path = substr($path, 0, $up);
76                         if ($up === FALSE) {
77                                 break;
78                         }
79                 }
80                 return;
81         }
82
83         function restricted()
84         {
85                 $this->handler;
86                 return $this->restricted;
87         }
88
89         function safetitle()
90         {
91                 return trim($this->meta['og:title'] ?? strip_tags($this->title));
92         }
93         function name()
94         {
95                 return $this->safetitle ?: $this->link;
96         }
97
98         function last()
99         {
100                 return filemtime($this->page);
101         }
102         function lastiso()
103         {
104                 return date(DATE_ATOM, $this->last);
105         }
106
107         function dateparts()
108         {
109                 preg_match('< / (\d{4}) [/-] (\d{2}) (?:- (\d{2}) )? - >x', $this->page, $ymd);
110                 array_shift($ymd);
111                 return $ymd;
112         }
113         function dateiso()
114         {
115                 return implode('-', $this->dateparts()) . 'T12:00:00+02:00';
116         }
117         function date()
118         {
119                 return showdate($this->dateparts);
120         }
121
122         function story()
123         {
124                 if ( preg_match('{
125                         (?: < (?: p | figure [^>]* ) >\s* )+ (<img\ [^>]*>) | \n <hr\ />
126                 }x', $this->body, $img, PREG_OFFSET_CAPTURE) ) {
127                         # strip part after matching divider (image)
128                         if (isset($img[1])) {
129                                 $this->img = $img[1][0];
130                         }
131                         return substr($this->body, 0, $img[0][1]);
132                 }
133                 return $this->body;
134         }
135
136         function teaser()
137         {
138                 if ($override = @$this->meta['og:description']) {
139                         # prefer specific page description if found in metadata
140                         return $override;
141                 }
142
143                 # paragraph contents following the page header if any
144                 if (preg_match('{
145                         \G (?> \s+ | <div [^>]*> | \[\[[^]]*\]\] )* <p> \s* (.*?) </p>
146                 }sx', $this->body, $bodyp, 0)) {
147                         return $bodyp[1];
148                 }
149         }
150
151         function img()
152         {
153                 $this->img = NULL;
154                 $this->story;
155                 return $this->img;
156         }
157         function image()
158         {
159                 if ($override = @$this->meta['og:image']) {
160                         # prefer specific page image if found in metadata
161                         return $override;
162                 }
163
164                 if ( preg_match('/\bsrc="([^"]*)"/', $this->img, $src) ) {
165                         return $src[1];
166                 }
167         }
168         function thumb($size = '300x')
169         {
170                 if (!$this->image or $this->image[0] !== '/') return;
171                 return preg_replace(
172                         ['{^(?:/thumb/[^/]*)?}', '/\.groot(?=\.\w+$)/'], ["thumb/$size", ''],
173                         $this->image
174                 );
175         }
176
177         function widget($name, $params = [])
178         {
179                 $path = stream_resolve_include_path("widget/$name.php");
180                 if (!file_exists($path)) {
181                         return '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
182                 }
183
184                 ob_start();
185                 $Page = clone $this;
186                 $Page->handler = $Page->handler . $Page->path; // .= with explicit getter
187                 $Page->path = '';
188                 foreach ($params as $param) {
189                         if ($set = strpos($param, '=')) {
190                                 $Page->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()
209         {
210                 $doc = ob_get_clean();
211
212                 if (!empty($this->place['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) {
230                                 list ($placeholder, $name, $params) = $sub;
231                                 $html = $this->place[$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 }