From 1c9be8254bd13c85be728699ceb68c34d7fd5d89 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Mon, 26 Feb 2024 11:58:11 +0100 Subject: [PATCH 1/9] initial automatic cleanup --- .gitattributes | 2 + .github/workflows/dokuwiki.yml | 11 + .travis.yml | 13 - LICENSE | 339 +++++++++++++++++++++++++ _test/GeneralTest.php | 86 +++++++ conf/default.php | 1 + conf/metadata.php | 2 +- syntax.php | 437 ++++++++++++++++----------------- 8 files changed, 653 insertions(+), 238 deletions(-) create mode 100644 .gitattributes create mode 100644 .github/workflows/dokuwiki.yml delete mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 _test/GeneralTest.php diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..050b5e0 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,2 @@ +/.* export-ignore +/_test export-ignore diff --git a/.github/workflows/dokuwiki.yml b/.github/workflows/dokuwiki.yml new file mode 100644 index 0000000..8268881 --- /dev/null +++ b/.github/workflows/dokuwiki.yml @@ -0,0 +1,11 @@ +name: DokuWiki Default Tasks +on: + push: + pull_request: + schedule: + - cron: '58 2 25 * *' + + +jobs: + all: + uses: dokuwiki/github-action/.github/workflows/all.yml@main diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 0e27461..0000000 --- a/.travis.yml +++ /dev/null @@ -1,13 +0,0 @@ -language: php -php: - - "7.0" - - "5.6" -# - "5.5" -# - "5.4" -# - "5.3" -env: - - DOKUWIKI=master - - DOKUWIKI=stable -before_install: wget https://raw.github.com/splitbrain/dokuwiki-travis/master/travis.sh -install: sh travis.sh -script: cd _test && phpunit --stderr --group plugin_filelist diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + , 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/_test/GeneralTest.php b/_test/GeneralTest.php new file mode 100644 index 0000000..e22e2dc --- /dev/null +++ b/_test/GeneralTest.php @@ -0,0 +1,86 @@ +assertFileExists($file); + + $info = confToHash($file); + + $this->assertArrayHasKey('base', $info); + $this->assertArrayHasKey('author', $info); + $this->assertArrayHasKey('email', $info); + $this->assertArrayHasKey('date', $info); + $this->assertArrayHasKey('name', $info); + $this->assertArrayHasKey('desc', $info); + $this->assertArrayHasKey('url', $info); + + $this->assertEquals('filelist', $info['base']); + $this->assertRegExp('/^https?:\/\//', $info['url']); + $this->assertTrue(mail_isvalid($info['email'])); + $this->assertRegExp('/^\d\d\d\d-\d\d-\d\d$/', $info['date']); + $this->assertTrue(false !== strtotime($info['date'])); + } + + /** + * Test to ensure that every conf['...'] entry in conf/default.php has a corresponding meta['...'] entry in + * conf/metadata.php. + */ + public function testPluginConf(): void + { + $conf_file = __DIR__ . '/../conf/default.php'; + $meta_file = __DIR__ . '/../conf/metadata.php'; + + if (!file_exists($conf_file) && !file_exists($meta_file)) { + self::markTestSkipped('No config files exist -> skipping test'); + } + + if (file_exists($conf_file)) { + include($conf_file); + } + if (file_exists($meta_file)) { + include($meta_file); + } + + $this->assertEquals( + gettype($conf), + gettype($meta), + 'Both ' . DOKU_PLUGIN . 'filelist/conf/default.php and ' . DOKU_PLUGIN . 'filelist/conf/metadata.php have to exist and contain the same keys.' + ); + + if ($conf !== null && $meta !== null) { + foreach ($conf as $key => $value) { + $this->assertArrayHasKey( + $key, + $meta, + 'Key $meta[\'' . $key . '\'] missing in ' . DOKU_PLUGIN . 'filelist/conf/metadata.php' + ); + } + + foreach ($meta as $key => $value) { + $this->assertArrayHasKey( + $key, + $conf, + 'Key $conf[\'' . $key . '\'] missing in ' . DOKU_PLUGIN . 'filelist/conf/default.php' + ); + } + } + + } +} diff --git a/conf/default.php b/conf/default.php index 09fdf9e..c5a2daa 100644 --- a/conf/default.php +++ b/conf/default.php @@ -1,4 +1,5 @@ _path_is_absolute($mediadir)) { $mediadir = DOKU_INC . '/' . $mediadir; } - $this->mediadir = $this->_win_path_convert($this->_realpath($mediadir).'/'); + $this->mediadir = $this->_win_path_convert($this->_realpath($mediadir) . '/'); } - function getType(){ return 'substition'; } - function getPType(){ return 'block'; } - function getSort(){ return 222; } + public function getType() + { + return 'substition'; + } - function connectTo($mode) { - $this->Lexer->addSpecialPattern('\{\{filename>.+?\}\}',$mode,'plugin_filelist'); - $this->Lexer->addSpecialPattern('\{\{filelist>.+?\}\}',$mode,'plugin_filelist'); + public function getPType() + { + return 'block'; + } + + public function getSort() + { + return 222; + } + + public function connectTo($mode) + { + $this->Lexer->addSpecialPattern('\{\{filename>.+?\}\}', $mode, 'plugin_filelist'); + $this->Lexer->addSpecialPattern('\{\{filelist>.+?\}\}', $mode, 'plugin_filelist'); } /** * Handle the match */ - function handle($match, $state, $pos, Doku_Handler $handler) { + public function handle($match, $state, $pos, Doku_Handler $handler) + { // do not allow the syntax in comments if (!$this->getConf('allow_in_comments') && isset($_REQUEST['comment'])) - return false; + return false; $match = substr($match, 2, -2); - list($type, $match) = explode('>', $match, 2); - list($pattern, $flags) = explode('&', $match, 2); + [$type, $match] = explode('>', $match, 2); + [$pattern, $flags] = explode('&', $match, 2); if ($type == 'filename') { - if (strpos($flags, '|') !== FALSE) { - list($flags, $title) = explode('\|', $flags); + if (strpos($flags, '|') !== false) { + [$flags, $title] = explode('\|', $flags); } else { $title = ''; } } // load default config options - $flags = $this->getConf('defaults').'&'.$flags; + $flags = $this->getConf('defaults') . '&' . $flags; $flags = explode('&', $flags); - $params = array( - 'sort' => 'name', - 'order' => 'asc', - 'index' => 0, - 'limit' => 0, - 'offset' => 0, - 'style' => 'list', - 'tableheader' => 0, - 'tableshowsize' => 0, - 'tableshowdate' => 0, - 'direct' => 0, - 'recursive' => 0, - 'titlefile' => '_title.txt', - 'cache' => 0, - 'randlinks' => 0, - 'preview' => 0, - 'previewsize' => 32, - 'link' => 2, - 'showsize' => 0, - 'showdate' => 0, - 'showcreator' => 0, - 'listsep' => '", "', - 'onhover' => 0, - 'ftp' => 0, - ); - foreach($flags as $flag) { - list($name, $value) = explode('=', $flag); + + $params = ['sort' => 'name', 'order' => 'asc', 'index' => 0, 'limit' => 0, 'offset' => 0, 'style' => 'list', 'tableheader' => 0, 'tableshowsize' => 0, 'tableshowdate' => 0, 'direct' => 0, 'recursive' => 0, 'titlefile' => '_title.txt', 'cache' => 0, 'randlinks' => 0, 'preview' => 0, 'previewsize' => 32, 'link' => 2, 'showsize' => 0, 'showdate' => 0, 'showcreator' => 0, 'listsep' => '", "', 'onhover' => 0, 'ftp' => 0]; + foreach ($flags as $flag) { + [$name, $value] = explode('=', $flag); $params[trim($name)] = trim($value); } @@ -99,27 +93,27 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { // Trim list separator $params['listsep'] = trim($params['listsep'], '"'); - return array($type, $pattern, $params, $title, $pos); + return [$type, $pattern, $params, $title, $pos]; } /** * Create output */ - function render($mode, Doku_Renderer $renderer, $data) { + public function render($mode, Doku_Renderer $renderer, $data) + { global $conf; - list($type, $pattern, $params, $title, $pos) = $data; + [$type, $pattern, $params, $title, $pos] = $data; if ($mode == 'odt') { $this->is_odt_export = true; } - + // disable caching if ($params['cache'] === 0) { $renderer->nocache(); } if ($mode == 'xhtml' || $mode == 'odt') { - $result = $this->_create_filelist($pattern, $params); if ($type == 'filename') { $result = $this->_filter_out_directories($result); @@ -129,7 +123,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { if ($result == DOKU_PLUGIN_FILELIST_NOMATCH) { $renderer->cdata('[n/a: ' . $this->getLang('error_nomatch') . ']'); return true; - } else if ($result == DOKU_PLUGIN_FILELIST_OUTSIDEJAIL) { + } elseif ($result == DOKU_PLUGIN_FILELIST_OUTSIDEJAIL) { $renderer->cdata('[n/a: ' . $this->getLang('error_outsidejail') . ']'); return true; } @@ -140,9 +134,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { } switch ($type) { - case 'filename': - $filename = $result['files'][$params['index']]['name']; $filepath = $result['files'][$params['index']]['path']; @@ -157,21 +149,21 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { case 'list': case 'olist': if (!$this->is_odt_export) { - $renderer->doc .= '
'.DOKU_LF; + $renderer->doc .= '
' . DOKU_LF; } $this->_render_list($result, $params, $renderer); if (!$this->is_odt_export) { - $renderer->doc .= '
'.DOKU_LF; + $renderer->doc .= '
' . DOKU_LF; } break; case 'table': if (!$this->is_odt_export) { - $renderer->doc .= '
'.DOKU_LF; + $renderer->doc .= '
' . DOKU_LF; } $this->_render_table($result, $params, $pos, $renderer); if (!$this->is_odt_export) { - $renderer->doc .= '
'.DOKU_LF; + $renderer->doc .= '
' . DOKU_LF; } break; @@ -180,7 +172,6 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { break; } return true; - } } return false; @@ -200,39 +191,40 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $renderer the renderer to use * @return void */ - function _render_link($filename, $filepath, $basedir, $webdir, $params, Doku_Renderer $renderer) { + public function _render_link($filename, $filepath, $basedir, $webdir, $params, Doku_Renderer $renderer) + { global $conf; //prepare for formating $link['target'] = $conf['target']['extern']; - $link['style'] = ''; - $link['pre'] = ''; - $link['suf'] = ''; - $link['more'] = ''; - $link['url'] = $this->_get_link_url ($filepath, $basedir, $webdir, $params['randlinks'], $params['direct'], $params['ftp']); + $link['style'] = ''; + $link['pre'] = ''; + $link['suf'] = ''; + $link['more'] = ''; + $link['url'] = $this->_get_link_url($filepath, $basedir, $webdir, $params['randlinks'], $params['direct'], $params['ftp']); - $link['name'] = $filename; - $link['title'] = $renderer->_xmlEntities($link['url']); - if($conf['relnofollow']) $link['more'] .= ' rel="nofollow"'; + $link['name'] = $filename; + $link['title'] = $renderer->_xmlEntities($link['url']); + if ($conf['relnofollow']) $link['more'] .= ' rel="nofollow"'; if ($params['link']) { switch ($params['link']) { case 1: // Link without background image - $link['class'] = 'media'; + $link['class'] = 'media'; break; default: // Link with background image - list($ext,$mime) = mimetype(basename($filepath)); - $link['class'] .= ' mediafile mf_'.$ext; + [$ext, $mime] = mimetype(basename($filepath)); + $link['class'] .= ' mediafile mf_' . $ext; break; } //output formatted - if ( !$this->is_odt_export ) { + if (!$this->is_odt_export) { $renderer->doc .= $renderer->_formatLink($link); } else { - $this->render_odt_link ($link, $renderer); + $this->render_odt_link($link, $renderer); } } else { // No link, just plain text. @@ -247,18 +239,19 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $renderer the renderer to use * @return void */ - protected function render_odt_link ($link, Doku_Renderer $renderer) { - if ( method_exists ($renderer, 'getODTProperties') === true ) { - $properties = array (); + protected function render_odt_link($link, Doku_Renderer $renderer) + { + if (method_exists($renderer, 'getODTProperties')) { + $properties = []; // Get CSS properties for ODT export. - $renderer->getODTProperties ($properties, 'a', $link['class'], NULL, 'screen'); + $renderer->getODTProperties($properties, 'a', $link['class'], null, 'screen'); // Insert image if present for that media class. - if ( empty($properties ['background-image']) === false ) { + if (empty($properties ['background-image']) === false) { $properties ['background-image'] = - $renderer->replaceURLPrefix ($properties ['background-image'], DOKU_INC); - $renderer->_odtAddImage ($properties ['background-image']); + $renderer->replaceURLPrefix($properties ['background-image'], DOKU_INC); + $renderer->_odtAddImage($properties ['background-image']); } } @@ -274,7 +267,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $renderer the renderer to use * @return void */ - function _render_list($result, $params, Doku_Renderer $renderer) { + public function _render_list($result, $params, Doku_Renderer $renderer) + { $this->_render_list_items($result['files'], $result['basedir'], $result['webdir'], $params, $renderer); } @@ -289,7 +283,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $level the level to render * @return void */ - function _render_list_items($files, $basedir, $webdir, $params, Doku_Renderer $renderer, $level = 1) { + public function _render_list_items($files, $basedir, $webdir, $params, Doku_Renderer $renderer, $level = 1) + { global $conf; if ($params['style'] == 'olist') { @@ -306,47 +301,40 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $renderer->p_open(); } $renderer->cdata($file['name']); - $this->_render_list_items($file['children'], $basedir, $webdir, $params, $renderer, $level+1); + $this->_render_list_items($file['children'], $basedir, $webdir, $params, $renderer, $level + 1); if ($this->is_odt_export) { $renderer->p_close(); } $renderer->listitem_close(); - } else if ($file['children'] === false) { + } elseif ($file['children'] === false) { // open list item $renderer->listitem_open($level); if ($this->is_odt_export) { $renderer->p_open(); } - // render the preview image if ($params['preview']) { $this->_render_preview_image($file['path'], $basedir, $webdir, $params, $renderer); } - // render the file link $this->_render_link($file['name'], $file['path'], $basedir, $webdir, $params, $renderer); - // render filesize if ($params['showsize']) { - $renderer->cdata($params['listsep'].$this->_size_readable($file['size'], 'PiB', 'bi', '%01.1f %s')); + $renderer->cdata($params['listsep'] . $this->_size_readable($file['size'], 'PiB', 'bi', '%01.1f %s')); } - // render lastmodified if ($params['showdate']) { - $renderer->cdata($params['listsep'].strftime($conf['dformat'], $file['mtime'])); + $renderer->cdata($params['listsep'] . strftime($conf['dformat'], $file['mtime'])); } - // render lastmodified if ($params['showcreator']) { - $renderer->cdata($params['listsep'].$file['creator']); + $renderer->cdata($params['listsep'] . $file['creator']); } - // close list item if ($this->is_odt_export) { $renderer->p_close(); } $renderer->listitem_close(); - } else { // ignore empty directories continue; @@ -368,11 +356,12 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $renderer the renderer to use * @return void */ - function _render_table($result, $params, $pos, Doku_Renderer $renderer) { + public function _render_table($result, $params, $pos, Doku_Renderer $renderer) + { global $conf; if (!$this->is_odt_export) { - $renderer->table_open(NULL, NULL, $pos); + $renderer->table_open(null, null, $pos); } else { $columns = 1; if ($params['tableshowsize'] || $params['showsize']) { @@ -387,7 +376,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { if ($params['preview']) { $columns++; } - $renderer->table_open($columns, NULL, $pos); + $renderer->table_open($columns, null, $pos); } if ($params['tableheader']) { @@ -421,7 +410,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $renderer->tableheader_open(1, 'center', 1); switch ($params['preview']) { case 1: - $renderer->cdata($this->getLang('preview').' / '.$this->getLang('filetype')); + $renderer->cdata($this->getLang('preview') . ' / ' . $this->getLang('filetype')); break; case 2: $renderer->cdata($this->getLang('preview')); @@ -482,10 +471,11 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $renderer the renderer to use * @return void */ - function _render_page($result, $params, Doku_Renderer $renderer) { - if ( method_exists ($renderer, 'getLastlevel') === false ) { - $class_vars = get_class_vars (get_class($renderer)); - if ($class_vars ['lastlevel'] !== NULL) { + public function _render_page($result, $params, Doku_Renderer $renderer) + { + if (method_exists($renderer, 'getLastlevel') === false) { + $class_vars = get_class_vars(get_class($renderer)); + if ($class_vars ['lastlevel'] !== null) { // Old releases before "hrun": $lastlevel is accessible $lastlevel = $renderer->lastlevel + 1; } else { @@ -510,9 +500,10 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $level the level to render * @return void */ - function _render_page_section($files, $basedir, $webdir, $params, Doku_Renderer $renderer, $level) { - $trees = array(); - $leafs = array(); + public function _render_page_section($files, $basedir, $webdir, $params, Doku_Renderer $renderer, $level) + { + $trees = []; + $leafs = []; foreach ($files as $file) { if ($file['children'] !== false) { @@ -548,15 +539,16 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $renderer the renderer to use * @return void */ - protected function _render_preview_image ($filepath, $basedir, $webdir, $params, Doku_Renderer $renderer) { + protected function _render_preview_image($filepath, $basedir, $webdir, $params, Doku_Renderer $renderer) + { $imagepath = $this->get_preview_image_path($filepath, $params, $isImage); if (!empty($imagepath)) { if ($isImage == false) { // Generate link to returned filetype icon - $imgLink = $this->_get_link_url ($imagepath, $basedir, $webdir, 0, 1); + $imgLink = $this->_get_link_url($imagepath, $basedir, $webdir, 0, 1); } else { // Generate link to image file - $imgLink = $this->_get_link_url ($filepath, $basedir, $webdir, $params['randlinks'], $params['direct'], $params['ftp']); + $imgLink = $this->_get_link_url($filepath, $basedir, $webdir, $params['randlinks'], $params['direct'], $params['ftp']); } $previewsize = $params['previewsize']; @@ -569,10 +561,10 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { } if (!$this->is_odt_export) { - $renderer->doc .= ''; + $renderer->doc .= ''; } else { - list($width, $height) = $renderer->_odtGetImageSize ($imagepath, $previewsize, $previewsize); - $renderer->_odtAddImage ($imagepath, $width.'cm', $height.'cm'); + [$width, $height] = $renderer->_odtGetImageSize($imagepath, $previewsize, $previewsize); + $renderer->_odtAddImage($imagepath, $width . 'cm', $height . 'cm'); } } } @@ -588,37 +580,32 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @return a filelist data structure containing the found files and base- * and webdir */ - function _create_filelist($pattern, $params) { + public function _create_filelist($pattern, $params) + { global $conf; global $ID; $allowed_absolute_paths = explode(',', $this->getConf('allowed_absolute_paths')); - $result = array( - 'files' => array(), - 'basedir' => false, - 'webdir' => false, - ); + $result = ['files' => [], 'basedir' => false, 'webdir' => false]; // we don't want to use $conf['media'] here as that path has symlinks resolved if (!$params['direct']) { // if media path is not absolute, precede it with the current namespace if ($pattern[0] != ':') { - $pattern = ':'.getNS($ID) . ':' . $pattern; + $pattern = ':' . getNS($ID) . ':' . $pattern; } // replace : with / and prepend mediadir $pattern = $this->mediadir . str_replace(':', '/', $pattern); - } elseif($params['direct'] == 2){ + } elseif ($params['direct'] == 2) { // treat path as relative to first configured path - $pattern = $allowed_absolute_paths[0].'/'.$pattern; - } else { + $pattern = $allowed_absolute_paths[0] . '/' . $pattern; + } elseif (!$this->_path_is_absolute($pattern)) { // if path is not absolute, precede it with DOKU_INC - if (!$this->_path_is_absolute($pattern)) { - $pattern = DOKU_INC.$pattern; - } + $pattern = DOKU_INC . $pattern; } // get the canonicalized basedir (without resolving symlinks) - $dir = $this->_realpath($this->_win_path_convert(dirname($pattern))).'/'; + $dir = $this->_realpath($this->_win_path_convert(dirname($pattern))) . '/'; // if the directory does not exist, we of course have no matches if (!$dir || !file_exists($dir)) { @@ -629,10 +616,11 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $web_paths = explode(',', $this->getConf('web_paths')); $basedir = false; $webdir = false; - if (count($allowed_absolute_paths) == count($web_paths)) { - for($i = 0; $i < count($allowed_absolute_paths); $i++) { + if (count($allowed_absolute_paths) === count($web_paths)) { + $counter = count($allowed_absolute_paths); + for ($i = 0; $i < $counter; $i++) { $abs_path = $this->_win_path_convert(trim($allowed_absolute_paths[$i])); - if (strstr($dir, $abs_path) == $dir) { + if (strstr($dir, (string) $abs_path) == $dir) { $basedir = $abs_path; $webdir = trim($web_paths[$i]); break; @@ -662,19 +650,19 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $callback = false; $reverseflag = false; if ($params['sort'] == 'mtime') { - $callback = array($this, '_compare_mtimes'); + $callback = [$this, '_compare_mtimes']; if ($params['order'] == 'asc') $reverseflag = true; - } else if ($params['sort'] == 'ctime') { - $callback = array($this, '_compare_ctimes'); + } elseif ($params['sort'] == 'ctime') { + $callback = [$this, '_compare_ctimes']; if ($params['order'] == 'asc') $reverseflag = true; - } else if ($params['sort'] == 'size') { - $callback = array($this, '_compare_sizes'); + } elseif ($params['sort'] == 'size') { + $callback = [$this, '_compare_sizes']; if ($params['order'] == 'desc') $reverseflag = true; - } else if ($params['sort'] == 'iname') { - $callback = array($this, '_compare_inames'); + } elseif ($params['sort'] == 'iname') { + $callback = [$this, '_compare_inames']; if ($params['order'] == 'desc') $reverseflag = true; } else { - $callback = array($this, '_compare_names'); + $callback = [$this, '_compare_names']; if ($params['order'] == 'desc') $reverseflag = true; } $this->_sort_filelist($result['files'], $callback, $reverseflag); @@ -682,8 +670,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { // return the list if (count($result['files']) > 0) return $result; - else - return DOKU_PLUGIN_FILELIST_NOMATCH; + else return DOKU_PLUGIN_FILELIST_NOMATCH; } /** @@ -695,9 +682,12 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $reverse true if the result is to be reversed * @return the sorted tree */ - function _sort_filelist(&$files, $callback, $reverse) { + public function _sort_filelist(&$files, $callback, $reverse) + { // sort subtrees - for ($i = 0; $i < count($files); $i++) { + $counter = count($files); + // sort subtrees + for ($i = 0; $i < $counter; $i++) { if ($files[$i]['children'] !== false) { $children = $files[$i]['children']; $this->_sort_filelist($children, $callback, $reverse); @@ -720,8 +710,9 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $prefix the prefix to attach to all processed nodes * @return a flattened representation of the tree */ - function _flatten_filelist($files, $prefix = '') { - $result = array(); + public function _flatten_filelist($files, $prefix = '') + { + $result = []; foreach ($files as $file) { if ($file['children'] !== false) { $result = array_merge($result, $this->_flatten_filelist($file['children'], $prefix . $file['name'] . '/')); @@ -741,12 +732,13 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * DOKU_PLUGIN_FILELIST_NOMATCH if there are no files left or * the given result if it was not an array (but an errorcode) */ - function _filter_out_directories($result) { + public function _filter_out_directories($result) + { if (!is_array($result)) { return $result; } - $filtered = array(); + $filtered = []; $files = $result['files']; foreach ($files as $file) { if ($file['children'] === false) { @@ -772,7 +764,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * * @see */ - function _crawl_files($pattern, $params) { + public function _crawl_files($pattern, $params) + { $split = explode('/', $pattern); $match = array_pop($split); $path = implode('/', $split); @@ -780,13 +773,13 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { return false; } - $ext = explode(',',$this->getConf('extensions')); - $ext = array_map('trim',$ext); - $ext = array_map('preg_quote_cb',$ext); - $ext = join('|',$ext); + $ext = explode(',', $this->getConf('extensions')); + $ext = array_map('trim', $ext); + $ext = array_map('preg_quote_cb', $ext); + $ext = implode('|', $ext); if (($dir = opendir($path)) !== false) { - $result = array(); + $result = []; while (($file = readdir($dir)) !== false) { if ($file == '.' || $file == '..') { // ignore . and .. @@ -803,7 +796,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $filepath = $path . '/' . $file; if ($this->_fnmatch($match, $file) || (is_dir($filepath) && $params['recursive'])) { - if(!is_dir($filepath) && !preg_match('/('.$ext.')$/i',$file)){ + if (!is_dir($filepath) && !preg_match('/(' . $ext . ')$/i', $file)) { continue; } @@ -812,8 +805,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $mid = $this->_convert_mediapath($filepath); $perm = auth_quickaclcheck($mid); if ($perm < AUTH_READ) continue; - } else { - if (!is_readable($filepath)) continue; + } elseif (!is_readable($filepath)) { + continue; } $filename = $file; @@ -825,10 +818,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { if (is_readable($titlefile) && $perm >= AUTH_READ) { $filename = io_readFile($titlefile, false); } - } else { - if (is_readable($titlefile)) { - $filename = io_readFile($titlefile, false); - } + } elseif (is_readable($titlefile)) { + $filename = io_readFile($titlefile, false); } } @@ -839,7 +830,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $medialog = new MediaChangeLog($mid); $revinfo = $medialog->getRevisionInfo(@filemtime(fullpath(mediaFN($mid)))); - if($revinfo['user']) { + if ($revinfo['user']) { $creator = $revinfo['user']; } else { $creator = $revinfo['ip']; @@ -849,16 +840,7 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { $creator = $this->getLang('creatorunknown'); } - $entry = array( - 'name' => $filename, - 'path' => $filepath, - 'mtime' => filemtime($filepath), - 'ctime' => filectime($filepath), - 'size' => filesize($filepath), - 'children' => ((is_dir($filepath) && $params['recursive']) ? $this->_crawl_files($filepath . '/' . $match, $params) : false), - 'treesize' => 0, - 'creator' => $creator, - ); + $entry = ['name' => $filename, 'path' => $filepath, 'mtime' => filemtime($filepath), 'ctime' => filectime($filepath), 'size' => filesize($filepath), 'children' => ((is_dir($filepath) && $params['recursive']) ? $this->_crawl_files($filepath . '/' . $match, $params) : false), 'treesize' => 0, 'creator' => $creator]; // calculate tree size if ($entry['children'] !== false) { @@ -883,33 +865,29 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { //~~ Comparators - function _compare_names($a, $b) { + public function _compare_names($a, $b) + { return strcmp($a['name'], $b['name']); } - function _compare_inames($a, $b) { + public function _compare_inames($a, $b) + { return strcmp(strtolower($a['name']), strtolower($b['name'])); } - function _compare_ctimes($a, $b) { - if ($a['ctime'] == $b['ctime']) { - return 0; - } - return (($a['ctime'] < $b['ctime']) ? -1 : 1); + public function _compare_ctimes($a, $b) + { + return $a['ctime'] <=> $b['ctime']; } - function _compare_mtimes($a, $b) { - if ($a['mtime'] == $b['mtime']) { - return 0; - } - return (($a['mtime'] < $b['mtime']) ? -1 : 1); + public function _compare_mtimes($a, $b) + { + return $a['mtime'] <=> $b['mtime']; } - function _compare_sizes($a, $b) { - if ($a['size'] == $b['size']) { - return 0; - } - return (($a['size'] < $b['size']) ? -1 : 1); + public function _compare_sizes($a, $b) + { + return $a['size'] <=> $b['size']; } //~~ Utility functions @@ -920,16 +898,18 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @author anonymous * @see */ - function _realpath($path) { - $path=explode('/', $path); - $output=array(); - for ($i=0; $i */ - function _fnmatch($pattern, $string) { - return preg_match("#^".strtr(preg_quote($pattern, '#'), array('\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']'))."$#i", $string); + public function _fnmatch($pattern, $string) + { + return preg_match("#^" . strtr(preg_quote($pattern, '#'), ['\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']']) . "$#i", $string); } /** @@ -950,29 +931,30 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $path the path to convert * @return the converted path */ - function _win_path_convert($path) { + public function _win_path_convert($path) + { return str_replace('\\', '/', trim($path)); } /** * Return human readable sizes * - * @author Aidan Lister + * @param int $size size in bytes + * @param string $max maximum unit + * @param string $system 'si' for SI, 'bi' for binary prefixes + * @param string $retstring return string format * @version 1.3.0 * @link http://aidanlister.com/repos/v/function.size_readable.php - * @param int $size size in bytes - * @param string $max maximum unit - * @param string $system 'si' for SI, 'bi' for binary prefixes - * @param string $retstring return string format + * @author Aidan Lister */ - function _size_readable($size, $max = null, $system = 'si', $retstring = '%01.2f %s') + public function _size_readable($size, $max = null, $system = 'si', $retstring = '%01.2f %s') { // Pick units - $systems['si']['prefix'] = array('B', 'K', 'MB', 'GB', 'TB', 'PB'); - $systems['si']['size'] = 1000; - $systems['bi']['prefix'] = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'); - $systems['bi']['size'] = 1024; - $sys = isset($systems[$system]) ? $systems[$system] : $systems['si']; + $systems['si']['prefix'] = ['B', 'K', 'MB', 'GB', 'TB', 'PB']; + $systems['si']['size'] = 1000; + $systems['bi']['prefix'] = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; + $systems['bi']['size'] = 1024; + $sys = $systems[$system] ?? $systems['si']; // Max unit to display $depth = count($sys['prefix']) - 1; @@ -999,7 +981,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $path the path to check * @return true if path is absolute, false otherwise */ - function _path_is_absolute($path) { + public function _path_is_absolute($path) + { if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { if ($path[1] == ':' || ($path[0] == '/' && $path[1] == '/')) { return true; @@ -1010,7 +993,8 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { } } - function _convert_mediapath($path) { + public function _convert_mediapath($path) + { $mid = str_replace('/', ':', substr($path, strlen($this->mediadir))); // strip media base dir return ltrim($mid, ':'); // strip leading : } @@ -1027,23 +1011,28 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $filename the file to check * @return string Image to use for preview image */ - protected function get_preview_image_path ($filename, $params, &$isImage) { - list($ext,$mime) = mimetype(basename($filename)); + protected function get_preview_image_path($filename, $params, &$isImage) + { + [$ext, $mime] = mimetype(basename($filename)); $imagepath = ''; $isImage = false; - if (($params['preview'] == 1 || $params['preview'] == 2) && - strncmp($mime, 'image', strlen('image')) == 0) { + if ( + ($params['preview'] == 1 || $params['preview'] == 2) && + strncmp($mime, 'image', strlen('image')) == 0 + ) { // The file is an image. Return itself as the image path. $imagepath = $filename; $isImage = true; } - if (($params['preview'] == 1 && empty($imagepath)) || - $params['preview'] == 3 ) { + if ( + ($params['preview'] == 1 && empty($imagepath)) || + $params['preview'] == 3 + ) { // No image. Return DokuWiki image for file extension. if (!empty($ext)) { - $imagepath = DOKU_INC.'lib/images/fileicons/32x32/'.$ext.'.png'; + $imagepath = DOKU_INC . 'lib/images/fileicons/32x32/' . $ext . '.png'; } else { - $imagepath = DOKU_INC.'lib/images/fileicons/32x32/file.png'; + $imagepath = DOKU_INC . 'lib/images/fileicons/32x32/file.png'; } } return $imagepath; @@ -1058,22 +1047,22 @@ class syntax_plugin_filelist extends DokuWiki_Syntax_Plugin { * @param $params the parameters of the filelist call * @return string the generated URL */ - protected function _get_link_url ($filepath, $basedir, $webdir, $randlinks, $direct, $ftp=false) { + protected function _get_link_url($filepath, $basedir, $webdir, $randlinks, $direct, $ftp = false) + { $urlparams = ''; if ($randlinks) { - $urlparams = '?'.time(); + $urlparams = '?' . time(); } if (!$direct) { - $url = ml(':'.$this->_convert_mediapath($filepath)).$urlparams; + $url = ml(':' . $this->_convert_mediapath($filepath)) . $urlparams; } else { - $url = $webdir.substr($filepath, strlen($basedir)).$urlparams; - if ($ftp) - { - $url = str_replace('\\','/', $url); + $url = $webdir . substr($filepath, strlen($basedir)) . $urlparams; + if ($ftp) { + $url = str_replace('\\', '/', $url); if (strpos($url, 'http') === false) { - $url = 'ftp:'.$url; + $url = 'ftp:' . $url; } else { - $url = str_replace('http','ftp', $url); + $url = str_replace('http', 'ftp', $url); } } } From 28af4b6776c00b2e62e715a02cb1751a1eb6139a Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 14:49:08 +0100 Subject: [PATCH 2/9] Major Refactoring (will need some cleanup) This refactors the plugin from one mega syntax file into multiple classes. The plugin now focuses on one usecase: listing files that are external to the wiki and making them downloadable. All other usecases have been dropped. Also a bunch of other options have been dropped. A new dispatcher makes it possible to deliver files without the need to have the webserver pointing at them. --- Crawler.php | 192 ++++++++ Output.php | 283 ++++++++++++ Path.php | 144 ++++++ conf/default.php | 2 + conf/metadata.php | 2 + file.php | 40 ++ syntax.php | 1087 ++++----------------------------------------- 7 files changed, 745 insertions(+), 1005 deletions(-) create mode 100644 Crawler.php create mode 100644 Output.php create mode 100644 Path.php create mode 100644 file.php diff --git a/Crawler.php b/Crawler.php new file mode 100644 index 0000000..8fb777e --- /dev/null +++ b/Crawler.php @@ -0,0 +1,192 @@ +ext = explode(',', $extensions); + $this->ext = array_map('trim', $this->ext); + $this->ext = array_map('preg_quote_cb', $this->ext); + $this->ext = implode('|', $this->ext); + } + + public function setSortBy($sortby) + { + $this->sortby = $sortby; + } + + public function setSortReverse($sortreverse) + { + $this->sortreverse = $sortreverse; + } + + /** + * Does a (recursive) crawl for finding files based on a given pattern. + * Based on a safe glob reimplementation using fnmatch and opendir. + * + * @param string $path the path to search in + * @param string $pattern the pattern to match to + * @param bool $recursive whether to search recursively + * @param string $titlefile the name of the title file + * @return array a hierarchical filelist or false if nothing could be found + * + * @see http://www.php.net/manual/en/function.glob.php#71083 + */ + public function crawl($root, $local, $pattern, $recursive, $titlefile) + { + $path = $root . $local; + + if (($dir = opendir($path)) === false) return []; + $result = []; + while (($file = readdir($dir)) !== false) { + if ($file[0] == '.' || $file == $titlefile) { + // ignore hidden, system and title files + continue; + } + $self = $local . '/' . $file; + $filepath = $path . '/' . $file; + if (!is_readable($filepath)) continue; + + if ($this->fnmatch($pattern, $file) || (is_dir($filepath) && $recursive)) { + if (!is_dir($filepath) && !$this->isExtensionAllowed($file)) { + continue; + } + + // get title file + $filename = $file; + if (is_dir($filepath)) { + $title = $filepath . '/' . $titlefile; + if (is_readable($title)) { + $filename = io_readFile($title, false); + } + } + + // prepare entry + if (!is_dir($filepath) || $recursive) { + $entry = [ + 'name' => $filename, + 'local' => $self, + 'path' => $filepath, + 'mtime' => filemtime($filepath), + 'ctime' => filectime($filepath), + 'size' => filesize($filepath), + 'children' => ((is_dir($filepath) && $recursive) ? + $this->crawl($root, $self, $pattern, $recursive, $titlefile) : + false + ), + 'treesize' => 0, + ]; + + // calculate tree size + if ($entry['children'] !== false) { + foreach ($entry['children'] as $child) { + $entry['treesize'] += $child['treesize']; + } + } else { + $entry['treesize'] = 1; + } + + // add entry to result + $result[] = $entry; + } + } + } + closedir($dir); + return $this->sortItems($result); + } + + /** + * Sort the given items by the current sortby and sortreverse settings + * + * @param array $items + * @return array + */ + protected function sortItems($items) + { + $callback = [$this, 'compare' . ucfirst($this->sortby)]; + if (!is_callable($callback)) return $items; + + usort($items, $callback); + if ($this->sortreverse) { + $items = array_reverse($items); + } + return $items; + } + + /** + * Check if a file is allowed by the configured extensions + * + * @param string $file + * @return bool + */ + protected function isExtensionAllowed($file) + { + if ($this->ext === '') return true; // no restriction + return preg_match('/(' . $this->ext . ')$/i', $file); + } + + + /** + * Replacement for fnmatch() for windows systems. + * + * @author jk at ricochetsolutions dot com + * @link http://www.php.net/manual/en/function.fnmatch.php#71725 + */ + protected function fnmatch($pattern, $string) + { + return preg_match( + "#^" . strtr( + preg_quote($pattern, '#'), + [ + '\*' => '.*', + '\?' => '.', + '\[' => '[', + '\]' => ']' + ] + ) . "$#i", + $string + ); + } + + public function compareName($a, $b) + { + return strcmp($a['name'], $b['name']); + } + + public function compareIname($a, $b) + { + return strcmp(strtolower($a['name']), strtolower($b['name'])); + } + + public function compareCtime($a, $b) + { + return $a['ctime'] <=> $b['ctime']; + } + + public function compareMtime($a, $b) + { + return $a['mtime'] <=> $b['mtime']; + } + + public function compareSize($a, $b) + { + return $a['size'] <=> $b['size']; + } +} diff --git a/Output.php b/Output.php new file mode 100644 index 0000000..be7b7ae --- /dev/null +++ b/Output.php @@ -0,0 +1,283 @@ +renderer = $renderer; + $this->basedir = $basedir; + $this->webdir = $webdir; + $this->files = $files; + } + + public function renderAsList($params) + { + if ($this->renderer instanceof \Doku_Renderer_xhtml) { + $this->renderer->doc .= '
'; + } + + $this->renderListItems($this->files, $params); + + if ($this->renderer instanceof \Doku_Renderer_xhtml) { + $this->renderer->doc .= '
'; + } + } + + /** + * Renders the files as a table, including details if configured that way. + * + * @param array $params the parameters of the filelist call + */ + public function renderAsTable($params) + { + if ($this->renderer instanceof \Doku_Renderer_xhtml) { + $this->renderer->doc .= '
'; + } + + $items = $this->flattenResultTree($this->files); + $this->renderTableItems($items, $params); + + if ($this->renderer instanceof \Doku_Renderer_xhtml) { + $this->renderer->doc .= '
'; + } + } + + + /** + * Renders the files as a table, including details if configured that way. + * + * @param array $params the parameters of the filelist call + */ + protected function renderTableItems($items, $params) + { + + $renderer = $this->renderer; + + + // count the columns + $columns = 1; + if ($params['showsize']) { + $columns++; + } + if ($params['showdate']) { + $columns++; + } + + $renderer->table_open($columns); + + if ($params['tableheader']) { + $renderer->tablethead_open(); + $renderer->tablerow_open(); + + $renderer->tableheader_open(); + $renderer->cdata($this->getLang('filename')); + $renderer->tableheader_close(); + + if ($params['showsize']) { + $renderer->tableheader_open(); + $renderer->cdata($this->getLang('filesize')); + $renderer->tableheader_close(); + } + + if ($params['showdate']) { + $renderer->tableheader_open(); + $renderer->cdata($this->getLang('lastmodified')); + $renderer->tableheader_close(); + } + + $renderer->tablerow_close(); + $renderer->tablethead_close(); + } + + $renderer->tabletbody_open(); + foreach ($items as $item) { + $renderer->tablerow_open(); + $renderer->tablecell_open(); + $this->renderItemLink($item, $params['randlinks']); + $renderer->tablecell_close(); + + if ($params['showsize']) { + $renderer->tablecell_open(1, 'right'); + $renderer->cdata(filesize_h($item['size'])); + $renderer->tablecell_close(); + } + + if ($params['showdate']) { + $renderer->tablecell_open(); + $renderer->cdata(dformat($item['mtime'])); + $renderer->tablecell_close(); + } + + $renderer->tablerow_close(); + } + $renderer->tabletbody_close(); + $renderer->table_close(); + } + + + /** + * Recursively renders a tree of files as list items. + * + * @param array $items the files to render + * @param array $params the parameters of the filelist call + * @param int $level the level to render + * @return void + */ + protected function renderListItems($items, $params, $level = 1) + { + if ($params['style'] == 'olist') { + $this->renderer->listo_open(); + } else { + $this->renderer->listu_open(); + } + + foreach ($items as $file) { + if ($file['children'] === false && $file['treesize'] === 0) continue; // empty directory + + $this->renderer->listitem_open($level); + $this->renderer->listcontent_open(); + + if ($file['children'] !== false && $file['treesize'] > 0) { + // render the directory and its subtree + $this->renderer->cdata($file['name']); + $this->renderListItems($file['children'], $params, $level + 1); + } elseif ($file['children'] === false) { + // render the file link + $this->renderItemLink($file, $params['randlinks']); + + // render filesize + if ($params['showsize']) { + $this->renderer->cdata($params['listsep'] . filesize_h($file['size'])); + } + // render lastmodified + if ($params['showdate']) { + $this->renderer->cdata($params['listsep'] . dformat($file['mtime'])); + } + } + + $this->renderer->listcontent_close(); + $this->renderer->listitem_close(); + } + + if ($params['style'] == 'olist') { + $this->renderer->listo_close(); + } else { + $this->renderer->listu_close(); + } + } + + protected function renderItemLink($item, $cachebuster = false) + { + if ($this->renderer instanceof \Doku_Renderer_xhtml) { + $this->renderItemLinkXHTML($item, $cachebuster); + } else { + $this->renderItemLinkAny($item, $cachebuster); + } + } + + /** + * Render a file link on the XHTML renderer + */ + protected function renderItemLinkXHTML($item, $cachebuster = false) + { + global $conf; + /** @var \Doku_Renderer_xhtml $renderer */ + $renderer = $this->renderer; + + //prepare for formating + $link['target'] = $conf['target']['extern']; + $link['style'] = ''; + $link['pre'] = ''; + $link['suf'] = ''; + $link['more'] = ''; + $link['url'] = $this->itemWebUrl($item, $cachebuster); + $link['name'] = $item['name']; + $link['title'] = $renderer->_xmlEntities($link['url']); + if ($conf['relnofollow']) $link['more'] .= ' rel="nofollow"'; + [$ext,] = mimetype(basename($item['local'])); + $link['class'] .= ' mediafile mf_' . $ext; + $renderer->doc .= $renderer->_formatLink($link); + } + + /** + * Render a file link on any Renderer + * @param array $item + * @param bool $cachebuster + * @return void + */ + protected function renderItemLinkAny($item, $cachebuster = false) + { + $this->renderer->externalmedialink($this->itemWebUrl($item, $cachebuster), $item['name']); + } + + /** + * Construct the Web URL for a given item + * + * @param array $item The item data as returned by the Crawler + * @param bool $cachbuster add a cachebuster to the URL? + * @return string + */ + protected function itemWebUrl($item, $cachbuster = false) + { + if (str_ends_with($this->webdir, '=')) { + $url = $this->webdir . rawurlencode($item['local']); + } else { + $url = $this->webdir . $item['local']; + } + + if ($cachbuster) { + if (strpos($url, '?') === false) { + $url .= '?t=' . $item['mtime']; + } else { + $url .= '&t=' . $item['mtime']; + } + } + return $url; + } + + /** + * Flattens the filelist by recursively walking through all subtrees and + * merging them with a prefix attached to the filenames. + * + * @param array $items the tree to flatten + * @param string $prefix the prefix to attach to all processed nodes + * @return array a flattened representation of the tree + */ + protected function flattenResultTree($items, $prefix = '') + { + $result = []; + foreach ($items as $file) { + if ($file['children'] !== false) { + $result = array_merge( + $result, + $this->flattenResultTree($file['children'], $prefix . $file['name'] . '/') + ); + } else { + $file['name'] = $prefix . $file['name']; + $result[] = $file; + } + } + return $result; + } + + protected function getLang($key) + { + $syntax = plugin_load('syntax', 'filelist'); + return $syntax->getLang($key); + } +} diff --git a/Path.php b/Path.php new file mode 100644 index 0000000..479c8a2 --- /dev/null +++ b/Path.php @@ -0,0 +1,144 @@ +paths = $this->parsePathConfig($pathConfig); + } + + /** + * Parse the path configuration into an internal array + * + * roots (and aliases) are always saved with a trailing slash + * + * @return array + */ + protected function parsePathConfig($pathConfig) + { + $paths = []; + $lines = explode("\n", $pathConfig); + $lastRoot = ''; + foreach ($lines as $line) { + $line = trim($line); + if (empty($line)) { + continue; + } + + if (str_starts_with($line, 'A>')) { + // this is an alias for the last read root + $line = trim(substr($line, 2)); + if (!isset($paths[$lastRoot])) continue; // no last root, no alias + $alias = $this->cleanPath($line); + $paths[$lastRoot]['alias'] = $alias; + $paths[$alias] = &$paths[$lastRoot]; // alias references the original + } elseif (str_starts_with($line, 'W>')) { + // this is a web path for the last read root + $line = trim(substr($line, 2)); + if (!isset($paths[$lastRoot])) continue; // no last path, no web path + $paths[$lastRoot]['web'] = $line; + } else { + // this is a new path + $line = $this->cleanPath($line); + $lastRoot = $line; + $paths[$line] = [ + 'root' => $line, + 'web' => DOKU_BASE . 'lib/plugins/filelist/file.php?root=' . rawurlencode($line).'&file=', + ]; + } + } + + return $paths; + } + + /** + * Check if a given path is listable and return it's configuration + * + * @param string $path + * @param bool $addTrailingSlash + * @return array + * @throws \Exception if the given path is not allowed + */ + public function getPathInfo($path, $addTrailingSlash = true) + { + $path = $this->cleanPath($path, $addTrailingSlash); + + $paths = $this->paths; + $allowed = array_keys($paths); + usort($allowed, function ($a, $b) { + return strlen($a) - strlen($b); + }); + $allowed = array_map('preg_quote_cb', $allowed); + $regex = '/^(' . implode('|', $allowed) . ')/'; + + if (!preg_match($regex, $path, $matches)) { + throw new \Exception('Path not allowed: ' . $path); + } + $match = $matches[1]; + + $pathInfo = $paths[$match]; + $pathInfo['local'] = substr($path, strlen($match)); + $pathInfo['path'] = $pathInfo['root'] . $pathInfo['local']; + + + return $pathInfo; + } + + /** + * Clean a path for better comparison + * + * Converts all backslashes to forward slashes + * Keeps leading double backslashes for UNC paths + * Ensure a single trailing slash unless disabled + * + * @param string $path + * @return string + */ + public static function cleanPath($path, $addTrailingSlash = true) + { + if (str_starts_with($path, '\\\\')) { + $unc = '\\\\'; + } else { + $unc = ''; + } + $path = ltrim($path, '\\'); + $path = str_replace('\\', '/', $path); + $path = self::realpath($path); + if ($addTrailingSlash) { + $path = rtrim($path, '/'); + $path .= '/'; + } + + return $unc . $path; + } + + /** + * Canonicalizes a given path. A bit like realpath, but without the resolving of symlinks. + * + * @author anonymous + * @see + */ + public static function realpath($path) + { + $path = explode('/', $path); + $output = []; + $counter = count($path); + for ($i = 0; $i < $counter; $i++) { + if ('.' == $path[$i]) continue; + if ('' === $path[$i] && $i > 0) continue; + if ('..' == $path[$i] && '..' != $output[count($output) - 1]) { + array_pop($output); + continue; + } + $output[] = $path[$i]; + } + return implode('/', $output); + } +} diff --git a/conf/default.php b/conf/default.php index c5a2daa..9568f60 100644 --- a/conf/default.php +++ b/conf/default.php @@ -4,6 +4,8 @@ * Options for the filelist plugin */ +$conf['paths'] = ''; + $conf['allow_in_comments'] = 0; $conf['allowed_absolute_paths'] = DOKU_INC; $conf['web_paths'] = DOKU_URL; diff --git a/conf/metadata.php b/conf/metadata.php index 3e1078f..4ae4b38 100644 --- a/conf/metadata.php +++ b/conf/metadata.php @@ -7,6 +7,8 @@ * @author Gina Haeussge */ +$meta['paths'] = array(''); + $meta['allow_in_comments'] = array('onoff'); $meta['allowed_absolute_paths'] = array(''); $meta['web_paths'] = array(''); diff --git a/file.php b/file.php new file mode 100644 index 0000000..e89049b --- /dev/null +++ b/file.php @@ -0,0 +1,40 @@ +getConf('paths')); +$path = $INPUT->str('root') . $INPUT->str('file'); + +try { + $pathInfo = $pathUtil->getPathInfo($path, false); + if (!is_readable($pathInfo['path'])) { + header('Content-Type: text/plain'); + http_status(404); + echo 'Path not readable: ' . $pathInfo['path']; + exit; + } + [$ext, $mime, $download] = mimetype($pathInfo['path'], false); + $basename = basename($pathInfo['path']); + header('Content-Type: ' . $mime); + if ($download) { + header('Content-Disposition: attachment; filename="' . $basename . '"'); + } + http_sendfile($pathInfo['path']); + readfile($pathInfo['path']); +} catch (Exception $e) { + header('Content-Type: text/plain'); + http_status(403); + echo $e->getMessage(); + exit; +} + diff --git a/syntax.php b/syntax.php index 7c26d3d..4138dcf 100644 --- a/syntax.php +++ b/syntax.php @@ -1,6 +1,9 @@ */ - -define('DOKU_PLUGIN_FILELIST_NOMATCH', -1); -define('DOKU_PLUGIN_FILELIST_OUTSIDEJAIL', -2); - -/** - * All DokuWiki plugins to extend the parser/rendering mechanism - * need to inherit from this class - */ class syntax_plugin_filelist extends SyntaxPlugin { - public $mediadir; - public $is_odt_export = false; - - public function __construct() - { - global $conf; - $mediadir = $conf['mediadir']; - if (!$this->_path_is_absolute($mediadir)) { - $mediadir = DOKU_INC . '/' . $mediadir; - } - $this->mediadir = $this->_win_path_convert($this->_realpath($mediadir) . '/'); - } - + /** @inheritdoc */ public function getType() { return 'substition'; } + /** @inheritdoc */ public function getPType() { return 'block'; } + /** @inheritdoc */ public function getSort() { return 222; } + /** @inheritdoc */ public function connectTo($mode) { - $this->Lexer->addSpecialPattern('\{\{filename>.+?\}\}', $mode, 'plugin_filelist'); $this->Lexer->addSpecialPattern('\{\{filelist>.+?\}\}', $mode, 'plugin_filelist'); } - /** - * Handle the match - */ + /** @inheritdoc */ public function handle($match, $state, $pos, Doku_Handler $handler) { + global $INPUT; - // do not allow the syntax in comments - if (!$this->getConf('allow_in_comments') && isset($_REQUEST['comment'])) + // do not allow the syntax in discussion plugin comments + if (!$this->getConf('allow_in_comments') && $INPUT->has('comment')) { return false; - - $match = substr($match, 2, -2); - [$type, $match] = explode('>', $match, 2); - [$pattern, $flags] = explode('&', $match, 2); - - if ($type == 'filename') { - if (strpos($flags, '|') !== false) { - [$flags, $title] = explode('\|', $flags); - } else { - $title = ''; - } } + $match = substr($match, strlen('{{filelist>'), -2); + [$path, $flags] = explode('&', $match, 2); + // load default config options $flags = $this->getConf('defaults') . '&' . $flags; - $flags = explode('&', $flags); - $params = ['sort' => 'name', 'order' => 'asc', 'index' => 0, 'limit' => 0, 'offset' => 0, 'style' => 'list', 'tableheader' => 0, 'tableshowsize' => 0, 'tableshowdate' => 0, 'direct' => 0, 'recursive' => 0, 'titlefile' => '_title.txt', 'cache' => 0, 'randlinks' => 0, 'preview' => 0, 'previewsize' => 32, 'link' => 2, 'showsize' => 0, 'showdate' => 0, 'showcreator' => 0, 'listsep' => '", "', 'onhover' => 0, 'ftp' => 0]; + $params = [ + 'sort' => 'name', + 'order' => 'asc', + 'index' => 0, + 'limit' => 0, + 'offset' => 0, + 'style' => 'list', + 'tableheader' => 0, + 'tableshowsize' => 0, + 'tableshowdate' => 0, + 'direct' => 0, + 'recursive' => 0, + 'titlefile' => '_title.txt', + 'cache' => 0, + 'randlinks' => 0, + 'preview' => 0, + 'previewsize' => 32, + 'link' => 2, + 'showsize' => 0, + 'showdate' => 0, + 'showcreator' => 0, + 'listsep' => '", "', + 'onhover' => 0, + 'ftp' => 0 + ]; foreach ($flags as $flag) { [$name, $value] = explode('=', $flag); - $params[trim($name)] = trim($value); + $params[trim($name)] = trim(trim($value), '"'); // quotes can be use to keep whitespace } - // recursive filelistings are not supported for the filename command - if ($type == 'filename') { - $params['recursive'] = 0; - } + // separate path and pattern + $path = Path::cleanPath($path, false); + $parts = explode('/', $path); + $pattern = array_pop($parts); + $base = join('/', $parts) . '/'; - // Trim list separator - $params['listsep'] = trim($params['listsep'], '"'); - - return [$type, $pattern, $params, $title, $pos]; + return [$base, $pattern, $params]; } /** * Create output */ - public function render($mode, Doku_Renderer $renderer, $data) + public function render($format, Doku_Renderer $renderer, $data) { - global $conf; + [$base, $pattern, $params] = $data; - [$type, $pattern, $params, $title, $pos] = $data; - - if ($mode == 'odt') { - $this->is_odt_export = true; + if ($format != 'xhtml' && $format != 'odt') { + return false; } // disable caching if ($params['cache'] === 0) { $renderer->nocache(); } - if ($mode == 'xhtml' || $mode == 'odt') { - $result = $this->_create_filelist($pattern, $params); - if ($type == 'filename') { - $result = $this->_filter_out_directories($result); - } - // if we got nothing back, display a message - if ($result == DOKU_PLUGIN_FILELIST_NOMATCH) { - $renderer->cdata('[n/a: ' . $this->getLang('error_nomatch') . ']'); - return true; - } elseif ($result == DOKU_PLUGIN_FILELIST_OUTSIDEJAIL) { - $renderer->cdata('[n/a: ' . $this->getLang('error_outsidejail') . ']'); - return true; - } - // if limit is set for a filelist, cut out the relevant slice from the files - if (($type == 'filelist') && ($params['limit'] != 0)) { - $result['files'] = array_slice($result['files'], $params['offset'], $params['limit']); - } - - switch ($type) { - case 'filename': - $filename = $result['files'][$params['index']]['name']; - $filepath = $result['files'][$params['index']]['path']; - - $this->_render_link($filename, $filepath, $result['basedir'], $result['webdir'], $params, $renderer); - return true; - - case 'filelist': - if (count($result['files']) == 0) - break; - - switch ($params['style']) { - case 'list': - case 'olist': - if (!$this->is_odt_export) { - $renderer->doc .= '
' . DOKU_LF; - } - $this->_render_list($result, $params, $renderer); - if (!$this->is_odt_export) { - $renderer->doc .= '
' . DOKU_LF; - } - break; - - case 'table': - if (!$this->is_odt_export) { - $renderer->doc .= '
' . DOKU_LF; - } - $this->_render_table($result, $params, $pos, $renderer); - if (!$this->is_odt_export) { - $renderer->doc .= '
' . DOKU_LF; - } - break; - - case 'page': - $this->_render_page($result, $params, $renderer); - break; - } - return true; - } + try { + $pathHelper = new Path($this->getConf('paths')); + $pathInfo = $pathHelper->getPathInfo($base); + } catch (Exception $e) { + $renderer->cdata('[n/a: ' . $this->getLang('error_outsidejail') . ']'); + return true; } - return false; + + $crawler = new Crawler($this->getConf('extensions')); + $crawler->setSortBy($params['sort']); + $crawler->setSortReverse($params['order'] === 'desc'); + $result = $crawler->crawl($pathInfo['root'], $pathInfo['local'], $pattern, $params['recursive'], $params['titlefile']); + + // if we got nothing back, display a message + if ($result == []) { + $renderer->cdata('[n/a: ' . $this->getLang('error_nomatch') . ']'); + return true; + } + + $output = new Output($renderer, $pathInfo['root'], $pathInfo['web'], $result); + + switch ($params['style']) { + case 'list': + case 'olist': + $output->renderAsList($params); + break; + case 'table': + $output->renderAsTable($params); + break; + + } + return true; + } - //~~ Render functions - - /** - * Creates the downloadlink for the given filename, based on the given - * parameters, and adds it to the output of the renderer. - * - * @param $filename the name of the file - * @param $filepath the path of the file - * @param $basedir the basedir of the file - * @param $webdir the base URL of the file - * @param $params the parameters of the filelist command - * @param $renderer the renderer to use - * @return void - */ - public function _render_link($filename, $filepath, $basedir, $webdir, $params, Doku_Renderer $renderer) - { - global $conf; - - //prepare for formating - $link['target'] = $conf['target']['extern']; - $link['style'] = ''; - $link['pre'] = ''; - $link['suf'] = ''; - $link['more'] = ''; - $link['url'] = $this->_get_link_url($filepath, $basedir, $webdir, $params['randlinks'], $params['direct'], $params['ftp']); - - $link['name'] = $filename; - $link['title'] = $renderer->_xmlEntities($link['url']); - if ($conf['relnofollow']) $link['more'] .= ' rel="nofollow"'; - - if ($params['link']) { - switch ($params['link']) { - case 1: - // Link without background image - $link['class'] = 'media'; - break; - default: - // Link with background image - [$ext, $mime] = mimetype(basename($filepath)); - $link['class'] .= ' mediafile mf_' . $ext; - break; - } - - //output formatted - if (!$this->is_odt_export) { - $renderer->doc .= $renderer->_formatLink($link); - } else { - $this->render_odt_link($link, $renderer); - } - } else { - // No link, just plain text. - $renderer->cdata($filename); - } - } - - /** - * Renders a link for odt mode. - * - * @param $link the link parameters - * @param $renderer the renderer to use - * @return void - */ - protected function render_odt_link($link, Doku_Renderer $renderer) - { - if (method_exists($renderer, 'getODTProperties')) { - $properties = []; - - // Get CSS properties for ODT export. - $renderer->getODTProperties($properties, 'a', $link['class'], null, 'screen'); - - // Insert image if present for that media class. - if (empty($properties ['background-image']) === false) { - $properties ['background-image'] = - $renderer->replaceURLPrefix($properties ['background-image'], DOKU_INC); - $renderer->_odtAddImage($properties ['background-image']); - } - } - - // Render link. - $renderer->externallink($link['url'], $link['name']); - } - - /** - * Renders a list. - * - * @param $result the filelist to render - * @param $params the parameters of the filelist call - * @param $renderer the renderer to use - * @return void - */ - public function _render_list($result, $params, Doku_Renderer $renderer) - { - $this->_render_list_items($result['files'], $result['basedir'], $result['webdir'], $params, $renderer); - } - - /** - * Recursively renders a tree of files as list items. - * - * @param $files the files to render - * @param $basedir the basedir to use - * @param $webdir the webdir to use - * @param $params the parameters of the filelist call - * @param $renderer the renderer to use - * @param $level the level to render - * @return void - */ - public function _render_list_items($files, $basedir, $webdir, $params, Doku_Renderer $renderer, $level = 1) - { - global $conf; - - if ($params['style'] == 'olist') { - $renderer->listo_open(); - } else { - $renderer->listu_open(); - } - - foreach ($files as $file) { - if ($file['children'] !== false && $file['treesize'] > 0) { - // render the directory and its subtree - $renderer->listitem_open($level); - if ($this->is_odt_export) { - $renderer->p_open(); - } - $renderer->cdata($file['name']); - $this->_render_list_items($file['children'], $basedir, $webdir, $params, $renderer, $level + 1); - if ($this->is_odt_export) { - $renderer->p_close(); - } - $renderer->listitem_close(); - } elseif ($file['children'] === false) { - // open list item - $renderer->listitem_open($level); - if ($this->is_odt_export) { - $renderer->p_open(); - } - // render the preview image - if ($params['preview']) { - $this->_render_preview_image($file['path'], $basedir, $webdir, $params, $renderer); - } - // render the file link - $this->_render_link($file['name'], $file['path'], $basedir, $webdir, $params, $renderer); - // render filesize - if ($params['showsize']) { - $renderer->cdata($params['listsep'] . $this->_size_readable($file['size'], 'PiB', 'bi', '%01.1f %s')); - } - // render lastmodified - if ($params['showdate']) { - $renderer->cdata($params['listsep'] . strftime($conf['dformat'], $file['mtime'])); - } - // render lastmodified - if ($params['showcreator']) { - $renderer->cdata($params['listsep'] . $file['creator']); - } - // close list item - if ($this->is_odt_export) { - $renderer->p_close(); - } - $renderer->listitem_close(); - } else { - // ignore empty directories - continue; - } - } - - if ($params['style'] == 'olist') { - $renderer->listo_close(); - } else { - $renderer->listu_close(); - } - } - - /** - * Renders the files as a table, including details if configured that way. - * - * @param $result the filelist to render - * @param $params the parameters of the filelist call - * @param $renderer the renderer to use - * @return void - */ - public function _render_table($result, $params, $pos, Doku_Renderer $renderer) - { - global $conf; - - if (!$this->is_odt_export) { - $renderer->table_open(null, null, $pos); - } else { - $columns = 1; - if ($params['tableshowsize'] || $params['showsize']) { - $columns++; - } - if ($params['tableshowdate'] || $params['showdate']) { - $columns++; - } - if ($params['showcreator']) { - $columns++; - } - if ($params['preview']) { - $columns++; - } - $renderer->table_open($columns, null, $pos); - } - - if ($params['tableheader']) { - if ($this->is_odt_export) { - $renderer->tablerow_open(); - } - - $renderer->tableheader_open(); - $renderer->cdata($this->getLang('filename')); - $renderer->tableheader_close(); - - if ($params['tableshowsize'] || $params['showsize']) { - $renderer->tableheader_open(); - $renderer->cdata($this->getLang('filesize')); - $renderer->tableheader_close(); - } - - if ($params['tableshowdate'] || $params['showdate']) { - $renderer->tableheader_open(); - $renderer->cdata($this->getLang('lastmodified')); - $renderer->tableheader_close(); - } - - if ($params['showcreator']) { - $renderer->tableheader_open(); - $renderer->cdata($this->getLang('createdby')); - $renderer->tableheader_close(); - } - - if ($params['preview']) { - $renderer->tableheader_open(1, 'center', 1); - switch ($params['preview']) { - case 1: - $renderer->cdata($this->getLang('preview') . ' / ' . $this->getLang('filetype')); - break; - case 2: - $renderer->cdata($this->getLang('preview')); - break; - case 3: - $renderer->cdata($this->getLang('filetype')); - break; - } - $renderer->tableheader_close(); - } - - if ($this->is_odt_export) { - $renderer->tablerow_close(); - } - } - - foreach ($result['files'] as $file) { - $renderer->tablerow_open(); - $renderer->tablecell_open(); - $this->_render_link($file['name'], $file['path'], $result['basedir'], $result['webdir'], $params, $renderer); - $renderer->tablecell_close(); - - if ($params['tableshowsize'] || $params['showsize']) { - $renderer->tablecell_open(1, 'right'); - $renderer->cdata($this->_size_readable($file['size'], 'PiB', 'bi', '%01.1f %s')); - $renderer->tablecell_close(); - } - - if ($params['tableshowdate'] || $params['showdate']) { - $renderer->tablecell_open(); - $renderer->cdata(strftime($conf['dformat'], $file['mtime'])); - $renderer->tablecell_close(); - } - - if ($params['showcreator']) { - $renderer->tablecell_open(); - $renderer->cdata($file['creator']); - $renderer->tablecell_close(); - } - - if ($params['preview']) { - $renderer->tablecell_open(1, 'center', 1); - - $this->_render_preview_image($file['path'], $result['basedir'], $result['webdir'], $params, $renderer); - $renderer->tablecell_close(); - } - - $renderer->tablerow_close(); - } - $renderer->table_close($pos); - } - - /** - * Renders a page. - * - * @param $result the filelist to render - * @param $params the parameters of the filelist call - * @param $renderer the renderer to use - * @return void - */ - public function _render_page($result, $params, Doku_Renderer $renderer) - { - if (method_exists($renderer, 'getLastlevel') === false) { - $class_vars = get_class_vars(get_class($renderer)); - if ($class_vars ['lastlevel'] !== null) { - // Old releases before "hrun": $lastlevel is accessible - $lastlevel = $renderer->lastlevel + 1; - } else { - // Release "hrun" or newer without method 'getLastlevel()'. - // Lastlevel can't be determined. Workaroud: always use level 1. - $lastlevel = 1; - } - } else { - $lastlevel = $renderer->getLastlevel() + 1; - } - $this->_render_page_section($result['files'], $result['basedir'], $result['webdir'], $params, $renderer, $lastlevel); - } - - /** - * Recursively renders a tree of files as page sections using headlines. - * - * @param $files the files to render - * @param $basedir the basedir to use - * @param $webdir the webdir to use - * @param $params the parameters of the filelist call - * @param $renderer the renderer to use - * @param $level the level to render - * @return void - */ - public function _render_page_section($files, $basedir, $webdir, $params, Doku_Renderer $renderer, $level) - { - $trees = []; - $leafs = []; - - foreach ($files as $file) { - if ($file['children'] !== false) { - if ($file['treesize'] > 0) { - $trees[] = $file; - } - } else { - $leafs[] = $file; - } - } - - $this->_render_list_items($leafs, $basedir, $webdir, $params, $renderer); - - if ($level < 7) { - foreach ($trees as $tree) { - $renderer->header($tree['name'], $level, 0); - $renderer->section_open($level); - $this->_render_page_section($tree['children'], $basedir, $webdir, $params, $renderer, $level + 1); - $renderer->section_close(); - } - } else { - $this->_render_list_items($trees, $basedir, $webdir, $params, $renderer); - } - } - - /** - * Render a preview item for file $filepath. - * - * @param $filepath the file for which a preview image shall be rendered - * @param $basedir the basedir to use - * @param $webdir the webdir to use - * @param $params the parameters of the filelist call - * @param $renderer the renderer to use - * @return void - */ - protected function _render_preview_image($filepath, $basedir, $webdir, $params, Doku_Renderer $renderer) - { - $imagepath = $this->get_preview_image_path($filepath, $params, $isImage); - if (!empty($imagepath)) { - if ($isImage == false) { - // Generate link to returned filetype icon - $imgLink = $this->_get_link_url($imagepath, $basedir, $webdir, 0, 1); - } else { - // Generate link to image file - $imgLink = $this->_get_link_url($filepath, $basedir, $webdir, $params['randlinks'], $params['direct'], $params['ftp']); - } - - $previewsize = $params['previewsize']; - if ($previewsize == 0) { - $previewsize = 32; - } - $imgclass = ''; - if ($params['onhover']) { - $imgclass = 'class="filelist_preview"'; - } - - if (!$this->is_odt_export) { - $renderer->doc .= ''; - } else { - [$width, $height] = $renderer->_odtGetImageSize($imagepath, $previewsize, $previewsize); - $renderer->_odtAddImage($imagepath, $width . 'cm', $height . 'cm'); - } - } - } - - //~~ Filelist functions - - /** - * Creates the filelist based on the given glob-pattern and - * sorting and ordering parameters. - * - * @param $pattern the pattern - * @param $params the parameters of the filelist command - * @return a filelist data structure containing the found files and base- - * and webdir - */ - public function _create_filelist($pattern, $params) - { - global $conf; - global $ID; - - $allowed_absolute_paths = explode(',', $this->getConf('allowed_absolute_paths')); - - $result = ['files' => [], 'basedir' => false, 'webdir' => false]; - - // we don't want to use $conf['media'] here as that path has symlinks resolved - if (!$params['direct']) { - // if media path is not absolute, precede it with the current namespace - if ($pattern[0] != ':') { - $pattern = ':' . getNS($ID) . ':' . $pattern; - } - // replace : with / and prepend mediadir - $pattern = $this->mediadir . str_replace(':', '/', $pattern); - } elseif ($params['direct'] == 2) { - // treat path as relative to first configured path - $pattern = $allowed_absolute_paths[0] . '/' . $pattern; - } elseif (!$this->_path_is_absolute($pattern)) { - // if path is not absolute, precede it with DOKU_INC - $pattern = DOKU_INC . $pattern; - } - // get the canonicalized basedir (without resolving symlinks) - $dir = $this->_realpath($this->_win_path_convert(dirname($pattern))) . '/'; - - // if the directory does not exist, we of course have no matches - if (!$dir || !file_exists($dir)) { - return DOKU_PLUGIN_FILELIST_NOMATCH; - } - - // match pattern aginst allowed paths - $web_paths = explode(',', $this->getConf('web_paths')); - $basedir = false; - $webdir = false; - if (count($allowed_absolute_paths) === count($web_paths)) { - $counter = count($allowed_absolute_paths); - for ($i = 0; $i < $counter; $i++) { - $abs_path = $this->_win_path_convert(trim($allowed_absolute_paths[$i])); - if (strstr($dir, (string) $abs_path) == $dir) { - $basedir = $abs_path; - $webdir = trim($web_paths[$i]); - break; - } - } - } - - // $basedir is false if $dir was not in one of the allowed paths - if ($basedir === false) { - return DOKU_PLUGIN_FILELIST_OUTSIDEJAIL; - } - - // retrieve fileinformation - $result['basedir'] = $basedir; - $result['webdir'] = $webdir; - $result['files'] = $this->_crawl_files($this->_win_path_convert($pattern), $params); - if (!$result['files']) { - return DOKU_PLUGIN_FILELIST_NOMATCH; - } - - // flatten filelist if the displaymode is table - if ($params['style'] == 'table') { - $result['files'] = $this->_flatten_filelist($result['files']); - } - - // sort the list - $callback = false; - $reverseflag = false; - if ($params['sort'] == 'mtime') { - $callback = [$this, '_compare_mtimes']; - if ($params['order'] == 'asc') $reverseflag = true; - } elseif ($params['sort'] == 'ctime') { - $callback = [$this, '_compare_ctimes']; - if ($params['order'] == 'asc') $reverseflag = true; - } elseif ($params['sort'] == 'size') { - $callback = [$this, '_compare_sizes']; - if ($params['order'] == 'desc') $reverseflag = true; - } elseif ($params['sort'] == 'iname') { - $callback = [$this, '_compare_inames']; - if ($params['order'] == 'desc') $reverseflag = true; - } else { - $callback = [$this, '_compare_names']; - if ($params['order'] == 'desc') $reverseflag = true; - } - $this->_sort_filelist($result['files'], $callback, $reverseflag); - - // return the list - if (count($result['files']) > 0) - return $result; - else return DOKU_PLUGIN_FILELIST_NOMATCH; - } - - /** - * Recursively sorts the given tree using the given callback. Optionally - * reverses the sorted tree before returning it. - * - * @param $files the files to sort - * @param $callback the callback function to use for comparison - * @param $reverse true if the result is to be reversed - * @return the sorted tree - */ - public function _sort_filelist(&$files, $callback, $reverse) - { - // sort subtrees - $counter = count($files); - // sort subtrees - for ($i = 0; $i < $counter; $i++) { - if ($files[$i]['children'] !== false) { - $children = $files[$i]['children']; - $this->_sort_filelist($children, $callback, $reverse); - $files[$i]['children'] = $children; - } - } - - // sort current tree - usort($files, $callback); - if ($reverse) { - $files = array_reverse($files); - } - } - - /** - * Flattens the filelist by recursively walking through all subtrees and - * merging them with a prefix attached to the filenames. - * - * @param $files the tree to flatten - * @param $prefix the prefix to attach to all processed nodes - * @return a flattened representation of the tree - */ - public function _flatten_filelist($files, $prefix = '') - { - $result = []; - foreach ($files as $file) { - if ($file['children'] !== false) { - $result = array_merge($result, $this->_flatten_filelist($file['children'], $prefix . $file['name'] . '/')); - } else { - $file['name'] = $prefix . $file['name']; - $result[] = $file; - } - } - return $result; - } - - /** - * Filters out directories and their subtrees from the result. - * - * @param $result the result to filter - * @return the result without any directories contained therein, - * DOKU_PLUGIN_FILELIST_NOMATCH if there are no files left or - * the given result if it was not an array (but an errorcode) - */ - public function _filter_out_directories($result) - { - if (!is_array($result)) { - return $result; - } - - $filtered = []; - $files = $result['files']; - foreach ($files as $file) { - if ($file['children'] === false) { - $filtered[] = $file; - } - } - - if (count($filtered) == 0) { - return DOKU_PLUGIN_FILELIST_NOMATCH; - } else { - $result['files'] = $filtered; - return $result; - } - } - - /** - * Does a (recursive) crawl for finding files based on a given pattern. - * Based on a safe glob reimplementation using fnmatch and opendir. - * - * @param $pattern the pattern to match to - * @param params the parameters of the filelist call - * @return a hierarchical filelist or false if nothing could be found - * - * @see - */ - public function _crawl_files($pattern, $params) - { - $split = explode('/', $pattern); - $match = array_pop($split); - $path = implode('/', $split); - if (!is_dir($path)) { - return false; - } - - $ext = explode(',', $this->getConf('extensions')); - $ext = array_map('trim', $ext); - $ext = array_map('preg_quote_cb', $ext); - $ext = implode('|', $ext); - - if (($dir = opendir($path)) !== false) { - $result = []; - while (($file = readdir($dir)) !== false) { - if ($file == '.' || $file == '..') { - // ignore . and .. - continue; - } - if ($file == $params['titlefile']) { - // ignore the title file - continue; - } - if ($file[0] == '.') { - // ignore hidden files - continue; - } - $filepath = $path . '/' . $file; - - if ($this->_fnmatch($match, $file) || (is_dir($filepath) && $params['recursive'])) { - if (!is_dir($filepath) && !preg_match('/(' . $ext . ')$/i', $file)) { - continue; - } - - if (!$params['direct']) { - // exclude prohibited media files via ACLs - $mid = $this->_convert_mediapath($filepath); - $perm = auth_quickaclcheck($mid); - if ($perm < AUTH_READ) continue; - } elseif (!is_readable($filepath)) { - continue; - } - - $filename = $file; - if (is_dir($filepath)) { - $titlefile = $filepath . '/' . $params['titlefile']; - if (!$params['direct']) { - $mid = $this->_convert_mediapath($titlefile); - $perm = auth_quickaclcheck($mid); - if (is_readable($titlefile) && $perm >= AUTH_READ) { - $filename = io_readFile($titlefile, false); - } - } elseif (is_readable($titlefile)) { - $filename = io_readFile($titlefile, false); - } - } - - // prepare entry - $creator = ''; - if (!is_dir($filepath) || $params['recursive']) { - if (!$params['direct']) { - $medialog = new MediaChangeLog($mid); - $revinfo = $medialog->getRevisionInfo(@filemtime(fullpath(mediaFN($mid)))); - - if ($revinfo['user']) { - $creator = $revinfo['user']; - } else { - $creator = $revinfo['ip']; - } - } - if (empty($creator)) { - $creator = $this->getLang('creatorunknown'); - } - - $entry = ['name' => $filename, 'path' => $filepath, 'mtime' => filemtime($filepath), 'ctime' => filectime($filepath), 'size' => filesize($filepath), 'children' => ((is_dir($filepath) && $params['recursive']) ? $this->_crawl_files($filepath . '/' . $match, $params) : false), 'treesize' => 0, 'creator' => $creator]; - - // calculate tree size - if ($entry['children'] !== false) { - foreach ($entry['children'] as $child) { - $entry['treesize'] += $child['treesize']; - } - } else { - $entry['treesize'] = 1; - } - - // add entry to result - $result[] = $entry; - } - } - } - closedir($dir); - return $result; - } else { - return false; - } - } - - //~~ Comparators - - public function _compare_names($a, $b) - { - return strcmp($a['name'], $b['name']); - } - - public function _compare_inames($a, $b) - { - return strcmp(strtolower($a['name']), strtolower($b['name'])); - } - - public function _compare_ctimes($a, $b) - { - return $a['ctime'] <=> $b['ctime']; - } - - public function _compare_mtimes($a, $b) - { - return $a['mtime'] <=> $b['mtime']; - } - - public function _compare_sizes($a, $b) - { - return $a['size'] <=> $b['size']; - } - - //~~ Utility functions - - /** - * Canonicalizes a given path. A bit like realpath, but without the resolving of symlinks. - * - * @author anonymous - * @see - */ - public function _realpath($path) - { - $path = explode('/', $path); - $output = []; - $counter = count($path); - for ($i = 0; $i < $counter; $i++) { - if ('.' == $path[$i]) continue; - if ('..' == $path[$i] && '..' != $output[count($output) - 1]) { - array_pop($output); - continue; - } - $output[] = $path[$i]; - } - return implode('/', $output); - } - - /** - * Replacement for fnmatch() for windows systems. - * - * @author jk at ricochetsolutions dot com - * @see - */ - public function _fnmatch($pattern, $string) - { - return preg_match("#^" . strtr(preg_quote($pattern, '#'), ['\*' => '.*', '\?' => '.', '\[' => '[', '\]' => ']']) . "$#i", $string); - } - - /** - * Converts backslashs in paths to slashs. - * - * @param $path the path to convert - * @return the converted path - */ - public function _win_path_convert($path) - { - return str_replace('\\', '/', trim($path)); - } - - /** - * Return human readable sizes - * - * @param int $size size in bytes - * @param string $max maximum unit - * @param string $system 'si' for SI, 'bi' for binary prefixes - * @param string $retstring return string format - * @version 1.3.0 - * @link http://aidanlister.com/repos/v/function.size_readable.php - * @author Aidan Lister - */ - public function _size_readable($size, $max = null, $system = 'si', $retstring = '%01.2f %s') - { - // Pick units - $systems['si']['prefix'] = ['B', 'K', 'MB', 'GB', 'TB', 'PB']; - $systems['si']['size'] = 1000; - $systems['bi']['prefix'] = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']; - $systems['bi']['size'] = 1024; - $sys = $systems[$system] ?? $systems['si']; - - // Max unit to display - $depth = count($sys['prefix']) - 1; - if ($max && false !== $d = array_search($max, $sys['prefix'])) { - $depth = $d; - } - - // Loop - $i = 0; - while ($size >= $sys['size'] && $i < $depth) { - $size /= $sys['size']; - $i++; - } - - return sprintf($retstring, $size, $sys['prefix'][$i]); - } - - /** - * Determines whether a given path is absolute or relative. - * On windows plattforms, it does so by checking whether the second character - * of the path is a :, on all other plattforms it checks for a / as the - * first character. - * - * @param $path the path to check - * @return true if path is absolute, false otherwise - */ - public function _path_is_absolute($path) - { - if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { - if ($path[1] == ':' || ($path[0] == '/' && $path[1] == '/')) { - return true; - } - return false; - } else { - return ($path[0] == '/'); - } - } - - public function _convert_mediapath($path) - { - $mid = str_replace('/', ':', substr($path, strlen($this->mediadir))); // strip media base dir - return ltrim($mid, ':'); // strip leading : - } - - /** - * The function determines the preview image path for the given file - * depending on the file type and the 'preview' config option value: - * 1: Display file as preview image if itself is an image otherwise - * choose DokuWiki image corresponding to the file extension - * 2: Display file as preview image if itself is an image otherwise - * display no image - * 3. Display DokuWiki image corresponding to the file extension - * - * @param $filename the file to check - * @return string Image to use for preview image - */ - protected function get_preview_image_path($filename, $params, &$isImage) - { - [$ext, $mime] = mimetype(basename($filename)); - $imagepath = ''; - $isImage = false; - if ( - ($params['preview'] == 1 || $params['preview'] == 2) && - strncmp($mime, 'image', strlen('image')) == 0 - ) { - // The file is an image. Return itself as the image path. - $imagepath = $filename; - $isImage = true; - } - if ( - ($params['preview'] == 1 && empty($imagepath)) || - $params['preview'] == 3 - ) { - // No image. Return DokuWiki image for file extension. - if (!empty($ext)) { - $imagepath = DOKU_INC . 'lib/images/fileicons/32x32/' . $ext . '.png'; - } else { - $imagepath = DOKU_INC . 'lib/images/fileicons/32x32/file.png'; - } - } - return $imagepath; - } - - /** - * Create URL for file $filepath. - * - * @param $filepath the file for which a preview image shall be rendered - * @param $basedir the basedir to use - * @param $webdir the webdir to use - * @param $params the parameters of the filelist call - * @return string the generated URL - */ - protected function _get_link_url($filepath, $basedir, $webdir, $randlinks, $direct, $ftp = false) - { - $urlparams = ''; - if ($randlinks) { - $urlparams = '?' . time(); - } - if (!$direct) { - $url = ml(':' . $this->_convert_mediapath($filepath)) . $urlparams; - } else { - $url = $webdir . substr($filepath, strlen($basedir)) . $urlparams; - if ($ftp) { - $url = str_replace('\\', '/', $url); - if (strpos($url, 'http') === false) { - $url = 'ftp:' . $url; - } else { - $url = str_replace('http', 'ftp', $url); - } - } - } - return $url; - } } From 1eeb87d74f0d95e9b45b77fe7f7a8b6e96304e77 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 15:54:14 +0100 Subject: [PATCH 3/9] adjust tests This could really use some more tests but this has to suffice for now. --- Output.php | 2 +- Path.php | 12 +- _test/PathTest.php | 113 +++++++++++ _test/SyntaxTest.php | 195 +++++++++++++++++++ _test/filelist.test.php | 407 ---------------------------------------- syntax.php | 2 +- 6 files changed, 321 insertions(+), 410 deletions(-) create mode 100644 _test/PathTest.php create mode 100644 _test/SyntaxTest.php delete mode 100644 _test/filelist.test.php diff --git a/Output.php b/Output.php index be7b7ae..36d3174 100644 --- a/Output.php +++ b/Output.php @@ -210,7 +210,7 @@ class Output $link['title'] = $renderer->_xmlEntities($link['url']); if ($conf['relnofollow']) $link['more'] .= ' rel="nofollow"'; [$ext,] = mimetype(basename($item['local'])); - $link['class'] .= ' mediafile mf_' . $ext; + $link['class'] = 'media mediafile mf_' . $ext; $renderer->doc .= $renderer->_formatLink($link); } diff --git a/Path.php b/Path.php index 479c8a2..01c85a3 100644 --- a/Path.php +++ b/Path.php @@ -14,6 +14,16 @@ class Path $this->paths = $this->parsePathConfig($pathConfig); } + /** + * Access the parsed paths + * + * @return array + */ + public function getPaths() + { + return $this->paths; + } + /** * Parse the path configuration into an internal array * @@ -133,7 +143,7 @@ class Path for ($i = 0; $i < $counter; $i++) { if ('.' == $path[$i]) continue; if ('' === $path[$i] && $i > 0) continue; - if ('..' == $path[$i] && '..' != $output[count($output) - 1]) { + if ('..' == $path[$i] && '..' != ($output[count($output) - 1] ?? '')) { array_pop($output); continue; } diff --git a/_test/PathTest.php b/_test/PathTest.php new file mode 100644 index 0000000..c020094 --- /dev/null +++ b/_test/PathTest.php @@ -0,0 +1,113 @@ +path = new Path( + << alias + W> webfoo +EOT + ); + } + + /** + * Test the configuration parsing for paths and aliases + */ + public function testGetPaths() + { + $expect = [ + 'C:/xampp/htdocs/wiki/' => [ + 'root' => 'C:/xampp/htdocs/wiki/', + 'web' => '/lib/plugins/filelist/file.php?root=C%3A%2Fxampp%2Fhtdocs%2Fwiki%2F&file=', + ], + '\\\\server/share/path/' => [ + 'root' => '\\\\server/share/path/', + 'web' => '/lib/plugins/filelist/file.php?root=%5C%5Cserver%2Fshare%2Fpath%2F&file=', + ], + '/linux/file/path/' => [ + 'root' => '/linux/file/path/', + 'web' => '/lib/plugins/filelist/file.php?root=%2Flinux%2Ffile%2Fpath%2F&file=', + ], + '/linux/another/path/' => [ + 'root' => '/linux/another/path/', + 'alias' => 'alias/', + 'web' => 'webfoo', + ], + 'alias/' => [ + 'root' => '/linux/another/path/', + 'alias' => 'alias/', + 'web' => 'webfoo', + ], + ]; + + $this->assertEquals($expect, $this->path->getPaths()); + } + + /** + * Data provider for testGetPathInfoSuccess + */ + public function providePathInfoSuccess() + { + return [ + ['/linux/another/path', '/linux/another/path/'], + ['/linux/another/path/foo', '/linux/another/path/foo/'], + ['alias', '/linux/another/path/'], + ['alias/foo', '/linux/another/path/foo/'], + ['C:\\xampp\\htdocs\\wiki', 'C:/xampp/htdocs/wiki/'], + ['C:\\xampp\\htdocs\\wiki\\foo', 'C:/xampp/htdocs/wiki/foo/'], + ['\\\\server\\share\\path\\', '\\\\server/share/path/'], + ['\\\\server\\share\\path\\foo', '\\\\server/share/path/foo/'], + ]; + } + + /** + * @dataProvider providePathInfoSuccess + */ + public function testGetPathInfoSuccess($path, $expect) + { + $pathInfo = $this->path->getPathInfo($path); + $this->assertEquals($expect, $pathInfo['path']); + } + + public function providePathInfoFailure() + { + return [ + ['/linux/file/path/../../../etc/'], + ['W:\\xampp\\htdocs\\wiki\\foo\\bar'], + ['/'], + ['./'], + ['../'], + ]; + } + + /** + * @dataProvider providePathInfoFailure + */ + public function testGetPathInfoFailure($path) + { + $this->expectExceptionMessageMatches('/Path not allowed/'); + $this->path->getPathInfo($path); + } +} diff --git a/_test/SyntaxTest.php b/_test/SyntaxTest.php new file mode 100644 index 0000000..b19e23a --- /dev/null +++ b/_test/SyntaxTest.php @@ -0,0 +1,195 @@ +pluginsEnabled[] = 'filelist'; + parent::setUp(); + + // Setup config so that access to the TMP directory will be allowed + $conf ['plugin']['filelist']['paths'] = TMP_DIR . '/filelistdata/' . "\n" . 'W> http://localhost/'; + + } + + public static function setUpBeforeClass(): void + { + parent::setUpBeforeClass(); + + // copy test files to test directory + \TestUtils::rcopy(TMP_DIR, dirname(__FILE__) . '/filelistdata'); + } + + /** + * Run a list of checks on the given document + * + * @param Document $doc + * @param array $structure Array of selectors and expected count or content + * @return void + */ + protected function structureCheck(Document $doc, $structure) + { + foreach ($structure as $selector => $expected) { + if (is_numeric($expected)) { + $this->assertEquals( + $expected, + $doc->find($selector)->count(), + 'Selector ' . $selector . ' not found' + ); + } else { + $this->assertStringContainsString( + $expected, + $doc->find($selector)->text(), + 'Selector ' . $selector . ' not found' + ); + }; + } + } + + + /** + * This function checks that all files are listed in not recursive mode. + */ + public function test_not_recursive() + { + global $conf; + + // Render filelist + $instructions = p_get_instructions('{{filelist>' . TMP_DIR . '/filelistdata/*&style=list&direct=1}}'); + $xhtml = p_render('xhtml', $instructions, $info); + + // We should find: + // - example.txt + // - exampleimage.png + $result = strpos($xhtml, 'example.txt'); + $this->assertFalse($result === false, '"example.txt" not listed'); + $result = strpos($xhtml, 'exampleimage.png'); + $this->assertFalse($result === false, '"exampleimage.png" not listed'); + } + + /** + * This function checks that all files are listed in recursive mode. + */ + public function test_recursive() + { + // Render filelist + $instructions = p_get_instructions('{{filelist>' . TMP_DIR . '/filelistdata/*&style=list&direct=1&recursive=1}}'); + $xhtml = p_render('xhtml', $instructions, $info); + + // We should find: + // - exampledir + // - example2.txt + // - example.txt + // - exampleimage.png + $result = strpos($xhtml, 'exampledir'); + $this->assertFalse($result === false, '"exampledir" not listed'); + $result = strpos($xhtml, 'example2.txt'); + $this->assertFalse($result === false, '"example2.txt" not listed'); + $result = strpos($xhtml, 'example.txt'); + $this->assertFalse($result === false, '"example.txt" not listed'); + $result = strpos($xhtml, 'exampleimage.png'); + $this->assertFalse($result === false, '"exampleimage.png" not listed'); + } + + /** + * This function checks that the unordered list mode + * generates the expected XHTML structure. + */ + public function testUnorderedList() + { + // Render filelist + $instructions = p_get_instructions('{{filelist>' . TMP_DIR . '/filelistdata/*&style=list&direct=1&recursive=1}}'); + $xhtml = p_render('xhtml', $instructions, $info); + + $doc = new Document(); + $doc->html($xhtml); + + $structure = [ + 'div.filelist-plugin' => 1, + 'div.filelist-plugin > ul' => 1, + 'div.filelist-plugin > ul > li' => 3, + 'div.filelist-plugin > ul > li:nth-child(1)' => 1, + 'div.filelist-plugin > ul > li:nth-child(1) a' => 'example.txt', + 'div.filelist-plugin > ul > li:nth-child(2) ul' => 1, + 'div.filelist-plugin > ul > li:nth-child(2) ul > li' => 1, + 'div.filelist-plugin > ul > li:nth-child(2) ul > li a' => 'example2.txt', + ]; + + $this->structureCheck($doc, $structure); + } + + /** + * This function checks that the ordered list mode + * generates the expected XHTML structure. + */ + public function testOrderedList() + { + // Render filelist + $instructions = p_get_instructions('{{filelist>' . TMP_DIR . '/filelistdata/*&style=olist&direct=1&recursive=1}}'); + $xhtml = p_render('xhtml', $instructions, $info); + + $doc = new Document(); + $doc->html($xhtml); + + $structure = [ + 'div.filelist-plugin' => 1, + 'div.filelist-plugin > ol' => 1, + 'div.filelist-plugin > ol > li' => 3, + 'div.filelist-plugin > ol > li:nth-child(1)' => 1, + 'div.filelist-plugin > ol > li:nth-child(1) a' => 'example.txt', + 'div.filelist-plugin > ol > li:nth-child(2) ol' => 1, + 'div.filelist-plugin > ol > li:nth-child(2) ol > li' => 1, + 'div.filelist-plugin > ol > li:nth-child(2) ol > li a' => 'example2.txt', + ]; + + $this->structureCheck($doc, $structure); + } + + /** + * This function checks that the table mode + * generates the expected XHTML structure. + */ + public function test_table() + { + global $conf; + + // Render filelist + $instructions = p_get_instructions('{{filelist>' . TMP_DIR . '/filelistdata/*&style=table&direct=1&recursive=1}}'); + $xhtml = p_render('xhtml', $instructions, $info); + + $doc = new Document(); + $doc->html($xhtml); + + $structure = [ + 'div.filelist-plugin' => 1, + 'div.filelist-plugin table' => 1, + 'div.filelist-plugin table > tbody > tr' => 3, + 'div.filelist-plugin table > tbody > tr:nth-child(1) a' => 'example.txt', + 'div.filelist-plugin table > tbody > tr:nth-child(2) a' => 'exampledir/example2.txt', + 'div.filelist-plugin table > tbody > tr:nth-child(3) a' => 'exampleimage.png', + ]; + + $this->structureCheck($doc, $structure); + } +} diff --git a/_test/filelist.test.php b/_test/filelist.test.php deleted file mode 100644 index 3d6bea9..0000000 --- a/_test/filelist.test.php +++ /dev/null @@ -1,407 +0,0 @@ -pluginsEnabled[] = 'filelist'; - parent::setUp(); - - // Setup config so that access to the TMP directory will be allowed - $conf ['plugin']['filelist']['allowed_absolute_paths'] = TMP_DIR.'/filelistdata/'; - $conf ['plugin']['filelist']['web_paths'] = 'http://localhost/'; - } - - public static function setUpBeforeClass(){ - parent::setUpBeforeClass(); - - // copy test files to test directory - TestUtils::rcopy(TMP_DIR, dirname(__FILE__) . '/filelistdata'); - } - - /** - * This function checks that all files are listed in not recursive mode. - */ - public function test_not_recursive () { - global $conf; - - // Render filelist - $instructions = p_get_instructions('{{filelist>'.TMP_DIR.'/filelistdata/*&style=list&direct=1}}'); - $xhtml = p_render('xhtml', $instructions, $info); - - // We should find: - // - example.txt - // - exampleimage.png - $result = strpos ($xhtml, 'example.txt'); - $this->assertFalse($result===false, '"example.txt" not listed'); - $result = strpos ($xhtml, 'exampleimage.png'); - $this->assertFalse($result===false, '"exampleimage.png" not listed'); - } - - /** - * This function checks that all files are listed in recursive mode. - */ - public function test_recursive () { - global $conf; - - // Render filelist - $instructions = p_get_instructions('{{filelist>'.TMP_DIR.'/filelistdata/*&style=list&direct=1&recursive=1}}'); - $xhtml = p_render('xhtml', $instructions, $info); - - // We should find: - // - exampledir - // - example2.txt - // - example.txt - // - exampleimage.png - $result = strpos ($xhtml, 'exampledir'); - $this->assertFalse($result===false, '"exampledir" not listed'); - $result = strpos ($xhtml, 'example2.txt'); - $this->assertFalse($result===false, '"example2.txt" not listed'); - $result = strpos ($xhtml, 'example.txt'); - $this->assertFalse($result===false, '"example.txt" not listed'); - $result = strpos ($xhtml, 'exampleimage.png'); - $this->assertFalse($result===false, '"exampleimage.png" not listed'); - } - - /** - * This function checks that the unordered list mode - * generates the expected XHTML structure. - */ - public function test_list () { - global $conf; - - // Render filelist - $instructions = p_get_instructions('{{filelist>'.TMP_DIR.'/filelistdata/*&style=list&direct=1&recursive=1}}'); - $xhtml = p_render('xhtml', $instructions, $info); - - $doc = new DOMDocument(); - $doc->loadHTML($xhtml); - - $first = $doc->documentElement; - $this->assertEquals('html', $first->tagName); - - $children = $first->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('body', $children[0]->nodeName); - - // We should have 'div' first - $children = $children[0]->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('div', $children[0]->nodeName); - - // It should have the childs text, 'ol' - $children = $children[0]->childNodes; - $this->assertTrue($children->length==2); - $this->assertEquals('#text', $children[0]->nodeName); - $this->assertEquals('ul', $children[1]->nodeName); - - // The 'ol' element should have 3 'li' childs - $children = $children[1]->childNodes; - $this->assertTrue($children->length==6); - $this->assertEquals('li', $children[0]->nodeName); - $this->assertEquals('#text', $children[1]->nodeName); - $this->assertEquals('li', $children[2]->nodeName); - $this->assertEquals('#text', $children[3]->nodeName); - $this->assertEquals('li', $children[4]->nodeName); - $this->assertEquals('#text', $children[5]->nodeName); - - // First child of first 'li' should be the link to 'example.txt' - $node = $children[0]; - $node_childs = $node->childNodes; - $this->assertEquals('level1', $node->getAttribute('class')); - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example.txt', $node_childs[0]->nodeValue); - - // First child of second 'li' is directory 'exampledir' and another 'ol' - $node = $children[2]; - $node_childs = $node->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('#text', $node_childs[0]->nodeName); - $this->assertEquals('exampledir', $node_childs[0]->nodeValue); - $this->assertEquals('ul', $node_childs[1]->nodeName); - - // That 'ol' should have one 'li' with 'class=level2' - $node_childs = $node_childs[1]->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('li', $node_childs[0]->nodeName); - $this->assertEquals('level2', $node_childs[0]->getAttribute('class')); - $this->assertEquals('#text', $node_childs[1]->nodeName); - - // The link of that 'li' should reference 'example2.txt' - $node_childs = $node_childs[0]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example2.txt', $node_childs[0]->nodeValue); - - // First child of third 'li' should be the link to 'exampleimage.png' - $node = $children[4]; - $node_childs = $node->childNodes; - $this->assertEquals('level1', $node->getAttribute('class')); - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('exampleimage.png', $node_childs[0]->nodeValue); - } - - /** - * This function checks that the ordered list mode - * generates the expected XHTML structure. - */ - public function test_olist () { - global $conf; - - // Render filelist - $instructions = p_get_instructions('{{filelist>'.TMP_DIR.'/filelistdata/*&style=olist&direct=1&recursive=1}}'); - $xhtml = p_render('xhtml', $instructions, $info); - - $doc = new DOMDocument(); - $doc->loadHTML($xhtml); - - $first = $doc->documentElement; - $this->assertEquals('html', $first->tagName); - - $children = $first->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('body', $children[0]->nodeName); - - // We should have 'div' first - $children = $children[0]->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('div', $children[0]->nodeName); - - // It should have the childs text, 'ol' - $children = $children[0]->childNodes; - $this->assertTrue($children->length==2); - $this->assertEquals('#text', $children[0]->nodeName); - $this->assertEquals('ol', $children[1]->nodeName); - - // The 'ol' element should have 3 'li' childs - $children = $children[1]->childNodes; - $this->assertTrue($children->length==6); - $this->assertEquals('li', $children[0]->nodeName); - $this->assertEquals('#text', $children[1]->nodeName); - $this->assertEquals('li', $children[2]->nodeName); - $this->assertEquals('#text', $children[3]->nodeName); - $this->assertEquals('li', $children[4]->nodeName); - $this->assertEquals('#text', $children[5]->nodeName); - - // First child of first 'li' should be the link to 'example.txt' - $node = $children[0]; - $node_childs = $node->childNodes; - $this->assertEquals('level1', $node->getAttribute('class')); - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example.txt', $node_childs[0]->nodeValue); - - // First child of second 'li' is directory 'exampledir' and another 'ol' - $node = $children[2]; - $node_childs = $node->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('#text', $node_childs[0]->nodeName); - $this->assertEquals('exampledir', $node_childs[0]->nodeValue); - $this->assertEquals('ol', $node_childs[1]->nodeName); - - // That 'ol' should have one 'li' with 'class=level2' - $node_childs = $node_childs[1]->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('li', $node_childs[0]->nodeName); - $this->assertEquals('level2', $node_childs[0]->getAttribute('class')); - $this->assertEquals('#text', $node_childs[1]->nodeName); - - // The link of that 'li' should reference 'example2.txt' - $node_childs = $node_childs[0]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example2.txt', $node_childs[0]->nodeValue); - - // First child of third 'li' should be the link to 'exampleimage.png' - $node = $children[4]; - $node_childs = $node->childNodes; - $this->assertEquals('level1', $node->getAttribute('class')); - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('exampleimage.png', $node_childs[0]->nodeValue); - } - - /** - * This function checks that the page mode - * generates the expected XHTML structure. - */ - public function test_page () { - global $conf; - - // Render filelist - $instructions = p_get_instructions('{{filelist>'.TMP_DIR.'/filelistdata/*&style=page&direct=1&recursive=1}}'); - $xhtml = p_render('xhtml', $instructions, $info); - - $doc = new DOMDocument(); - $doc->loadHTML($xhtml); - - $first = $doc->documentElement; - $this->assertEquals('html', $first->tagName); - - $children = $first->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('body', $children[0]->nodeName); - - // We should have a 'ul', 'h1', '#test' and 'div' node - $children = $children[0]->childNodes; - $this->assertTrue($children->length==4); - $this->assertEquals('ul', $children[0]->nodeName); - $this->assertEquals('h1', $children[1]->nodeName); - $this->assertEquals('#text', $children[2]->nodeName); - $this->assertEquals('div', $children[3]->nodeName); - - // 'ul' should have the childs 'li', text, 'li', text - //$children = $children[0]->childNodes; - $node_childs = $children[0]->childNodes; - $this->assertTrue($children->length==4); - $this->assertEquals('li', $node_childs[0]->nodeName); - $this->assertEquals('#text', $node_childs[1]->nodeName); - $this->assertEquals('li', $node_childs[2]->nodeName); - $this->assertEquals('#text', $node_childs[3]->nodeName); - - // Check first 'li' contents - $node = $node_childs[0]; - $node_childs = $node->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example.txt', $node_childs[0]->nodeValue); - - // Check second 'li' contents - $node = $children[0]->childNodes; - $node_childs = $node[2]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('exampleimage.png', $node_childs[0]->nodeValue); - - // Check 'h1' contents - $node = $children[1]; - $this->assertEquals('h1', $node->nodeName); - $this->assertEquals('exampledir', $node->nodeValue); - - // Check 'div' contents - $node = $children[3]; - $this->assertEquals('div', $node->nodeName); - $this->assertEquals('level1', $node->getAttribute('class')); - - // Check 'div' childs - $node_childs = $node->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('#text', $node_childs[0]->nodeName); - $this->assertEquals('ul', $node_childs[1]->nodeName); - - // Check 'ul' childs, we should have 'li' - $node_childs = $node_childs[1]->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('li', $node_childs[0]->nodeName); - $this->assertEquals('#text', $node_childs[1]->nodeName); - - // The 'li' should have a 'a' - $node_childs = $node_childs[0]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example2.txt', $node_childs[0]->nodeValue); - } - - /** - * This function checks that the table mode - * generates the expected XHTML structure. - */ - public function test_table () { - global $conf; - - // Render filelist - $instructions = p_get_instructions('{{filelist>'.TMP_DIR.'/filelistdata/*&style=table&direct=1&recursive=1}}'); - $xhtml = p_render('xhtml', $instructions, $info); - - $doc = new DOMDocument(); - $doc->loadHTML($xhtml); - - $first = $doc->documentElement; - $this->assertEquals('html', $first->tagName); - - $children = $first->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('body', $children[0]->nodeName); - - // We should have a 'div' node - $children = $children[0]->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('div', $children[0]->nodeName); - $this->assertEquals('filelist-plugin', $children[0]->getAttribute('class')); - - // Check 'div' childs - $children = $children[0]->childNodes; - $this->assertTrue($children->length==3); - $this->assertEquals('#text', $children[0]->nodeName); - $this->assertEquals('div', $children[1]->nodeName); - $this->assertEquals('table sectionedit1', $children[1]->getAttribute('class')); - $this->assertEquals('#text', $children[2]->nodeName); - - // Check inner 'div' content - $children = $children[1]->childNodes; - $this->assertTrue($children->length==1); - $this->assertEquals('table', $children[0]->nodeName); - - // Check inner 'table' content - $children = $children[0]->childNodes; - $this->assertTrue($children->length==3); - $this->assertEquals('tr', $children[0]->nodeName); - $this->assertEquals('tr', $children[1]->nodeName); - $this->assertEquals('tr', $children[2]->nodeName); - - // Check table row 1 - $node_childs = $children[0]->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('td', $node_childs[0]->nodeName); - $this->assertEquals('#text', $node_childs[1]->nodeName); - - // Check table row 1/cell 1 content - $node_childs = $node_childs[0]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('example.txt', $node_childs[0]->nodeValue); - - // Check table row 2 - $node_childs = $children[1]->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('td', $node_childs[0]->nodeName); - $this->assertEquals('#text', $node_childs[1]->nodeName); - - // Check table row 2/cell 1 content - $node_childs = $node_childs[0]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('exampledir/example2.txt', $node_childs[0]->nodeValue); - - // Check table row 3 - $node_childs = $children[2]->childNodes; - $this->assertTrue($node_childs->length==2); - $this->assertEquals('td', $node_childs[0]->nodeName); - $this->assertEquals('#text', $node_childs[1]->nodeName); - - // Check table row 3/cell 1 content - $node_childs = $node_childs[0]->childNodes; - $this->assertTrue($node_childs->length==1); - $this->assertEquals('a', $node_childs[0]->nodeName); - $this->assertEquals('exampleimage.png', $node_childs[0]->nodeValue); - - /*print_r ($node_childs->children[1]); - foreach ($node_childs as $node) { - print ("\nTEST:".$node->nodeName." : ".$node->nodeValue."\n"); - }*/ - } -} diff --git a/syntax.php b/syntax.php index 4138dcf..efd95da 100644 --- a/syntax.php +++ b/syntax.php @@ -80,7 +80,7 @@ class syntax_plugin_filelist extends SyntaxPlugin 'ftp' => 0 ]; foreach ($flags as $flag) { - [$name, $value] = explode('=', $flag); + [$name, $value] = sexplode('=', $flag, 2, ''); $params[trim($name)] = trim(trim($value), '"'); // quotes can be use to keep whitespace } From 05f444a48767d0c1608632b322f6c25bd0e8c49b Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 15:57:33 +0100 Subject: [PATCH 4/9] style cleanup --- Crawler.php | 1 - Path.php | 12 +++++------- file.php | 3 ++- syntax.php | 14 +++++++++----- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/Crawler.php b/Crawler.php index 8fb777e..e8d4ccb 100644 --- a/Crawler.php +++ b/Crawler.php @@ -4,7 +4,6 @@ namespace dokuwiki\plugin\filelist; class Crawler { - /** @var string regexp to check extensions */ protected $ext; diff --git a/Path.php b/Path.php index 01c85a3..82944dc 100644 --- a/Path.php +++ b/Path.php @@ -46,7 +46,7 @@ class Path // this is an alias for the last read root $line = trim(substr($line, 2)); if (!isset($paths[$lastRoot])) continue; // no last root, no alias - $alias = $this->cleanPath($line); + $alias = static::cleanPath($line); $paths[$lastRoot]['alias'] = $alias; $paths[$alias] = &$paths[$lastRoot]; // alias references the original } elseif (str_starts_with($line, 'W>')) { @@ -56,11 +56,11 @@ class Path $paths[$lastRoot]['web'] = $line; } else { // this is a new path - $line = $this->cleanPath($line); + $line = static::cleanPath($line); $lastRoot = $line; $paths[$line] = [ 'root' => $line, - 'web' => DOKU_BASE . 'lib/plugins/filelist/file.php?root=' . rawurlencode($line).'&file=', + 'web' => DOKU_BASE . 'lib/plugins/filelist/file.php?root=' . rawurlencode($line) . '&file=', ]; } } @@ -78,13 +78,11 @@ class Path */ public function getPathInfo($path, $addTrailingSlash = true) { - $path = $this->cleanPath($path, $addTrailingSlash); + $path = static::cleanPath($path, $addTrailingSlash); $paths = $this->paths; $allowed = array_keys($paths); - usort($allowed, function ($a, $b) { - return strlen($a) - strlen($b); - }); + usort($allowed, static fn($a, $b) => strlen($a) - strlen($b)); $allowed = array_map('preg_quote_cb', $allowed); $regex = '/^(' . implode('|', $allowed) . ')/'; diff --git a/file.php b/file.php index e89049b..e3f5b9d 100644 --- a/file.php +++ b/file.php @@ -1,5 +1,7 @@ getMessage(); exit; } - diff --git a/syntax.php b/syntax.php index efd95da..86c2733 100644 --- a/syntax.php +++ b/syntax.php @@ -88,7 +88,7 @@ class syntax_plugin_filelist extends SyntaxPlugin $path = Path::cleanPath($path, false); $parts = explode('/', $path); $pattern = array_pop($parts); - $base = join('/', $parts) . '/'; + $base = implode('/', $parts) . '/'; return [$base, $pattern, $params]; } @@ -121,7 +121,14 @@ class syntax_plugin_filelist extends SyntaxPlugin $crawler = new Crawler($this->getConf('extensions')); $crawler->setSortBy($params['sort']); $crawler->setSortReverse($params['order'] === 'desc'); - $result = $crawler->crawl($pathInfo['root'], $pathInfo['local'], $pattern, $params['recursive'], $params['titlefile']); + + $result = $crawler->crawl( + $pathInfo['root'], + $pathInfo['local'], + $pattern, + $params['recursive'], + $params['titlefile'] + ); // if we got nothing back, display a message if ($result == []) { @@ -139,10 +146,7 @@ class syntax_plugin_filelist extends SyntaxPlugin case 'table': $output->renderAsTable($params); break; - } return true; - } - } From 75a1469d5acd0db35d19da370c314d4824b449e3 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 15:58:41 +0100 Subject: [PATCH 5/9] readme cleanup --- README | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/README b/README index fb3b0fc..c2327f4 100644 --- a/README +++ b/README @@ -1,9 +1,27 @@ -====== Filelist Plugin for DokuWiki ====== +filelist plugin for DokuWiki -All documentation for the Filelist Plugin is available online at: +Lists files matching a given glob pattern. - * https://dokuwiki.org/plugin:filelist +All documentation for this plugin can be found at +https://www.dokuwiki.org/plugin:filelist -(c) 2007 - 2012 by Gina Häußge -(c) 2012 - 2016 by Dokufreaks -See COPYING for license info. +If you install this plugin manually, make sure it is installed in +lib/plugins/filelist/ - if the folder is called different it +will not work! + +Please refer to http://www.dokuwiki.org/extensions for additional info +on how to install extensions in DokuWiki. + +---- +Copyright (C) Gina Häußge, Dokufreaks + +This program is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; version 2 of the License + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +See the LICENSING file for details From afea42266189e8303849e514a2898aaa57154d87 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 16:02:02 +0100 Subject: [PATCH 6/9] removed obsolete configs and language strings --- conf/default.php | 3 --- conf/metadata.php | 3 --- lang/de/lang.php | 4 ---- lang/de/settings.php | 2 -- lang/en/lang.php | 4 ---- lang/en/settings.php | 2 -- lang/nl/settings.php | 2 -- syntax.php | 12 ------------ 8 files changed, 32 deletions(-) diff --git a/conf/default.php b/conf/default.php index 9568f60..fc3e2af 100644 --- a/conf/default.php +++ b/conf/default.php @@ -5,9 +5,6 @@ */ $conf['paths'] = ''; - $conf['allow_in_comments'] = 0; -$conf['allowed_absolute_paths'] = DOKU_INC; -$conf['web_paths'] = DOKU_URL; $conf['defaults'] = ''; $conf['extensions'] = ''; diff --git a/conf/metadata.php b/conf/metadata.php index 4ae4b38..762f687 100644 --- a/conf/metadata.php +++ b/conf/metadata.php @@ -8,9 +8,6 @@ */ $meta['paths'] = array(''); - $meta['allow_in_comments'] = array('onoff'); -$meta['allowed_absolute_paths'] = array(''); -$meta['web_paths'] = array(''); $meta['defaults'] = array('string'); $meta['extensions'] = array('string'); diff --git a/lang/de/lang.php b/lang/de/lang.php index 9289c86..219d5ba 100644 --- a/lang/de/lang.php +++ b/lang/de/lang.php @@ -12,7 +12,3 @@ $lang['filesize'] = 'Dateigröße'; $lang['lastmodified'] = 'Letzte Änderung'; $lang['error_nomatch'] = 'Keine Treffer'; $lang['error_outsidejail'] = 'Zugriff verweigert'; -$lang['preview'] = 'Vorschau'; -$lang['filetype'] = 'Dateityp'; -$lang['createdby'] = 'Erstellt von'; -$lang['creatorunknown'] = 'Unbekannt'; diff --git a/lang/de/settings.php b/lang/de/settings.php index 03bd821..5fa1887 100644 --- a/lang/de/settings.php +++ b/lang/de/settings.php @@ -1,5 +1,3 @@ */ $lang['allow_in_comments'] = 'Of de filelist syntax toegestaan is voor gebruik in commentaar.'; -$lang['allowed_absolute_paths'] = 'Komma-gescheiden lijst van absolute zoekpaden.'; -$lang['web_paths'] = 'Komma-gescheiden lijst van urls waarop overeenkomende paden uit voorgaande lijst gevonden kunnen worden. Het aantal elementen MOET exact gelijk zijn aan dat van allowed_absolute_paths.'; $lang['defaults'] = 'Default options. Gebruik dezelfde syntax als de inline configuratie.'; $lang['extensions'] = 'Komma-gescheiden lijst van toegestane bestandsextensies voor de lijst.'; diff --git a/syntax.php b/syntax.php index 86c2733..e3cdb82 100644 --- a/syntax.php +++ b/syntax.php @@ -57,27 +57,15 @@ class syntax_plugin_filelist extends SyntaxPlugin $params = [ 'sort' => 'name', 'order' => 'asc', - 'index' => 0, - 'limit' => 0, - 'offset' => 0, 'style' => 'list', 'tableheader' => 0, - 'tableshowsize' => 0, - 'tableshowdate' => 0, - 'direct' => 0, 'recursive' => 0, 'titlefile' => '_title.txt', 'cache' => 0, 'randlinks' => 0, - 'preview' => 0, - 'previewsize' => 32, - 'link' => 2, 'showsize' => 0, 'showdate' => 0, - 'showcreator' => 0, 'listsep' => '", "', - 'onhover' => 0, - 'ftp' => 0 ]; foreach ($flags as $flag) { [$name, $value] = sexplode('=', $flag, 2, ''); From e9fa344990a6e9911b36e4f0f3d98f7a922480dc Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 16:03:09 +0100 Subject: [PATCH 7/9] removed obsolete javascript --- script.js | 50 -------------------------------------------------- 1 file changed, 50 deletions(-) delete mode 100644 script.js diff --git a/script.js b/script.js deleted file mode 100644 index 001241a..0000000 --- a/script.js +++ /dev/null @@ -1,50 +0,0 @@ -/* - * For Filelist Plugin - * - * @author joachimmueller - */ - -/* - * run on document load, setup everything we need - */ -jQuery(function () { - "use strict"; - - // CONFIG - - // these 2 variable determine popup's distance from the cursor - // you might want to adjust to get the right result - var xOffset = 10; - var yOffset = 30; - - // END CONFIG - - jQuery("img.filelist_preview").hover(function (e) { - this.t = this.title; - this.title = ""; - - var c; - if (this.t !== "") { - c = "
" + this.t; - } else { - c = ""; - } - jQuery("body").append("

Image preview" + c + "

"); - jQuery("#plugin__filelist_preview") - .css("top", (e.pageY - xOffset) + "px") - .css("left", (e.pageX + yOffset) + "px") - .css("max-width", "300px") - .css("max-height", "300px") - .css("position", "absolute") - .fadeIn("fast"); - }, function () { - this.title = this.t; - jQuery("#plugin__filelist_preview").remove(); - }); - jQuery("img.filelist_preview").mousemove(function (e) { - jQuery("#plugin__filelist_preview") - .css("top", (e.pageY - xOffset) + "px") - .css("left", (e.pageX + yOffset) + "px") - .css("position", "absolute"); - }); -}); From d64cc5d9b5d9444f79255bdc4d42a2a50895a2d1 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 16:04:21 +0100 Subject: [PATCH 8/9] added deleted.files --- deleted.files | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 deleted.files diff --git a/deleted.files b/deleted.files new file mode 100644 index 0000000..4e3ebab --- /dev/null +++ b/deleted.files @@ -0,0 +1,5 @@ +# This is a list of files that were present in previous releases +# but were removed later. They should not exist in your installation. +.travis.yml +_test/filelist.test.php +script.js From 1d52ebc3553e1c1de3e237e3c9f90f47568ca32b Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Tue, 27 Feb 2024 17:00:11 +0100 Subject: [PATCH 9/9] fix mail in plugin.info --- plugin.info.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugin.info.txt b/plugin.info.txt index cb40c3f..48b9be2 100644 --- a/plugin.info.txt +++ b/plugin.info.txt @@ -1,6 +1,6 @@ base filelist author Gina Häußge, Dokufreaks -email gina@foosel.net, freaks@dokuwiki.org +email freaks@dokuwiki.org date 2020-09-27 name Filelist Plugin desc Lists files matching a given glob pattern.