From c3413364e899c9a3fd349480069bbe9b8c803d5a Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 13:27:20 +0200 Subject: [PATCH 01/33] visibility,reformatting,use $INPUT,renaming, refactoring,phpdocs replace deprecated utf8 functions --- action.php | 1028 ++++++++++++++++++++++++++++------------------------ admin.php | 190 +++++----- 2 files changed, 646 insertions(+), 572 deletions(-) diff --git a/action.php b/action.php index 5f5bf12..3ba46b9 100644 --- a/action.php +++ b/action.php @@ -4,17 +4,59 @@ * @author Esther Brunner */ +use dokuwiki\Extension\Event; +use dokuwiki\Subscriptions\SubscriberManager; +use dokuwiki\Utf8\PhpString; + /** * Class action_plugin_discussion + * + * Data format of file metadir/.comments: + * array = [ + * 'status' => int whether comments are 0=disabled/1=open/2=closed, + * 'number' => int number of visible comments, + * 'title' => string alternative title for discussion section + * 'comments' => [ + * ''=> [ + * 'cid' => string comment id - long random string + * 'raw' => string comment text, + * 'xhtml' => string rendered html, + * 'parent' => null|string null or empty string at highest level, otherwise comment id of parent + * 'replies' => string[] array with comment ids + * 'user' => [ + * 'id' => string, + * 'name' => string, + * 'mail' => string, + * 'address' => string, + * 'url' => string + * ], + * 'date' => [ + * 'created' => int timestamp, + * 'modified' => int (not defined if not modified) + * ], + * 'show' => bool, whether shown (still be moderated, or hidden by moderator or user self) + * ], + * ... + * ] + * 'subscribers' => [ + * '' => [ + * 'hash' => string unique token, + * 'active' => bool, true if confirmed + * 'confirmsent' => bool, true if confirmation mail is sent + * ], + * ... + * ] */ class action_plugin_discussion extends DokuWiki_Action_Plugin{ /** @var helper_plugin_avatar */ - var $avatar = null; - var $style = null; - var $use_avatar = null; + protected $avatar = null; + /** @var null|string */ + protected $style = null; + /** @var null|bool */ + protected $useAvatar = null; /** @var helper_plugin_discussion */ - var $helper = null; + protected $helper = null; /** * load helper @@ -26,86 +68,20 @@ public function __construct() { /** * Register the handlers * - * @param Doku_Event_Handler $contr DokuWiki's event controller object. + * @param Doku_Event_Handler $controller DokuWiki's event controller object. */ - public function register(Doku_Event_Handler $contr) { - $contr->register_hook( - 'ACTION_ACT_PREPROCESS', - 'BEFORE', - $this, - 'handle_act_preprocess', - array() - ); - $contr->register_hook( - 'TPL_ACT_RENDER', - 'AFTER', - $this, - 'comments', - array() - ); - $contr->register_hook( - 'INDEXER_PAGE_ADD', - 'AFTER', - $this, - 'idx_add_discussion', - array('id' => 'page', 'text' => 'body') - ); - $contr->register_hook( - 'FULLTEXT_SNIPPET_CREATE', - 'BEFORE', - $this, - 'idx_add_discussion', - array('id' => 'id', 'text' => 'text') - ); - $contr->register_hook( - 'INDEXER_VERSION_GET', - 'BEFORE', - $this, - 'idx_version', - array() - ); - $contr->register_hook( - 'FULLTEXT_PHRASE_MATCH', - 'AFTER', - $this, - 'ft_phrase_match', - array() - ); - $contr->register_hook( - 'PARSER_METADATA_RENDER', - 'AFTER', - $this, - 'update_comment_status', - array() - ); - $contr->register_hook( - 'TPL_METAHEADER_OUTPUT', - 'BEFORE', - $this, - 'handle_tpl_metaheader_output', - array() - ); - $contr->register_hook( - 'TOOLBAR_DEFINE', - 'AFTER', - $this, - 'handle_toolbar_define', - array() - ); - $contr->register_hook( - 'AJAX_CALL_UNKNOWN', - 'BEFORE', - $this, - 'handle_ajax_call', - array() - ); - $contr->register_hook( - 'TPL_TOC_RENDER', - 'BEFORE', - $this, - 'handle_toc_render', - array() - ); + public function register(Doku_Event_Handler $controller) { + $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleCommentActions'); + $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'renderCommentsSection'); + $controller->register_hook('INDEXER_PAGE_ADD', 'AFTER', $this, 'addCommentsToIndex', ['id' => 'page', 'text' => 'body']); + $controller->register_hook('FULLTEXT_SNIPPET_CREATE', 'BEFORE', $this, 'addCommentsToIndex', ['id' => 'id', 'text' => 'text']); + $controller->register_hook('INDEXER_VERSION_GET', 'BEFORE', $this, 'addIndexVersion', []); + $controller->register_hook('FULLTEXT_PHRASE_MATCH', 'AFTER', $this, 'fulltextPhraseMatchInComments', []); + $controller->register_hook('PARSER_METADATA_RENDER', 'AFTER', $this, 'update_comment_status', []); + $controller->register_hook('TPL_METAHEADER_OUTPUT', 'BEFORE', $this, 'addToolbarToCommentfield', []); + $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'modifyToolbar', []); + $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'ajaxPreviewComments', []); + $controller->register_hook('TPL_TOC_RENDER', 'BEFORE', $this, 'addDiscussionToTOC', []); } /** @@ -116,16 +92,18 @@ public function register(Doku_Event_Handler $contr) { * @param Doku_Event $event * @param $params */ - public function handle_ajax_call(Doku_Event $event, $params) { + public function ajaxPreviewComments(Doku_Event $event, $params) { + global $INPUT; if($event->data != 'discussion_preview') return; + $event->preventDefault(); $event->stopPropagation(); print p_locale_xhtml('preview'); print '
'; - if(!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) { + if(!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) { print p_locale_xhtml('denied'); } else { - print $this->_render($_REQUEST['comment']); + print $this->renderComment($INPUT->post->str('comment')); } print '
'; } @@ -138,39 +116,40 @@ public function handle_ajax_call(Doku_Event $event, $params) { * @param Doku_Event $event * @param $params */ - public function handle_toc_render(Doku_Event $event, $params) { + public function addDiscussionToTOC(Doku_Event $event, $params) { global $ACT; - if($this->_hasDiscussion($title) && $event->data && $ACT != 'admin') { - $tocitem = array( 'hid' => 'discussion__section', + if($this->hasDiscussion($title) && $event->data && $ACT != 'admin') { + $tocitem = ['hid' => 'discussion__section', 'title' => $this->getLang('discussion'), 'type' => 'ul', - 'level' => 1 ); + 'level' => 1]; - array_push($event->data, $tocitem); + $event->data[] = $tocitem; } } /** - * Modify Tollbar for use with discussion plugin + * Modify Toolbar for use with discussion plugin * * @author Michael Klier * * @param Doku_Event $event * @param $param */ - public function handle_toolbar_define(Doku_Event $event, $param) { + public function modifyToolbar(Doku_Event $event, $param) { global $ACT; if($ACT != 'show') return; - if($this->_hasDiscussion($title) && $this->getConf('wikisyntaxok')) { - $toolbar = array(); + if($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) { + $toolbar = []; foreach($event->data as $btn) { if($btn['type'] == 'mediapopup') continue; if($btn['type'] == 'signature') continue; if($btn['type'] == 'linkwiz') continue; if($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin - if(preg_match("/=+?/", $btn['open'])) continue; - array_push($toolbar, $btn); + if(isset($btn['open']) && preg_match("/=+?/", $btn['open'])) continue; + + $toolbar[] = $btn; } $event->data = $toolbar; } @@ -184,19 +163,19 @@ public function handle_toolbar_define(Doku_Event $event, $param) { * @param Doku_Event $event * @param $param */ - public function handle_tpl_metaheader_output(Doku_Event $event, $param) { + public function addToolbarToCommentfield(Doku_Event $event, $param) { global $ACT; global $ID; if($ACT != 'show') return; - if($this->_hasDiscussion($title) && $this->getConf('wikisyntaxok')) { + if($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) { // FIXME ugly workaround, replace this once DW the toolbar code is more flexible @require_once(DOKU_INC.'inc/toolbar.php'); ob_start(); print 'NS = "' . getNS($ID) . '";'; // we have to define NS, otherwise we get get JS errors toolbar_JSdefines('toolbar'); $script = ob_get_clean(); - array_push($event->data['script'], array('type' => 'text/javascript', 'charset' => "utf-8", '_data' => $script)); + $event->data['script'][] = ['type' => 'text/javascript', 'charset' => "utf-8", '_data' => $script]; } } @@ -205,109 +184,115 @@ public function handle_tpl_metaheader_output(Doku_Event $event, $param) { * * @param Doku_Event $event * @param $param - * @return bool + * @return void */ - public function handle_act_preprocess(Doku_Event $event, $param) { - global $ID; - global $INFO; - global $lang; + public function handleCommentActions(Doku_Event $event, $param) { + global $ID, $INFO, $lang, $INPUT; // handle newthread ACTs if ($event->data == 'newthread') { // we can handle it -> prevent others - $event->data = $this->_newThread(); + $event->data = $this->newThread(); } // enable captchas - if (in_array($_REQUEST['comment'], array('add', 'save'))) { - $this->_captchaCheck(); - $this->_recaptchaCheck(); + if (in_array($INPUT->str('comment'), ['add', 'save'])) { + $this->captchaCheck(); + $this->recaptchaCheck(); } // if we are not in show mode or someone wants to unsubscribe, that was all for now - if ($event->data != 'show' && $event->data != 'discussion_unsubscribe' && $event->data != 'discussion_confirmsubscribe') return; + if ($event->data != 'show' + && $event->data != 'discussion_unsubscribe' + && $event->data != 'discussion_confirmsubscribe') { + return; + } if ($event->data == 'discussion_unsubscribe' or $event->data == 'discussion_confirmsubscribe') { - if (!isset($_REQUEST['hash'])) { - return; - } else { + if ($INPUT->has('hash')) { $file = metaFN($ID, '.comments'); $data = unserialize(io_readFile($file)); - $themail = ''; - foreach($data['subscribers'] as $mail => $info) { + $matchedMail = ''; + foreach ($data['subscribers'] as $mail => $info) { // convert old style subscribers just in case - if(!is_array($info)) { + if (!is_array($info)) { $hash = $data['subscribers'][$mail]; - $data['subscribers'][$mail]['hash'] = $hash; + $data['subscribers'][$mail]['hash'] = $hash; $data['subscribers'][$mail]['active'] = true; $data['subscribers'][$mail]['confirmsent'] = true; } - if ($data['subscribers'][$mail]['hash'] == $_REQUEST['hash']) { - $themail = $mail; + if ($data['subscribers'][$mail]['hash'] == $INPUT->str('hash')) { + $matchedMail = $mail; } } - if($themail != '') { - if($event->data == 'discussion_unsubscribe') { - unset($data['subscribers'][$themail]); - msg(sprintf($lang['subscr_unsubscribe_success'], $themail, $ID), 1); - } elseif($event->data == 'discussion_confirmsubscribe') { - $data['subscribers'][$themail]['active'] = true; - msg(sprintf($lang['subscr_subscribe_success'], $themail, $ID), 1); + if ($matchedMail != '') { + if ($event->data == 'discussion_unsubscribe') { + unset($data['subscribers'][$matchedMail]); + msg(sprintf($lang['subscr_unsubscribe_success'], $matchedMail, $ID), 1); + } else { //$event->data == 'discussion_confirmsubscribe' + $data['subscribers'][$matchedMail]['active'] = true; + msg(sprintf($lang['subscr_subscribe_success'], $matchedMail, $ID), 1); } io_saveFile($file, serialize($data)); $event->data = 'show'; } - return; } + return; } else { // do the data processing for comments - $cid = $_REQUEST['cid']; - switch ($_REQUEST['comment']) { + $cid = $INPUT->str('cid'); + switch ($INPUT->str('comment')) { case 'add': - if(empty($_REQUEST['text'])) return; // don't add empty comments - if(isset($_SERVER['REMOTE_USER']) && !$this->getConf('adminimport')) { - $comment['user']['id'] = $_SERVER['REMOTE_USER']; + if(empty($INPUT->str('text'))) return; // don't add empty comments + + if($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) { + $comment['user']['id'] = $INPUT->server->str('REMOTE_USER'); $comment['user']['name'] = $INFO['userinfo']['name']; $comment['user']['mail'] = $INFO['userinfo']['mail']; - } elseif((isset($_SERVER['REMOTE_USER']) && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) || !isset($_SERVER['REMOTE_USER'])) { - if(empty($_REQUEST['name']) or empty($_REQUEST['mail'])) return; // don't add anonymous comments - if(!mail_isvalid($_REQUEST['mail'])) { + } elseif(($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) + || !$INPUT->server->has('REMOTE_USER')) { + // don't add anonymous comments + if(empty($INPUT->str('name')) or empty($INPUT->str('mail'))) { + return; + } + + if(!mail_isvalid($INPUT->str('mail'))) { msg($lang['regbadmail'], -1); return; } else { - $comment['user']['id'] = 'test'.hsc($_REQUEST['user']); - $comment['user']['name'] = hsc($_REQUEST['name']); - $comment['user']['mail'] = hsc($_REQUEST['mail']); + $comment['user']['id'] = 'test'.hsc($INPUT->str('user')); + $comment['user']['name'] = hsc($INPUT->str('name')); + $comment['user']['mail'] = hsc($INPUT->str('mail')); } } - $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($_REQUEST['address']) : ''; - $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->_checkURL($_REQUEST['url']) : ''; - $comment['subscribe'] = ($this->getConf('subscribe')) ? $_REQUEST['subscribe'] : ''; - $comment['date'] = array('created' => $_REQUEST['date']); - $comment['raw'] = cleanText($_REQUEST['text']); - $repl = $_REQUEST['reply']; + $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : ''; + $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : ''; + $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : ''; + $comment['date'] = ['created' => $INPUT->str('date')]; + $comment['raw'] = cleanText($INPUT->str('text')); + $reply = $INPUT->str('reply'); if($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { $comment['show'] = false; } else { $comment['show'] = true; } - $this->_add($comment, $repl); + $this->add($comment, $reply); break; case 'save': - $raw = cleanText($_REQUEST['text']); - $this->save(array($cid), $raw); + $raw = cleanText($INPUT->str('text')); + $this->save([$cid], $raw); break; case 'delete': - $this->save(array($cid), ''); + $this->save([$cid], ''); break; case 'toogle': - $this->save(array($cid), '', 'toogle'); + $this->save([$cid], '', 'toogle'); break; } } @@ -316,19 +301,23 @@ public function handle_act_preprocess(Doku_Event $event, $param) { /** * Main function; dispatches the visual comment actions */ - public function comments(Doku_Event $event, $param) { + public function renderCommentsSection(Doku_Event $event, $param) { + global $INPUT; if ($event->data != 'show') return; // nothing to do for us - $cid = $_REQUEST['cid']; + $cid = $INPUT->str('cid'); + if(!$cid) { - $cid = $_REQUEST['reply']; + $cid = $INPUT->str('reply'); } - switch ($_REQUEST['comment']) { + var_dump($cid); + var_dump($INPUT->str('comment')); + switch ($INPUT->str('comment')) { case 'edit': - $this->_show(NULL, $cid); + $this->showDiscussionSection(null, $cid); break; - default: - $this->_show($cid); + default: //'reply' or no action specifiec + $this->showDiscussionSection($cid); break; } } @@ -336,7 +325,7 @@ public function comments(Doku_Event $event, $param) { /** * Redirects browser to given comment anchor */ - protected function _redirect($cid) { + protected function redirect($cid) { global $ID; global $ACT; @@ -391,23 +380,30 @@ public function isDiscussionEnabled() { } /** - * Shows all comments of the current page + * Shows all comments of the current page, if no reply or edit requested, then comment form is shown on the end + * + * @param null|string $reply comment id on which the user requested a reply + * @param null|string $edit comment id which the user requested for editing */ - protected function _show($reply = null, $edit = null) { - global $ID; - global $INFO; + protected function showDiscussionSection($reply = null, $edit = null) { + global $ID, $INFO, $INPUT; // get .comments meta file name $file = metaFN($ID, '.comments'); - if (!$INFO['exists']) return false; - if (!@file_exists($file) && !$this->isDiscussionEnabled()) return false; - if (!$_SERVER['REMOTE_USER'] && !$this->getConf('showguests')) return false; + if (!$INFO['exists']) return; + if (!@file_exists($file) && !$this->isDiscussionEnabled()) return; + if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('showguests')) return; // load data + $data = []; if (@file_exists($file)) { $data = unserialize(io_readFile($file, false)); - if (!$data['status']) return false; // comments are turned off + // comments are turned off + if (!$data['status']) { + return; + } + var_dump($data); } elseif (!@file_exists($file) && $this->isDiscussionEnabled() && $INFO['exists']) { // set status to show the comment form $data['status'] = 1; @@ -415,13 +411,17 @@ protected function _show($reply = null, $edit = null) { } // show discussion wrapper only on certain circumstances - $cnt = empty($data['comments']) ? 0 : count($data['comments']); - $keys = []; - if (is_array($data['comments'])){ - $keys = @array_keys($data['comments']); + if(empty($data['comments']) || !is_array($data['comments'])) { + $cnt = 0; + $keys = []; + } else { + $cnt = count($data['comments']); + $keys = array_keys($data['comments']); } + $show = false; - if($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) || $this->getConf('allowguests') || isset($_SERVER['REMOTE_USER'])) { + if($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) + || $this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER')) { $show = true; // section title $title = ($data['title'] ? hsc($data['title']) : $this->getLang('discussion')); @@ -435,49 +435,55 @@ protected function _show($reply = null, $edit = null) { // now display the comments if (isset($data['comments'])) { if (!$this->getConf('usethreading')) { - $data['comments'] = $this->_flattenThreads($data['comments']); - uasort($data['comments'], '_sortCallback'); + $data['comments'] = $this->flattenThreads($data['comments']); + uasort($data['comments'], [$this, 'sortCallback']); } if($this->getConf('newestfirst')) { $data['comments'] = array_reverse($data['comments']); } - foreach ($data['comments'] as $key => $value) { - if ($key == $edit) $this->_form($value['raw'], 'save', $edit); // edit form - else $this->_print($key, $data, '', $reply); + foreach ($data['comments'] as $cid => $value) { + if ($cid == $edit) { // edit form + $this->showCommentForm($value['raw'], 'save', $edit); + } else { + $this->showCommentWithReplies($cid, $data, '', $reply); + } } } - // comment form - if (($data['status'] == 1) && (!$reply || !$this->getConf('usethreading')) && !$edit) $this->_form(''); + // comment form shown on the end, if no comment form of $reply or $edit is requested before + if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) { + $this->showCommentForm(''); + } if($show) { ptln('', 2); // level2 hfeed ptln(''); // comment_wrapper } - + // check for toggle print configuration - if($this->getConf('visibilityButton')) { + if($this->getConf('visibilityButton')) { // print the hide/show discussion section button - $this->_print_toggle_button(); + $this->showDiscussionToggleButton(); } - - return true; } /** - * @param array $comments - * @param null|array $keys - * @return array + * Remove the parent-child relation, such that the comment structure becomes flat + * + * @param array $comments array with all comments + * @param null|array $cids comment ids of replies, which should be flatten + * @return array returned array with flattened comment structure */ - protected function _flattenThreads($comments, $keys = null) { - if (is_null($keys)) - $keys = array_keys($comments); + protected function flattenThreads($comments, $cids = null) { + if (is_null($cids)) { + $cids = array_keys($comments); + } - foreach($keys as $cid) { + foreach($cids as $cid) { if (!empty($comments[$cid]['replies'])) { $rids = $comments[$cid]['replies']; - $comments = $this->_flattenThreads($comments, $rids); - $comments[$cid]['replies'] = array(); + $comments = $this->flattenThreads($comments, $rids); + $comments[$cid]['replies'] = []; } $comments[$cid]['parent'] = ''; } @@ -487,15 +493,25 @@ protected function _flattenThreads($comments, $keys = null) { /** * Adds a new comment and then displays all comments * - * @param array $comment - * @param string $parent + * @param array $comment with + * 'raw' => string comment text, + * 'user' => [ + * 'id' => string, + * 'name' => string, + * 'mail' => string + * ], + * 'date' => [ + * 'created' => int timestamp + * ] + * 'show' => bool + * 'subscribe' => bool + * @param string $parent comment id of parent * @return bool */ - protected function _add($comment, $parent) { - global $ID; - global $TEXT; + protected function add($comment, $parent) { + global $ID, $TEXT, $INPUT; - $otxt = $TEXT; // set $TEXT to comment text for wordblock check + $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check $TEXT = $comment['raw']; // spamcheck against the DokuWiki blacklist @@ -504,24 +520,27 @@ protected function _add($comment, $parent) { return false; } - if ((!$this->getConf('allowguests')) - && ($comment['user']['id'] != $_SERVER['REMOTE_USER']) + if (!$this->getConf('allowguests') + && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER') ) { return false; // guest comments not allowed } - $TEXT = $otxt; // restore global $TEXT + $TEXT = $originalTxt; // restore global $TEXT // get discussion meta file name $file = metaFN($ID, '.comments'); // create comments file if it doesn't exist yet if(!@file_exists($file)) { - $data = array('status' => 1, 'number' => 0); + $data = ['status' => 1, 'number' => 0]; io_saveFile($file, serialize($data)); } else { $data = unserialize(io_readFile($file, false)); - if ($data['status'] != 1) return false; // comments off or closed + // comments off or closed + if ($data['status'] != 1) { + return false; + } } if ($comment['date']['created']) { @@ -537,22 +556,22 @@ protected function _add($comment, $parent) { $cid = md5($comment['user']['id'].$date); // create a unique id if (!is_array($data['comments'][$parent])) { - $parent = NULL; // invalid parent comment + $parent = null; // invalid parent comment } // render the comment - $xhtml = $this->_render($comment['raw']); + $xhtml = $this->renderComment($comment['raw']); // fill in the new comment - $data['comments'][$cid] = array( + $data['comments'][$cid] = [ 'user' => $comment['user'], - 'date' => array('created' => $date), + 'date' => ['created' => $date], 'raw' => $comment['raw'], 'xhtml' => $xhtml, 'parent' => $parent, - 'replies' => array(), + 'replies' => [], 'show' => $comment['show'] - ); + ]; if($comment['subscribe']) { $mail = $comment['user']['mail']; @@ -587,28 +606,28 @@ protected function _add($comment, $parent) { // notify subscribers of the page $data['comments'][$cid]['cid'] = $cid; - $this->_notify($data['comments'][$cid], $data['subscribers']); + $this->notify($data['comments'][$cid], $data['subscribers']); // save the comment metadata file io_saveFile($file, serialize($data)); - $this->_addLogEntry($date, $ID, 'cc', '', $cid); + $this->addLogEntry($date, $ID, 'cc', '', $cid); - $this->_redirect($cid); + $this->redirect($cid); return true; } /** * Saves the comment with the given ID and then displays all comments * - * @param array|string $cids - * @param string $raw - * @param string $act - * @return bool + * @param array|string $cids array with comment ids to save, or a single string comment id + * @param string $raw if empty comment is deleted, otherwise edited text is stored (note: storing is per one cid!) + * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw + * @return bool succeed? */ - public function save($cids, $raw, $act = NULL) { - global $ID; + public function save($cids, $raw, $act = null) { + global $ID, $INPUT; - if(!$cids) return false; // do nothing if we get no comment id + if(empty($cids)) return false; // do nothing if we get no comment id if ($raw) { global $TEXT; @@ -629,7 +648,9 @@ public function save($cids, $raw, $act = NULL) { $file = metaFN($ID, '.comments'); $data = unserialize(io_readFile($file, false)); - if (!is_array($cids)) $cids = array($cids); + if (!is_array($cids)) { + $cids = [$cids]; + } foreach ($cids as $cid) { if (is_array($data['comments'][$cid]['user'])) { @@ -641,51 +662,53 @@ public function save($cids, $raw, $act = NULL) { } // someone else was trying to edit our comment -> abort - if (($user != $_SERVER['REMOTE_USER']) && (!$this->helper->isDiscussionMod())) return false; + if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionMod()) { + return false; + } $date = time(); // need to convert to new format? if ($convert) { - $data['comments'][$cid]['user'] = array( + $data['comments'][$cid]['user'] = [ 'id' => $user, 'name' => $data['comments'][$cid]['name'], 'mail' => $data['comments'][$cid]['mail'], 'url' => $data['comments'][$cid]['url'], 'address' => $data['comments'][$cid]['address'], - ); - $data['comments'][$cid]['date'] = array( + ]; + $data['comments'][$cid]['date'] = [ 'created' => $data['comments'][$cid]['date'] - ); + ]; } if ($act == 'toogle') { // toogle visibility $now = $data['comments'][$cid]['show']; $data['comments'][$cid]['show'] = !$now; - $data['number'] = $this->_count($data); + $data['number'] = $this->countVisibleComments($data); $type = ($data['comments'][$cid]['show'] ? 'sc' : 'hc'); } elseif ($act == 'show') { // show comment $data['comments'][$cid]['show'] = true; - $data['number'] = $this->_count($data); + $data['number'] = $this->countVisibleComments($data); $type = 'sc'; // show comment } elseif ($act == 'hide') { // hide comment $data['comments'][$cid]['show'] = false; - $data['number'] = $this->_count($data); + $data['number'] = $this->countVisibleComments($data); $type = 'hc'; // hide comment } elseif (!$raw) { // remove the comment - $data['comments'] = $this->_removeComment($cid, $data['comments']); - $data['number'] = $this->_count($data); + $data['comments'] = $this->removeComment($cid, $data['comments']); + $data['number'] = $this->countVisibleComments($data); $type = 'dc'; // delete comment } else { // save changed comment - $xhtml = $this->_render($raw); + $xhtml = $this->renderComment($raw); // now change the comment's content $data['comments'][$cid]['date']['modified'] = $date; @@ -698,19 +721,23 @@ public function save($cids, $raw, $act = NULL) { // save the comment metadata file io_saveFile($file, serialize($data)); - $this->_addLogEntry($date, $ID, $type, '', $cid); + $this->addLogEntry($date, $ID, $type, '', $cid); - $this->_redirect($cid); + $this->redirect($cid); return true; } /** - * Recursive function to remove a comment + * Recursive function to remove a comment from the data array + * + * @param string $cid comment id to be removed + * @param array $comments array with all comments + * @return array returns modified array with all remaining comments */ - protected function _removeComment($cid, $comments) { + protected function removeComment($cid, $comments) { if (is_array($comments[$cid]['replies'])) { foreach ($comments[$cid]['replies'] as $rid) { - $comments = $this->_removeComment($rid, $comments); + $comments = $this->removeComment($rid, $comments); } } unset($comments[$cid]); @@ -720,47 +747,60 @@ protected function _removeComment($cid, $comments) { /** * Prints an individual comment * - * @param string $cid - * @param array $data - * @param string $parent - * @param string $reply - * @param bool $visible - * @return bool + * @param string $cid comment id + * @param array $data array with all comments by reference + * @param string $parent comment id of parent + * @param string $reply comment id on which the user requested a reply + * @param bool $isVisible is marked as visible */ - protected function _print($cid, &$data, $parent = '', $reply = '', $visible = true) { - if (!isset($data['comments'][$cid])) return false; // comment was removed + protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true) { + // comment was removed + if (!isset($data['comments'][$cid])) { + return; + } $comment = $data['comments'][$cid]; - if (!is_array($comment)) return false; // corrupt datatype + // corrupt datatype + if (!is_array($comment)) { + return; + } - if ($comment['parent'] != $parent) return true; // reply to an other comment + // handle only replies to given parent comment + if ($comment['parent'] != $parent) { + return; + } - if (!$comment['show']) { // comment hidden - if ($this->helper->isDiscussionMod()) $hidden = ' comment_hidden'; - else return true; + // comment hidden + if (!$comment['show']) { + if ($this->helper->isDiscussionMod()) { + $hidden = ' comment_hidden'; + } else { + return; + } } else { $hidden = ''; } // print the actual comment - $this->_print_comment($cid, $data, $parent, $reply, $visible, $hidden); + $this->showComment($cid, $data, $parent, $reply, $isVisible, $hidden); // replies to this comment entry? - $this->_print_replies($cid, $data, $reply, $visible); + $this->showReplies($cid, $data, $reply, $isVisible); // reply form - $this->_print_form($cid, $reply); - return true; + $this->showReplyForm($cid, $reply); } /** - * @param $cid - * @param $data - * @param $parent - * @param $reply - * @param $visible - * @param $hidden + * Print the comment + * + * @param string $cid comment id + * @param array $data array with all comments by reference + * @param string $parent comment id of parent + * @param string $reply comment id on which the user requested a reply + * @param bool $isVisible is marked as visible + * @param string $hidden extra class, for the admin only hidden view */ - protected function _print_comment($cid, &$data, $parent, $reply, $visible, $hidden) { - global $conf, $lang, $HIGH; + protected function showComment($cid, &$data, $parent, $reply, $isVisible, $hidden) { + global $conf, $lang, $HIGH, $INPUT; $comment = $data['comments'][$cid]; // comment head with date and user data @@ -785,32 +825,34 @@ protected function _print_comment($cid, &$data, $parent, $reply, $visible, $hidd } if (is_array($comment['date'])) { // new format $created = $comment['date']['created']; - $modified = $comment['date']['modified']; + $modified = $comment['date']['modified'] ?: null; } else { // old format $created = $comment['date']; $modified = $comment['edited']; } // show username or real name? - if ((!$this->getConf('userealname')) && ($user)) { + if (!$this->getConf('userealname') && $user) { $showname = $user; } else { $showname = $name; } // show avatar image? - if ($this->_use_avatar()) { + if ($this->useAvatar()) { $user_data['name'] = $name; $user_data['user'] = $user; $user_data['mail'] = $mail; $avatar = $this->avatar->getXHTML($user_data, $name, 'left'); - if($avatar) $head .= $avatar; + if($avatar) { + $head .= $avatar; + } } if ($this->getConf('linkemail') && $mail) { $head .= $this->email($mail, $showname, 'email fn'); } elseif ($url) { - $head .= $this->external_link($this->_checkURL($url), $showname, 'urlextern url fn'); + $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn'); } else { $head .= ''.$showname.''; } @@ -831,26 +873,27 @@ protected function _print_comment($cid, &$data, $parent, $reply, $visible, $hidd // main comment content ptln('
_use_avatar() ? $this->_get_style() : '').'>', 6); + ($this->useAvatar() ? $this->getWidthStyle() : '').'>', 6); echo ($HIGH?html_hilight($comment['xhtml'],$HIGH):$comment['xhtml']).DOKU_LF; ptln('
', 6); // class="comment_body" - if ($visible) { + if ($isVisible) { ptln('
', 6); // show reply button? - if (($data['status'] == 1) && !$reply && $comment['show'] - && ($this->getConf('allowguests') || $_SERVER['REMOTE_USER']) && $this->getConf('usethreading') + if ($data['status'] == 1 && !$reply && $comment['show'] + && ($this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER')) + && $this->getConf('usethreading') ) { - $this->_button($cid, $this->getLang('btn_reply'), 'reply', true); + $this->showButton($cid, $this->getLang('btn_reply'), 'reply', true); } // show edit, show/hide and delete button? - if ((($user == $_SERVER['REMOTE_USER']) && ($user != '')) || ($this->helper->isDiscussionMod())) { - $this->_button($cid, $lang['btn_secedit'], 'edit', true); + if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionMod()) { + $this->showButton($cid, $lang['btn_secedit'], 'edit', true); $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show')); - $this->_button($cid, $label, 'toogle'); - $this->_button($cid, $lang['btn_delete'], 'delete'); + $this->showButton($cid, $label, 'toogle'); + $this->showButton($cid, $lang['btn_delete'], 'delete'); } ptln('
', 6); // class="comment_buttons" } @@ -858,34 +901,38 @@ protected function _print_comment($cid, &$data, $parent, $reply, $visible, $hidd } /** - * @param string $cid - * @param string $reply + * If requested by user, show comment form to write a reply + * + * @param string $cid current comment id + * @param string $reply comment id on which the user requested a reply */ - protected function _print_form($cid, $reply) + protected function showReplyForm($cid, $reply) { if ($this->getConf('usethreading') && $reply == $cid) { ptln('
', 4); - $this->_form('', 'add', $cid); + $this->showCommentForm('', 'add', $cid); ptln('
', 4); // class="comment_replies" } } /** - * @param string $cid - * @param array $data + * + * + * @param string $cid comment id + * @param array $data array with all comments by reference * @param string $reply - * @param bool $visible + * @param bool $isVisible */ - protected function _print_replies($cid, &$data, $reply, &$visible) + protected function showReplies($cid, &$data, $reply, &$isVisible) { $comment = $data['comments'][$cid]; if (!count($comment['replies'])) { return; } - ptln('
_get_style().'>', 4); - $visible = ($comment['show'] && $visible); + ptln('
getWidthStyle().'>', 4); + $isVisible = ($comment['show'] && $isVisible); foreach ($comment['replies'] as $rid) { - $this->_print($rid, $data, $cid, $reply, $visible); + $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible); } ptln('
', 4); } @@ -895,14 +942,13 @@ protected function _print_replies($cid, &$data, $reply, &$visible) * * @return bool */ - protected function _use_avatar() + protected function useAvatar() { - if (is_null($this->use_avatar)) { - $this->use_avatar = $this->getConf('useavatar') - && (!plugin_isdisabled('avatar')) - && ($this->avatar =& plugin_load('helper', 'avatar')); + if (is_null($this->useAvatar)) { + $this->useAvatar = $this->getConf('useavatar') + && ($this->avatar = $this->loadHelper('avatar', false)); } - return $this->use_avatar; + return $this->useAvatar; } /** @@ -910,9 +956,9 @@ protected function _use_avatar() * * @return string */ - protected function _get_style() { + protected function getWidthStyle() { if (is_null($this->style)){ - if ($this->_use_avatar()) { + if ($this->useAvatar()) { $this->style = ' style="margin-left: '.($this->avatar->getConf('size') + 14).'px;"'; } else { $this->style = ' style="margin-left: 20px;"'; @@ -922,24 +968,22 @@ protected function _get_style() { } /** - * Show the button which toggle the visibility of the discussion section + * Show the button which toggles between show/hide of the entire discussion section */ - protected function _print_toggle_button() { + protected function showDiscussionToggleButton() { ptln('
'); ptln(''); ptln('
'); } - + /** * Outputs the comment form */ - protected function _form($raw = '', $act = 'add', $cid = NULL) { - global $lang; - global $conf; - global $ID; + protected function showCommentForm($raw = '', $act = 'add', $cid = null) { + global $lang, $conf, $ID, $INPUT; // not for unregistered users when guest comments aren't allowed - if (!$_SERVER['REMOTE_USER'] && !$this->getConf('allowguests')) { + if (!$INPUT->server->has('REMOTE_USER') && !$this->getConf('allowguests')) { ?>
getLang('noguests'); ?> @@ -948,9 +992,9 @@ protected function _form($raw = '', $act = 'add', $cid = NULL) { return; } - // fill $raw with $_REQUEST['text'] if it's empty (for failed CAPTCHA check) - if (!$raw && ($_REQUEST['comment'] == 'show')) { - $raw = $_REQUEST['text']; + // fill $raw with $INPUT->str('text') if it's empty (for failed CAPTCHA check) + if (!$raw && $INPUT->str('comment') == 'show') { + $raw = $INPUT->str('text'); } ?> @@ -967,19 +1011,19 @@ protected function _form($raw = '', $act = 'add', $cid = NULL) { getConf('adminimport') && $this->helper->isDiscussionMod())) { + if(!$INPUT->server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionMod())) { ?>
- @@ -1065,7 +1109,7 @@ protected function _form($raw = '', $act = 'add', $cid = NULL) { - getConf('subscribe')) { ?> + server->has('REMOTE_USER') || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers']) && $this->getConf('subscribe')) { ?>
server->str('REMOTE_ADDR'); + $user = $INPUT->server->str('REMOTE_USER'); - $strip = array("\t", "\n"); - $logline = array( + $strip = ["\t", "\n"]; + $logline = [ 'date' => $date, 'ip' => $remote, 'type' => str_replace($strip, '', $type), @@ -1143,12 +1185,12 @@ protected function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra 'user' => $user, 'sum' => str_replace($strip, '', $summary), 'extra' => str_replace($strip, '', $extra) - ); + ]; // add changelog line $logline = implode("\t", $logline)."\n"; io_saveFile($changelog, $logline, true); //global changelog cache - $this->_trimRecentCommentsLog($changelog); + $this->trimRecentCommentsLog($changelog); // tell the indexer to re-index the page @unlink(metaFN($id, '.indexed')); @@ -1164,7 +1206,7 @@ protected function _addLogEntry($date, $id, $type = 'cc', $summary = '', $extra * @param string $changelog file path * @return bool */ - protected function _trimRecentCommentsLog($changelog) { + protected function trimRecentCommentsLog($changelog) { global $conf; if (@file_exists($changelog) && @@ -1182,7 +1224,7 @@ protected function _trimRecentCommentsLog($changelog) { io_saveFile($changelog.'_tmp', ''); // presave tmp as 2nd lock $trim_time = time() - $conf['recent_days']*86400; - $out_lines = array(); + $out_lines = []; $num = count($lines); for ($i=0; $i<$num; $i++) { @@ -1224,14 +1266,13 @@ protected function _trimRecentCommentsLog($changelog) { * Sends a notify mail on new comment * * @param array $comment data array of the new comment - * @param array $subscribers data of the subscribers + * @param array $subscribers data of the subscribers by reference * * @author Andreas Gohr * @author Esther Brunner */ - protected function _notify($comment, &$subscribers) { - global $conf; - global $ID; + protected function notify($comment, &$subscribers) { + global $conf, $ID, $INPUT, $auth; $notify_text = io_readfile($this->localfn('subscribermail')); $confirm_text = io_readfile($this->localfn('confirmsubscribe')); @@ -1239,11 +1280,11 @@ protected function _notify($comment, &$subscribers) { $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe'); $mailer = new Mailer(); - if (empty($_SERVER['REMOTE_USER'])) { + if (!$INPUT->server->has('REMOTE_USER')) { $mailer->from($conf['mailfromnobody']); } - $replace = array( + $replace = [ 'PAGE' => $ID, 'TITLE' => $conf['title'], 'DATE' => dformat($comment['date']['created'], $conf['dformat']), @@ -1252,13 +1293,13 @@ protected function _notify($comment, &$subscribers) { 'COMMENTURL' => wl($ID, '', true) . '#comment_' . $comment['cid'], 'UNSUBSCRIBE' => wl($ID, 'do=subscribe', true, '&'), 'DOKUWIKIURL' => DOKU_URL - ); + ]; - $confirm_replace = array( + $confirm_replace = [ 'PAGE' => $ID, 'TITLE' => $conf['title'], 'DOKUWIKIURL' => DOKU_URL - ); + ]; $mailer->subject($subject_notify); @@ -1272,34 +1313,36 @@ protected function _notify($comment, &$subscribers) { // send email to moderators if ($this->getConf('moderatorsnotify')) { - $mods = trim($this->getConf('moderatorgroups')); - if (!empty($mods)) { - global $auth; + $moderatorgrpsString = trim($this->getConf('moderatorgroups')); + if (!empty($moderatorgrpsString)) { // create a clean mods list - $mods = explode(',', $mods); - $mods = array_map('trim', $mods); - $mods = array_unique($mods); - $mods = array_filter($mods); + $moderatorgroups = explode(',', $moderatorgrpsString); + $moderatorgroups = array_map('trim', $moderatorgroups); + $moderatorgroups = array_unique($moderatorgroups); + $moderatorgroups = array_filter($moderatorgroups); // search for moderators users - foreach($mods as $mod) { - if(!$auth->isCaseSensitive()) $mod = utf8_strtolower($mod); + foreach($moderatorgroups as $moderatorgroup) { + if(!$auth->isCaseSensitive()) { + $moderatorgroup = PhpString::strtolower($moderatorgroup); + } // create a clean mailing list - $dests = array(); - if($mod[0] == '@') { - foreach($auth->retrieveUsers(0, 0, array('grps' => $auth->cleanGroup(substr($mod, 1)))) as $user) { + $bccs = []; + if($moderatorgroup[0] == '@') { + foreach($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) { if (!empty($user['mail'])) { - array_push($dests, $user['mail']); + $bccs[] = $user['mail']; } } } else { - $userdata = $auth->getUserData($auth->cleanUser($mod)); + //it is an user + $userdata = $auth->getUserData($auth->cleanUser($moderatorgroup)); if (!empty($userdata['mail'])) { - array_push($dests, $userdata['mail']); + $bccs[] = $userdata['mail']; } } - $dests = array_unique($dests); + $bccs = array_unique($bccs); // notify the users - $mailer->bcc(implode(',', $dests)); + $mailer->bcc(implode(',', $bccs)); $mailer->send(); } } @@ -1307,18 +1350,13 @@ protected function _notify($comment, &$subscribers) { // notify page subscribers if (actionOK('subscribe')) { - $data = array('id' => $ID, 'addresslist' => '', 'self' => false); - if (class_exists('Subscription')) { /* Introduced in DokuWiki 2013-05-10 */ - trigger_event( - 'COMMON_NOTIFY_ADDRESSLIST', $data, - array(new Subscription(), 'notifyaddresses') - ); - } else { /* Old, deprecated default handler */ - trigger_event( - 'COMMON_NOTIFY_ADDRESSLIST', $data, - 'subscription_addresslist' - ); - } + $data = ['id' => $ID, 'addresslist' => '', 'self' => false]; + //FIXME default callback, needed to mentioned it again? + Event::createAndTrigger( + 'COMMON_NOTIFY_ADDRESSLIST', $data, + [new SubscriberManager(), 'notifyAddresses'] + ); + $to = $data['addresslist']; if(!empty($to)) { $mailer->bcc($to); @@ -1337,7 +1375,7 @@ protected function _notify($comment, &$subscribers) { $mailer->subject($subject_notify); $mailer->setBody($notify_text, $replace); $mailer->send(); - } elseif(!$data['active'] && !$data['confirmsent']) { + } elseif(!$data['confirmsent']) { $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&'); $mailer->subject($subject_subscribe); @@ -1352,49 +1390,53 @@ protected function _notify($comment, &$subscribers) { /** * Counts the number of visible comments * - * @param array $data + * @param array $data array with all comments * @return int */ - protected function _count($data) { + protected function countVisibleComments($data) { $number = 0; foreach ($data['comments'] as $comment) { if ($comment['parent']) continue; if (!$comment['show']) continue; + $number++; $rids = $comment['replies']; if (count($rids)) { - $number = $number + $this->_countReplies($data, $rids); + $number = $number + $this->countVisibleReplies($data, $rids); } } return $number; } /** + * Count visible replies on the comments + * * @param array $data * @param array $rids - * @return int + * @return int counted replies */ - protected function _countReplies(&$data, $rids) { + protected function countVisibleReplies(&$data, $rids) { $number = 0; foreach ($rids as $rid) { if (!isset($data['comments'][$rid])) continue; // reply was removed if (!$data['comments'][$rid]['show']) continue; + $number++; $rids = $data['comments'][$rid]['replies']; if (count($rids)) { - $number = $number + $this->_countReplies($data, $rids); + $number = $number + $this->countVisibleReplies($data, $rids); } } return $number; } /** - * Renders the comment text + * Renders the raw comment (wiki)text to html * - * @param string $raw + * @param string $raw comment text * @return null|string */ - protected function _render($raw) { + protected function renderComment($raw) { if ($this->getConf('wikisyntaxok')) { // Note the warning for render_text: // "very ineffecient for small pieces of data - try not to use" @@ -1413,12 +1455,12 @@ protected function _render($raw) { * @param string $title * @return bool */ - protected function _hasDiscussion(&$title) { + protected function hasDiscussion(&$title) { global $ID; - $cfile = metaFN($ID, '.comments'); + $file = metaFN($ID, '.comments'); - if (!@file_exists($cfile)) { + if (!@file_exists($file)) { if ($this->isDiscussionEnabled()) { return true; } else { @@ -1426,14 +1468,18 @@ protected function _hasDiscussion(&$title) { } } - $comments = unserialize(io_readFile($cfile, false)); + $comments = unserialize(io_readFile($file, false)); if ($comments['title']) { $title = hsc($comments['title']); } $num = $comments['number']; - if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return false; - else return true; + if (!$comments['status'] || ($comments['status'] == 2 && $num == 0)) { + //disabled, or closed and no comments + return false; + } else { + return true; + } } /** @@ -1441,11 +1487,11 @@ protected function _hasDiscussion(&$title) { * * @return string */ - protected function _newThread() { - global $ID, $INFO; + protected function newThread() { + global $ID, $INFO, $INPUT; - $ns = cleanID($_REQUEST['ns']); - $title = str_replace(':', '', $_REQUEST['title']); + $ns = cleanID($INPUT->str('ns')); + $title = str_replace(':', '', $INPUT->str('title')); $back = $ID; $ID = ($ns ? $ns.':' : '').cleanID($title); $INFO = pageinfo(); @@ -1464,10 +1510,10 @@ protected function _newThread() { if (!@file_exists($INFO['filepath'])) { global $TEXT; - $TEXT = pageTemplate(array(($ns ? $ns.':' : '').$title)); + $TEXT = pageTemplate(($ns ? $ns.':' : '').$title); if (!$TEXT) { - $data = array('id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back); - $TEXT = $this->_pageTemplate($data); + $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back]; + $TEXT = $this->pageTemplate($data); } return 'preview'; } else { @@ -1484,64 +1530,61 @@ protected function _newThread() { * @param array $data * @return string */ - protected function _pageTemplate($data) { - global $conf, $INFO; + protected function pageTemplate($data) { + global $conf, $INFO, $INPUT; $id = $data['id']; - $user = $_SERVER['REMOTE_USER']; + $user = $INPUT->server->str('REMOTE_USER'); $tpl = io_readFile(DOKU_PLUGIN.'discussion/_template.txt'); // standard replacements - $replace = array( + $replace = [ '@NS@' => $data['ns'], '@PAGE@' => strtr(noNS($id),'_',' '), '@USER@' => $user, '@NAME@' => $INFO['userinfo']['name'], '@MAIL@' => $INFO['userinfo']['mail'], '@DATE@' => dformat(time(), $conf['dformat']), - ); + ]; // additional replacements $replace['@BACK@'] = $data['back']; $replace['@TITLE@'] = $data['title']; // avatar if useavatar and avatar plugin available - if ($this->getConf('useavatar') - && (@file_exists(DOKU_PLUGIN.'avatar/syntax.php')) - && (!plugin_isdisabled('avatar')) - ) { + if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) { $replace['@AVATAR@'] = '{{avatar>'.$user.' }} '; } else { $replace['@AVATAR@'] = ''; } // tag if tag plugin is available - if ((@file_exists(DOKU_PLUGIN.'tag/syntax/tag.php')) - && (!plugin_isdisabled('tag')) - ) { + if (!plugin_isdisabled('tag')){ $replace['@TAG@'] = "\n\n{{tag>}}"; } else { $replace['@TAG@'] = ''; } - // do the replace - $tpl = str_replace(array_keys($replace), array_values($replace), $tpl); - return $tpl; + // perform the replacements in tpl + return str_replace(array_keys($replace), array_values($replace), $tpl); } /** * Checks if the CAPTCHA string submitted is valid */ - protected function _captchaCheck() { + protected function captchaCheck() { + global $INPUT; /** @var helper_plugin_captcha $captcha */ - if (plugin_isdisabled('captcha') || (!$captcha = plugin_load('helper', 'captcha'))) - return; // CAPTCHA is disabled or not available + if (!$captcha = $this->loadHelper('captcha', false)) { + // CAPTCHA is disabled or not available + return; + } if ($captcha->isEnabled() && !$captcha->check()) { - if ($_REQUEST['comment'] == 'save') { - $_REQUEST['comment'] = 'edit'; - } elseif ($_REQUEST['comment'] == 'add') { - $_REQUEST['comment'] = 'show'; + if ($INPUT->str('comment') == 'save') { + $INPUT->set('comment', 'edit'); + } elseif ($INPUT->str('comment') == 'add') { + $INPUT->set('comment', 'show'); } } } @@ -1551,21 +1594,22 @@ protected function _captchaCheck() { * * @author Adrian Schlegel */ - protected function _recaptchaCheck() { - /** @var $recaptcha helper_plugin_recaptcha */ - if (plugin_isdisabled('recaptcha') || (!$recaptcha = plugin_load('helper', 'recaptcha'))) + protected function recaptchaCheck() { + global $INPUT; + /** @var helper_plugin_recaptcha $recaptcha */ + if (!$recaptcha = plugin_load('helper', 'recaptcha')) return; // reCAPTCHA is disabled or not available // do nothing if logged in user and no reCAPTCHA required - if (!$recaptcha->getConf('forusers') && $_SERVER['REMOTE_USER']) return; + if (!$recaptcha->getConf('forusers') && $INPUT->server->has('REMOTE_USER')) return; - $resp = $recaptcha->check(); - if (!$resp->is_valid) { + $response = $recaptcha->check(); + if (!$response->is_valid) { msg($recaptcha->getLang('testfailed'),-1); - if ($_REQUEST['comment'] == 'save') { - $_REQUEST['comment'] = 'edit'; - } elseif ($_REQUEST['comment'] == 'add') { - $_REQUEST['comment'] = 'show'; + if ($INPUT->str('comment') == 'save') { + $INPUT->str('comment', 'edit'); + } elseif ($INPUT->str('comment') == 'add') { + $INPUT->str('comment', 'show'); } } } @@ -1578,7 +1622,7 @@ protected function _recaptchaCheck() { * @param Doku_Event $event * @param $param */ - public function idx_version(Doku_Event $event, $param) { + public function addIndexVersion(Doku_Event $event, $param) { $event->data['discussion'] = '0.1'; } @@ -1586,26 +1630,36 @@ public function idx_version(Doku_Event $event, $param) { * Adds the comments to the index * * @param Doku_Event $event - * @param $param + * @param array $param with + * 'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event + * 'text' => string 'body'/'text' */ - public function idx_add_discussion(Doku_Event $event, $param) { - + public function addCommentsToIndex(Doku_Event $event, $param) { // get .comments meta file name $file = metaFN($event->data[$param['id']], '.comments'); if (!@file_exists($file)) return; $data = unserialize(io_readFile($file, false)); - if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off + + // comments are turned off or no comments available to index + if (!$data['status'] || $data['number'] == 0) return; // now add the comments if (isset($data['comments'])) { foreach ($data['comments'] as $key => $value) { - $event->data[$param['text']] .= DOKU_LF.$this->_addCommentWords($key, $data); + $event->data[$param['text']] .= DOKU_LF.$this->addCommentWords($key, $data); } } } - function ft_phrase_match(Doku_Event $event, $param) { + /** + * Checks if the phrase occurs in the comments and return event result true if matching + * + * @param Doku_Event $event + * @param $param + * @return void + */ + public function fulltextPhraseMatchInComments(Doku_Event $event, $param) { if ($event->result === true) return; // get .comments meta file name @@ -1613,38 +1667,51 @@ function ft_phrase_match(Doku_Event $event, $param) { if (!@file_exists($file)) return; $data = unserialize(io_readFile($file, false)); - if ((!$data['status']) || ($data['number'] == 0)) return; // comments are turned off + + // comments are turned off or no comments available to match + if (!$data['status'] || $data['number'] == 0) return; $matched = false; // now add the comments if (isset($data['comments'])) { - foreach ($data['comments'] as $key => $value) { - $matched = $this->comment_phrase_match($event->data['phrase'], $key, $data); + foreach ($data['comments'] as $cid => $value) { + $matched = $this->phraseMatchInComment($event->data['phrase'], $cid, $data); if ($matched) break; } } - if ($matched) + if ($matched) { $event->result = true; + } } - function comment_phrase_match($phrase, $cid, &$data, $parent = '') { + /** + * Match the phrase in the comment and its replies + * + * @param string $phrase phrase to search + * @param string $cid comment id + * @param array $data array with all comments by reference + * @param string $parent cid of parent + * @return bool if match true, otherwise false + */ + protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '') { if (!isset($data['comments'][$cid])) return false; // comment was removed + $comment = $data['comments'][$cid]; if (!is_array($comment)) return false; // corrupt datatype if ($comment['parent'] != $parent) return false; // reply to an other comment if (!$comment['show']) return false; // hidden comment - $text = utf8_strtolower($comment['raw']); + $text = PhpString::strtolower($comment['raw']); if (strpos($text, $phrase) !== false) { return true; } if (is_array($comment['replies'])) { // and the replies foreach ($comment['replies'] as $rid) { - if ($this->comment_phrase_match($phrase, $rid, $data, $cid)) { + if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) { return true; } } @@ -1653,7 +1720,7 @@ function comment_phrase_match($phrase, $cid, &$data, $parent = '') { } /** - * Saves the current comment status and title in the .comments file + * Saves the current comment status and title from metadata into the .comments file * * @param Doku_Event $event * @param $param @@ -1664,9 +1731,9 @@ public function update_comment_status(Doku_Event $event, $param) { $meta = $event->data['current']; $file = metaFN($ID, '.comments'); $status = ($this->isDiscussionEnabled() ? 1 : 0); - $title = NULL; + $title = null; if (isset($meta['plugin_discussion'])) { - $status = $meta['plugin_discussion']['status']; + $status = $meta['plugin_discussion']['status']; // 0, 1 or 2 $title = $meta['plugin_discussion']['title']; } else if ($status == 1) { // Don't enable comments when automatic comments are on - this already happens automatically @@ -1675,7 +1742,7 @@ public function update_comment_status(Doku_Event $event, $param) { } if ($status || @file_exists($file)) { - $data = array(); + $data = []; if (@file_exists($file)) { $data = unserialize(io_readFile($file, false)); } @@ -1683,24 +1750,26 @@ public function update_comment_status(Doku_Event $event, $param) { if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) { $data['title'] = $title; $data['status'] = $status; - if (!isset($data['number'])) + if (!isset($data['number'])) { $data['number'] = 0; + } io_saveFile($file, serialize($data)); } } } /** - * Adds the words of a given comment to the index + * Return words of a given comment and its replies, suitable to be added to the index * - * @param string $cid - * @param array $data - * @param string $parent + * @param string $cid comment id + * @param array $data array with all comments by reference + * @param string $parent cid of parent * @return string */ - protected function _addCommentWords($cid, &$data, $parent = '') { + protected function addCommentWords($cid, &$data, $parent = '') { if (!isset($data['comments'][$cid])) return ''; // comment was removed + $comment = $data['comments'][$cid]; if (!is_array($comment)) return ''; // corrupt datatype @@ -1710,7 +1779,7 @@ protected function _addCommentWords($cid, &$data, $parent = '') { $text = $comment['raw']; // we only add the raw comment text if (is_array($comment['replies'])) { // and the replies foreach ($comment['replies'] as $rid) { - $text .= $this->_addCommentWords($rid, $data, $cid); + $text .= $this->addCommentWords($rid, $data, $cid); } } return ' '.$text; @@ -1722,46 +1791,47 @@ protected function _addCommentWords($cid, &$data, $parent = '') { * @param string $url * @return string */ - protected function _checkURL($url) { + protected function checkURL($url) { if(preg_match("#^http://|^https://#", $url)) { return hsc($url); } elseif(substr($url, 0, 4) == 'www.') { - return hsc('http://' . $url); + return hsc('https://' . $url); } else { return ''; } } -} -/** - * Sort threads - * - * @param $a - * @param $b - * @return int - */ -function _sortCallback($a, $b) { - if (is_array($a['date'])) { - // new format - $createdA = $a['date']['created']; - } else { - // old format - $createdA = $a['date']; - } + /** + * Sort threads + * + * @param $a + * @param $b + * @return int + */ + function sortCallback($a, $b) { + if (is_array($a['date'])) { + // new format + $createdA = $a['date']['created']; + } else { + // old format + $createdA = $a['date']; + } - if (is_array($b['date'])) { - // new format - $createdB = $b['date']['created']; - } else { - // old format - $createdB = $b['date']; - } + if (is_array($b['date'])) { + // new format + $createdB = $b['date']['created']; + } else { + // old format + $createdB = $b['date']; + } - if ($createdA == $createdB) { - return 0; - } else { - return ($createdA < $createdB) ? -1 : 1; + if ($createdA == $createdB) { + return 0; + } else { + return ($createdA < $createdB) ? -1 : 1; + } } + } -// vim:ts=4:sw=4:et:enc=utf-8: + diff --git a/admin.php b/admin.php index aaea638..4e727da 100644 --- a/admin.php +++ b/admin.php @@ -4,6 +4,8 @@ * @author Esther Brunner */ +use dokuwiki\Utf8\PhpString; + /** * Class admin_plugin_discussion */ @@ -12,60 +14,61 @@ class admin_plugin_discussion extends DokuWiki_Admin_Plugin { /** * @return int */ - function getMenuSort() { return 200; } + public function getMenuSort() { return 200; } /** * @return bool */ - function forAdminOnly() { return false; } - - function handle() { - global $lang; + public function forAdminOnly() { return false; } - $cid = $_REQUEST['cid']; - if (is_array($cid)) $cid = array_keys($cid); + public function handle() { + global $lang, $INPUT; + $cids = $INPUT->post->arr('cid'); + if (is_array($cids)) { + $cids = array_keys($cids); + } /** @var action_plugin_discussion $action */ - $action =& plugin_load('action', 'discussion'); + $action = plugin_load('action', 'discussion'); if (!$action) return; // couldn't load action plugin component - switch ($_REQUEST['comment']) { + switch ($INPUT->post->str('comment')) { case $lang['btn_delete']: - $action->save($cid, ''); + $action->save($cids, ''); break; case $this->getLang('btn_show'): - $action->save($cid, '', 'show'); + $action->save($cids, '', 'show'); break; case $this->getLang('btn_hide'): - $action->save($cid, '', 'hide'); + $action->save($cids, '', 'hide'); break; case $this->getLang('btn_change'): - $this->_changeStatus($_REQUEST['status']); + $this->changeStatus($INPUT->post->str('status')); break; } } - function html() { - global $conf; + public function html() { + global $conf, $INPUT; + + $first = $INPUT->int('first'); - $first = $_REQUEST['first']; - if (!is_numeric($first)) $first = 0; - $num = ($conf['recent']) ? $conf['recent'] : 20; + $num = $conf['recent'] ?: 20; ptln('

'.$this->getLang('menu').'

'); - $threads = $this->_getThreads(); + $threads = $this->getThreads(); // slice the needed chunk of discussion pages - $more = ((count($threads) > ($first + $num)) ? true : false); + $isMore = count($threads) > ($first + $num); $threads = array_slice($threads, $first, $num); foreach ($threads as $thread) { - $comments = $this->_getComments($thread); - $this->_threadHead($thread); + $comments = $this->getComments($thread); + $this->threadHead($thread); if ($comments === false) { ptln('', 6); // class="level2" continue; @@ -75,10 +78,10 @@ function html() { ptln('
', 10); ptln('', 10); ptln('', 10); - echo html_buildlist($comments, 'admin_discussion', array($this, '_commentItem'), array($this, '_li_comment')); - $this->_actionButtons($thread['id']); + echo html_buildlist($comments, 'admin_discussion', [$this, 'commentItem'], [$this, 'liComment']); + $this->actionButtons(); } - $this->_browseDiscussionLinks($more, $first, $num); + $this->browseDiscussionLinks($isMore, $first, $num); } @@ -87,17 +90,15 @@ function html() { * * @return array */ - function _getThreads() { + protected function getThreads() { global $conf; - require_once(DOKU_INC.'inc/search.php'); - // returns the list of pages in the given namespace and it's subspaces - $items = array(); - search($items, $conf['datadir'], 'search_allpages', array()); + $items = []; + search($items, $conf['datadir'], 'search_allpages', []); // add pages with comments to result - $result = array(); + $result = []; foreach ($items as $item) { $id = $item['id']; @@ -106,15 +107,15 @@ function _getThreads() { if (!@file_exists($file)) continue; // skip if no comments file $date = filemtime($file); - $result[] = array( + $result[] = [ 'id' => $id, 'file' => $file, 'date' => $date, - ); + ]; } // finally sort by time of last comment - usort($result, array('admin_plugin_discussion', '_threadCmp')); + usort($result, ['admin_plugin_discussion', 'threadCmp']); return $result; } @@ -130,11 +131,15 @@ function _getThreads() { * @param array $b * @return int */ - function _threadCmp($a, $b) { + protected function threadCmp($a, $b) { if ($a['date'] == $b['date']) { return strcmp($a['id'], $b['id']); } - return ($a['date'] < $b['date']) ? 1 : -1; + if ($a['date'] < $b['date']) { + return 1; + } else { + return -1; + } } /** @@ -143,14 +148,14 @@ function _threadCmp($a, $b) { * @param array $thread * @return bool */ - function _threadHead($thread) { + protected function threadHead($thread) { $id = $thread['id']; - $labels = array( + $labels = [ 0 => $this->getLang('off'), 1 => $this->getLang('open'), 2 => $this->getLang('closed') - ); + ]; $title = p_get_metadata($id, 'title'); if (!$title) { $title = $id; @@ -162,7 +167,7 @@ function _threadHead($thread) { ptln('', 10); ptln($this->getLang('status').': ', 10); @@ -177,10 +182,15 @@ function _threadHead($thread) { /** * Returns the full comments data for a given wiki page * - * @param array $thread + * @param array $thread by reference with: + * 'id' => string, + * 'file' => string file location of .comments metadata file + * 'status' => int + * 'number' => int number of visible comments + * * @return array|bool */ - function _getComments(&$thread) { + protected function getComments(&$thread) { $id = $thread['id']; if (!$thread['file']) { @@ -195,9 +205,9 @@ function _getComments(&$thread) { if (!$data['status']) return false; // comments are turned off if (!$data['comments']) return false; // no comments - $result = array(); + $result = []; foreach ($data['comments'] as $cid => $comment) { - $this->_addComment($cid, $data, $result); + $this->addComment($cid, $data, $result); } if (empty($result)) { @@ -210,16 +220,18 @@ function _getComments(&$thread) { /** * Recursive function to add the comment hierarchy to the result * - * @param string $cid - * @param array $data - * @param array $result - * @param string $parent - * @param int $level + * @param string $cid comment id of current comment + * @param array $data array with all comments by reference + * @param array $result array with all comments by reference enhanced with level + * @param string $parent comment id of parent or empty + * @param int $level level of current comment, higher is deeper */ - function _addComment($cid, &$data, &$result, $parent = '', $level = 1) { + protected function addComment($cid, &$data, &$result, $parent = '', $level = 1) { if (!is_array($data['comments'][$cid])) return; // corrupt datatype + $comment = $data['comments'][$cid]; - if ($comment['parent'] != $parent) return; // answer to another comment + // handle only replies to given parent comment + if ($comment['parent'] != $parent) return; // okay, add the comment to the result $comment['id'] = $cid; @@ -229,18 +241,18 @@ function _addComment($cid, &$data, &$result, $parent = '', $level = 1) { // check answers to this comment if (count($comment['replies'])) { foreach ($comment['replies'] as $rid) { - $this->_addComment($rid, $data, $result, $cid, $level + 1); + $this->addComment($rid, $data, $result, $cid, $level + 1); } } } /** - * Checkbox and info about a comment item + * Returns html of checkbox and info about a comment item * - * @param array $comment - * @return string + * @param array $comment array with comment data + * @return string html of checkbox and info */ - function _commentItem($comment) { + public function commentItem($comment) { global $conf; // prepare variables @@ -257,8 +269,8 @@ function _commentItem($comment) { $created = $comment['date']; } $abstract = preg_replace('/\s+?/', ' ', strip_tags($comment['xhtml'])); - if (utf8_strlen($abstract) > 160) { - $abstract = utf8_substr($abstract, 0, 160).'...'; + if (PhpString::strlen($abstract) > 160) { + $abstract = PhpString::substr($abstract, 0, 160).'...'; } return ' '. @@ -267,23 +279,20 @@ function _commentItem($comment) { } /** - * list item tag + * Returns html of list item openings tag * * @param array $comment * @return string */ - function _li_comment($comment) { - $show = ($comment['show'] ? '' : ' hidden'); - return '
  • '; + public function liComment($comment) { + $showclass = ($comment['show'] ? '' : ' hidden'); + return '
  • '; } /** * Show buttons to bulk remove, hide or show comments - * - * @param string $id - * @return bool */ - function _actionButtons($id) { + protected function actionButtons() { global $lang; ptln('
    ', 12); @@ -294,26 +303,24 @@ function _actionButtons($id) { ptln('
    ', 10); // class="no" ptln('', 8); ptln('
  • ', 6); // class="level2" - return true; } /** * Displays links to older newer discussions * - * @param bool $more - * @param int $first - * @param int $num - * @return bool + * @param bool $isMore whether there are more pages needed + * @param int $first first entry on this page + * @param int $num number of entries per page */ - function _browseDiscussionLinks($more, $first, $num) { + protected function browseDiscussionLinks($isMore, $first, $num) { global $ID; - if (($first == 0) && (!$more)) return true; + if ($first == 0 && !$isMore) return; - $params = array('do' => 'admin', 'page' => 'discussion'); + $params = ['do' => 'admin', 'page' => 'discussion']; $last = $first+$num; ptln('
    ', 8); - $ret = ''; + $return = ''; if ($first > 0) { $first -= $num; if ($first < 0) { @@ -321,33 +328,31 @@ function _browseDiscussionLinks($more, $first, $num) { } $params['first'] = $first; ptln('

    ', 8); - $ret = '<< '.$this->getLang('newer').''; - if ($more) { - $ret .= ' | '; + $return = '<< '.$this->getLang('newer').''; + if ($isMore) { + $return .= ' | '; } else { - ptln($ret, 10); + ptln($return, 10); ptln('

    ', 8); } - } else if ($more) { + } else if ($isMore) { ptln('

    ', 8); } - if ($more) { + if ($isMore) { $params['first'] = $last; - $ret .= ''.$this->getLang('older').' >>'; - ptln($ret, 10); + $return .= ''.$this->getLang('older').' >>'; + ptln($return, 10); ptln('

    ', 8); } ptln('
    ', 6); // class="level1" - return true; } /** - * Changes the status of a comment + * Changes the status of a comment section * - * @param $new - * @return bool + * @param int $new 0=disabled, 1=enabled, 2=closed */ - function _changeStatus($new) { + protected function changeStatus($new) { global $ID; // get discussion meta file name @@ -355,19 +360,18 @@ function _changeStatus($new) { $data = unserialize(io_readFile($file, false)); $old = $data['status']; - if ($old == $new) return true; + if ($old == $new) { + return; + } // save the comment metadata file $data['status'] = $new; io_saveFile($file, serialize($data)); // look for ~~DISCUSSION~~ command in page file and change it accordingly - $patterns = array('~~DISCUSSION:off\2~~', '~~DISCUSSION\2~~', '~~DISCUSSION:closed\2~~'); + $patterns = ['~~DISCUSSION:off\2~~', '~~DISCUSSION\2~~', '~~DISCUSSION:closed\2~~']; $replace = $patterns[$new]; $wiki = preg_replace('/~~DISCUSSION([\w:]*)(\|?.*?)~~/', $replace, rawWiki($ID)); saveWikiText($ID, $wiki, $this->getLang('statuschanged'), true); - - return true; } } -// vim:ts=4:sw=4:et:enc=utf-8: From 283a3029a8b60f309e24296d28025c9b1c450296 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 16:29:36 +0200 Subject: [PATCH 02/33] reformatting, unused params, forgotten debug statements --- action.php | 767 +++++++++++++++++++++++++++++------------------------ 1 file changed, 415 insertions(+), 352 deletions(-) diff --git a/action.php b/action.php index 3ba46b9..5a212cb 100644 --- a/action.php +++ b/action.php @@ -47,7 +47,8 @@ * ... * ] */ -class action_plugin_discussion extends DokuWiki_Action_Plugin{ +class action_plugin_discussion extends DokuWiki_Action_Plugin +{ /** @var helper_plugin_avatar */ protected $avatar = null; @@ -61,7 +62,8 @@ class action_plugin_discussion extends DokuWiki_Action_Plugin{ /** * load helper */ - public function __construct() { + public function __construct() + { $this->helper = plugin_load('helper', 'discussion'); } @@ -70,7 +72,8 @@ public function __construct() { * * @param Doku_Event_Handler $controller DokuWiki's event controller object. */ - public function register(Doku_Event_Handler $controller) { + public function register(Doku_Event_Handler $controller) + { $controller->register_hook('ACTION_ACT_PREPROCESS', 'BEFORE', $this, 'handleCommentActions'); $controller->register_hook('TPL_ACT_RENDER', 'AFTER', $this, 'renderCommentsSection'); $controller->register_hook('INDEXER_PAGE_ADD', 'AFTER', $this, 'addCommentsToIndex', ['id' => 'page', 'text' => 'body']); @@ -87,20 +90,21 @@ public function register(Doku_Event_Handler $controller) { /** * Preview Comments * - * @author Michael Klier - * * @param Doku_Event $event * @param $params + * @author Michael Klier + * */ - public function ajaxPreviewComments(Doku_Event $event, $params) { + public function ajaxPreviewComments(Doku_Event $event) + { global $INPUT; - if($event->data != 'discussion_preview') return; + if ($event->data != 'discussion_preview') return; $event->preventDefault(); $event->stopPropagation(); print p_locale_xhtml('preview'); print '
    '; - if(!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) { + if (!$INPUT->server->str('REMOTE_USER') && !$this->getConf('allowguests')) { print p_locale_xhtml('denied'); } else { print $this->renderComment($INPUT->post->str('comment')); @@ -111,18 +115,19 @@ public function ajaxPreviewComments(Doku_Event $event, $params) { /** * Adds a TOC item if a discussion exists * - * @author Michael Klier - * * @param Doku_Event $event * @param $params + * @author Michael Klier + * */ - public function addDiscussionToTOC(Doku_Event $event, $params) { + public function addDiscussionToTOC(Doku_Event $event) + { global $ACT; - if($this->hasDiscussion($title) && $event->data && $ACT != 'admin') { + if ($this->hasDiscussion($title) && $event->data && $ACT != 'admin') { $tocitem = ['hid' => 'discussion__section', - 'title' => $this->getLang('discussion'), - 'type' => 'ul', - 'level' => 1]; + 'title' => $this->getLang('discussion'), + 'type' => 'ul', + 'level' => 1]; $event->data[] = $tocitem; } @@ -131,23 +136,24 @@ public function addDiscussionToTOC(Doku_Event $event, $params) { /** * Modify Toolbar for use with discussion plugin * - * @author Michael Klier - * * @param Doku_Event $event * @param $param + * @author Michael Klier + * */ - public function modifyToolbar(Doku_Event $event, $param) { + public function modifyToolbar(Doku_Event $event) + { global $ACT; - if($ACT != 'show') return; + if ($ACT != 'show') return; - if($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) { + if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) { $toolbar = []; - foreach($event->data as $btn) { - if($btn['type'] == 'mediapopup') continue; - if($btn['type'] == 'signature') continue; - if($btn['type'] == 'linkwiz') continue; - if($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin - if(isset($btn['open']) && preg_match("/=+?/", $btn['open'])) continue; + foreach ($event->data as $btn) { + if ($btn['type'] == 'mediapopup') continue; + if ($btn['type'] == 'signature') continue; + if ($btn['type'] == 'linkwiz') continue; + if ($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin + if (isset($btn['open']) && preg_match("/=+?/", $btn['open'])) continue; $toolbar[] = $btn; } @@ -158,19 +164,20 @@ public function modifyToolbar(Doku_Event $event, $param) { /** * Dirty workaround to add a toolbar to the discussion plugin * - * @author Michael Klier - * * @param Doku_Event $event * @param $param + * @author Michael Klier + * */ - public function addToolbarToCommentfield(Doku_Event $event, $param) { + public function addToolbarToCommentfield(Doku_Event $event) + { global $ACT; global $ID; - if($ACT != 'show') return; + if ($ACT != 'show') return; - if($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) { + if ($this->hasDiscussion($title) && $this->getConf('wikisyntaxok')) { // FIXME ugly workaround, replace this once DW the toolbar code is more flexible - @require_once(DOKU_INC.'inc/toolbar.php'); + @require_once(DOKU_INC . 'inc/toolbar.php'); ob_start(); print 'NS = "' . getNS($ID) . '";'; // we have to define NS, otherwise we get get JS errors toolbar_JSdefines('toolbar'); @@ -186,7 +193,8 @@ public function addToolbarToCommentfield(Doku_Event $event, $param) { * @param $param * @return void */ - public function handleCommentActions(Doku_Event $event, $param) { + public function handleCommentActions(Doku_Event $event) + { global $ID, $INFO, $lang, $INPUT; // handle newthread ACTs @@ -243,27 +251,27 @@ public function handleCommentActions(Doku_Event $event, $param) { return; } else { // do the data processing for comments - $cid = $INPUT->str('cid'); + $cid = $INPUT->str('cid'); switch ($INPUT->str('comment')) { case 'add': - if(empty($INPUT->str('text'))) return; // don't add empty comments + if (empty($INPUT->str('text'))) return; // don't add empty comments - if($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) { + if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) { $comment['user']['id'] = $INPUT->server->str('REMOTE_USER'); $comment['user']['name'] = $INFO['userinfo']['name']; $comment['user']['mail'] = $INFO['userinfo']['mail']; - } elseif(($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) + } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) || !$INPUT->server->has('REMOTE_USER')) { // don't add anonymous comments - if(empty($INPUT->str('name')) or empty($INPUT->str('mail'))) { + if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) { return; } - if(!mail_isvalid($INPUT->str('mail'))) { + if (!mail_isvalid($INPUT->str('mail'))) { msg($lang['regbadmail'], -1); return; } else { - $comment['user']['id'] = 'test'.hsc($INPUT->str('user')); + $comment['user']['id'] = 'test' . hsc($INPUT->str('user')); $comment['user']['name'] = hsc($INPUT->str('name')); $comment['user']['mail'] = hsc($INPUT->str('mail')); } @@ -274,7 +282,7 @@ public function handleCommentActions(Doku_Event $event, $param) { $comment['date'] = ['created' => $INPUT->str('date')]; $comment['raw'] = cleanText($INPUT->str('text')); $reply = $INPUT->str('reply'); - if($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { + if ($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { $comment['show'] = false; } else { $comment['show'] = true; @@ -283,7 +291,7 @@ public function handleCommentActions(Doku_Event $event, $param) { break; case 'save': - $raw = cleanText($INPUT->str('text')); + $raw = cleanText($INPUT->str('text')); $this->save([$cid], $raw); break; @@ -301,22 +309,22 @@ public function handleCommentActions(Doku_Event $event, $param) { /** * Main function; dispatches the visual comment actions */ - public function renderCommentsSection(Doku_Event $event, $param) { + public function renderCommentsSection(Doku_Event $event) + { global $INPUT; if ($event->data != 'show') return; // nothing to do for us - $cid = $INPUT->str('cid'); + $cid = $INPUT->str('cid'); - if(!$cid) { + if (!$cid) { $cid = $INPUT->str('reply'); } - var_dump($cid); - var_dump($INPUT->str('comment')); + switch ($INPUT->str('comment')) { case 'edit': $this->showDiscussionSection(null, $cid); break; - default: //'reply' or no action specifiec + default: //'reply' or no action specified $this->showDiscussionSection($cid); break; } @@ -325,13 +333,14 @@ public function renderCommentsSection(Doku_Event $event, $param) { /** * Redirects browser to given comment anchor */ - protected function redirect($cid) { + protected function redirect($cid) + { global $ID; global $ACT; if ($ACT !== 'show') return; - if($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { + if ($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { msg($this->getLang('moderation'), 1); @session_start(); global $MSG; @@ -355,23 +364,26 @@ protected function redirect($cid) { * * @return bool */ - public function isDiscussionEnabled() { + public function isDiscussionEnabled() + { global $INFO; - if($this->getConf('excluded_ns') == '') { + if ($this->getConf('excluded_ns') == '') { $isNamespaceExcluded = false; } else { + global $ID; + $ns = getNS($ID); // $INFO['namespace'] is not yet available, if used in update_comment_status() $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $INFO['namespace']); } - if($this->getConf('automatic')) { - if($isNamespaceExcluded) { + if ($this->getConf('automatic')) { + if ($isNamespaceExcluded) { return false; } else { return true; } } else { - if($isNamespaceExcluded) { + if ($isNamespaceExcluded) { return true; } else { return false; @@ -385,7 +397,8 @@ public function isDiscussionEnabled() { * @param null|string $reply comment id on which the user requested a reply * @param null|string $edit comment id which the user requested for editing */ - protected function showDiscussionSection($reply = null, $edit = null) { + protected function showDiscussionSection($reply = null, $edit = null) + { global $ID, $INFO, $INPUT; // get .comments meta file name @@ -403,7 +416,6 @@ protected function showDiscussionSection($reply = null, $edit = null) { if (!$data['status']) { return; } - var_dump($data); } elseif (!@file_exists($file) && $this->isDiscussionEnabled() && $INFO['exists']) { // set status to show the comment form $data['status'] = 1; @@ -411,7 +423,7 @@ protected function showDiscussionSection($reply = null, $edit = null) { } // show discussion wrapper only on certain circumstances - if(empty($data['comments']) || !is_array($data['comments'])) { + if (empty($data['comments']) || !is_array($data['comments'])) { $cnt = 0; $keys = []; } else { @@ -420,7 +432,7 @@ protected function showDiscussionSection($reply = null, $edit = null) { } $show = false; - if($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) + if ($cnt > 1 || ($cnt == 1 && $data['comments'][$keys[0]]['show'] == 1) || $this->getConf('allowguests') || $INPUT->server->has('REMOTE_USER')) { $show = true; // section title @@ -436,9 +448,9 @@ protected function showDiscussionSection($reply = null, $edit = null) { if (isset($data['comments'])) { if (!$this->getConf('usethreading')) { $data['comments'] = $this->flattenThreads($data['comments']); - uasort($data['comments'], [$this, 'sortCallback']); + uasort($data['comments'], [$this, 'sortThreadsOnCreation']); } - if($this->getConf('newestfirst')) { + if ($this->getConf('newestfirst')) { $data['comments'] = array_reverse($data['comments']); } foreach ($data['comments'] as $cid => $value) { @@ -455,13 +467,13 @@ protected function showDiscussionSection($reply = null, $edit = null) { $this->showCommentForm(''); } - if($show) { + if ($show) { ptln('
    ', 2); // level2 hfeed ptln(''); // comment_wrapper } // check for toggle print configuration - if($this->getConf('visibilityButton')) { + if ($this->getConf('visibilityButton')) { // print the hide/show discussion section button $this->showDiscussionToggleButton(); } @@ -470,16 +482,17 @@ protected function showDiscussionSection($reply = null, $edit = null) { /** * Remove the parent-child relation, such that the comment structure becomes flat * - * @param array $comments array with all comments + * @param array $comments array with all comments * @param null|array $cids comment ids of replies, which should be flatten * @return array returned array with flattened comment structure */ - protected function flattenThreads($comments, $cids = null) { + protected function flattenThreads($comments, $cids = null) + { if (is_null($cids)) { $cids = array_keys($comments); } - foreach($cids as $cid) { + foreach ($cids as $cid) { if (!empty($comments[$cid]['replies'])) { $rids = $comments[$cid]['replies']; $comments = $this->flattenThreads($comments, $rids); @@ -508,7 +521,8 @@ protected function flattenThreads($comments, $cids = null) { * @param string $parent comment id of parent * @return bool */ - protected function add($comment, $parent) { + protected function add($comment, $parent) + { global $ID, $TEXT, $INPUT; $originalTxt = $TEXT; // set $TEXT to comment text for wordblock check @@ -521,7 +535,7 @@ protected function add($comment, $parent) { } if (!$this->getConf('allowguests') - && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER') + && $comment['user']['id'] != $INPUT->server->str('REMOTE_USER') ) { return false; // guest comments not allowed } @@ -532,7 +546,7 @@ protected function add($comment, $parent) { $file = metaFN($ID, '.comments'); // create comments file if it doesn't exist yet - if(!@file_exists($file)) { + if (!@file_exists($file)) { $data = ['status' => 1, 'number' => 0]; io_saveFile($file, serialize($data)); } else { @@ -553,7 +567,7 @@ protected function add($comment, $parent) { $date = time(); } - $cid = md5($comment['user']['id'].$date); // create a unique id + $cid = md5($comment['user']['id'] . $date); // create a unique id if (!is_array($data['comments'][$parent])) { $parent = null; // invalid parent comment @@ -564,25 +578,25 @@ protected function add($comment, $parent) { // fill in the new comment $data['comments'][$cid] = [ - 'user' => $comment['user'], - 'date' => ['created' => $date], - 'raw' => $comment['raw'], - 'xhtml' => $xhtml, - 'parent' => $parent, - 'replies' => [], - 'show' => $comment['show'] + 'user' => $comment['user'], + 'date' => ['created' => $date], + 'raw' => $comment['raw'], + 'xhtml' => $xhtml, + 'parent' => $parent, + 'replies' => [], + 'show' => $comment['show'] ]; - if($comment['subscribe']) { + if ($comment['subscribe']) { $mail = $comment['user']['mail']; - if($data['subscribers']) { - if(!$data['subscribers'][$mail]) { + if ($data['subscribers']) { + if (!$data['subscribers'][$mail]) { $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand()); $data['subscribers'][$mail]['active'] = false; $data['subscribers'][$mail]['confirmsent'] = false; } else { // convert old style subscribers and set them active - if(!is_array($data['subscribers'][$mail])) { + if (!is_array($data['subscribers'][$mail])) { $hash = $data['subscribers'][$mail]; $data['subscribers'][$mail]['hash'] = $hash; $data['subscribers'][$mail]['active'] = true; @@ -590,7 +604,7 @@ protected function add($comment, $parent) { } } } else { - $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand()); + $data['subscribers'][$mail]['hash'] = md5($mail . mt_rand()); $data['subscribers'][$mail]['active'] = false; $data['subscribers'][$mail]['confirmsent'] = false; } @@ -624,10 +638,11 @@ protected function add($comment, $parent) { * @param string|null $act 'toogle', 'show', 'hide', null. If null, it depends on $raw * @return bool succeed? */ - public function save($cids, $raw, $act = null) { + public function save($cids, $raw, $act = null) + { global $ID, $INPUT; - if(empty($cids)) return false; // do nothing if we get no comment id + if (empty($cids)) return false; // do nothing if we get no comment id if ($raw) { global $TEXT; @@ -654,10 +669,10 @@ public function save($cids, $raw, $act = null) { foreach ($cids as $cid) { if (is_array($data['comments'][$cid]['user'])) { - $user = $data['comments'][$cid]['user']['id']; + $user = $data['comments'][$cid]['user']['id']; $convert = false; } else { - $user = $data['comments'][$cid]['user']; + $user = $data['comments'][$cid]['user']; $convert = true; } @@ -671,14 +686,14 @@ public function save($cids, $raw, $act = null) { // need to convert to new format? if ($convert) { $data['comments'][$cid]['user'] = [ - 'id' => $user, - 'name' => $data['comments'][$cid]['name'], - 'mail' => $data['comments'][$cid]['mail'], - 'url' => $data['comments'][$cid]['url'], - 'address' => $data['comments'][$cid]['address'], + 'id' => $user, + 'name' => $data['comments'][$cid]['name'], + 'mail' => $data['comments'][$cid]['mail'], + 'url' => $data['comments'][$cid]['url'], + 'address' => $data['comments'][$cid]['address'], ]; $data['comments'][$cid]['date'] = [ - 'created' => $data['comments'][$cid]['date'] + 'created' => $data['comments'][$cid]['date'] ]; } @@ -712,8 +727,8 @@ public function save($cids, $raw, $act = null) { // now change the comment's content $data['comments'][$cid]['date']['modified'] = $date; - $data['comments'][$cid]['raw'] = $raw; - $data['comments'][$cid]['xhtml'] = $xhtml; + $data['comments'][$cid]['raw'] = $raw; + $data['comments'][$cid]['xhtml'] = $xhtml; $type = 'ec'; // edit comment } @@ -734,7 +749,8 @@ public function save($cids, $raw, $act = null) { * @param array $comments array with all comments * @return array returns modified array with all remaining comments */ - protected function removeComment($cid, $comments) { + protected function removeComment($cid, $comments) + { if (is_array($comments[$cid]['replies'])) { foreach ($comments[$cid]['replies'] as $rid) { $comments = $this->removeComment($rid, $comments); @@ -753,7 +769,8 @@ protected function removeComment($cid, $comments) { * @param string $reply comment id on which the user requested a reply * @param bool $isVisible is marked as visible */ - protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true) { + protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = '', $isVisible = true) + { // comment was removed if (!isset($data['comments'][$cid])) { return; @@ -799,35 +816,36 @@ protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = ' * @param bool $isVisible is marked as visible * @param string $hidden extra class, for the admin only hidden view */ - protected function showComment($cid, &$data, $parent, $reply, $isVisible, $hidden) { + protected function showComment($cid, &$data, $parent, $reply, $isVisible, $hidden) + { global $conf, $lang, $HIGH, $INPUT; $comment = $data['comments'][$cid]; // comment head with date and user data - ptln('
    ', 4); + ptln('
    ', 4); ptln('
    ', 6); - ptln('', 8); + ptln('', 8); $head = ''; // prepare variables if (is_array($comment['user'])) { // new format - $user = $comment['user']['id']; - $name = $comment['user']['name']; - $mail = $comment['user']['mail']; - $url = $comment['user']['url']; + $user = $comment['user']['id']; + $name = $comment['user']['name']; + $mail = $comment['user']['mail']; + $url = $comment['user']['url']; $address = $comment['user']['address']; } else { // old format - $user = $comment['user']; - $name = $comment['name']; - $mail = $comment['mail']; - $url = $comment['url']; + $user = $comment['user']; + $name = $comment['name']; + $mail = $comment['mail']; + $url = $comment['url']; $address = $comment['address']; } if (is_array($comment['date'])) { // new format - $created = $comment['date']['created']; - $modified = $comment['date']['modified'] ?: null; + $created = $comment['date']['created']; + $modified = $comment['date']['modified'] ?? null; } else { // old format - $created = $comment['date']; + $created = $comment['date']; $modified = $comment['edited']; } @@ -844,7 +862,7 @@ protected function showComment($cid, &$data, $parent, $reply, $isVisible, $hidde $user_data['user'] = $user; $user_data['mail'] = $mail; $avatar = $this->avatar->getXHTML($user_data, $name, 'left'); - if($avatar) { + if ($avatar) { $head .= $avatar; } } @@ -854,27 +872,27 @@ protected function showComment($cid, &$data, $parent, $reply, $isVisible, $hidde } elseif ($url) { $head .= $this->external_link($this->checkURL($url), $showname, 'urlextern url fn'); } else { - $head .= ''.$showname.''; + $head .= '' . $showname . ''; } if ($address) { - $head .= ', '.$address.''; + $head .= ', ' . $address . ''; } - $head .= ', '. - ''. - dformat($created, $conf['dformat']).''; + $head .= ', ' . + '' . + dformat($created, $conf['dformat']) . ''; if ($modified) { - $head .= ', '.dformat($modified, $conf['dformat']). + $head .= ', ' . dformat($modified, $conf['dformat']) . ''; } ptln($head, 8); ptln('
    ', 6); // class="comment_head" // main comment content - ptln('
    useAvatar() ? $this->getWidthStyle() : '').'>', 6); - echo ($HIGH?html_hilight($comment['xhtml'],$HIGH):$comment['xhtml']).DOKU_LF; + ptln('
    useAvatar() ? $this->getWidthStyle() : '') . '>', 6); + echo ($HIGH ? html_hilight($comment['xhtml'], $HIGH) : $comment['xhtml']) . DOKU_LF; ptln('
    ', 6); // class="comment_body" if ($isVisible) { @@ -919,7 +937,7 @@ protected function showReplyForm($cid, $reply) * * * @param string $cid comment id - * @param array $data array with all comments by reference + * @param array $data array with all comments by reference * @param string $reply * @param bool $isVisible */ @@ -929,7 +947,7 @@ protected function showReplies($cid, &$data, $reply, &$isVisible) if (!count($comment['replies'])) { return; } - ptln('
    getWidthStyle().'>', 4); + ptln('
    getWidthStyle() . '>', 4); $isVisible = ($comment['show'] && $isVisible); foreach ($comment['replies'] as $rid) { $this->showCommentWithReplies($rid, $data, $cid, $reply, $isVisible); @@ -946,7 +964,7 @@ protected function useAvatar() { if (is_null($this->useAvatar)) { $this->useAvatar = $this->getConf('useavatar') - && ($this->avatar = $this->loadHelper('avatar', false)); + && ($this->avatar = $this->loadHelper('avatar', false)); } return $this->useAvatar; } @@ -956,10 +974,11 @@ protected function useAvatar() * * @return string */ - protected function getWidthStyle() { - if (is_null($this->style)){ + protected function getWidthStyle() + { + if (is_null($this->style)) { if ($this->useAvatar()) { - $this->style = ' style="margin-left: '.($this->avatar->getConf('size') + 14).'px;"'; + $this->style = ' style="margin-left: ' . ($this->avatar->getConf('size') + 14) . 'px;"'; } else { $this->style = ' style="margin-left: 20px;"'; } @@ -970,16 +989,19 @@ protected function getWidthStyle() { /** * Show the button which toggles between show/hide of the entire discussion section */ - protected function showDiscussionToggleButton() { + protected function showDiscussionToggleButton() + { ptln('
    '); - ptln(''); + ptln(''); ptln('
    '); } /** * Outputs the comment form */ - protected function showCommentForm($raw = '', $act = 'add', $cid = null) { + protected function showCommentForm($raw = '', $act = 'add', $cid = null) + { global $lang, $conf, $ID, $INPUT; // not for unregistered users when guest comments aren't allowed @@ -999,129 +1021,149 @@ protected function showCommentForm($raw = '', $act = 'add', $cid = null) { ?>
    -
    -
    - - - - - - server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionMod())) { - ?> - -
    - -
    -
    - -
    - " + accept-charset=""> +
    + + + + + + server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionMod())) { + ?> + +
    + +
    +
    + +
    + getConf('urlfield')) { - ?> -
    - -
    - getConf('urlfield')) { + ?> +
    + +
    + getConf('addressfield')) { - ?> -
    - -
    - getConf('addressfield')) { + ?> +
    + +
    + getConf('adminimport') && ($this->helper->isDiscussionMod())) { - ?> -
    - -
    - getConf('adminimport') && ($this->helper->isDiscussionMod())) { + ?> +
    + +
    + - - -
    - getLang('entercomment'); echo ($this->getConf('wikisyntaxok') ? "" : ":"); - if($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?> - - - getConf('wikisyntaxok')) { ?> -
    - -
    - -
    - -
    - - loadHelper('captcha', false); - if ($captcha && $captcha->isEnabled()) { - echo $captcha->getHTML(); - } - - /** @var helper_plugin_recaptcha $recaptcha */ - $recaptcha = $this->loadHelper('recaptcha', false); - if ($recaptcha && $recaptcha->isEnabled()) { - echo $recaptcha->getHTML(); - } - ?> - - - - - server->has('REMOTE_USER') || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers']) && $this->getConf('subscribe')) { ?> -
    - - -
    - - -
    -
     
    -
    - + // for saving a comment + } else { + ?> + + +
    + getLang('entercomment'); + echo($this->getConf('wikisyntaxok') ? "" : ":"); + if ($this->getConf('wikisyntaxok')) echo '. ' . $this->getLang('wikisyntax') . ':'; ?> + + + getConf('wikisyntaxok')) { ?> +
    + +
    + +
    + +
    + + loadHelper('captcha', false); + if ($captcha && $captcha->isEnabled()) { + echo $captcha->getHTML(); + } + + /** @var helper_plugin_recaptcha $recaptcha */ + $recaptcha = $this->loadHelper('recaptcha', false); + if ($recaptcha && $recaptcha->isEnabled()) { + echo $recaptcha->getHTML(); + } + ?> + + + + + server->has('REMOTE_USER') + || $INPUT->server->has('REMOTE_USER') && !$conf['subscribers']) + && $this->getConf('subscribe')) { ?> +
    + + +
    + + +
    +
     
    +
    +
    -
    -
    - - - - - -
    + +
    + + + + + +
    - * @author Ben Coburn - * - * @param int $date + * @param int $date * @param string $id page id * @param string $type create/edit/delete/show/hide comment 'cc', 'ec', 'dc', 'sc', 'hc' * @param string $summary * @param string $extra + * @author Ben Coburn + * + * @author Esther Brunner */ - protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') { + protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = '') + { global $conf, $INPUT; - $changelog = $conf['metadir'].'/_comments.changes'; + $changelog = $conf['metadir'] . '/_comments.changes'; //use current time if none supplied - if(!$date) { + if (!$date) { $date = time(); } $remote = $INPUT->server->str('REMOTE_ADDR'); - $user = $INPUT->server->str('REMOTE_USER'); + $user = $INPUT->server->str('REMOTE_USER'); $strip = ["\t", "\n"]; $logline = [ - 'date' => $date, - 'ip' => $remote, - 'type' => str_replace($strip, '', $type), - 'id' => $id, - 'user' => $user, - 'sum' => str_replace($strip, '', $summary), - 'extra' => str_replace($strip, '', $extra) + 'date' => $date, + 'ip' => $remote, + 'type' => str_replace($strip, '', $type), + 'id' => $id, + 'user' => $user, + 'sum' => str_replace($strip, '', $summary), + 'extra' => str_replace($strip, '', $extra) ]; // add changelog line - $logline = implode("\t", $logline)."\n"; + $logline = implode("\t", $logline) . "\n"; io_saveFile($changelog, $logline, true); //global changelog cache $this->trimRecentCommentsLog($changelog); @@ -1201,39 +1245,41 @@ protected function addLogEntry($date, $id, $type = 'cc', $summary = '', $extra = * changes or $conf['recent'] items, which ever is larger. * The trimming is only done once a day. * - * @author Ben Coburn - * * @param string $changelog file path * @return bool + * @author Ben Coburn + * */ - protected function trimRecentCommentsLog($changelog) { + protected function trimRecentCommentsLog($changelog) + { global $conf; - if (@file_exists($changelog) && - (filectime($changelog) + 86400) < time() && - !@file_exists($changelog.'_tmp') + if (@file_exists($changelog) + && (filectime($changelog) + 86400) < time() + && !@file_exists($changelog . '_tmp') ) { io_lock($changelog); $lines = file($changelog); - if (count($lines)<$conf['recent']) { + if (count($lines) < $conf['recent']) { // nothing to trim io_unlock($changelog); return true; } - io_saveFile($changelog.'_tmp', ''); // presave tmp as 2nd lock - $trim_time = time() - $conf['recent_days']*86400; + // presave tmp as 2nd lock + io_saveFile($changelog . '_tmp', ''); + $trim_time = time() - $conf['recent_days'] * 86400; $out_lines = []; $num = count($lines); - for ($i=0; $i<$num; $i++) { + for ($i = 0; $i < $num; $i++) { $log = parseChangelogLine($lines[$i]); if ($log === false) continue; // discard junk if ($log['date'] < $trim_time) { - $old_lines[$log['date'].".$i"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions) + $old_lines[$log['date'] . ".$i"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions) } else { - $out_lines[$log['date'].".$i"] = $lines[$i]; // definitely keep these lines + $out_lines[$log['date'] . ".$i"] = $lines[$i]; // definitely keep these lines } } @@ -1243,17 +1289,17 @@ protected function trimRecentCommentsLog($changelog) { $extra = $conf['recent'] - count($out_lines); // do we need extra lines do bring us up to minimum if ($extra > 0) { ksort($old_lines); - $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines); + $out_lines = array_merge(array_slice($old_lines, -$extra), $out_lines); } // save trimmed changelog - io_saveFile($changelog.'_tmp', implode('', $out_lines)); + io_saveFile($changelog . '_tmp', implode('', $out_lines)); @unlink($changelog); - if (!rename($changelog.'_tmp', $changelog)) { + if (!rename($changelog . '_tmp', $changelog)) { // rename failed so try another way... io_unlock($changelog); io_saveFile($changelog, implode('', $out_lines)); - @unlink($changelog.'_tmp'); + @unlink($changelog . '_tmp'); } else { io_unlock($changelog); } @@ -1265,19 +1311,20 @@ protected function trimRecentCommentsLog($changelog) { /** * Sends a notify mail on new comment * - * @param array $comment data array of the new comment - * @param array $subscribers data of the subscribers by reference + * @param array $comment data array of the new comment + * @param array $subscribers data of the subscribers by reference * * @author Andreas Gohr * @author Esther Brunner */ - protected function notify($comment, &$subscribers) { + protected function notify($comment, &$subscribers) + { global $conf, $ID, $INPUT, $auth; $notify_text = io_readfile($this->localfn('subscribermail')); $confirm_text = io_readfile($this->localfn('confirmsubscribe')); - $subject_notify = '['.$conf['title'].'] '.$this->getLang('mail_newcomment'); - $subject_subscribe = '['.$conf['title'].'] '.$this->getLang('subscribe'); + $subject_notify = '[' . $conf['title'] . '] ' . $this->getLang('mail_newcomment'); + $subject_subscribe = '[' . $conf['title'] . '] ' . $this->getLang('subscribe'); $mailer = new Mailer(); if (!$INPUT->server->has('REMOTE_USER')) { @@ -1321,14 +1368,14 @@ protected function notify($comment, &$subscribers) { $moderatorgroups = array_unique($moderatorgroups); $moderatorgroups = array_filter($moderatorgroups); // search for moderators users - foreach($moderatorgroups as $moderatorgroup) { - if(!$auth->isCaseSensitive()) { + foreach ($moderatorgroups as $moderatorgroup) { + if (!$auth->isCaseSensitive()) { $moderatorgroup = PhpString::strtolower($moderatorgroup); } // create a clean mailing list $bccs = []; - if($moderatorgroup[0] == '@') { - foreach($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) { + if ($moderatorgroup[0] == '@') { + foreach ($auth->retrieveUsers(0, 0, ['grps' => $auth->cleanGroup(substr($moderatorgroup, 1))]) as $user) { if (!empty($user['mail'])) { $bccs[] = $user['mail']; } @@ -1358,7 +1405,7 @@ protected function notify($comment, &$subscribers) { ); $to = $data['addresslist']; - if(!empty($to)) { + if (!empty($to)) { $mailer->bcc($to); $mailer->send(); } @@ -1367,15 +1414,15 @@ protected function notify($comment, &$subscribers) { // notify comment subscribers if (!empty($subscribers)) { - foreach($subscribers as $mail => $data) { + foreach ($subscribers as $mail => $data) { $mailer->bcc($mail); - if($data['active']) { + if ($data['active']) { $replace['UNSUBSCRIBE'] = wl($ID, 'do=discussion_unsubscribe&hash=' . $data['hash'], true, '&'); $mailer->subject($subject_notify); $mailer->setBody($notify_text, $replace); $mailer->send(); - } elseif(!$data['confirmsent']) { + } elseif (!$data['confirmsent']) { $confirm_replace['SUBSCRIBE'] = wl($ID, 'do=discussion_confirmsubscribe&hash=' . $data['hash'], true, '&'); $mailer->subject($subject_subscribe); @@ -1393,7 +1440,8 @@ protected function notify($comment, &$subscribers) { * @param array $data array with all comments * @return int */ - protected function countVisibleComments($data) { + protected function countVisibleComments($data) + { $number = 0; foreach ($data['comments'] as $comment) { if ($comment['parent']) continue; @@ -1415,7 +1463,8 @@ protected function countVisibleComments($data) { * @param array $rids * @return int counted replies */ - protected function countVisibleReplies(&$data, $rids) { + protected function countVisibleReplies(&$data, $rids) + { $number = 0; foreach ($rids as $rid) { if (!isset($data['comments'][$rid])) continue; // reply was removed @@ -1436,7 +1485,8 @@ protected function countVisibleReplies(&$data, $rids) { * @param string $raw comment text * @return null|string */ - protected function renderComment($raw) { + protected function renderComment($raw) + { if ($this->getConf('wikisyntaxok')) { // Note the warning for render_text: // "very ineffecient for small pieces of data - try not to use" @@ -1455,7 +1505,8 @@ protected function renderComment($raw) { * @param string $title * @return bool */ - protected function hasDiscussion(&$title) { + protected function hasDiscussion(&$title) + { global $ID; $file = metaFN($ID, '.comments'); @@ -1487,14 +1538,15 @@ protected function hasDiscussion(&$title) { * * @return string */ - protected function newThread() { + protected function newThread() + { global $ID, $INFO, $INPUT; - $ns = cleanID($INPUT->str('ns')); + $ns = cleanID($INPUT->str('ns')); $title = str_replace(':', '', $INPUT->str('title')); - $back = $ID; - $ID = ($ns ? $ns.':' : '').cleanID($title); - $INFO = pageinfo(); + $back = $ID; + $ID = ($ns ? $ns . ':' : '') . cleanID($title); + $INFO = pageinfo(); // check if we are allowed to create this file if ($INFO['perm'] >= AUTH_CREATE) { @@ -1510,7 +1562,7 @@ protected function newThread() { if (!@file_exists($INFO['filepath'])) { global $TEXT; - $TEXT = pageTemplate(($ns ? $ns.':' : '').$title); + $TEXT = pageTemplate(($ns ? $ns . ':' : '') . $title); if (!$TEXT) { $data = ['id' => $ID, 'ns' => $ns, 'title' => $title, 'back' => $back]; $TEXT = $this->pageTemplate($data); @@ -1530,36 +1582,37 @@ protected function newThread() { * @param array $data * @return string */ - protected function pageTemplate($data) { + protected function pageTemplate($data) + { global $conf, $INFO, $INPUT; - $id = $data['id']; + $id = $data['id']; $user = $INPUT->server->str('REMOTE_USER'); - $tpl = io_readFile(DOKU_PLUGIN.'discussion/_template.txt'); + $tpl = io_readFile(DOKU_PLUGIN . 'discussion/_template.txt'); // standard replacements $replace = [ - '@NS@' => $data['ns'], - '@PAGE@' => strtr(noNS($id),'_',' '), - '@USER@' => $user, - '@NAME@' => $INFO['userinfo']['name'], - '@MAIL@' => $INFO['userinfo']['mail'], - '@DATE@' => dformat(time(), $conf['dformat']), + '@NS@' => $data['ns'], + '@PAGE@' => strtr(noNS($id), '_', ' '), + '@USER@' => $user, + '@NAME@' => $INFO['userinfo']['name'], + '@MAIL@' => $INFO['userinfo']['mail'], + '@DATE@' => dformat(time(), $conf['dformat']), ]; // additional replacements - $replace['@BACK@'] = $data['back']; + $replace['@BACK@'] = $data['back']; $replace['@TITLE@'] = $data['title']; // avatar if useavatar and avatar plugin available if ($this->getConf('useavatar') && !plugin_isdisabled('avatar')) { - $replace['@AVATAR@'] = '{{avatar>'.$user.' }} '; + $replace['@AVATAR@'] = '{{avatar>' . $user . ' }} '; } else { $replace['@AVATAR@'] = ''; } // tag if tag plugin is available - if (!plugin_isdisabled('tag')){ + if (!plugin_isdisabled('tag')) { $replace['@TAG@'] = "\n\n{{tag>}}"; } else { $replace['@TAG@'] = ''; @@ -1572,7 +1625,8 @@ protected function pageTemplate($data) { /** * Checks if the CAPTCHA string submitted is valid */ - protected function captchaCheck() { + protected function captchaCheck() + { global $INPUT; /** @var helper_plugin_captcha $captcha */ if (!$captcha = $this->loadHelper('captcha', false)) { @@ -1594,7 +1648,8 @@ protected function captchaCheck() { * * @author Adrian Schlegel */ - protected function recaptchaCheck() { + protected function recaptchaCheck() + { global $INPUT; /** @var helper_plugin_recaptcha $recaptcha */ if (!$recaptcha = plugin_load('helper', 'recaptcha')) @@ -1605,7 +1660,7 @@ protected function recaptchaCheck() { $response = $recaptcha->check(); if (!$response->is_valid) { - msg($recaptcha->getLang('testfailed'),-1); + msg($recaptcha->getLang('testfailed'), -1); if ($INPUT->str('comment') == 'save') { $INPUT->str('comment', 'edit'); } elseif ($INPUT->str('comment') == 'add') { @@ -1622,7 +1677,8 @@ protected function recaptchaCheck() { * @param Doku_Event $event * @param $param */ - public function addIndexVersion(Doku_Event $event, $param) { + public function addIndexVersion(Doku_Event $event) + { $event->data['discussion'] = '0.1'; } @@ -1634,7 +1690,8 @@ public function addIndexVersion(Doku_Event $event, $param) { * 'id' => string 'page'/'id' for respectively INDEXER_PAGE_ADD and FULLTEXT_SNIPPET_CREATE event * 'text' => string 'body'/'text' */ - public function addCommentsToIndex(Doku_Event $event, $param) { + public function addCommentsToIndex(Doku_Event $event, $param) + { // get .comments meta file name $file = metaFN($event->data[$param['id']], '.comments'); @@ -1647,7 +1704,7 @@ public function addCommentsToIndex(Doku_Event $event, $param) { // now add the comments if (isset($data['comments'])) { foreach ($data['comments'] as $key => $value) { - $event->data[$param['text']] .= DOKU_LF.$this->addCommentWords($key, $data); + $event->data[$param['text']] .= DOKU_LF . $this->addCommentWords($key, $data); } } } @@ -1659,7 +1716,8 @@ public function addCommentsToIndex(Doku_Event $event, $param) { * @param $param * @return void */ - public function fulltextPhraseMatchInComments(Doku_Event $event, $param) { + public function fulltextPhraseMatchInComments(Doku_Event $event) + { if ($event->result === true) return; // get .comments meta file name @@ -1695,7 +1753,8 @@ public function fulltextPhraseMatchInComments(Doku_Event $event, $param) { * @param string $parent cid of parent * @return bool if match true, otherwise false */ - protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '') { + protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '') + { if (!isset($data['comments'][$cid])) return false; // comment was removed $comment = $data['comments'][$cid]; @@ -1709,7 +1768,7 @@ protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '') { return true; } - if (is_array($comment['replies'])) { // and the replies + if (is_array($comment['replies'])) { // and the replies foreach ($comment['replies'] as $rid) { if ($this->phraseMatchInComment($phrase, $rid, $data, $cid)) { return true; @@ -1725,7 +1784,8 @@ protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '') { * @param Doku_Event $event * @param $param */ - public function update_comment_status(Doku_Event $event, $param) { + public function update_comment_status(Doku_Event $event) + { global $ID; $meta = $event->data['current']; @@ -1735,7 +1795,7 @@ public function update_comment_status(Doku_Event $event, $param) { if (isset($meta['plugin_discussion'])) { $status = $meta['plugin_discussion']['status']; // 0, 1 or 2 $title = $meta['plugin_discussion']['title']; - } else if ($status == 1) { + } elseif ($status == 1) { // Don't enable comments when automatic comments are on - this already happens automatically // and if comments are turned off in the admin this only updates the .comments file return; @@ -1748,7 +1808,7 @@ public function update_comment_status(Doku_Event $event, $param) { } if (!array_key_exists('title', $data) || $data['title'] !== $title || !isset($data['status']) || $data['status'] !== $status) { - $data['title'] = $title; + $data['title'] = $title; $data['status'] = $status; if (!isset($data['number'])) { $data['number'] = 0; @@ -1762,11 +1822,12 @@ public function update_comment_status(Doku_Event $event, $param) { * Return words of a given comment and its replies, suitable to be added to the index * * @param string $cid comment id - * @param array $data array with all comments by reference + * @param array $data array with all comments by reference * @param string $parent cid of parent * @return string */ - protected function addCommentWords($cid, &$data, $parent = '') { + protected function addCommentWords($cid, &$data, $parent = '') + { if (!isset($data['comments'][$cid])) return ''; // comment was removed @@ -1777,12 +1838,12 @@ protected function addCommentWords($cid, &$data, $parent = '') { if (!$comment['show']) return ''; // hidden comment $text = $comment['raw']; // we only add the raw comment text - if (is_array($comment['replies'])) { // and the replies + if (is_array($comment['replies'])) { // and the replies foreach ($comment['replies'] as $rid) { $text .= $this->addCommentWords($rid, $data, $cid); } } - return ' '.$text; + return ' ' . $text; } /** @@ -1791,10 +1852,11 @@ protected function addCommentWords($cid, &$data, $parent = '') { * @param string $url * @return string */ - protected function checkURL($url) { - if(preg_match("#^http://|^https://#", $url)) { + protected function checkURL($url) + { + if (preg_match("#^http://|^https://#", $url)) { return hsc($url); - } elseif(substr($url, 0, 4) == 'www.') { + } elseif (substr($url, 0, 4) == 'www.') { return hsc('https://' . $url); } else { return ''; @@ -1804,25 +1866,26 @@ protected function checkURL($url) { /** * Sort threads * - * @param $a - * @param $b + * @param array $a array with comment properties + * @param array $b array with comment properties * @return int */ - function sortCallback($a, $b) { + function sortThreadsOnCreation($a, $b) + { if (is_array($a['date'])) { // new format - $createdA = $a['date']['created']; + $createdA = $a['date']['created']; } else { // old format - $createdA = $a['date']; + $createdA = $a['date']; } if (is_array($b['date'])) { // new format - $createdB = $b['date']['created']; + $createdB = $b['date']['created']; } else { // old format - $createdB = $b['date']; + $createdB = $b['date']; } if ($createdA == $createdB) { From 64829c37106252c090bb45ac0286a7d85bfc0e99 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 21:58:28 +0200 Subject: [PATCH 03/33] syntax: visibility, php8 warnings, refactoring, reformatting --- syntax/comments.php | 43 +++++++++------- syntax/threads.php | 123 ++++++++++++++++++++++++-------------------- 2 files changed, 90 insertions(+), 76 deletions(-) diff --git a/syntax/comments.php b/syntax/comments.php index 75b5901..d949eaf 100644 --- a/syntax/comments.php +++ b/syntax/comments.php @@ -20,26 +20,26 @@ class syntax_plugin_discussion_comments extends DokuWiki_Syntax_Plugin { * * @return string */ - function getType() { return 'substition'; } + public function getType() { return 'substition'; } /** * Paragraph Type * * @return string */ - function getPType() { return 'block'; } + public function getPType() { return 'block'; } /** * Sort for applying this mode * * @return int */ - function getSort() { return 230; } + public function getSort() { return 230; } /** * Connect pattern to lexer */ - function connectTo($mode) { + public function connectTo($mode) { if ($mode == 'base') { $this->Lexer->addSpecialPattern('~~DISCUSSION[^\r\n]*?~~', $mode, 'plugin_discussion_comments'); } @@ -54,37 +54,40 @@ function connectTo($mode) { * @param Doku_Handler $handler The Doku_Handler object * @return array Return an array with all data you want to use in render */ - function handle($match, $state, $pos, Doku_Handler $handler) { - + public function handle($match, $state, $pos, Doku_Handler $handler) { // strip markup $match = substr($match, 12, -2); // split title (if there is one) - list($match, $title) = explode('|', $match, 2); + list($match, $title) = array_pad(explode('|', $match, 2), 2, ''); // assign discussion state - if ($match == ':off') $status = 0; - else if ($match == ':closed') $status = 2; - else $status = 1; + if ($match == ':off') { + $status = 0; + } elseif ($match == ':closed') { + $status = 2; + } else { + // comments enabled + $status = 1; + } - return array($status, $title); + return [$status, $title]; } /** * Handles the actual output creation. * - * @param $mode string output format being rendered - * @param $renderer Doku_Renderer the current renderer object - * @param $data array data created by handler() - * @return boolean rendered correctly? + * @param string $format output format being rendered + * @param Doku_Renderer $renderer the current renderer object + * @param array $data data created by handler() + * @return boolean rendered correctly? */ - function render($mode, Doku_Renderer $renderer, $data) { + public function render($format, Doku_Renderer $renderer, $data) { list($status, $title) = $data; - if ($mode == 'metadata') { - /** @var $renderer Doku_Renderer_metadata */ - $renderer->meta['plugin_discussion'] = array('status' => $status, 'title' => $title); + if ($format == 'metadata') { + /** @var Doku_Renderer_metadata $renderer */ + $renderer->meta['plugin_discussion'] = ['status' => $status, 'title' => $title]; } return true; } } -// vim:ts=4:sw=4:et:enc=utf-8: diff --git a/syntax/threads.php b/syntax/threads.php index f17cd86..e1a5a95 100644 --- a/syntax/threads.php +++ b/syntax/threads.php @@ -1,7 +1,7 @@ */ @@ -16,7 +16,7 @@ class syntax_plugin_discussion_threads extends DokuWiki_Syntax_Plugin { * * @return string */ - function getType() { return 'substition'; } + public function getType() { return 'substition'; } /** * Paragraph Type @@ -24,19 +24,19 @@ function getType() { return 'substition'; } * @see Doku_Handler_Block * @return string */ - function getPType() { return 'block'; } + public function getPType() { return 'block'; } /** * Sort for applying this mode * * @return int */ - function getSort() { return 306; } + public function getSort() { return 306; } /** * @param string $mode */ - function connectTo($mode) { + public function connectTo($mode) { $this->Lexer->addSpecialPattern('\{\{threads>.+?\}\}', $mode, 'plugin_discussion_threads'); } @@ -49,18 +49,18 @@ function connectTo($mode) { * @param Doku_Handler $handler The Doku_Handler object * @return array Return an array with all data you want to use in render */ - function handle($match, $state, $pos, Doku_Handler $handler) { + public function handle($match, $state, $pos, Doku_Handler $handler) { global $ID; $customFlags = array(); $match = substr($match, 10, -2); // strip {{threads> from start and }} from end - list($match, $flags) = explode('&', $match, 2); + list($match, $flags) = array_pad(explode('&', $match, 2),2, ''); $flags = explode('&', $flags); // Identify the count/skipempty flag and remove it before passing it to pagelist foreach($flags as $key => $flag) { if (substr($flag, 0, 5) == "count") { - $tmp = explode('=', $flag); + $tmp = array_pad(explode('=', $flag, 2),2, 0); $customFlags['count'] = $tmp[1]; unset($flags[$key]); } elseif (substr($flag, 0, 9) == "skipempty") { @@ -73,41 +73,51 @@ function handle($match, $state, $pos, Doku_Handler $handler) { } // Ignore params if invalid values have been passed - if(!array_key_exists('count', $customFlags) || $customFlags['count'] <= 0 || !is_numeric($customFlags['count'])) $customFlags['count'] = false; - if(!array_key_exists('skipempty', $customFlags) && !$customFlags['skipempty']) $customFlags['skipempty'] = false; + if(!array_key_exists('count', $customFlags) || $customFlags['count'] <= 0 || !is_numeric($customFlags['count'])) { + $customFlags['count'] = 0; + } + if(!array_key_exists('skipempty', $customFlags) && !$customFlags['skipempty']) { + $customFlags['skipempty'] = false; + } - list($ns, $refine) = explode(' ', $match, 2); + list($ns, $refine) = array_pad(explode(' ', $match, 2), 2, ''); - if (($ns == '*') || ($ns == ':')) $ns = ''; - elseif ($ns == '.') $ns = getNS($ID); - else $ns = cleanID($ns); + if ($ns == '*' || $ns == ':') { + $ns = ''; + } elseif ($ns == '.') { + $ns = getNS($ID); + } else { + $ns = cleanID($ns); + } - return array($ns, $flags, $refine, $customFlags); + return [$ns, $flags, $refine, $customFlags]; } /** * Handles the actual output creation. * - * @param $mode string output format being rendered - * @param $renderer Doku_Renderer the current renderer object - * @param $data array data created by handler() - * @return boolean rendered correctly? + * @param string $format output format being rendered + * @param Doku_Renderer $renderer the current renderer object + * @param array $data data created by handler() + * @return boolean rendered correctly? */ - function render($mode, Doku_Renderer $renderer, $data) { + public function render($format, Doku_Renderer $renderer, $data) { list($ns, $flags, $refine, $customFlags) = $data; $count = $customFlags['count']; $skipEmpty = $customFlags['skipempty']; $noNewThreadForm = $customFlags['nonewthreadform']; $i = 0; - $pages = array(); - /** @var helper_plugin_discussion $my */ - if ($my =& plugin_load('helper', 'discussion')) $pages = $my->getThreads($ns, null, $skipEmpty); + $pages = []; + /** @var helper_plugin_discussion $helper */ + if ($helper = $this->loadHelper('discussion')) { + $pages = $helper->getThreads($ns, null, $skipEmpty); + } // use tag refinements? if ($refine) { /** @var helper_plugin_tag $tag */ - if (plugin_isdisabled('tag') || (!$tag = plugin_load('helper', 'tag'))) { + if (!$tag = $this->loadHelper('tag', false)) { msg('The Tag Plugin must be installed to use tag refinements.', -1); } else { $pages = $tag->tagRefine($pages, $refine); @@ -115,36 +125,35 @@ function render($mode, Doku_Renderer $renderer, $data) { } if (!$pages) { - if ((auth_quickaclcheck($ns.':*') >= AUTH_CREATE) && ($mode == 'xhtml')) { + if (auth_quickaclcheck($ns.':*') >= AUTH_CREATE && $format == 'xhtml') { $renderer->nocache(); if ($noNewThreadForm !== true) { - $renderer->doc .= $this->_newThreadForm($ns); + $renderer->doc .= $this->newThreadForm($ns); } } return true; // nothing to display - } + } - if ($mode == 'xhtml') { - /** @var $renderer Doku_Renderer_xhtml */ + if ($format == 'xhtml') { + /** @var Doku_Renderer_xhtml $renderer */ // prevent caching to ensure content is always fresh $renderer->nocache(); // show form to start a new discussion thread? if ($noNewThreadForm !== true) { - $perm_create = (auth_quickaclcheck($ns.':*') >= AUTH_CREATE); - if ($perm_create && ($this->getConf('threads_formposition') == 'top')) { - $renderer->doc .= $this->_newThreadForm($ns); + $hasCreatePermission = auth_quickaclcheck($ns.':*') >= AUTH_CREATE; + if ($hasCreatePermission && $this->getConf('threads_formposition') == 'top') { + $renderer->doc .= $this->newThreadForm($ns); } } // let Pagelist Plugin do the work for us - /** @var $pagelist helper_plugin_pagelist */ - if (plugin_isdisabled('pagelist') - || (!$pagelist =& plugin_load('helper', 'pagelist'))) { + /** @var helper_plugin_pagelist $pagelist */ + if (!$pagelist = $this->loadHelper('pagelist', false)) { msg('The Pagelist Plugin must be installed for threads lists to work.', -1); return false; } - $pagelist->column['comments'] = true; + $pagelist->addColumn('discussion', 'comments'); $pagelist->setFlags($flags); $pagelist->startList(); foreach ($pages as $page) { @@ -152,22 +161,25 @@ function render($mode, Doku_Renderer $renderer, $data) { $pagelist->addPage($page); $i++; - if($count != false && $i >= $count) break; // Only display the n discussion threads specified by the count flag + if($count > 0 && $i >= $count) { + // Only display the n discussion threads specified by the count flag + break; + } } $renderer->doc .= $pagelist->finishList(); // show form to start a new discussion thread? if ($noNewThreadForm !== true) { - if ($perm_create && ($this->getConf('threads_formposition') == 'bottom')) { - $renderer->doc .= $this->_newThreadForm($ns); + if ($hasCreatePermission && $this->getConf('threads_formposition') == 'bottom') { + $renderer->doc .= $this->newThreadForm($ns); } } return true; // for metadata renderer - } elseif ($mode == 'metadata') { - /** @var $renderer Doku_Renderer_metadata */ + } elseif ($format == 'metadata') { + /** @var Doku_Renderer_metadata $renderer */ foreach ($pages as $page) { $renderer->meta['relation']['references'][$page['id']] = true; } @@ -183,24 +195,23 @@ function render($mode, Doku_Renderer $renderer, $data) { * Show the form to start a new discussion thread * * @param string $ns - * @return string + * @return string html */ - function _newThreadForm($ns) { + protected function newThreadForm($ns) { global $ID; global $lang; - return '
    '.DOKU_LF. - '
    '.DOKU_LF. - DOKU_TAB.'
    '.DOKU_LF. - DOKU_TAB.DOKU_TAB.' '.$this->getLang('newthread').': '.DOKU_LF. - DOKU_TAB.DOKU_TAB.''.DOKU_LF. - DOKU_TAB.DOKU_TAB.''.DOKU_LF. - DOKU_TAB.DOKU_TAB.''.DOKU_LF. - DOKU_TAB.DOKU_TAB.''.DOKU_LF. - DOKU_TAB.DOKU_TAB.''.DOKU_LF. - DOKU_TAB.'
    '.DOKU_LF. - '
    '.DOKU_LF. - '
    '.DOKU_LF; + return '
    ' + . '
    ' + . '
    ' + . ' ' . $this->getLang('newthread') . ': ' + . '' + . '' + . '' + . '' + . '' + . '
    ' + . '
    ' + . '
    '; } } -// vim:ts=4:sw=4:et:enc=utf-8: From dfc5d08b5eea7cef6dcb63789032dcac586bcb87 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 22:00:21 +0200 Subject: [PATCH 04/33] syntax: reformatting --- syntax/comments.php | 35 ++++++++++++++++++--------- syntax/threads.php | 58 ++++++++++++++++++++++++++++----------------- 2 files changed, 60 insertions(+), 33 deletions(-) diff --git a/syntax/comments.php b/syntax/comments.php index d949eaf..fa7cc64 100644 --- a/syntax/comments.php +++ b/syntax/comments.php @@ -13,33 +13,44 @@ * All DokuWiki plugins to extend the parser/rendering mechanism * need to inherit from this class */ -class syntax_plugin_discussion_comments extends DokuWiki_Syntax_Plugin { +class syntax_plugin_discussion_comments extends DokuWiki_Syntax_Plugin +{ /** * Syntax Type * * @return string */ - public function getType() { return 'substition'; } + public function getType() + { + return 'substition'; + } /** * Paragraph Type * * @return string */ - public function getPType() { return 'block'; } + public function getPType() + { + return 'block'; + } /** * Sort for applying this mode * * @return int */ - public function getSort() { return 230; } + public function getSort() + { + return 230; + } /** * Connect pattern to lexer */ - public function connectTo($mode) { + public function connectTo($mode) + { if ($mode == 'base') { $this->Lexer->addSpecialPattern('~~DISCUSSION[^\r\n]*?~~', $mode, 'plugin_discussion_comments'); } @@ -48,13 +59,14 @@ public function connectTo($mode) { /** * Handler to prepare matched data for the rendering process * - * @param string $match The text matched by the patterns - * @param int $state The lexer state for the match - * @param int $pos The character position of the matched text - * @param Doku_Handler $handler The Doku_Handler object + * @param string $match The text matched by the patterns + * @param int $state The lexer state for the match + * @param int $pos The character position of the matched text + * @param Doku_Handler $handler The Doku_Handler object * @return array Return an array with all data you want to use in render */ - public function handle($match, $state, $pos, Doku_Handler $handler) { + public function handle($match, $state, $pos, Doku_Handler $handler) + { // strip markup $match = substr($match, 12, -2); @@ -82,7 +94,8 @@ public function handle($match, $state, $pos, Doku_Handler $handler) { * @param array $data data created by handler() * @return boolean rendered correctly? */ - public function render($format, Doku_Renderer $renderer, $data) { + public function render($format, Doku_Renderer $renderer, $data) + { list($status, $title) = $data; if ($format == 'metadata') { /** @var Doku_Renderer_metadata $renderer */ diff --git a/syntax/threads.php b/syntax/threads.php index e1a5a95..b23a45d 100644 --- a/syntax/threads.php +++ b/syntax/threads.php @@ -9,58 +9,70 @@ /** * Class syntax_plugin_discussion_threads */ -class syntax_plugin_discussion_threads extends DokuWiki_Syntax_Plugin { +class syntax_plugin_discussion_threads extends DokuWiki_Syntax_Plugin +{ /** * Syntax Type * * @return string */ - public function getType() { return 'substition'; } + public function getType() + { + return 'substition'; + } /** * Paragraph Type * - * @see Doku_Handler_Block * @return string + * @see Doku_Handler_Block */ - public function getPType() { return 'block'; } + public function getPType() + { + return 'block'; + } /** * Sort for applying this mode * * @return int */ - public function getSort() { return 306; } + public function getSort() + { + return 306; + } /** * @param string $mode */ - public function connectTo($mode) { + public function connectTo($mode) + { $this->Lexer->addSpecialPattern('\{\{threads>.+?\}\}', $mode, 'plugin_discussion_threads'); } /** * Handler to prepare matched data for the rendering process * - * @param string $match The text matched by the patterns - * @param int $state The lexer state for the match - * @param int $pos The character position of the matched text - * @param Doku_Handler $handler The Doku_Handler object + * @param string $match The text matched by the patterns + * @param int $state The lexer state for the match + * @param int $pos The character position of the matched text + * @param Doku_Handler $handler The Doku_Handler object * @return array Return an array with all data you want to use in render */ - public function handle($match, $state, $pos, Doku_Handler $handler) { + public function handle($match, $state, $pos, Doku_Handler $handler) + { global $ID; $customFlags = array(); $match = substr($match, 10, -2); // strip {{threads> from start and }} from end - list($match, $flags) = array_pad(explode('&', $match, 2),2, ''); + list($match, $flags) = array_pad(explode('&', $match, 2), 2, ''); $flags = explode('&', $flags); // Identify the count/skipempty flag and remove it before passing it to pagelist - foreach($flags as $key => $flag) { + foreach ($flags as $key => $flag) { if (substr($flag, 0, 5) == "count") { - $tmp = array_pad(explode('=', $flag, 2),2, 0); + $tmp = array_pad(explode('=', $flag, 2), 2, 0); $customFlags['count'] = $tmp[1]; unset($flags[$key]); } elseif (substr($flag, 0, 9) == "skipempty") { @@ -73,10 +85,10 @@ public function handle($match, $state, $pos, Doku_Handler $handler) { } // Ignore params if invalid values have been passed - if(!array_key_exists('count', $customFlags) || $customFlags['count'] <= 0 || !is_numeric($customFlags['count'])) { + if (!array_key_exists('count', $customFlags) || $customFlags['count'] <= 0 || !is_numeric($customFlags['count'])) { $customFlags['count'] = 0; } - if(!array_key_exists('skipempty', $customFlags) && !$customFlags['skipempty']) { + if (!array_key_exists('skipempty', $customFlags) && !$customFlags['skipempty']) { $customFlags['skipempty'] = false; } @@ -101,7 +113,8 @@ public function handle($match, $state, $pos, Doku_Handler $handler) { * @param array $data data created by handler() * @return boolean rendered correctly? */ - public function render($format, Doku_Renderer $renderer, $data) { + public function render($format, Doku_Renderer $renderer, $data) + { list($ns, $flags, $refine, $customFlags) = $data; $count = $customFlags['count']; $skipEmpty = $customFlags['skipempty']; @@ -125,7 +138,7 @@ public function render($format, Doku_Renderer $renderer, $data) { } if (!$pages) { - if (auth_quickaclcheck($ns.':*') >= AUTH_CREATE && $format == 'xhtml') { + if (auth_quickaclcheck($ns . ':*') >= AUTH_CREATE && $format == 'xhtml') { $renderer->nocache(); if ($noNewThreadForm !== true) { $renderer->doc .= $this->newThreadForm($ns); @@ -141,7 +154,7 @@ public function render($format, Doku_Renderer $renderer, $data) { // show form to start a new discussion thread? if ($noNewThreadForm !== true) { - $hasCreatePermission = auth_quickaclcheck($ns.':*') >= AUTH_CREATE; + $hasCreatePermission = auth_quickaclcheck($ns . ':*') >= AUTH_CREATE; if ($hasCreatePermission && $this->getConf('threads_formposition') == 'top') { $renderer->doc .= $this->newThreadForm($ns); } @@ -157,11 +170,11 @@ public function render($format, Doku_Renderer $renderer, $data) { $pagelist->setFlags($flags); $pagelist->startList(); foreach ($pages as $page) { - $page['class'] = 'discussion_status'.$page['status']; + $page['class'] = 'discussion_status' . $page['status']; $pagelist->addPage($page); $i++; - if($count > 0 && $i >= $count) { + if ($count > 0 && $i >= $count) { // Only display the n discussion threads specified by the count flag break; } @@ -197,7 +210,8 @@ public function render($format, Doku_Renderer $renderer, $data) { * @param string $ns * @return string html */ - protected function newThreadForm($ns) { + protected function newThreadForm($ns) + { global $ID; global $lang; From da3a8801411b256bbc4e1df1dc1db5700f5241a8 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 22:24:28 +0200 Subject: [PATCH 05/33] remove autoloaded files, php8 warnings --- convert.php | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/convert.php b/convert.php index d773162..a73be27 100644 --- a/convert.php +++ b/convert.php @@ -16,11 +16,6 @@ die('Conversion already completed.'); require_once(DOKU_INC.'inc/init.php'); -require_once(DOKU_INC.'inc/common.php'); -require_once(DOKU_INC.'inc/io.php'); -require_once(DOKU_INC.'inc/search.php'); -require_once(DOKU_INC.'inc/pageutils.php'); -require_once(DOKU_INC.'inc/parserutils.php'); $files = getDiscussionPages(); $n = 0; @@ -108,7 +103,7 @@ function convertDiscussionPage($file) { $in = '//'; $out = ': //'; } - list($meta, $raw) = explode($out, $comment, 2); + list($meta, $raw) = array_pad(explode($out, $comment, 2),2, ''); $raw = trim($raw); // skip empty comments @@ -117,12 +112,12 @@ function convertDiscussionPage($file) { continue; } - list($mail, $meta) = explode($in, $meta, 2); - list($name, $strd) = explode(', ', $meta, 2); + list($mail, $meta) = array_pad(explode($in, $meta, 2),2, ''); + list($name, $strd) = array_pad(explode(', ', $meta, 2),2, ''); $date = strtotime($strd); if ($date == -1) $date = time(); if ($mail) { - list($mail) = explode(' |', $mail, 2); + list($mail) = array_pad(explode(' |', $mail, 2),2, ''); $mail = substr(strrchr($mail, '>'), 1); } $cid = md5($name.$date); From ab996e0efa9c7b651f73a5f568f733f5cd3712b9 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 22:26:42 +0200 Subject: [PATCH 06/33] convert: reformatting --- convert.php | 109 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 62 insertions(+), 47 deletions(-) diff --git a/convert.php b/convert.php index a73be27..72d849e 100644 --- a/convert.php +++ b/convert.php @@ -6,30 +6,31 @@ /* ----- Settings ----- */ -define('DOKU_INC', realpath(dirname(__FILE__).'/../../../').'/'); -define('DISCUSSION_NS', 'discussion'); +define('DOKU_INC', realpath(dirname(__FILE__) . '/../../../') . '/'); +const DISCUSSION_NS = 'discussion'; /* ----- Main ----- */ // conversion script should only be run once -if (@file_exists(dirname(__FILE__).'/convert_completed')) -die('Conversion already completed.'); +if (@file_exists(dirname(__FILE__) . '/convert_completed')) { + die('Conversion already completed.'); +} -require_once(DOKU_INC.'inc/init.php'); +require_once(DOKU_INC . 'inc/init.php'); $files = getDiscussionPages(); -$n = 0; +$n = 0; foreach ($files as $file) { if (convertDiscussionPage($file)) { - echo $file['id'].'
    '; + echo $file['id'] . '
    '; $n++; } } if ($n > 0) { - io_saveFile(dirname(__FILE__).'/convert_completed', ''); - echo '
    Successfully converted '.$n.' discussion pages to new comments meta files.'; + io_saveFile(dirname(__FILE__) . '/convert_completed', ''); + echo '
    Successfully converted ' . $n . ' discussion pages to new comments meta files.'; } else { echo 'No discussion pages found.'; } @@ -39,44 +40,54 @@ /** * returns a list of all discussion pages in the wiki */ -function getDiscussionPages() { +function getDiscussionPages() +{ global $conf; - $data = array(); - search($data, $conf['datadir'], 'search_discussionpages', array()); + $data = []; + search($data, $conf['datadir'], 'search_discussionpages', []); return $data; } /** * function for the search callback */ -function search_discussionpages(&$data, $base, $file, $type, $lvl, $opts) { +function search_discussionpages(&$data, $base, $file, $type, $lvl, $opts) +{ global $conf; - if ($type == 'd') return true; // recurse into directories - if (!preg_match('#'.preg_quote('/'.DISCUSSION_NS.'/', '#').'#u', $file)) return false; - if (!preg_match('#\.txt$#', $file)) return false; + // recurse into directories + if ($type == 'd') { + return true; + } + if (!preg_match('#' . preg_quote('/' . DISCUSSION_NS . '/', '#') . '#u', $file)) { + return false; + } + if (!preg_match('#\.txt$#', $file)) { + return false; + } - $id = pathID(str_replace(DISCUSSION_NS.'/', '', $file)); - $data[] = array( - 'id' => $id, - 'old' => $conf['datadir'].$file, - 'new' => metaFN($id, '.comments') - ); + $id = pathID(str_replace(DISCUSSION_NS . '/', '', $file)); + $data[] = [ + 'id' => $id, + 'old' => $conf['datadir'] . $file, + 'new' => metaFN($id, '.comments') + ]; return true; } /** * this converts individual discussion pages to .comment meta files */ -function convertDiscussionPage($file) { +function convertDiscussionPage($file) +{ // read the old file $data = io_readFile($file['old'], false); // handle file with no comments yet if (trim($data) == '') { - io_saveFile($file['new'], serialize(array('status' => 1, 'number' => 0))); + io_saveFile($file['new'], serialize(['status' => 1, 'number' => 0])); @unlink($file['old']); return true; } @@ -85,26 +96,29 @@ function convertDiscussionPage($file) { $old = explode('----', $data); // merge with possibly already existing (newer) comments - $comments = array(); - if (@file_exists($file['new'])) + $comments = []; + if (@file_exists($file['new'])) { $comments = unserialize(io_readFile($file['old'], false)); + } // set general info - if (!isset($comments['status'])) $comments['status'] = 1; + if (!isset($comments['status'])) { + $comments['status'] = 1; + } $comments['number'] += count($old); foreach ($old as $comment) { // prepare comment data if (strpos($comment, '') !== false) { - $in = ''; + $in = ''; $out = ':'; } else { - $in = '//'; + $in = '//'; $out = ': //'; } - list($meta, $raw) = array_pad(explode($out, $comment, 2),2, ''); - $raw = trim($raw); + list($meta, $raw) = array_pad(explode($out, $comment, 2), 2, ''); + $raw = trim($raw); // skip empty comments if (!$raw) { @@ -112,30 +126,32 @@ function convertDiscussionPage($file) { continue; } - list($mail, $meta) = array_pad(explode($in, $meta, 2),2, ''); - list($name, $strd) = array_pad(explode(', ', $meta, 2),2, ''); + list($mail, $meta) = array_pad(explode($in, $meta, 2), 2, ''); + list($name, $strd) = array_pad(explode(', ', $meta, 2), 2, ''); $date = strtotime($strd); - if ($date == -1) $date = time(); + if ($date == -1) { + $date = time(); + } if ($mail) { - list($mail) = array_pad(explode(' |', $mail, 2),2, ''); + list($mail) = array_pad(explode(' |', $mail, 2), 2, ''); $mail = substr(strrchr($mail, '>'), 1); } - $cid = md5($name.$date); + $cid = md5($name . $date); // render comment $xhtml = p_render('xhtml', p_get_instructions($raw), $info); // fill in the converted comment - $comments['comments'][$cid] = array( - 'user' => array( - 'name' => hsc($name), - 'mail' => hsc($mail)), - 'date' => array('created' => $date), - 'show' => true, - 'raw' => $raw, - 'xhtml' => $xhtml, - 'replies' => array() - ); + $comments['comments'][$cid] = [ + 'user' => [ + 'name' => hsc($name), + 'mail' => hsc($mail)], + 'date' => ['created' => $date], + 'show' => true, + 'raw' => $raw, + 'xhtml' => $xhtml, + 'replies' => [] + ]; } // save the new file @@ -146,4 +162,3 @@ function convertDiscussionPage($file) { return true; } -// vim:ts=4:sw=4:et:enc=utf-8: From 9699b3e248db4babddf501bd7cbfee611835c147 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 22:27:17 +0200 Subject: [PATCH 07/33] admin: reformatting --- admin.php | 121 +++++++++++++++++++++++++++++++----------------------- 1 file changed, 70 insertions(+), 51 deletions(-) diff --git a/admin.php b/admin.php index 4e727da..549efb9 100644 --- a/admin.php +++ b/admin.php @@ -9,19 +9,27 @@ /** * Class admin_plugin_discussion */ -class admin_plugin_discussion extends DokuWiki_Admin_Plugin { +class admin_plugin_discussion extends DokuWiki_Admin_Plugin +{ /** * @return int */ - public function getMenuSort() { return 200; } + public function getMenuSort() + { + return 200; + } /** * @return bool */ - public function forAdminOnly() { return false; } + public function forAdminOnly() + { + return false; + } - public function handle() { + public function handle() + { global $lang, $INPUT; $cids = $INPUT->post->arr('cid'); @@ -51,14 +59,15 @@ public function handle() { } } - public function html() { + public function html() + { global $conf, $INPUT; $first = $INPUT->int('first'); $num = $conf['recent'] ?: 20; - ptln('

    '.$this->getLang('menu').'

    '); + ptln('

    ' . $this->getLang('menu') . '

    '); $threads = $this->getThreads(); @@ -74,7 +83,7 @@ public function html() { continue; } - ptln('
    ', 8); + ptln('', 8); ptln('
    ', 10); ptln('', 10); ptln('', 10); @@ -90,7 +99,8 @@ public function html() { * * @return array */ - protected function getThreads() { + protected function getThreads() + { global $conf; // returns the list of pages in the given namespace and it's subspaces @@ -108,9 +118,9 @@ protected function getThreads() { $date = filemtime($file); $result[] = [ - 'id' => $id, - 'file' => $file, - 'date' => $date, + 'id' => $id, + 'file' => $file, + 'date' => $date, ]; } @@ -131,7 +141,8 @@ protected function getThreads() { * @param array $b * @return int */ - protected function threadCmp($a, $b) { + protected function threadCmp($a, $b) + { if ($a['date'] == $b['date']) { return strcmp($a['id'], $b['id']); } @@ -148,7 +159,8 @@ protected function threadCmp($a, $b) { * @param array $thread * @return bool */ - protected function threadHead($thread) { + protected function threadHead($thread) + { $id = $thread['id']; $labels = [ @@ -160,22 +172,22 @@ protected function threadHead($thread) { if (!$title) { $title = $id; } - ptln('

    '.hsc($title).'

    ', 6); - ptln('', 6); + ptln('

    ' . hsc($title) . '

    ', 6); + ptln('', 6); ptln('
    ', 8); ptln('', 10); ptln('', 10); - ptln($this->getLang('status').': ', 10); foreach ($labels as $key => $label) { $selected = ($key == $thread['status'] ? ' selected="selected"' : ''); - ptln('', 12); + ptln('', 12); } ptln(' ', 10); - ptln('', 10); + ptln('', 10); ptln('
    ', 8); ptln('', 6); ptln('
    ', 6); - ptln(''.$id.' ', 8); + ptln('' . $id . ' ', 8); return true; } @@ -190,7 +202,8 @@ protected function threadHead($thread) { * * @return array|bool */ - protected function getComments(&$thread) { + protected function getComments(&$thread) + { $id = $thread['id']; if (!$thread['file']) { @@ -221,12 +234,13 @@ protected function getComments(&$thread) { * Recursive function to add the comment hierarchy to the result * * @param string $cid comment id of current comment - * @param array $data array with all comments by reference - * @param array $result array with all comments by reference enhanced with level + * @param array $data array with all comments by reference + * @param array $result array with all comments by reference enhanced with level * @param string $parent comment id of parent or empty - * @param int $level level of current comment, higher is deeper + * @param int $level level of current comment, higher is deeper */ - protected function addComment($cid, &$data, &$result, $parent = '', $level = 1) { + protected function addComment($cid, &$data, &$result, $parent = '', $level = 1) + { if (!is_array($data['comments'][$cid])) return; // corrupt datatype $comment = $data['comments'][$cid]; @@ -252,30 +266,31 @@ protected function addComment($cid, &$data, &$result, $parent = '', $level = 1) * @param array $comment array with comment data * @return string html of checkbox and info */ - public function commentItem($comment) { + public function commentItem($comment) + { global $conf; // prepare variables if (is_array($comment['user'])) { // new format - $name = $comment['user']['name']; - $mail = $comment['user']['mail']; - } else { // old format - $name = $comment['name']; - $mail = $comment['mail']; + $name = $comment['user']['name']; + $mail = $comment['user']['mail']; + } else { // old format + $name = $comment['name']; + $mail = $comment['mail']; } if (is_array($comment['date'])) { // new format - $created = $comment['date']['created']; - } else { // old format - $created = $comment['date']; + $created = $comment['date']['created']; + } else { // old format + $created = $comment['date']; } $abstract = preg_replace('/\s+?/', ' ', strip_tags($comment['xhtml'])); if (PhpString::strlen($abstract) > 160) { - $abstract = PhpString::substr($abstract, 0, 160).'...'; + $abstract = PhpString::substr($abstract, 0, 160) . '...'; } - return ' '. - $this->email($mail, $name, 'email').', '.strftime($conf['dformat'], $created).': '. - ''.$abstract.''; + return ' ' . + $this->email($mail, $name, 'email') . ', ' . strftime($conf['dformat'], $created) . ': ' . + '' . $abstract . ''; } /** @@ -284,21 +299,23 @@ public function commentItem($comment) { * @param array $comment * @return string */ - public function liComment($comment) { + public function liComment($comment) + { $showclass = ($comment['show'] ? '' : ' hidden'); - return '
  • '; + return '
  • '; } /** * Show buttons to bulk remove, hide or show comments */ - protected function actionButtons() { + protected function actionButtons() + { global $lang; ptln('
    ', 12); - ptln('', 14); - ptln('', 14); - ptln('', 14); + ptln('', 14); + ptln('', 14); + ptln('', 14); ptln('
    ', 12); // class="comment_buttons" ptln('
  • ', 10); // class="no" ptln('', 8); @@ -309,16 +326,17 @@ protected function actionButtons() { * Displays links to older newer discussions * * @param bool $isMore whether there are more pages needed - * @param int $first first entry on this page - * @param int $num number of entries per page + * @param int $first first entry on this page + * @param int $num number of entries per page */ - protected function browseDiscussionLinks($isMore, $first, $num) { + protected function browseDiscussionLinks($isMore, $first, $num) + { global $ID; if ($first == 0 && !$isMore) return; $params = ['do' => 'admin', 'page' => 'discussion']; - $last = $first+$num; + $last = $first + $num; ptln('
    ', 8); $return = ''; if ($first > 0) { @@ -328,19 +346,19 @@ protected function browseDiscussionLinks($isMore, $first, $num) { } $params['first'] = $first; ptln('

    ', 8); - $return = '<< '.$this->getLang('newer').''; + $return = '<< ' . $this->getLang('newer') . ''; if ($isMore) { $return .= ' | '; } else { ptln($return, 10); ptln('

    ', 8); } - } else if ($isMore) { + } elseif ($isMore) { ptln('

    ', 8); } if ($isMore) { $params['first'] = $last; - $return .= ''.$this->getLang('older').' >>'; + $return .= '' . $this->getLang('older') . ' >>'; ptln($return, 10); ptln('

    ', 8); } @@ -352,7 +370,8 @@ protected function browseDiscussionLinks($isMore, $first, $num) { * * @param int $new 0=disabled, 1=enabled, 2=closed */ - protected function changeStatus($new) { + protected function changeStatus($new) + { global $ID; // get discussion meta file name From f8c74f2e3422ec044a28e4476a54ab3fd167c333 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 23:00:02 +0200 Subject: [PATCH 08/33] not use $INFO in isDiscussionEnabled() isDiscusssionEnabled is used in update_comment_status(), which is triggered by the use of the meta renderer. In pageinfo() the $INFO array is collected, which requires the meta renderer. So we cannot use yet $INFO here. --- action.php | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/action.php b/action.php index 5a212cb..515bdec 100644 --- a/action.php +++ b/action.php @@ -366,14 +366,13 @@ protected function redirect($cid) */ public function isDiscussionEnabled() { - global $INFO; + global $ID; if ($this->getConf('excluded_ns') == '') { $isNamespaceExcluded = false; } else { - global $ID; $ns = getNS($ID); // $INFO['namespace'] is not yet available, if used in update_comment_status() - $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $INFO['namespace']); + $isNamespaceExcluded = preg_match($this->getConf('excluded_ns'), $ns); } if ($this->getConf('automatic')) { From f7bcfbede96112b0b6bed3c1d01a18caa4521c8b Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 23:00:33 +0200 Subject: [PATCH 09/33] phpdocs, refactor --- action.php | 135 ++++++++++++++++++++++++++--------------------------- 1 file changed, 65 insertions(+), 70 deletions(-) diff --git a/action.php b/action.php index 515bdec..143e812 100644 --- a/action.php +++ b/action.php @@ -91,9 +91,7 @@ public function register(Doku_Event_Handler $controller) * Preview Comments * * @param Doku_Event $event - * @param $params * @author Michael Klier - * */ public function ajaxPreviewComments(Doku_Event $event) { @@ -116,9 +114,7 @@ public function ajaxPreviewComments(Doku_Event $event) * Adds a TOC item if a discussion exists * * @param Doku_Event $event - * @param $params * @author Michael Klier - * */ public function addDiscussionToTOC(Doku_Event $event) { @@ -137,9 +133,7 @@ public function addDiscussionToTOC(Doku_Event $event) * Modify Toolbar for use with discussion plugin * * @param Doku_Event $event - * @param $param * @author Michael Klier - * */ public function modifyToolbar(Doku_Event $event) { @@ -153,6 +147,7 @@ public function modifyToolbar(Doku_Event $event) if ($btn['type'] == 'signature') continue; if ($btn['type'] == 'linkwiz') continue; if ($btn['type'] == 'NewTable') continue; //skip button for Edittable Plugin + //FIXME does nothing. Checks for '=' on toplevel, but today it are special buttons and a picker with subarray if (isset($btn['open']) && preg_match("/=+?/", $btn['open'])) continue; $toolbar[] = $btn; @@ -165,9 +160,7 @@ public function modifyToolbar(Doku_Event $event) * Dirty workaround to add a toolbar to the discussion plugin * * @param Doku_Event $event - * @param $param * @author Michael Klier - * */ public function addToolbarToCommentfield(Doku_Event $event) { @@ -190,8 +183,6 @@ public function addToolbarToCommentfield(Doku_Event $event) * Handles comment actions, dispatches data processing routines * * @param Doku_Event $event - * @param $param - * @return void */ public function handleCommentActions(Doku_Event $event) { @@ -249,65 +240,67 @@ public function handleCommentActions(Doku_Event $event) } return; - } else { - // do the data processing for comments - $cid = $INPUT->str('cid'); - switch ($INPUT->str('comment')) { - case 'add': - if (empty($INPUT->str('text'))) return; // don't add empty comments - - if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) { - $comment['user']['id'] = $INPUT->server->str('REMOTE_USER'); - $comment['user']['name'] = $INFO['userinfo']['name']; - $comment['user']['mail'] = $INFO['userinfo']['mail']; - } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) - || !$INPUT->server->has('REMOTE_USER')) { - // don't add anonymous comments - if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) { - return; - } + } - if (!mail_isvalid($INPUT->str('mail'))) { - msg($lang['regbadmail'], -1); - return; - } else { - $comment['user']['id'] = 'test' . hsc($INPUT->str('user')); - $comment['user']['name'] = hsc($INPUT->str('name')); - $comment['user']['mail'] = hsc($INPUT->str('mail')); - } + // do the data processing for comments + $cid = $INPUT->str('cid'); + switch ($INPUT->str('comment')) { + case 'add': + if (empty($INPUT->str('text'))) return; // don't add empty comments + + if ($INPUT->server->has('REMOTE_USER') && !$this->getConf('adminimport')) { + $comment['user']['id'] = $INPUT->server->str('REMOTE_USER'); + $comment['user']['name'] = $INFO['userinfo']['name']; + $comment['user']['mail'] = $INFO['userinfo']['mail']; + } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) + || !$INPUT->server->has('REMOTE_USER')) { + // don't add anonymous comments + if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) { + return; } - $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : ''; - $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : ''; - $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : ''; - $comment['date'] = ['created' => $INPUT->str('date')]; - $comment['raw'] = cleanText($INPUT->str('text')); - $reply = $INPUT->str('reply'); - if ($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { - $comment['show'] = false; + + if (!mail_isvalid($INPUT->str('mail'))) { + msg($lang['regbadmail'], -1); + return; } else { - $comment['show'] = true; + $comment['user']['id'] = 'test' . hsc($INPUT->str('user')); + $comment['user']['name'] = hsc($INPUT->str('name')); + $comment['user']['mail'] = hsc($INPUT->str('mail')); } - $this->add($comment, $reply); - break; + } + $comment['user']['address'] = ($this->getConf('addressfield')) ? hsc($INPUT->str('address')) : ''; + $comment['user']['url'] = ($this->getConf('urlfield')) ? $this->checkURL($INPUT->str('url')) : ''; + $comment['subscribe'] = ($this->getConf('subscribe')) ? $INPUT->has('subscribe') : ''; + $comment['date'] = ['created' => $INPUT->str('date')]; + $comment['raw'] = cleanText($INPUT->str('text')); + $reply = $INPUT->str('reply'); + if ($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { + $comment['show'] = false; + } else { + $comment['show'] = true; + } + $this->add($comment, $reply); + break; - case 'save': - $raw = cleanText($INPUT->str('text')); - $this->save([$cid], $raw); - break; + case 'save': + $raw = cleanText($INPUT->str('text')); + $this->save([$cid], $raw); + break; - case 'delete': - $this->save([$cid], ''); - break; + case 'delete': + $this->save([$cid], ''); + break; - case 'toogle': - $this->save([$cid], '', 'toogle'); - break; - } + case 'toogle': + $this->save([$cid], '', 'toogle'); + break; } } /** * Main function; dispatches the visual comment actions + * + * @param Doku_Event $event */ public function renderCommentsSection(Doku_Event $event) { @@ -332,6 +325,8 @@ public function renderCommentsSection(Doku_Event $event) /** * Redirects browser to given comment anchor + * + * @param string $cid comment id */ protected function redirect($cid) { @@ -362,7 +357,7 @@ protected function redirect($cid) /** * Checks config settings to enable/disable discussions * - * @return bool + * @return bool true if enabled */ public function isDiscussionEnabled() { @@ -415,7 +410,7 @@ protected function showDiscussionSection($reply = null, $edit = null) if (!$data['status']) { return; } - } elseif (!@file_exists($file) && $this->isDiscussionEnabled() && $INFO['exists']) { + } elseif (!@file_exists($file) && $this->isDiscussionEnabled()) { // set status to show the comment form $data['status'] = 1; $data['number'] = 0; @@ -463,7 +458,7 @@ protected function showDiscussionSection($reply = null, $edit = null) // comment form shown on the end, if no comment form of $reply or $edit is requested before if ($data['status'] == 1 && (!$reply || !$this->getConf('usethreading')) && !$edit) { - $this->showCommentForm(''); + $this->showCommentForm('', 'add'); } if ($show) { @@ -933,12 +928,12 @@ protected function showReplyForm($cid, $reply) } /** - * + * Show the replies to the given comment * * @param string $cid comment id * @param array $data array with all comments by reference - * @param string $reply - * @param bool $isVisible + * @param string $reply comment id on which the user requested a reply + * @param bool $isVisible is marked as visible by reference */ protected function showReplies($cid, &$data, $reply, &$isVisible) { @@ -998,8 +993,12 @@ protected function showDiscussionToggleButton() /** * Outputs the comment form + * + * @param string $raw the existing comment text in case of edit + * @param string $act action 'add' or 'save' + * @param string|null $cid comment id to be responded to or null */ - protected function showCommentForm($raw = '', $act = 'add', $cid = null) + protected function showCommentForm($raw, $act, $cid = null) { global $lang, $conf, $ID, $INPUT; @@ -1622,7 +1621,7 @@ protected function pageTemplate($data) } /** - * Checks if the CAPTCHA string submitted is valid + * Checks if the CAPTCHA string submitted is valid, modifies action if needed */ protected function captchaCheck() { @@ -1643,7 +1642,7 @@ protected function captchaCheck() } /** - * checks if the submitted reCAPTCHA string is valid + * checks if the submitted reCAPTCHA string is valid, modifies action if needed * * @author Adrian Schlegel */ @@ -1674,7 +1673,6 @@ protected function recaptchaCheck() * to the index whenever there has been a change that concerns the index content. * * @param Doku_Event $event - * @param $param */ public function addIndexVersion(Doku_Event $event) { @@ -1712,8 +1710,6 @@ public function addCommentsToIndex(Doku_Event $event, $param) * Checks if the phrase occurs in the comments and return event result true if matching * * @param Doku_Event $event - * @param $param - * @return void */ public function fulltextPhraseMatchInComments(Doku_Event $event) { @@ -1781,7 +1777,6 @@ protected function phraseMatchInComment($phrase, $cid, &$data, $parent = '') * Saves the current comment status and title from metadata into the .comments file * * @param Doku_Event $event - * @param $param */ public function update_comment_status(Doku_Event $event) { From 20d55e56636d36879df5feb93e449d21f9965e22 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 23:04:04 +0200 Subject: [PATCH 10/33] simplify signature --- action.php | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/action.php b/action.php index 143e812..f52b8f9 100644 --- a/action.php +++ b/action.php @@ -793,7 +793,7 @@ protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = ' } // print the actual comment - $this->showComment($cid, $data, $parent, $reply, $isVisible, $hidden); + $this->showComment($cid, $data, $reply, $isVisible, $hidden); // replies to this comment entry? $this->showReplies($cid, $data, $reply, $isVisible); // reply form @@ -804,13 +804,12 @@ protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = ' * Print the comment * * @param string $cid comment id - * @param array $data array with all comments by reference - * @param string $parent comment id of parent + * @param array $data array with all comments * @param string $reply comment id on which the user requested a reply * @param bool $isVisible is marked as visible * @param string $hidden extra class, for the admin only hidden view */ - protected function showComment($cid, &$data, $parent, $reply, $isVisible, $hidden) + protected function showComment($cid, $data, $reply, $isVisible, $hidden) { global $conf, $lang, $HIGH, $INPUT; $comment = $data['comments'][$cid]; From f3535bedaa229d7b98b9a136d702b33034abac0f Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 23:13:57 +0200 Subject: [PATCH 11/33] helper: visibility --- helper.php | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/helper.php b/helper.php index 4cac0c7..6621fcb 100644 --- a/helper.php +++ b/helper.php @@ -12,7 +12,7 @@ class helper_plugin_discussion extends DokuWiki_Plugin { /** * @return array */ - function getMethods() { + public function getMethods() { $result = array(); $result[] = array( 'name' => 'th', @@ -43,6 +43,12 @@ function getMethods() { 'number (optional)' => 'integer'), 'return' => array('pages' => 'array'), ); + $result[] = array( + 'name' => 'isDiscussionModerator', + 'desc' => 'check if current user is member of moderator groups', + 'params' => array(), + 'return' => array('isModerator' => 'boolean') + ); return $result; } @@ -51,7 +57,7 @@ function getMethods() { * * @return string */ - function th() { + public function th() { return $this->getLang('discussion'); } @@ -62,7 +68,7 @@ function th() { * @param null|int $num * @return string */ - function td($id, $num = null) { + public function td($id, $num = null) { $section = '#discussion__section'; if (!isset($num)) { @@ -94,7 +100,7 @@ function td($id, $num = null) { * @param string|bool $skipEmpty * @return array */ - function getThreads($ns, $num = null, $skipEmpty = false) { + public function getThreads($ns, $num = null, $skipEmpty = false) { global $conf; require_once(DOKU_INC.'inc/search.php'); @@ -156,7 +162,7 @@ function getThreads($ns, $num = null, $skipEmpty = false) { * @param int|null $num * @return array */ - function getComments($ns, $num = NULL) { + public function getComments($ns, $num = NULL) { global $conf; $first = $_REQUEST['first']; @@ -209,7 +215,7 @@ function getComments($ns, $num = NULL) { * @param array $seen * @return array|bool */ - function _handleRecentComment($line, $ns, &$seen) { + protected function _handleRecentComment($line, $ns, &$seen) { if (empty($line)) return false; //skip empty lines // split the line into parts @@ -279,7 +285,7 @@ function _handleRecentComment($line, $ns, &$seen) { /** * @return bool */ - function isDiscussionMod() { + public function isDiscussionModerator() { global $USERINFO; $groups = trim($this->getConf('moderatorgroups')); From 06ed893a2308b880b9a5d0cc2b0bdfb1088ac20a Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 23:28:43 +0200 Subject: [PATCH 12/33] update signature td() to recent pagelist version --- helper.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/helper.php b/helper.php index 6621fcb..aad3686 100644 --- a/helper.php +++ b/helper.php @@ -64,11 +64,13 @@ public function th() { /** * Returns the link to the discussion section of a page * - * @param string $id - * @param null|int $num + * @param string $id page id + * @param string $col column name, used if more columns needed per plugin + * @param string $class class name per cell set by reference + * @param null|int $num number of visible comments -- internally used, not by pagelist plugin * @return string */ - public function td($id, $num = null) { + public function td($id, $col = null, &$class=null, $num = null) { $section = '#discussion__section'; if (!isset($num)) { @@ -138,7 +140,7 @@ public function getThreads($ns, $num = null, $skipEmpty = false) { 'user' => $meta['creator'], 'desc' => $meta['description']['abstract'], 'num' => $number, - 'comments' => $this->td($id, $number), + 'comments' => $this->td($id, null, $class, $number), 'status' => $status, 'perm' => $perm, 'exists' => true, From ecbf11fb74f47cc68971a23c58ae78a2837a8458 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Sun, 18 Sep 2022 23:46:30 +0200 Subject: [PATCH 13/33] helper: reformatting --- helper.php | 211 +++++++++++++++++++++++++++++------------------------ 1 file changed, 116 insertions(+), 95 deletions(-) diff --git a/helper.php b/helper.php index aad3686..e9699a8 100644 --- a/helper.php +++ b/helper.php @@ -7,48 +7,50 @@ /** * Class helper_plugin_discussion */ -class helper_plugin_discussion extends DokuWiki_Plugin { +class helper_plugin_discussion extends DokuWiki_Plugin +{ /** * @return array */ - public function getMethods() { - $result = array(); - $result[] = array( - 'name' => 'th', - 'desc' => 'returns the header of the comments column for pagelist', - 'return' => array('header' => 'string'), - ); - $result[] = array( - 'name' => 'td', - 'desc' => 'returns the link to the discussion section with number of comments', - 'params' => array( - 'id' => 'string', - 'number of comments (optional)' => 'integer'), - 'return' => array('link' => 'string'), - ); - $result[] = array( - 'name' => 'getThreads', - 'desc' => 'returns pages with discussion sections, sorted by recent comments', - 'params' => array( - 'namespace' => 'string', - 'number (optional)' => 'integer'), - 'return' => array('pages' => 'array'), - ); - $result[] = array( - 'name' => 'getComments', - 'desc' => 'returns recently added or edited comments individually', - 'params' => array( - 'namespace' => 'string', - 'number (optional)' => 'integer'), - 'return' => array('pages' => 'array'), - ); - $result[] = array( - 'name' => 'isDiscussionModerator', - 'desc' => 'check if current user is member of moderator groups', - 'params' => array(), - 'return' => array('isModerator' => 'boolean') - ); + public function getMethods() + { + $result = []; + $result[] = [ + 'name' => 'th', + 'desc' => 'returns the header of the comments column for pagelist', + 'return' => ['header' => 'string'], + ]; + $result[] = [ + 'name' => 'td', + 'desc' => 'returns the link to the discussion section with number of comments', + 'params' => [ + 'id' => 'string', + 'number of comments (optional)' => 'integer'], + 'return' => ['link' => 'string'], + ]; + $result[] = [ + 'name' => 'getThreads', + 'desc' => 'returns pages with discussion sections, sorted by recent comments', + 'params' => [ + 'namespace' => 'string', + 'number (optional)' => 'integer'], + 'return' => ['pages' => 'array'], + ]; + $result[] = [ + 'name' => 'getComments', + 'desc' => 'returns recently added or edited comments individually', + 'params' => [ + 'namespace' => 'string', + 'number (optional)' => 'integer'], + 'return' => ['pages' => 'array'], + ]; + $result[] = [ + 'name' => 'isDiscussionModerator', + 'desc' => 'check if current user is member of moderator groups', + 'params' => [], + 'return' => ['isModerator' => 'boolean'] + ]; return $result; } @@ -57,7 +59,8 @@ public function getMethods() { * * @return string */ - public function th() { + public function th() + { return $this->getLang('discussion'); } @@ -70,7 +73,8 @@ public function th() { * @param null|int $num number of visible comments -- internally used, not by pagelist plugin * @return string */ - public function td($id, $col = null, &$class=null, $num = null) { + public function td($id, $col = null, &$class = null, $num = null) + { $section = '#discussion__section'; if (!isset($num)) { @@ -78,19 +82,22 @@ public function td($id, $col = null, &$class=null, $num = null) { $comments = unserialize(io_readFile($cfile, false)); $num = $comments['number']; - if ((!$comments['status']) || (($comments['status'] == 2) && (!$num))) return ''; + if (!$comments['status'] || ($comments['status'] == 2 && !$num)) { + return ''; + } } if ($num == 0) { - $comment = '0 '.$this->getLang('nocomments'); + $comment = '0 ' . $this->getLang('nocomments'); } elseif ($num == 1) { - $comment = '1 '.$this->getLang('comment'); + $comment = '1 ' . $this->getLang('comment'); } else { - $comment = $num.' '.$this->getLang('comments'); + $comment = $num . ' ' . $this->getLang('comments'); } - return ''. - $comment.''; + return '' + . $comment + . ''; } /** @@ -102,21 +109,20 @@ public function td($id, $col = null, &$class=null, $num = null) { * @param string|bool $skipEmpty * @return array */ - public function getThreads($ns, $num = null, $skipEmpty = false) { + public function getThreads($ns, $num = null, $skipEmpty = false) + { global $conf; - require_once(DOKU_INC.'inc/search.php'); - - $dir = $conf['datadir'].utf8_encodeFN(($ns ? '/'.str_replace(':', '/', $ns): '')); + $dir = $conf['datadir'] . utf8_encodeFN(($ns ? '/' . str_replace(':', '/', $ns) : '')); // returns the list of pages in the given namespace and it's subspaces - $items = array(); - search($items, $dir, 'search_allpages', array()); + $items = []; + search($items, $dir, 'search_allpages', []); // add pages with comments to result - $result = array(); + $result = []; foreach ($items as $item) { - $id = ($ns ? $ns.':' : '').$item['id']; + $id = ($ns ? $ns . ':' : '') . $item['id']; // some checks $perm = auth_quickaclcheck($id); @@ -127,31 +133,33 @@ public function getThreads($ns, $num = null, $skipEmpty = false) { $status = $data['status']; $number = $data['number']; - if (!$status || (($status == 2) && (!$number))) continue; // skip if comments are off or closed without comments - if($skipEmpty == 'y' && $number == 0) continue; // skip if discussion is empty and flag is set + if (!$status || ($status == 2 && !$number)) continue; // skip if comments are off or closed without comments + if ($skipEmpty == 'y' && $number == 0) continue; // skip if discussion is empty and flag is set $date = filemtime($file); $meta = p_get_metadata($id); - $result[$date.'_'.$id] = array( - 'id' => $id, - 'file' => $file, - 'title' => $meta['title'], - 'date' => $date, - 'user' => $meta['creator'], - 'desc' => $meta['description']['abstract'], - 'num' => $number, - 'comments' => $this->td($id, null, $class, $number), - 'status' => $status, - 'perm' => $perm, - 'exists' => true, - 'anchor' => 'discussion__section', - ); + $result[$date . '_' . $id] = [ + 'id' => $id, + 'file' => $file, + 'title' => $meta['title'], + 'date' => $date, + 'user' => $meta['creator'], + 'desc' => $meta['description']['abstract'], + 'num' => $number, + 'comments' => $this->td($id, null, $class, $number), + 'status' => $status, + 'perm' => $perm, + 'exists' => true, + 'anchor' => 'discussion__section', + ]; } // finally sort by time of last comment krsort($result); - if (is_numeric($num)) $result = array_slice($result, 0, $num); + if (is_numeric($num)) { + $result = array_slice($result, 0, $num); + } return $result; } @@ -164,29 +172,37 @@ public function getThreads($ns, $num = null, $skipEmpty = false) { * @param int|null $num * @return array */ - public function getComments($ns, $num = NULL) { + public function getComments($ns, $num = null) + { global $conf; - $first = $_REQUEST['first']; - if (!is_numeric($first)) $first = 0; + $first = $_REQUEST['first']; + if (!is_numeric($first)) { + $first = 0; + } - if ((!$num) || (!is_numeric($num))) $num = $conf['recent']; + if ((!$num) || (!is_numeric($num))) { + $num = $conf['recent']; + } - $result = array(); - $count = 0; + $result = []; + $count = 0; - if (!@file_exists($conf['metadir'].'/_comments.changes')) return $result; + if (!@file_exists($conf['metadir'] . '/_comments.changes')) { + return $result; + } // read all recent changes. (kept short) - $lines = file($conf['metadir'].'/_comments.changes'); + $lines = file($conf['metadir'] . '/_comments.changes'); - $seen = array(); //caches seen pages in order to skip them + $seen = []; //caches seen pages in order to skip them // handle lines $line_num = count($lines); for ($i = ($line_num - 1); $i >= 0; $i--) { - $rec = $this->_handleRecentComment($lines[$i], $ns, $seen); + $rec = $this->handleRecentComment($lines[$i], $ns, $seen); if ($rec !== false) { if (--$first >= 0) continue; // skip first entries + $result[$rec['date']] = $rec; $count++; // break when we have enough entries @@ -207,25 +223,26 @@ public function getComments($ns, $num = NULL) { * * don't call directly * + * @param string $line + * @param string $ns + * @param array $seen + * @return array|false * @see getRecentComments() * @author Andreas Gohr * @author Ben Coburn * @author Esther Brunner * - * @param string $line - * @param string $ns - * @param array $seen - * @return array|bool */ - protected function _handleRecentComment($line, $ns, &$seen) { + protected function handleRecentComment($line, $ns, &$seen) + { if (empty($line)) return false; //skip empty lines // split the line into parts $recent = parseChangelogLine($line); if ($recent === false) return false; - $cid = $recent['extra']; - $fullcid = $recent['id'].'#'.$recent['extra']; + $cid = $recent['extra']; + $fullcid = $recent['id'] . '#' . $recent['extra']; // skip seen ones if (isset($seen[$fullcid])) return false; @@ -241,7 +258,7 @@ protected function _handleRecentComment($line, $ns, &$seen) { if ($recent['type'] === 'hc') return false; // filter namespace or id - if (($ns) && (strpos($recent['id'].':', $ns.':') !== 0)) return false; + if ($ns && strpos($recent['id'] . ':', $ns . ':') !== 0) return false; // check ACL $recent['perm'] = auth_quickaclcheck($recent['id']); @@ -261,7 +278,7 @@ protected function _handleRecentComment($line, $ns, &$seen) { $parent_id = $cid; // Check for the comment and all parents if they exist and are visible. - do { + do { $tcid = $parent_id; // check if the comment still exists @@ -279,7 +296,7 @@ protected function _handleRecentComment($line, $ns, &$seen) { $recent['name'] = $data['comments'][$cid]['name']; } $recent['desc'] = strip_tags($data['comments'][$cid]['xhtml']); - $recent['anchor'] = 'comment_'.$cid; + $recent['anchor'] = 'comment_' . $cid; return $recent; } @@ -287,15 +304,19 @@ protected function _handleRecentComment($line, $ns, &$seen) { /** * @return bool */ - public function isDiscussionModerator() { global $USERINFO; + public function isDiscussionModerator() + { $groups = trim($this->getConf('moderatorgroups')); - if(auth_ismanager()) return true; + if (auth_ismanager()) { + return true; + } // Check if user is member of the moderator groups - if(!empty($groups) && auth_isMember($groups, $_SERVER['REMOTE_USER'], (array)$USERINFO['grps'])) return true; + if (!empty($groups) && auth_isMember($groups, $_SERVER['REMOTE_USER'], (array)$USERINFO['grps'])) { + return true; + } return false; } } -// vim:ts=4:sw=4:et:enc=utf-8: From 4aaefe28c16a48eb78edc8c021f46e486b011665 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Mon, 19 Sep 2022 00:09:01 +0200 Subject: [PATCH 14/33] helper: use $INPUT, phpdocs --- helper.php | 37 +++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/helper.php b/helper.php index e9699a8..c5dee9f 100644 --- a/helper.php +++ b/helper.php @@ -169,19 +169,16 @@ public function getThreads($ns, $num = null, $skipEmpty = false) * Note: also used for content by Feed Plugin * * @param string $ns - * @param int|null $num + * @param int|null $num number of comment per page * @return array */ public function getComments($ns, $num = null) { - global $conf; + global $conf, $INPUT; - $first = $_REQUEST['first']; - if (!is_numeric($first)) { - $first = 0; - } + $first = $INPUT->int('first'); - if ((!$num) || (!is_numeric($num))) { + if (!$num || !is_numeric($num)) { $num = $conf['recent']; } @@ -223,10 +220,20 @@ public function getComments($ns, $num = null) * * don't call directly * - * @param string $line - * @param string $ns - * @param array $seen - * @return array|false + * @param string $line comment changelog line + * @param string $ns namespace (or id) to filter + * @param array $seen array to cache seen pages + * @return array|false with + * 'type' => string, + * 'extra' => string comment id, + * 'id' => string page id, + * 'perm' => int ACL permission + * 'file' => string file path of wiki page + * 'exists' => bool wiki page exists + * 'name' => string name of user + * 'desc' => string text of comment + * 'anchor' => string + * * @see getRecentComments() * @author Andreas Gohr * @author Ben Coburn @@ -302,18 +309,20 @@ protected function handleRecentComment($line, $ns, &$seen) } /** - * @return bool + * Check if current user is member of the moderator groups + * + * @return bool is moderator? */ - global $USERINFO; public function isDiscussionModerator() { + global $USERINFO, $INPUT; $groups = trim($this->getConf('moderatorgroups')); if (auth_ismanager()) { return true; } // Check if user is member of the moderator groups - if (!empty($groups) && auth_isMember($groups, $_SERVER['REMOTE_USER'], (array)$USERINFO['grps'])) { + if (!empty($groups) && auth_isMember($groups, $INPUT->server->str('REMOTE_USER'), (array)$USERINFO['grps'])) { return true; } From 1cfa7c3cd0b1a8971e4fc633aeabbd3bc85b6fad Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Mon, 19 Sep 2022 00:10:01 +0200 Subject: [PATCH 15/33] replace deprecated event, strictness --- script.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/script.js b/script.js index 59d9366..0fd28e0 100644 --- a/script.js +++ b/script.js @@ -12,7 +12,7 @@ function isBlank(s){ for (var i = 0; i < s.length; i++){ var c = s.charAt(i); - if ((c != ' ') && (c != '\n') && (c != '\t')){ + if ((c !== ' ') && (c !== '\n') && (c !== '\t')){ return false; } } @@ -32,7 +32,7 @@ function validate(form){ } else { form.name.style.backgroundColor = '#fff'; } - if (isBlank(form.mail.value) || form.mail.value.indexOf("@") == -1){ + if (isBlank(form.mail.value) || form.mail.value.indexOf("@") === -1){ form.mail.focus(); form.mail.style.backgroundColor = '#fcc'; return false; @@ -87,13 +87,13 @@ jQuery(function() { } // init preview button - jQuery('#discussion__btn_preview').click(discussion_ajax_preview); + jQuery('#discussion__btn_preview').on('click', discussion_ajax_preview); // init field check - jQuery('#discussion__comment_form').submit(function() { return validate(this); }); + jQuery('#discussion__comment_form').on('submit',function() { return validate(this); }); // toggle section visibility - jQuery('#discussion__btn_toggle_visibility').click(function() { + jQuery('#discussion__btn_toggle_visibility').on('click', function() { jQuery('#comment_wrapper').toggle(); }); }); From 83f28d9be95bf97b59ef0466563d65a5d5698fa1 Mon Sep 17 00:00:00 2001 From: Gerrit Uitslag Date: Mon, 19 Sep 2022 00:10:31 +0200 Subject: [PATCH 16/33] renaming from helper function --- action.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/action.php b/action.php index f52b8f9..17a9e5f 100644 --- a/action.php +++ b/action.php @@ -252,7 +252,7 @@ public function handleCommentActions(Doku_Event $event) $comment['user']['id'] = $INPUT->server->str('REMOTE_USER'); $comment['user']['name'] = $INFO['userinfo']['name']; $comment['user']['mail'] = $INFO['userinfo']['mail']; - } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionMod()) + } elseif (($INPUT->server->has('REMOTE_USER') && $this->getConf('adminimport') && $this->helper->isDiscussionModerator()) || !$INPUT->server->has('REMOTE_USER')) { // don't add anonymous comments if (empty($INPUT->str('name')) or empty($INPUT->str('mail'))) { @@ -274,7 +274,7 @@ public function handleCommentActions(Doku_Event $event) $comment['date'] = ['created' => $INPUT->str('date')]; $comment['raw'] = cleanText($INPUT->str('text')); $reply = $INPUT->str('reply'); - if ($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { + if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) { $comment['show'] = false; } else { $comment['show'] = true; @@ -335,7 +335,7 @@ protected function redirect($cid) if ($ACT !== 'show') return; - if ($this->getConf('moderate') && !$this->helper->isDiscussionMod()) { + if ($this->getConf('moderate') && !$this->helper->isDiscussionModerator()) { msg($this->getLang('moderation'), 1); @session_start(); global $MSG; @@ -671,7 +671,7 @@ public function save($cids, $raw, $act = null) } // someone else was trying to edit our comment -> abort - if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionMod()) { + if ($user != $INPUT->server->str('REMOTE_USER') && !$this->helper->isDiscussionModerator()) { return false; } @@ -783,7 +783,7 @@ protected function showCommentWithReplies($cid, &$data, $parent = '', $reply = ' // comment hidden if (!$comment['show']) { - if ($this->helper->isDiscussionMod()) { + if ($this->helper->isDiscussionModerator()) { $hidden = ' comment_hidden'; } else { return; @@ -900,7 +900,7 @@ protected function showComment($cid, $data, $reply, $isVisible, $hidden) } // show edit, show/hide and delete button? - if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionMod()) { + if (($user == $INPUT->server->str('REMOTE_USER') && $user != '') || $this->helper->isDiscussionModerator()) { $this->showButton($cid, $lang['btn_secedit'], 'edit', true); $label = ($comment['show'] ? $this->getLang('btn_hide') : $this->getLang('btn_show')); $this->showButton($cid, $label, 'toogle'); @@ -1031,7 +1031,7 @@ protected function showCommentForm($raw, $act, $cid = null) server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionMod())) { + if (!$INPUT->server->has('REMOTE_USER') or ($this->getConf('adminimport') && $this->helper->isDiscussionModerator())) { ?>
    @@ -1082,7 +1082,7 @@ class="editstr('comment') == 'add' && empty($INPUT->str('mail' } // allow setting the comment date - if ($this->getConf('adminimport') && ($this->helper->isDiscussionMod())) { + if ($this->getConf('adminimport') && ($this->helper->isDiscussionModerator())) { ?>