Subversion Repositories oidplus

Rev

Rev 1266 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
635 daniel-mar 1
<?php
2
 
3
/*
4
 * OIDplus 2.0
1086 daniel-mar 5
 * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
635 daniel-mar 6
 *
7
 * Licensed under the Apache License, Version 2.0 (the "License");
8
 * you may not use this file except in compliance with the License.
9
 * You may obtain a copy of the License at
10
 *
11
 *     http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 * Unless required by applicable law or agreed to in writing, software
14
 * distributed under the License is distributed on an "AS IS" BASIS,
15
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 * See the License for the specific language governing permissions and
17
 * limitations under the License.
18
 */
19
 
1050 daniel-mar 20
namespace ViaThinkSoft\OIDplus;
635 daniel-mar 21
 
1086 daniel-mar 22
// phpcs:disable PSR1.Files.SideEffects
23
\defined('INSIDE_OIDPLUS') or die;
24
// phpcs:enable PSR1.Files.SideEffects
25
 
635 daniel-mar 26
class OIDplusPagePublicResources extends OIDplusPagePluginPublic {
27
 
1116 daniel-mar 28
        /**
29
         * @return array|mixed|string|string[]
30
         */
635 daniel-mar 31
        private function getMainTitle() {
32
                return _L('Documents and Resources');
33
        }
34
 
1116 daniel-mar 35
        /**
36
         * @param bool $html
37
         * @return void
38
         * @throws OIDplusException
39
         */
40
        public function init(bool $html=true) {
635 daniel-mar 41
                OIDplus::config()->prepareConfigKey('resource_plugin_autoopen_level', 'Resource plugin: How many levels should be open in the treeview when OIDplus is loaded?', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
42
                        if (!is_numeric($value) || ($value < 0)) {
43
                                throw new OIDplusException(_L('Please enter a valid value.'));
44
                        }
45
                });
46
                OIDplus::config()->delete('resource_plugin_title');
47
                OIDplus::config()->delete('resource_plugin_path');
48
                OIDplus::config()->prepareConfigKey('resource_plugin_hide_empty_path','Resource plugin: Hide empty paths? (0=no, 1=yes)', '1', OIDplusConfig::PROTECTION_EDITABLE, function($value) {
49
                        if (!is_numeric($value) || (($value != 0) && ($value != 1))) {
50
                                throw new OIDplusException(_L('Please enter a valid value (0=no, 1=yes).'));
51
                        }
52
                });
53
        }
54
 
1116 daniel-mar 55
        /**
1130 daniel-mar 56
         * @param string $file
1116 daniel-mar 57
         * @return string
1130 daniel-mar 58
         * @throws OIDplusConfigInitializationException|OIDplusException
1116 daniel-mar 59
         */
1130 daniel-mar 60
        private static function getDocumentContent(string $file): string {
635 daniel-mar 61
                $file = self::realname($file);
62
                $file2 = preg_replace('/\.([^.]+)$/', '$'.OIDplus::getCurrentLang().'.\1', $file);
63
                if (file_exists($file2)) $file = $file2;
64
 
65
                $cont = file_get_contents($file);
1143 daniel-mar 66
                if (!$cont) return '';
635 daniel-mar 67
 
68
                list($html, $js, $css) = extractHtmlContents($cont);
69
                $cont = '';
70
                if (!empty($js))  $cont .= "<script>\n$js\n</script>";
71
                if (!empty($css)) $cont .= "<style>\n$css\n</style>";
821 daniel-mar 72
                $cont .= stripHtmlComments($html);
635 daniel-mar 73
 
74
                return $cont;
75
        }
76
 
1116 daniel-mar 77
        /**
1130 daniel-mar 78
         * @param string $file
1116 daniel-mar 79
         * @return array|mixed|string
80
         * @throws OIDplusConfigInitializationException
81
         * @throws OIDplusException
82
         */
