Subversion Repositories oidplus

Rev

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