page: move placeholder_include() to widget 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
51         function __get($col)
52         {
53                 return $this->$col = $this->$col();  # run method and cache
54         }
55
56         function handler()
57         {
58                 $path = $this->link;
59                 $this->path = '';
60                 $this->restricted = FALSE;
61                 while (TRUE) {
62                         if (file_exists("$path/.private")) {
63                                 $this->restricted = $path;
64                         }
65
66                         if (file_exists("$path/index.php")) {
67                                 return $path;
68                         }
69
70                         $up = strrpos($path, '/');
71                         $this->path = substr($path, $up) . $this->path;
72                         $path = substr($path, 0, $up);
73                         if ($up === FALSE) {
74                                 break;
75                         }
76                 }
77                 return;
78         }
79
80         function restricted()
81         {
82                 $this->handler;
83                 return $this->restricted;
84         }
85
86         function safetitle()
87         {
88                 return trim($this->meta['og:title'] ?? strip_tags($this->title));
89         }
90         function name()
91         {
92                 return $this->safetitle ?: $this->link;
93         }
94
95         function last()
96         {
97                 return filemtime($this->page);
98         }
99         function lastiso()
100         {
101                 return date(DATE_ATOM, $this->last);
102         }
103
104         function dateparts()
105         {
106                 preg_match('< / (\d{4}) [/-] (\d{2}) (?:- (\d{2}) )? - >x', $this->page, $ymd);
107                 array_shift($ymd);
108                 return $ymd;
109         }
110         function dateiso()
111         {
112                 return implode('-', $this->dateparts()) . 'T12:00:00+02:00';
113         }
114         function date()
115         {
116                 return showdate($this->dateparts);
117         }
118
119         function story()
120         {
121                 if ( preg_match('{
122                         (?: < (?: p | figure [^>]* ) >\s* )+ (<img\ [^>]*>) | \n <hr\ />
123                 }x', $this->body, $img, PREG_OFFSET_CAPTURE) ) {
124                         # strip part after matching divider (image)
125                         if (isset($img[1])) {
126                                 $this->img = $img[1][0];
127                         }
128                         return substr($this->body, 0, $img[0][1]);
129                 }
130                 return $this->body;
131         }
132
133         function teaser()
134         {
135                 if ($override = @$this->meta['og:description']) {
136                         # prefer specific page description if found in metadata
137                         return $override;
138                 }
139
140                 # paragraph contents following the page header if any
141                 if (preg_match('{
142                         \G (?> \s+ | <div [^>]*> | \[\[[^]]*\]\] )* <p> \s* (.*?) </p>
143                 }sx', $this->body, $bodyp, 0)) {
144                         return $bodyp[1];
145                 }
146         }
147
148         function img()
149         {
150                 $this->img = NULL;
151                 $this->story;
152                 return $this->img;
153         }
154         function image()
155         {
156                 if ($override = @$this->meta['og:image']) {
157                         # prefer specific page image if found in metadata
158                         return $override;
159                 }
160
161                 if ( preg_match('/\bsrc="([^"]*)"/', $this->img, $src) ) {
162                         return $src[1];
163                 }
164         }
165         function thumb($size = '300x')
166         {
167                 if (!$this->image or $this->image[0] !== '/') return;
168                 return preg_replace(
169                         ['{^(?:/thumb/[^/]*)?}', '/\.groot(?=\.\w+$)/'], ["thumb/$size", ''],
170                         $this->image
171                 );
172         }
173
174         function widget($name, $params = [])
175         {
176                 $path = stream_resolve_include_path("widget/$name.php");
177                 if (!file_exists($path)) {
178                         return '<strong class="warn"><em>'.$name.'</em> ontbreekt</strong>';
179                 }
180
181                 ob_start();
182                 $Page = clone $this;
183                 $Page->handler = $Page->handler . $Page->path; // .= with explicit getter
184                 $Page->path = '';
185                 $Place = $GLOBALS['Place'];
186                 foreach ($params as $param) {
187                         if ($set = strpos($param, '=')) {
188                                 $Place[ substr($param, 0, $set) ] = substr($param, $set + 1);
189                         }
190                         elseif (!empty($param)) {
191                                 $Page->path .= '/'.$param;
192                         }
193                 }
194                 $Page->link .= $Page->path;
195                 try {
196                         include "widget/$name.php";
197                         return ob_get_clean();
198                 }
199                 catch (Exception $e) {
200                         return sprintf('<strong class="warn">%s</strong>',
201                                 "fout in <em>$name</em>: {$e->getMessage()}"
202                         );
203                 }
204         }
205 }
206
207 class PageSearch
208 {
209         function __construct($path = '.')
210         {
211                 $this->iterator = new RecursiveCallbackFilterIterator(
212                         new RecursiveDirectoryIterator($path),
213                         function ($current) {
214                                 if ($current->getFilename()[0] === '.') {
215                                         # skip hidden files and directories
216                                         return FALSE;
217                                 }
218                                 if ($current->isLink()) {
219                                         # ignore symlinks, original contents only
220                                         return FALSE;
221                                 }
222                                 if ($current->isDir()) {
223                                         # traverse subdirectories unless untracked in any amount
224                                         return !file_exists("$current/.gitignore");
225                                 }
226                                 # match **/*.html
227                                 return preg_match('/(?<!\.inc)\.html$/', $current->getFilename());
228                         }
229                 );
230         }
231
232         function files()
233         {
234                 # order alphabetically by link
235                 $dir = iterator_to_array(new RecursiveIteratorIterator($this->iterator));
236                 array_walk($dir, function (&$row, $name) {
237                         # prepare values for sorting (directory index first)
238                         $row = preg_replace('{/index\.html$}', '', $name);
239                 });
240                 asort($dir);
241                 return $dir;
242         }
243 }