1130 daniel-mar 83
        private static function getDocumentTitle(string $file) {
635 daniel-mar 84
                $file = self::realname($file);
85
                $file2 = preg_replace('/\.([^.]+)$/', '$'.OIDplus::getCurrentLang().'.\1', $file);
86
                if (file_exists($file2)) $file = $file2;
87
 
88
                $cont = file_get_contents($file);
89
 
90
                // make sure the program works even if the user provided HTML is not UTF-8
721 daniel-mar 91
                $cont = convert_to_utf8_no_bom($cont);
635 daniel-mar 92
 
93
                $m = array();
94
                if (preg_match('@<title>(.+)</title>@ismU', $cont, $m)) return $m[1];
95
                if (preg_match('@<h1>(.+)</h1>@ismU', $cont, $m)) return $m[1];
96
                if (preg_match('@<h2>(.+)</h2>@ismU', $cont, $m)) return $m[1];
97
                if (preg_match('@<h3>(.+)</h3>@ismU', $cont, $m)) return $m[1];
98
                if (preg_match('@<h4>(.+)</h4>@ismU', $cont, $m)) return $m[1];
99
                if (preg_match('@<h5>(.+)</h5>@ismU', $cont, $m)) return $m[1];
100
                if (preg_match('@<h6>(.+)</h6>@ismU', $cont, $m)) return $m[1];
101
                return pathinfo($file, PATHINFO_FILENAME); // filename without extension
102
        }
103
 
1116 daniel-mar 104
        /**
1130 daniel-mar 105
         * @param string $source
1116 daniel-mar 106
         * @return bool
107
         * @throws OIDplusException
108
         */
1130 daniel-mar 109
        protected static function mayAccessResource(string $source): bool {
635 daniel-mar 110
                if (OIDplus::authUtils()->isAdminLoggedIn()) return true;
111
 
112
                $candidates = array(
113
                        OIDplus::localpath().'userdata/resources/security.ini',
114
                        OIDplus::localpath().'res/security.ini'
115
                );
116
                foreach ($candidates as $ini_file) {
117
                        if (file_exists($ini_file)) {
118
                                $data = @parse_ini_file($ini_file, true);
1162 daniel-mar 119
                                if (isset($data['Security'][$source])) {
635 daniel-mar 120
                                        $level = $data['Security'][$source];
121
                                        if ($level == 'PUBLIC') {
122
                                                return true;
123
                                        } else if ($level == 'RA') {
124
                                                return
125
                                                        ((OIDplus::authUtils()->raNumLoggedIn() > 0) ||
126
                                                        (OIDplus::authUtils()->isAdminLoggedIn()));
127
                                        } else if ($level == 'ADMIN') {
128
                                                return OIDplus::authUtils()->isAdminLoggedIn();
129
                                        } else {
130
                                                throw new OIDplusException(_L('Unexpected security level in %1 (expect PUBLIC, RA or ADMIN)', $ini_file));
131
                                        }
132
                                }
133
                        }
134
                }
135
                return true;
136
        }
137
 
1116 daniel-mar 138
        /**
1130 daniel-mar 139
         * @param string $reldir
140
         * @param bool $onlydir
1116 daniel-mar 141
         * @return array
142
         * @throws OIDplusException
143
         */
1130 daniel-mar 144
        private static function myglob(string $reldir, bool $onlydir=false): array {
635 daniel-mar 145
                $out = array();
146
 
147
                $root = OIDplus::localpath().'userdata/resources/';
719 daniel-mar 148
                $res = $onlydir ? @glob($root.ltrim($reldir,'/'), GLOB_ONLYDIR) : @glob($root.ltrim($reldir,'/'));
149
                if ($res) foreach ($res as &$x) {
635 daniel-mar 150
                        $x = substr($x, strlen($root));
151
                        if (strpos($x,'$') !== false) continue;
152
                        $out[] = $x;
153
                }
154
 
155
                $root = OIDplus::localpath().'res/';
719 daniel-mar 156
                $res = $onlydir ? @glob($root.ltrim($reldir,'/'), GLOB_ONLYDIR) : @glob($root.ltrim($reldir,'/'));
157
                if ($res) foreach ($res as $x) {
635 daniel-mar 158
                        $x = substr($x, strlen($root));
159
                        if (strpos($x,'$') !== false) continue;
160
                        $out[] = $x;
161
                }
162
 
163
                $out = array_unique($out);
164
 
165
                return array_filter($out, function($v, $k) {
166
                        return self::mayAccessResource($v);
167
                }, ARRAY_FILTER_USE_BOTH);
168
        }
169
 
1116 daniel-mar 170
        /**
1130 daniel-mar 171
         * @param string $rel
1116 daniel-mar 172
         * @return string|null
173
         */
