Subversion Repositories oidplus

Rev

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

  1. <?php
  2.  
  3. /*
  4.  * OIDplus 2.0
  5.  * Copyright 2019 - 2023 Daniel Marschall, ViaThinkSoft
  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.  
  20. namespace ViaThinkSoft\OIDplus;
  21.  
  22. // phpcs:disable PSR1.Files.SideEffects
  23. \defined('INSIDE_OIDPLUS') or die;
  24. // phpcs:enable PSR1.Files.SideEffects
  25.  
  26. class OIDplusPagePublicResources extends OIDplusPagePluginPublic {
  27.  
  28.         /**
  29.          * @return array|mixed|string|string[]
  30.          */
  31.         private function getMainTitle() {
  32.                 return _L('Documents and Resources');
  33.         }
  34.  
  35.         /**
  36.          * @param bool $html
  37.          * @return void
  38.          * @throws OIDplusException
  39.          */
  40.         public function init(bool $html=true) {
  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.  
  55.         /**
  56.          * @param string $file
  57.          * @return string
  58.          * @throws OIDplusConfigInitializationException|OIDplusException
  59.          */
  60.         private static function getDocumentContent(string $file): string {
  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.                 if (!$cont) return '';
  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>";
  72.                 $cont .= stripHtmlComments($html);
  73.  
  74.                 return $cont;
  75.         }
  76.  
  77.         /**
  78.          * @param string $file
  79.          * @return array|mixed|string
  80.          * @throws OIDplusConfigInitializationException
  81.          * @throws OIDplusException
  82.          */
  83.         private static function getDocumentTitle(string $file) {
  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
  91.                 $cont = convert_to_utf8_no_bom($cont);
  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.  
  104.         /**
  105.          * @param string $source
  106.          * @return bool
  107.          * @throws OIDplusException
  108.          */
  109.         protected static function mayAccessResource(string $source): bool {
  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);
  119.                                 if (isset($data['Security'][$source])) {
  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.  
  138.         /**
  139.          * @param string $reldir
  140.          * @param bool $onlydir
  141.          * @return array
  142.          * @throws OIDplusException
  143.          */
  144.         private static function myglob(string $reldir, bool $onlydir=false): array {
  145.                 $out = array();
  146.  
  147.                 $root = OIDplus::localpath().'userdata/resources/';
  148.                 $res = $onlydir ? @glob($root.ltrim($reldir,'/'), GLOB_ONLYDIR) : @glob($root.ltrim($reldir,'/'));
  149.                 if ($res) foreach ($res as &$x) {
  150.                         $x = substr($x, strlen($root));
  151.                         if (strpos($x,'$') !== false) continue;
  152.                         $out[] = $x;
  153.                 }
  154.  
  155.                 $root = OIDplus::localpath().'res/';
  156.                 $res = $onlydir ? @glob($root.ltrim($reldir,'/'), GLOB_ONLYDIR) : @glob($root.ltrim($reldir,'/'));
  157.                 if ($res) foreach ($res as $x) {
  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.  
  170.         /**
  171.          * @param string $rel
  172.          * @return string|null
  173.          */
  174.         private static function realname(string $rel) {
  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.  
  182.         /**
  183.          * @param string $source
  184.          * @param string $target
  185.          * @return bool
  186.          */
  187.         protected static function checkRedirect(string $source, string &$target): bool {
  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);
  195.                                 if (isset($data['Redirects'][$source])) {
  196.                                         $target = $data['Redirects'][$source];
  197.                                         return true;
  198.                                 }
  199.                         }
  200.                 }
  201.                 return false;
  202.         }
  203.  
  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) {
  213.                 if (explode('$',$id,2)[0] === 'oidplus:resources') {
  214.                         $handled = true;
  215.  
  216.                         $tmp = explode('$',$id);
  217.                         $file = $tmp[1] ?? '';
  218.                         unset($tmp);
  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
  233.                                 //OIDplus::logger()->log("V2:[WARN]A", "LFI/RFI attack blocked (requested file '%1')", $file);
  234.                                 throw new OIDplusException(_L('This request is invalid'), _L('Access denied'));
  235.                         }
  236.  
  237.                         $out['text'] = '';
  238.  
  239.                         // Check for permission
  240.  
  241.                         if ($file != '') {
  242.                                 if (!self::mayAccessResource($file)) {
  243.                                         throw new OIDplusException(_L('Authentication error. Please log in.'), _L('Access denied'), 401);
  244.                                 }
  245.                         }
  246.  
  247.                         // Redirections
  248.  
  249.                         if ($file != '') {
  250.                                 $target = '';
  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 == '.') {
  264.                                         if (file_exists(__DIR__.'/img/main_icon16.png')) {
  265.                                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
  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.  
  277.                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($dir);
  278.                                         /*
  279.                                         $icon_candidate = pathinfo($realdir)['dirname'].'/'.pathinfo($realdir)['filename'].'_tree.png';
  280.                                         if (file_exists($icon_candidate)) {
  281.                                                 $tree_icon = $icon_candidate;
  282.                                         } else if (file_exists(__DIR__.'/img/folder_icon16.png')) {
  283.                                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon16.png';
  284.                                         } else {
  285.                                                 $tree_icon = null; // no icon
  286.                                         }
  287.                                         */
  288.  
  289.                                         $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
  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.  
  305.                                         $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_url_icon&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  306.                                         /*
  307.                                         $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_big.png';
  308.                                         if (file_exists($icon_candidate)) {
  309.                                                 $out['icon'] = $icon_candidate;
  310.                                         } else if (file_exists(__DIR__.'/img/leaf_url_icon.png')) {
  311.                                                 $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_url_icon.png';
  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.  
  322.                                         $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_doc_icon&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  323.                                         /*
  324.                                         $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_big.png';
  325.                                         if (file_exists($icon_candidate)) {
  326.                                                 $out['icon'] = $icon_candidate;
  327.                                         } else if (file_exists(__DIR__.'/img/leaf_doc_icon.png')) {
  328.                                                 $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_doc_icon.png';
  329.                                         } else {
  330.                                                 $out['icon'] = '';
  331.                                         }
  332.                                         */
  333.  
  334.                                         $out['text'] .= self::getDocumentContent($file);
  335.                                 } else {
  336.                                         throw new OIDplusException(_L('The system does not know how to handle this file type.'), _L('Unknown file type'));
  337.                                 }
  338.                         } else if (is_dir($realfile)) {
  339.                                 $out['title'] = ($file == '') ? $this->getMainTitle() : self::getFolderTitle($realfile);
  340.  
  341.                                 if ($file == '') {
  342.                                         $out['icon'] = file_exists(__DIR__.'/img/main_icon.png') ? OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon.png' : '';
  343.                                 } else {
  344.                                         $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  345.                                         /*
  346.                                         $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_big.png';
  347.                                         if (file_exists($icon_candidate)) {
  348.                                                 $out['icon'] = $icon_candidate;
  349.                                         } else if (file_exists(__DIR__.'/img/folder_icon.png')) {
  350.                                                 $out['icon'] = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon.png';
  351.                                         } else {
  352.                                                 $out['icon'] = null; // no icon
  353.                                         }
  354.                                         */
  355.                                 }
  356.  
  357.                                 if (file_exists(__DIR__.'/img/main_icon16.png')) {
  358.                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
  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);
  369.                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($dir);
  370.                                         /*
  371.                                         $icon_candidate = pathinfo($realdir)['dirname'].'/'.pathinfo($realdir)['filename'].'_tree.png';
  372.                                         if (file_exists($icon_candidate)) {
  373.                                                 $tree_icon = $icon_candidate;
  374.                                         } else if (file_exists(__DIR__.'/img/folder_icon16.png')) {
  375.                                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon16.png';
  376.                                         } else {
  377.                                                 $tree_icon = null; // no icon
  378.                                         }
  379.                                         */
  380.  
  381.                                         $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
  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')) {
  397.                                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_url_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  398.                                                 /*
  399.                                                 $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
  400.                                                 if (file_exists($icon_candidate)) {
  401.                                                         $tree_icon = $icon_candidate;
  402.                                                 } else if (file_exists(__DIR__.'/img/leaf_url_icon16.png')) {
  403.                                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_url_icon16.png';
  404.                                                 } else {
  405.                                                         $tree_icon = null; // default icon (folder)
  406.                                                 }
  407.                                                 */
  408.  
  409.                                                 $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
  410.  
  411.                                                 $out['text'] .= '<p><a href="'.htmlentities(self::getHyperlinkURL($realfile)).'" target="_blank">'.$ic.' '.htmlentities($this->getHyperlinkTitle($realfile)).'</a></p>';
  412.                                                 $count++;
  413.                                         } else {
  414.                                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_doc_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  415.                                                 /*
  416.                                                 $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
  417.                                                 if (file_exists($icon_candidate)) {
  418.                                                         $tree_icon = $icon_candidate;
  419.                                                 } else if (file_exists(__DIR__.'/img/leaf_doc_icon16.png')) {
  420.                                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_doc_icon16.png';
  421.                                                 } else {
  422.                                                         $tree_icon = null; // default icon (folder)
  423.                                                 }
  424.                                                 */
  425.  
  426.                                                 $ic = /*empty($tree_icon) ? '' : */'<img src="'.$tree_icon.'" alt="">';
  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 {
  437.                                 throw new OIDplusException(_L('This resource doesn\'t exist anymore.'), _L('Not found'));
  438.                         }
  439.                 }
  440.         }
  441.  
  442.         /**
  443.          * @param array $children
  444.          * @param string|null $rootdir
  445.          * @param int $depth
  446.          * @return void
  447.          * @throws OIDplusConfigInitializationException
  448.          * @throws OIDplusException
  449.          */
  450.         private function tree_rec(array &$children, string $rootdir=null, int $depth=0)/*: void*/ {
  451.                 if (is_null($rootdir)) $rootdir = '';
  452.                 if ($depth > 100) return; // something is wrong!
  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.  
  463.                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=folder_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($dir);
  464.                         /*
  465.                         $icon_candidate = pathinfo($realdir)['dirname'].'/'.pathinfo($realdir)['filename'].'_tree.png';
  466.                         if (file_exists($icon_candidate)) {
  467.                                 $tree_icon = $icon_candidate;
  468.                         } else if (file_exists(__DIR__.'/img/folder_icon16.png')) {
  469.                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/folder_icon16.png';
  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')) {
  494.                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_url_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  495.                                 /*
  496.                                 $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
  497.                                 if (file_exists($icon_candidate)) {
  498.                                         $tree_icon = $icon_candidate;
  499.                                 } else if (file_exists(__DIR__.'/img/leaf_url_icon16.png')) {
  500.                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_url_icon16.png';
  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,
  510.                                         'text' => $this->getHyperlinkTitle($realfile),
  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 {
  518.                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'show_icon.php?mode=leaf_doc_icon16&lang='.OIDplus::getCurrentLang().'&file='.urlencode($file);
  519.                                 /*
  520.                                 $icon_candidate = pathinfo($realfile)['dirname'].'/'.pathinfo($realfile)['filename'].'_tree.png';
  521.                                 if (file_exists($icon_candidate)) {
  522.                                         $tree_icon = $icon_candidate;
  523.                                 } else if (file_exists(__DIR__.'/img/leaf_doc_icon16.png')) {
  524.                                         $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/leaf_doc_icon16.png';
  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.  
  539.         /**
  540.          * @param array $json
  541.          * @param array $out
  542.          * @return void
  543.          */
  544.         private function publicSitemap_rec(array $json, array &$out) {
  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.  
  555.         /**
  556.          * @param array $out
  557.          * @return void
  558.          */
  559.         public function publicSitemap(array &$out) {
  560.                 $json = array();
  561.                 $this->tree($json, null/*RA EMail*/, false/*HTML tree algorithm*/, "*"/*display all*/);
  562.                 $this->publicSitemap_rec($json, $out);
  563.         }
  564.  
  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 {
  575.                 $children = array();
  576.  
  577.                 $this->tree_rec($children, '/');
  578.  
  579.                 if (!OIDplus::config()->getValue('resource_plugin_hide_empty_path', true) || (count($children) > 0)) {
  580.                         if (file_exists(__DIR__.'/img/main_icon16.png')) {
  581.                                 $tree_icon = OIDplus::webpath(__DIR__,OIDplus::PATH_RELATIVE).'img/main_icon16.png';
  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.  
  598.         /**
  599.          * @param string $request
  600.          * @return array|false
  601.          */
  602.         public function tree_search(string $request) {
  603.                 return false;
  604.         }
  605.  
  606.         /**
  607.          * @param string $file
  608.          * @return array|mixed|string|string[]|null
  609.          * @throws OIDplusConfigInitializationException
  610.          * @throws OIDplusException
  611.          */
  612.         private static function getHyperlinkTitle(string $file) {
  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
  622.                         URL=https://github.com/danielmarschall/oidplus/issues
  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.  
  641.         /**
  642.          * @param string $file
  643.          * @return mixed
  644.          * @throws OIDplusConfigInitializationException
  645.          * @throws OIDplusException
  646.          */
  647.         private static function getHyperlinkURL(string $file) {
  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
  672.                         URL=https://github.com/danielmarschall/oidplus/issues
  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.  
  692.         /**
  693.          * @param string $dir
  694.          * @return mixed|string
  695.          * @throws OIDplusConfigInitializationException
  696.          * @throws OIDplusException
  697.          */
  698.         private static function getFolderTitle(string $dir) {
  699.                 $data = @parse_ini_file("$dir/folder\$".OIDplus::getCurrentLang().".ini", true);
  700.                 if ($data && isset($data['Folder']['Title'])) {
  701.                         return $data['Folder']['Title'];
  702.                 }
  703.  
  704.                 $data = @parse_ini_file("$dir/folder.ini", true);
  705.                 if ($data && isset($data['Folder']['Title'])) {
  706.                         return $data['Folder']['Title'];
  707.                 }
  708.  
  709.                 return basename($dir);
  710.         }
  711. }
  712.