1130 daniel-mar 174
        private static function realname(string $rel) {
635 daniel-mar 175
                $candidate1 = OIDplus::localpath().'userdata/resources/'.$rel;
176
                $candidate2 = OIDplus::localpath().'res/'.$rel;
177
                if (file_exists($candidate1) || is_dir($candidate1)) return $candidate1;
178
                if (file_exists($candidate2) || is_dir($candidate2)) return $candidate2;
179
                return null;
180
        }
181
 
1116 daniel-mar 182
        /**
1130 daniel-mar 183
         * @param string $source
184
         * @param string $target
1116 daniel-mar 185
         * @return bool
186
         */
1130 daniel-mar 187
        protected static function checkRedirect(string $source, string &$target): bool {
635 daniel-mar 188
                $candidates = array(
189
                        OIDplus::localpath().'userdata/resources/redirect.ini',
190
                        OIDplus::localpath().'res/redirect.ini'
191
                );
192
                foreach ($candidates as $ini_file) {
193
                        if (file_exists($ini_file)) {
194
                                $data = @parse_ini_file($ini_file, true);
1162 daniel-mar 195
                                if (isset($data['Redirects'][$source])) {
635 daniel-mar 196
                                        $target = $data['Redirects'][$source];
197
                                        return true;
198
                                }
199
                        }
200
                }
201
                return false;
202
        }
203
 
1116 daniel-mar 204
        /**
205
         * @param string $id
206
         * @param array $out
207
         * @param bool $handled
208
         * @return void
209
         * @throws OIDplusConfigInitializationException
210
         * @throws OIDplusException
211
         */
212
        public function gui(string $id, array &$out, bool &$handled) {
635 daniel-mar 213
                if (explode('$',$id,2)[0] === 'oidplus:resources') {
214
                        $handled = true;
215
 
1062 daniel-mar 216
                        $tmp = explode('$',$id);
1130 daniel-mar 217
                        $file = $tmp[1] ?? '';
1062 daniel-mar 218
                        unset($tmp);
635 daniel-mar 219
 
220
                        // Security checks
221
 
222
                        if (
223
                                ($file != '') && (
224
                                (strpos($file, chr(0)) !== false) || // Directory traversal (LFI,RFI) helper
225
                                (strpos($file, '../') !== false) || ($file[0] == '/') || ($file[0] == '~') || // <-- Local File Injection (LFI)
226
                                ($file[0] == '.') || (strpos($file, '/.') !== false) ||                       // <-- Calling hidden files e.g. ".htpasswd"
227
                                (strpos($file, '://') !== false)                                              // <-- Remote File Injection (RFI)
228
                           )) {
229
                                if (strpos($file, chr(0)) !== false) {
230
                                        $file = str_replace(chr(0), '[NUL]', $file);
231
                                }
232
                                // This will not be logged anymore, because people could spam the log files otherwise
1267 daniel-mar 233
                                //OIDplus::logger()->log("V2:[WARN]A", "LFI/RFI attack blocked (requested file '%1')", $file);
1206 daniel-mar 234
                                throw new OIDplusException(_L('This request is invalid'), _L('Access denied'));
635 daniel-mar 235
                        }
236
 
237
                        $out['text'] = '';
238
 
239
                        // Check for permission
240
 
241
                        if ($file != '') {
242
                                if (!self::mayAccessResource($file)) {
1266 daniel-mar 243
                                        throw new OIDplusException(_L('Authentication error. Please log in.'), _L('Access denied'), 401);
635 daniel-mar 244
                                }
245
                        }
246
 
247
                        // Redirections
248
 
249
                        if ($file != '') {
1130 daniel-mar 250
                                $target = '';
635 daniel-mar 251
                                if (self::checkRedirect($file, $target)) {
252
                                        $out['title'] = _L('Please wait...');
253
                                        $out['text'] = '<p>'._L('You are being redirected...').'</p><script>window.location.href = '.js_escape($target).';</script>';
254
                                        return;
255
                                }
256
                        }
257
 
258
                        // First, "Go back to" line
259
 
260
                        if ($file != '') {
261
                                $dir = dirname($file);
262
 
263
                                if ($dir == '.') {
800 daniel-mar 264
                                        if (file_exists(__DIR__.'/img/main_icon16.png')) {
801 daniel-mar 265
                                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
635 daniel-mar 266
                                        } else {
267
                                                $tree_icon = null; // default icon (folder)
268
                                        }
269
 
270
                                        $ic = empty($tree_icon) ? '' : '<img src="'.$tree_icon.'" alt="">';
271
 
272
                                        $lng_gobackto = _L('Go back to').':';
273
                                        $out['text'] .= '<p><a '.OIDplus::gui()->link('oidplus:resources').'><img src="img/arrow_back.png" width="16" alt="'._L('Go back').'"> '.$lng_gobackto.' '.$ic.' '.htmlentities($this->getMainTitle()).'</a></p>';
274
                                } else {
275
                                        $realdir = self::realname($dir);
276
 
801 daniel-mar 277
                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($dir);
635 daniel-mar 278
                                        /*
279
                                        $icon_candidate = pathinfo($realdir)['dirname'].'/'.pathinfo($realdir)['filename'].'_tree.png';
280
                                        if (file_exists($icon_candidate)) {
281
                                                $tree_icon = $icon_candidate;
800 daniel-mar 282
                                        } else if (file_exists(__DIR__.'/img/folder_icon16.png')) {
801 daniel-mar 283
                                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon16.png';
635 daniel-mar 284
                                        } else {
285
                                                $tree_icon = null; // no icon
286
                                        }
287
                                        */
288
 
705 daniel-mar 289
                                        $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
635 daniel-mar 290
 
291
                                        $out['text'] .= '<p><a '.OIDplus::gui()->link('oidplus:resources$'.rtrim($dir,'/').'/').'><img src="img/arrow_back.png" width="16" alt="'._L('Go back').'"> '._L('Go back to').': '.$ic.' '.htmlentities(self::getFolderTitle($realdir)).'</a></p><br>';
292
                                }
293
                        }
294
 
295
                        // Then the content
296
 
297
                        $realfile = self::realname($file);
298
                        // $realfile2 = preg_replace('/\.([^.]+)$/', '$'.OIDplus::getCurrentLang().'.\1', $realfile);
299
                        // if (file_exists($realfile2)) $realfile = $realfile2;
300
 
301
                        if (file_exists($realfile) && (!is_dir($realfile))) {
302
                                if ((substr($file,-4,4) == '.url') || (substr($file,-5,5) == '.link')) {
303
                                        $out['title'] = $this->getHyperlinkTitle($realfile);
304
 
801 daniel-mar 305
                                        $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_url_icon&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 306
                                        /*
307
                                        $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_big.png';
308
                                        if (file_exists($icon_candidate)) {
309
                                                $out['icon'] = $icon_candidate;
800 daniel-mar 310
                                        } else if (file_exists(__DIR__.'/img/leaf_url_icon.png')) {
801 daniel-mar 311
                                                $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_url_icon.png';
635 daniel-mar 312
                                        } else {
313
                                                $out['icon'] = '';
314
                                        }
315
                                        */
316
 
317
                                        // Should not happen though, due to conditionalselect
318
                                        $out['text'] .= '<a href="'.htmlentities(self::getHyperlinkURL($realfile)).'" target="_blank">'._L('Open in new window').'</a>';
319
                                } else if ((substr($file,-4,4) == '.htm') || (substr($file,-5,5) == '.html')) {
320
                                        $out['title'] = $this->getDocumentTitle($file);
321
 
801 daniel-mar 322
                                        $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_doc_icon&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 323
                                        /*
324
                                        $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_big.png';
325
                                        if (file_exists($icon_candidate)) {
326
                                                $out['icon'] = $icon_candidate;
800 daniel-mar 327
                                        } else if (file_exists(__DIR__.'/img/leaf_doc_icon.png')) {
801 daniel-mar 328
                                                $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_doc_icon.png';
635 daniel-mar 329
                                        } else {
330
                                                $out['icon'] = '';
331
                                        }
332
                                        */
333
 
334
                                        $out['text'] .= self::getDocumentContent($file);
335
                                } else {
1206 daniel-mar 336
                                        throw new OIDplusException(_L('The system does not know how to handle this file type.'), _L('Unknown file type'));
635 daniel-mar 337
                                }
338
                        } else if (is_dir($realfile)) {
339
                                $out['title'] = ($file == '') ? $this->getMainTitle() : self::getFolderTitle($realfile);
340
 
341
                                if ($file == '') {
801 daniel-mar 342
                                        $out['icon'] = file_exists(__DIR__.'/img/main_icon.png') ? OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png' : '';
635 daniel-mar 343
                                } else {
801 daniel-mar 344
                                        $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 345
                                        /*
346
                                        $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_big.png';
347
                                        if (file_exists($icon_candidate)) {
348
                                                $out['icon'] = $icon_candidate;
800 daniel-mar 349
                                        } else if (file_exists(__DIR__.'/img/folder_icon.png')) {
801 daniel-mar 350
                                                $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon.png';
635 daniel-mar 351
                                        } else {
352
                                                $out['icon'] = null; // no icon
353
                                        }
354
                                        */
355
                                }
356
 
800 daniel-mar 357
                                if (file_exists(__DIR__.'/img/main_icon16.png')) {
801 daniel-mar 358
                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
635 daniel-mar 359
                                } else {
360
                                        $tree_icon = null; // default icon (folder)
361
                                }
362
 
363
                                $count = 0;
364
 
365
                                $dirs = self::myglob(rtrim($file,'/').'/'.'*', true);
366
                                natcasesort($dirs);
367
                                foreach ($dirs as $dir) {
368
                                        $realdir = self::realname($dir);
801 daniel-mar 369
                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($dir);
635 daniel-mar 370
                                        /*
371
                                        $icon_candidate = pathinfo($realdir)['dirname'].'/'.pathinfo($realdir)['filename'].'_tree.png';
372
                                        if (file_exists($icon_candidate)) {
373
                                                $tree_icon = $icon_candidate;
800 daniel-mar 374
                                        } else if (file_exists(__DIR__.'/img/folder_icon16.png')) {
801 daniel-mar 375
                                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon16.png';
635 daniel-mar 376
                                        } else {
377
                                                $tree_icon = null; // no icon
378
                                        }
379
                                        */
380
 
705 daniel-mar 381
                                        $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
635 daniel-mar 382
 
383
                                        $out['text'] .= '<p><a '.OIDplus::gui()->link('oidplus:resources$'.rtrim($dir,'/').'/').'>'.$ic.' '.htmlentities(self::getFolderTitle($realdir)).'</a></p>';
384
                                        $count++;
385
                                }
386
 
387
                                $files = array_merge(
388
                                        self::myglob(rtrim($file,'/').'/'.'*.htm'), // TODO: also PHP?
389
                                        self::myglob(rtrim($file,'/').'/'.'*.html'),
390
                                        self::myglob(rtrim($file,'/').'/'.'*.url'),
391
                                        self::myglob(rtrim($file,'/').'/'.'*.link')
392
                                );
393
                                natcasesort($files);
394
                                foreach ($files as $file) {
395
                                        $realfile = self::realname($file);
396
                                        if ((substr($file,-4,4) == '.url') || (substr($file,-5,5) == '.link')) {
801 daniel-mar 397
                                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_url_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 398
                                                /*
399
                                                $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
400
                                                if (file_exists($icon_candidate)) {
401
                                                        $tree_icon = $icon_candidate;
800 daniel-mar 402
                                                } else if (file_exists(__DIR__.'/img/leaf_url_icon16.png')) {
801 daniel-mar 403
                                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_url_icon16.png';
635 daniel-mar 404
                                                } else {
405
                                                        $tree_icon = null; // default icon (folder)
406
                                                }
407
                                                */
408
 
705 daniel-mar 409
                                                $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
635 daniel-mar 410
 
694 daniel-mar 411
                                                $out['text'] .= '<p><a href="'.htmlentities(self::getHyperlinkURL($realfile)).'" target="_blank">'.$ic.' '.htmlentities($this->getHyperlinkTitle($realfile)).'</a></p>';
635 daniel-mar 412
                                                $count++;
413
                                        } else {
801 daniel-mar 414
                                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_doc_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 415
                                                /*
416
                                                $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
417
                                                if (file_exists($icon_candidate)) {
418
                                                        $tree_icon = $icon_candidate;
800 daniel-mar 419
                                                } else if (file_exists(__DIR__.'/img/leaf_doc_icon16.png')) {
801 daniel-mar 420
                                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_doc_icon16.png';
635 daniel-mar 421
                                                } else {
422
                                                        $tree_icon = null; // default icon (folder)
423
                                                }
424
                                                */
425
 
705 daniel-mar 426
                                                $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
635 daniel-mar 427
 
428
                                                $out['text'] .= '<p><a '.OIDplus::gui()->link('oidplus:resources$'.$file).'>'.$ic.' '.htmlentities($this->getDocumentTitle($file)).'</a></p>';
429
                                                $count++;
430
                                        }
431
                                }
432
 
433
                                if ($count == 0) {
434
                                        $out['text'] .= '<p>'._L('This folder does not contain any elements').'</p>';
435
                                }
436
                        } else {
1206 daniel-mar 437
                                throw new OIDplusException(_L('This resource doesn\'t exist anymore.'), _L('Not found'));
635 daniel-mar 438
                        }
439
                }
440
        }
441
 
1116 daniel-mar 442
        /**
1130 daniel-mar 443
         * @param array $children
444
         * @param string|null $rootdir
1116 daniel-mar 445
         * @param int $depth
446
         * @return void
447
         * @throws OIDplusConfigInitializationException
448
         * @throws OIDplusException
449
         */
1130 daniel-mar 450
        private function tree_rec(array &$children, string $rootdir=null, int $depth=0)/*: void*/ {
635 daniel-mar 451
                if (is_null($rootdir)) $rootdir = '';
1116 daniel-mar 452
                if ($depth > 100) return; // something is wrong!
635 daniel-mar 453
 
454
                $dirs = self::myglob($rootdir.'*'.'/', true);
455
                natcasesort($dirs);
456
                foreach ($dirs as $dir) {
457
                        $tmp = array();
458
 
459
                        $this->tree_rec($tmp, $dir, $depth+1);
460
 
461
                        $realdir = self::realname($dir);
462
 
801 daniel-mar 463
                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($dir);
635 daniel-mar 464
                        /*
465
                        $icon_candidate = pathinfo($realdir)['dirname'].'/'.pathinfo($realdir)['filename'].'_tree.png';
466
                        if (file_exists($icon_candidate)) {
467
                                $tree_icon = $icon_candidate;
800 daniel-mar 468
                        } else if (file_exists(__DIR__.'/img/folder_icon16.png')) {
801 daniel-mar 469
                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon16.png';
635 daniel-mar 470
                        } else {
471
                                $tree_icon = null; // default icon (folder)
472
                        }
473
                        */
474
 
475
                        $children[] = array(
476
                                'id' => 'oidplus:resources$'.$dir,
477
                                'icon' => $tree_icon,
478
                                'text' => self::getFolderTitle($realdir),
479
                                'children' => $tmp,
480
                                'state' => array("opened" => $depth <= OIDplus::config()->getValue('resource_plugin_autoopen_level', 1)-1)
481
                        );
482
                }
483
 
484
                $files = array_merge(
485
                        self::myglob($rootdir.'*.htm'), // TODO: Also PHP?
486
                        self::myglob($rootdir.'*.html'),
487
                        self::myglob($rootdir.'*.url'),
488
                        self::myglob($rootdir.'*.link')
489
                );
490
                natcasesort($files);
491
                foreach ($files as $file) {
492
                        $realfile = self::realname($file);
493
                        if ((substr($file,-4,4) == '.url') || (substr($file,-5,5) == '.link')) {
801 daniel-mar 494
                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_url_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 495
                                /*
496
                                $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
497
                                if (file_exists($icon_candidate)) {
498
                                        $tree_icon = $icon_candidate;
800 daniel-mar 499
                                } else if (file_exists(__DIR__.'/img/leaf_url_icon16.png')) {
801 daniel-mar 500
                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_url_icon16.png';
635 daniel-mar 501
                                } else {
502
                                        $tree_icon = null; // default icon (folder)
503
                                }
504
                                */
505
 
506
                                $children[] = array(
507
                                        'id' => 'oidplus:resources$'.$file,
508
                                        'conditionalselect' => 'window.open('.js_escape(self::getHyperlinkURL($realfile)).'); false;',
509
                                        'icon' => $tree_icon,
694 daniel-mar 510
                                        'text' => $this->getHyperlinkTitle($realfile),
635 daniel-mar 511
                                        'state' => array("opened" => $depth <= OIDplus::config()->getValue('resource_plugin_autoopen_level', 1)-1),
512
                                        'a_attr' => array(
513
                                                'href' => self::getHyperlinkURL($realfile),
514
                                                'target' => '_blank'
515
                                        )
516
                                );
517
                        } else {
801 daniel-mar 518
                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_doc_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
635 daniel-mar 519
                                /*
520
                                $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
521
                                if (file_exists($icon_candidate)) {
522
                                        $tree_icon = $icon_candidate;
800 daniel-mar 523
                                } else if (file_exists(__DIR__.'/img/leaf_doc_icon16.png')) {
801 daniel-mar 524
                                        $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_doc_icon16.png';
635 daniel-mar 525
                                } else {
526
                                        $tree_icon = null; // default icon (folder)
527
                                }
528
                                */
529
                                $children[] = array(
530
                                        'id' => 'oidplus:resources$'.$file,
531
                                        'icon' => $tree_icon,
532
                                        'text' => $this->getDocumentTitle($file),
533
                                        'state' => array("opened" => $depth <= OIDplus::config()->getValue('resource_plugin_autoopen_level', 1)-1)
534
                                );
535
                        }
536
                }
537
        }
538
 
1116 daniel-mar 539
        /**
1130 daniel-mar 540
         * @param array $json
541
         * @param array $out
1116 daniel-mar 542
         * @return void
543
         */
1130 daniel-mar 544
        private function publicSitemap_rec(array $json, array &$out) {
635 daniel-mar 545
                foreach ($json as $x) {
546
                        if (isset($x['id']) && $x['id']) {
547
                                $out[] = $x['id'];
548
                        }
549
                        if (isset($x['children'])) {
550
                                $this->publicSitemap_rec($x['children'], $out);
551
                        }
552
                }
553
        }
554
 
1116 daniel-mar 555
        /**
556
         * @param array $out
557
         * @return void
558
         */
559
        public function publicSitemap(array &$out) {
635 daniel-mar 560
                $json = array();
1116 daniel-mar 561
                $this->tree($json, null/*RA EMail*/, false/*HTML tree algorithm*/, "*"/*display all*/);
635 daniel-mar 562
                $this->publicSitemap_rec($json, $out);
563
        }
564
 
1116 daniel-mar 565
        /**
566
         * @param array $json
567
         * @param string|null $ra_email
568
         * @param bool $nonjs
569
         * @param string $req_goto
570
         * @return bool
571
         * @throws OIDplusConfigInitializationException
572
         * @throws OIDplusException
573
         */
574
        public function tree(array &$json, string $ra_email=null, bool $nonjs=false, string $req_goto=''): bool {
635 daniel-mar 575
                $children = array();
576
 
577
                $this->tree_rec($children, '/');
578
 
579
                if (!OIDplus::config()->getValue('resource_plugin_hide_empty_path', true) || (count($children) > 0)) {
800 daniel-mar 580
                        if (file_exists(__DIR__.'/img/main_icon16.png')) {
801 daniel-mar 581
                                $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
635 daniel-mar 582
                        } else {
583
                                $tree_icon = null; // default icon (folder)
584
                        }
585
 
586
                        $json[] = array(
587
                                'id' => 'oidplus:resources',
588
                                'icon' => $tree_icon,
589
                                'state' => array("opened" => true),
590
                                'text' => $this->getMainTitle(),
591
                                'children' => $children
592
                        );
593
                }
594
 
595
                return true;
596
        }
597
 
1116 daniel-mar 598
        /**
599
         * @param string $request
600
         * @return array|false
601
         */
602
        public function tree_search(string $request) {
635 daniel-mar 603
                return false;
604
        }
605
 
1116 daniel-mar 606
        /**
1130 daniel-mar 607
         * @param string $file
1116 daniel-mar 608
         * @return array|mixed|string|string[]|null
609
         * @throws OIDplusConfigInitializationException
610
         * @throws OIDplusException
611
         */
1130 daniel-mar 612
        private static function getHyperlinkTitle(string $file) {
635 daniel-mar 613
                $file2 = preg_replace('/\.([^.]+)$/', '$'.OIDplus::getCurrentLang().'.\1', $file);
614
                if (file_exists($file2)) $file = $file2;
615
 
616
                if (substr($file,-4,4) == '.url') {
617
                        return preg_replace('/\\.[^.\\s]{3,4}$/', '', basename($file));
618
                } else if (substr($file,-5,5) == '.link') {
619
                        /*
620
                        [Link]
621
                        Title=Report a bug
1083 daniel-mar 622
                        URL=https://github.com/danielmarschall/oidplus/issues
635 daniel-mar 623
                        */
624
 
625
                        $data = @parse_ini_file($file, true);
626
                        if (!$data) {
627
                                throw new OIDplusException(_L('File %1 has an invalid INI format!',$file));
628
                        }
629
                        if (!isset($data['Link'])) {
630
                                throw new OIDplusException(_L('Could not find "%1" section at %2','Link',$file));
631
                        }
632
                        if (!isset($data['Link']['Title'])) {
633
                                throw new OIDplusException(_L('"%1" is missing in %2','Title',$file));
634
                        }
635
                        return $data['Link']['Title'];
636
                } else {
637
                        throw new OIDplusException(_L('Unexpected file extension for file %1',$file));
638
                }
639
        }
640
 
1116 daniel-mar 641
        /**
1130 daniel-mar 642
         * @param string $file
1116 daniel-mar 643
         * @return mixed
644
         * @throws OIDplusConfigInitializationException
645
         * @throws OIDplusException
646
         */
1130 daniel-mar 647
        private static function getHyperlinkURL(string $file) {
635 daniel-mar 648
                $file2 = preg_replace('/\.([^.]+)$/', '$'.OIDplus::getCurrentLang().'.\1', $file);
649
                if (file_exists($file2)) $file = $file2;
650
 
651
                if (substr($file,-4,4) == '.url') {
652
                        /*
653
                        [InternetShortcut]
654
                        URL=http://www.example.com/
655
                        */
656
 
657
                        $data = @parse_ini_file($file, true);
658
                        if (!$data) {
659
                                throw new OIDplusException(_L('File %1 has an invalid INI format!',$file));
660
                        }
661
                        if (!isset($data['InternetShortcut'])) {
662
                                throw new OIDplusException(_L('Could not find "%1" section at %2','InternetShortcut',$file));
663
                        }
664
                        if (!isset($data['InternetShortcut']['URL'])) {
665
                                throw new OIDplusException(_L('"%1" is missing in %2','URL',$file));
666
                        }
667
                        return $data['InternetShortcut']['URL'];
668
                } else if (substr($file,-5,5) == '.link') {
669
                        /*
670
                        [Link]
671
                        Title=Report a bug
1083 daniel-mar 672
                        URL=https://github.com/danielmarschall/oidplus/issues
635 daniel-mar 673
                        */
674
 
675
                        $data = @parse_ini_file($file, true);
676
                        if (!$data) {
677
                                throw new OIDplusException(_L('File %1 has an invalid INI format!',$file));
678
                        }
679
                        if (!isset($data['Link'])) {
680
                                throw new OIDplusException(_L('Could not find "%1" section at %2','Link',$file));
681
                        }
682
                        if (!isset($data['Link']['URL'])) {
683
                                throw new OIDplusException(_L('"%1" is missing in %2','URL',$file));
684
                        }
685
                        return $data['Link']['URL'];
686
                } else {
687
                        throw new OIDplusException(_L('Unexpected file extension for file %1',$file));
688
                }
689
 
690
        }
691
 
1116 daniel-mar 692
        /**
1130 daniel-mar 693
         * @param string $dir
1116 daniel-mar 694
         * @return mixed|string
695
         * @throws OIDplusConfigInitializationException
696
         * @throws OIDplusException
697
         */
1130 daniel-mar 698
        private static function getFolderTitle(string $dir) {
635 daniel-mar 699
                $data = @parse_ini_file("$dir/folder\$".OIDplus::getCurrentLang().".ini", true);
1162 daniel-mar 700
                if ($data && isset($data['Folder']['Title'])) {
635 daniel-mar 701
                        return $data['Folder']['Title'];
702
                }
703
 
704
                $data = @parse_ini_file("$dir/folder.ini", true);
1162 daniel-mar 705
                if ($data && isset($data['Folder']['Title'])) {
635 daniel-mar 706
                        return $data['Folder']['Title'];
707
                }
708
 
709
                return basename($dir);
710
        }
711
}