diff --git a/MenuItem.php b/MenuItem.php index 9bad087f..9055e730 100644 --- a/MenuItem.php +++ b/MenuItem.php @@ -1,6 +1,9 @@ getLang('renamepage'); } diff --git a/action/progress.php b/action/progress.php index 6b007826..ea1a98b5 100644 --- a/action/progress.php +++ b/action/progress.php @@ -1,66 +1,70 @@ */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); /** * Class action_plugin_move_progress */ -class action_plugin_move_progress extends DokuWiki_Action_Plugin { - +class action_plugin_move_progress extends ActionPlugin +{ /** * Register event handlers. * - * @param Doku_Event_Handler $controller The plugin controller + * @param EventHandler $controller The plugin controller */ - public function register(Doku_Event_Handler $controller) { + public function register(EventHandler $controller) + { $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax'); } /** * Step up * - * @param Doku_Event $event + * @param Event $event */ - public function handle_ajax(Doku_Event $event) { - if($event->data != 'plugin_move_progress') return; + public function handle_ajax(Event $event) + { + if ($event->data != 'plugin_move_progress') return; $event->preventDefault(); $event->stopPropagation(); global $INPUT; global $USERINFO; - if(!auth_ismanager($_SERVER['REMOTE_USER'], $USERINFO['grps'])) { + if (!auth_ismanager($_SERVER['REMOTE_USER'], $USERINFO['grps'])) { http_status(403); exit; } - $return = array( - 'error' => '', - 'complete' => false, - 'progress' => 0 - ); + $return = ['error' => '', 'complete' => false, 'progress' => 0]; /** @var helper_plugin_move_plan $plan */ $plan = plugin_load('helper', 'move_plan'); - if(!$plan->isCommited()) { + if (!$plan->isCommited()) { // There is no plan. Something went wrong $return['complete'] = true; } else { $todo = $plan->nextStep($INPUT->bool('skip')); $return['progress'] = $plan->getProgress(); $return['error'] = $plan->getLastError(); - if($todo === 0) $return['complete'] = true; + if ($todo === 0) $return['complete'] = true; } $json = new JSON(); header('Content-Type: application/json'); echo $json->encode($return); } -} \ No newline at end of file +} diff --git a/action/rename.php b/action/rename.php index ca7cb0d5..0906394a 100644 --- a/action/rename.php +++ b/action/rename.php @@ -1,30 +1,38 @@ */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); /** * Class action_plugin_move_rename */ -class action_plugin_move_rename extends DokuWiki_Action_Plugin { - +class action_plugin_move_rename extends ActionPlugin +{ /** * Register event handlers. * - * @param Doku_Event_Handler $controller The plugin controller + * @param EventHandler $controller The plugin controller */ - public function register(Doku_Event_Handler $controller) { + public function register(EventHandler $controller) + { $controller->register_hook('DOKUWIKI_STARTED', 'AFTER', $this, 'handle_init'); // TODO: DEPRECATED JAN 2018 $controller->register_hook('TEMPLATE_PAGETOOLS_DISPLAY', 'BEFORE', $this, 'handle_pagetools'); - $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton', array()); + $controller->register_hook('MENU_ITEMS_ASSEMBLY', 'AFTER', $this, 'addsvgbutton', []); $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax'); $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjaxMediaManager'); } @@ -32,7 +40,8 @@ public function register(Doku_Event_Handler $controller) { /** * set JavaScript info if renaming of current page is possible */ - public function handle_init() { + public function handle_init() + { global $JSINFO; global $INFO; global $INPUT; @@ -56,10 +65,11 @@ public function handle_init() { * * TODO: DEPRECATED JAN 2018 * - * @param Doku_Event $event + * @param Event $event */ - public function handle_pagetools(Doku_Event $event) { - if($event->data['view'] != 'main') return; + public function handle_pagetools(Event $event) + { + if ($event->data['view'] != 'main') return; if (!$this->getConf('pagetools_integration')) { return; } @@ -68,35 +78,37 @@ public function handle_pagetools(Doku_Event $event) { $offset = count($event->data['items']) - 1; $event->data['items'] = array_slice($event->data['items'], 0, $offset, true) + - array('plugin_move' => $newitem) + + ['plugin_move' => $newitem] + array_slice($event->data['items'], $offset, null, true); } /** * Add 'rename' button to page tools, new SVG based mechanism * - * @param Doku_Event $event + * @param Event $event */ - public function addsvgbutton(Doku_Event $event) { + public function addsvgbutton(Event $event) + { global $INFO, $JSINFO; - if( + if ( $event->data['view'] !== 'page' || !$this->getConf('pagetools_integration') || empty($JSINFO['move_renameokay']) ) { return; } - if(!$INFO['exists']) { + if (!$INFO['exists']) { return; } - array_splice($event->data['items'], -1, 0, array(new \dokuwiki\plugin\move\MenuItem())); + array_splice($event->data['items'], -1, 0, [new MenuItem()]); } /** * Rename a single page */ - public function handle_ajax(Doku_Event $event) { - if($event->data != 'plugin_move_rename') return; + public function handle_ajax(Event $event) + { + if ($event->data != 'plugin_move_rename') return; $event->preventDefault(); $event->stopPropagation(); @@ -113,26 +125,26 @@ public function handle_ajax(Doku_Event $event) { header('Content-Type: application/json'); - if($this->renameOkay($src) && $MoveOperator->movePage($src, $dst)) { + if ($this->renameOkay($src) && $MoveOperator->movePage($src, $dst)) { // all went well, redirect - echo $JSON->encode(array('redirect_url' => wl($dst, '', true, '&'))); + echo $JSON->encode(['redirect_url' => wl($dst, '', true, '&')]); } else { - if(isset($MSG[0])) { + if (isset($MSG[0])) { $error = $MSG[0]; // first error } else { $error = $this->getLang('cantrename'); } - echo $JSON->encode(array('error' => $error)); + echo $JSON->encode(['error' => $error]); } } /** * Handle media renames in media manager * - * @param Doku_Event $event + * @param Event $event * @return void */ - public function handleAjaxMediaManager(Doku_Event $event) + public function handleAjaxMediaManager(Event $event) { if ($event->data !== 'plugin_move_rename_mediamanager') return; @@ -191,17 +203,18 @@ public function handleAjaxMediaManager(Doku_Event $event) * @param $id * @return bool */ - public function renameOkay($id) { + public function renameOkay($id) + { global $conf; global $ACT; global $USERINFO; - if(!($ACT == 'show' || empty($ACT))) return false; - if(!page_exists($id)) return false; - if(auth_quickaclcheck($id) < AUTH_EDIT) return false; - if(checklock($id) !== false || @file_exists(wikiLockFN($id))) return false; - if(!$conf['useacl']) return true; - if(!isset($_SERVER['REMOTE_USER'])) return false; - if(!auth_isMember($this->getConf('allowrename'), $_SERVER['REMOTE_USER'], (array) $USERINFO['grps'])) return false; + if ($ACT != 'show' && !empty($ACT)) return false; + if (!page_exists($id)) return false; + if (auth_quickaclcheck($id) < AUTH_EDIT) return false; + if (checklock($id) !== false || @file_exists(wikiLockFN($id))) return false; + if (!$conf['useacl']) return true; + if (!isset($_SERVER['REMOTE_USER'])) return false; + if (!auth_isMember($this->getConf('allowrename'), $_SERVER['REMOTE_USER'], (array) $USERINFO['grps'])) return false; return true; } @@ -212,10 +225,10 @@ public function renameOkay($id) { * Alternatively give anything the class "plugin_move_page" - it will automatically be hidden and shown and * trigger the page move dialog. */ - public function tpl() { + public function tpl() + { echo ''; echo $this->getLang('renamepage'); echo ''; } - } diff --git a/action/rewrite.php b/action/rewrite.php index 10979507..1b73ba9c 100644 --- a/action/rewrite.php +++ b/action/rewrite.php @@ -1,63 +1,72 @@ */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); /** * Class action_plugin_move_rewrite */ -class action_plugin_move_rewrite extends DokuWiki_Action_Plugin { - +class action_plugin_move_rewrite extends ActionPlugin +{ /** * Register event handlers. * - * @param Doku_Event_Handler $controller The plugin controller + * @param EventHandler $controller The plugin controller */ - public function register(Doku_Event_Handler $controller) { - $controller->register_hook('IO_WIKIPAGE_READ', 'AFTER', $this, 'handle_read', array()); - $controller->register_hook('PARSER_CACHE_USE', 'BEFORE', $this, 'handle_cache', array()); + public function register(EventHandler $controller) + { + $controller->register_hook('IO_WIKIPAGE_READ', 'AFTER', $this, 'handle_read', []); + $controller->register_hook('PARSER_CACHE_USE', 'BEFORE', $this, 'handle_cache', []); } /** * Rewrite pages when they are read and they need to be updated. * - * @param Doku_Event $event The event object + * @param Event $event The event object * @param mixed $param Optional parameters (not used) */ - function handle_read(Doku_Event $event, $param) { + public function handle_read(Event $event, $param) + { global $ACT, $conf; - static $stack = array(); + static $stack = []; // handle only reads of the current revision - if($event->data[3]) return; + if ($event->data[3]) return; // only rewrite if not in move already $save = true; - if(helper_plugin_move_rewrite::isLocked()) { + if (helper_plugin_move_rewrite::isLocked()) { $save = false; } $id = $event->data[2]; - if($event->data[1]) $id = $event->data[1] . ':' . $id; + if ($event->data[1]) $id = $event->data[1] . ':' . $id; - if(!$id) { + if (!$id) { // try to reconstruct the id from the filename $path = $event->data[0][0]; - if(strpos($path, $conf['datadir']) === 0) { + if (strpos($path, (string) $conf['datadir']) === 0) { $path = substr($path, strlen($conf['datadir']) + 1); $id = pathID($path); } } - if(isset($stack[$id])) return; + if (isset($stack[$id])) return; // Don't change the page when the user is currently changing the page content or the page is locked - $forbidden_actions = array('save', 'preview', 'recover', 'revert'); - if((isset($ACT) && ( + $forbidden_actions = ['save', 'preview', 'recover', 'revert']; + if ( + (isset($ACT) && ( in_array($ACT, $forbidden_actions) || (is_array($ACT) && in_array(key($ACT), $forbidden_actions) ))) // checklock checks if the page lock hasn't expired and the page hasn't been locked by another user @@ -68,7 +77,7 @@ function handle_read(Doku_Event $event, $param) { /** @var helper_plugin_move_rewrite $helper */ $helper = plugin_load('helper', 'move_rewrite', true); - if(!is_null($helper)) { + if (!is_null($helper)) { $stack[$id] = true; $event->result = $helper->rewritePage($id, $event->result, $save); unset($stack[$id]); @@ -78,30 +87,31 @@ function handle_read(Doku_Event $event, $param) { /** * Handle the cache events, it looks if a page needs to be rewritten so it can expire the cache of the page * - * @param Doku_Event $event The even object + * @param Event $event The even object * @param mixed $param Optional parameters (not used) */ - function handle_cache(Doku_Event $event, $param) { + public function handle_cache(Event $event, $param) + { global $conf; /** @var $cache cache_parser */ $cache = $event->data; $id = $cache->page; - if(!$id) { + if (!$id) { // try to reconstruct the id from the filename $path = $cache->file; - if(strpos($path, $conf['datadir']) === 0) { + if (strpos($path, (string) $conf['datadir']) === 0) { $path = substr($path, strlen($conf['datadir']) + 1); $id = pathID($path); } } - if($id) { + if ($id) { /** @var helper_plugin_move_rewrite $helper */ $helper = $this->loadHelper('move_rewrite'); - if(!is_null($helper)) { + if (!is_null($helper)) { $meta = $helper->getMoveMeta($id); - if($meta && ($meta['pages'] || $meta['media'])) { + if ($meta && ($meta['pages'] || $meta['media'])) { $file = wikiFN($id, '', false); - if(is_writable($file)) + if (is_writable($file)) $cache->depends['purge'] = true; else // FIXME: print error here or fail silently? msg('Error: Page ' . hsc($id) . ' needs to be rewritten because of page renames but is not writable.', -1); diff --git a/action/tree.php b/action/tree.php index 644c9789..b6ee484e 100644 --- a/action/tree.php +++ b/action/tree.php @@ -1,42 +1,50 @@ */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); /** * Class action_plugin_move_rewrite */ -class action_plugin_move_tree extends DokuWiki_Action_Plugin { - +class action_plugin_move_tree extends ActionPlugin +{ /** * Register event handlers. * - * @param Doku_Event_Handler $controller The plugin controller + * @param EventHandler $controller The plugin controller */ - public function register(Doku_Event_Handler $controller) { + public function register(EventHandler $controller) + { $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax_call'); } /** * Render a subtree * - * @param Doku_Event $event + * @param Event $event * @param $params */ - public function handle_ajax_call(Doku_Event $event, $params) { - if($event->data != 'plugin_move_tree') return; + public function handle_ajax_call(Event $event, $params) + { + if ($event->data != 'plugin_move_tree') return; $event->preventDefault(); $event->stopPropagation(); global $INPUT; global $USERINFO; - if(!auth_ismanager($_SERVER['REMOTE_USER'], $USERINFO['grps'])) { + if (!auth_ismanager($_SERVER['REMOTE_USER'], $USERINFO['grps'])) { http_status(403); exit; } @@ -45,7 +53,7 @@ public function handle_ajax_call(Doku_Event $event, $params) { $plugin = plugin_load('admin', 'move_tree'); $ns = cleanID($INPUT->str('ns')); - if($INPUT->bool('is_media')) { + if ($INPUT->bool('is_media')) { $type = admin_plugin_move_tree::TYPE_MEDIA; } else { $type = admin_plugin_move_tree::TYPE_PAGES; @@ -54,10 +62,10 @@ public function handle_ajax_call(Doku_Event $event, $params) { $data = $plugin->tree($type, $ns, $ns); echo html_buildlist( - $data, 'tree_list', - array($plugin, 'html_list'), - array($plugin, 'html_li') + $data, + 'tree_list', + [$plugin, 'html_list'], + [$plugin, 'html_li'] ); } - -} \ No newline at end of file +} diff --git a/admin/main.php b/admin/main.php index 87a1b0d2..c3c28bcc 100644 --- a/admin/main.php +++ b/admin/main.php @@ -1,4 +1,7 @@ plan = plugin_load('helper', 'move_plan'); } @@ -26,9 +30,10 @@ public function __construct() { * @param $language * @return string */ - public function getMenuText($language) { + public function getMenuText($language) + { $label = $this->getLang('menu'); - if($this->plan->isCommited()) $label .= ' '.$this->getLang('inprogress'); + if ($this->plan->isCommited()) $label .= ' ' . $this->getLang('inprogress'); return $label; } @@ -38,7 +43,8 @@ public function getMenuText($language) { * * @return int The sort number */ - function getMenuSort() { + public function getMenuSort() + { return 1011; } @@ -47,23 +53,25 @@ function getMenuSort() { * * @return bool false */ - function forAdminOnly() { + public function forAdminOnly() + { return false; } /** * Handle the input */ - function handle() { + public function handle() + { global $INPUT; // create a new plan if possible and sufficient data was given $this->createPlanFromInput(); // handle workflow button presses - if($this->plan->isCommited()) { + if ($this->plan->isCommited()) { helper_plugin_move_rewrite::addLock(); //todo: right place? - switch($INPUT->str('ctl')) { + switch ($INPUT->str('ctl')) { case 'continue': $this->plan->nextStep(); break; @@ -80,9 +88,10 @@ function handle() { /** * Display the interface */ - function html() { + public function html() + { // decide what to do based on the plan's state - if($this->plan->isCommited()) { + if ($this->plan->isCommited()) { $this->GUI_progress(); } else { // display form @@ -95,32 +104,33 @@ function html() { * * @return bool */ - protected function createPlanFromInput() { + protected function createPlanFromInput() + { global $INPUT; global $ID; - if($this->plan->isCommited()) return false; + if ($this->plan->isCommited()) return false; $this->plan->setOption('autoskip', $INPUT->bool('autoskip')); $this->plan->setOption('autorewrite', $INPUT->bool('autorewrite')); - if($ID && $INPUT->has('dst')) { + if ($ID && $INPUT->has('dst')) { $dst = trim($INPUT->str('dst')); - if($dst == '') { + if ($dst == '') { msg($this->getLang('nodst'), -1); return false; } // input came from form - if($INPUT->str('class') == 'namespace') { + if ($INPUT->str('class') == 'namespace') { $src = getNS($ID); - if($INPUT->str('type') == 'both') { + if ($INPUT->str('type') == 'both') { $this->plan->addPageNamespaceMove($src, $dst); $this->plan->addMediaNamespaceMove($src, $dst); - } else if($INPUT->str('type') == 'page') { + } elseif ($INPUT->str('type') == 'page') { $this->plan->addPageNamespaceMove($src, $dst); - } else if($INPUT->str('type') == 'media') { + } elseif ($INPUT->str('type') == 'media') { $this->plan->addMediaNamespaceMove($src, $dst); } } else { @@ -128,22 +138,22 @@ protected function createPlanFromInput() { } $this->plan->commit(); return true; - } elseif($INPUT->has('json')) { + } elseif ($INPUT->has('json')) { // input came via JSON from tree manager $json = new JSON(JSON_LOOSE_TYPE); $data = $json->decode($INPUT->str('json')); - foreach((array) $data as $entry) { - if($entry['class'] == 'ns') { - if($entry['type'] == 'page') { + foreach ((array) $data as $entry) { + if ($entry['class'] == 'ns') { + if ($entry['type'] == 'page') { $this->plan->addPageNamespaceMove($entry['src'], $entry['dst']); - } elseif($entry['type'] == 'media') { + } elseif ($entry['type'] == 'media') { $this->plan->addMediaNamespaceMove($entry['src'], $entry['dst']); } - } elseif($entry['class'] == 'doc') { - if($entry['type'] == 'page') { + } elseif ($entry['class'] == 'doc') { + if ($entry['type'] == 'page') { $this->plan->addPageMove($entry['src'], $entry['dst']); - } elseif($entry['type'] == 'media') { + } elseif ($entry['type'] == 'media') { $this->plan->addMediaMove($entry['src'], $entry['dst']); } } @@ -159,30 +169,31 @@ protected function createPlanFromInput() { /** * Display the simple move form */ - protected function GUI_simpleForm() { + protected function GUI_simpleForm() + { global $ID; echo $this->locale_xhtml('move'); - $treelink = wl($ID, array('do'=>'admin', 'page'=>'move_tree')); + $treelink = wl($ID, ['do' => 'admin', 'page' => 'move_tree']); echo ''; - $form = new Doku_Form(array('action' => wl($ID), 'method' => 'post', 'class' => 'plugin_move_form')); + $form = new Doku_Form(['action' => wl($ID), 'method' => 'post', 'class' => 'plugin_move_form']); $form->addHidden('page', 'move_main'); $form->addHidden('id', $ID); $form->startFieldset($this->getLang('legend')); - $form->addElement(form_makeRadioField('class', 'page', $this->getLang('movepage') . ' ' . $ID . '', '', 'block radio click-page', array('checked' => 'checked'))); + $form->addElement(form_makeRadioField('class', 'page', $this->getLang('movepage') . ' ' . $ID . '', '', 'block radio click-page', ['checked' => 'checked'])); $form->addElement(form_makeRadioField('class', 'namespace', $this->getLang('movens') . ' ' . getNS($ID) . '', '', 'block radio click-ns')); $form->addElement(form_makeTextField('dst', $ID, $this->getLang('dst'), '', 'block indent')); - $form->addElement(form_makeMenuField('type', array('pages' => $this->getLang('move_pages'), 'media' => $this->getLang('move_media'), 'both' => $this->getLang('move_media_and_pages')), 'both', $this->getLang('content_to_move'), '', 'block indent select')); + $form->addElement(form_makeMenuField('type', ['pages' => $this->getLang('move_pages'), 'media' => $this->getLang('move_media'), 'both' => $this->getLang('move_media_and_pages')], 'both', $this->getLang('content_to_move'), '', 'block indent select')); - $form->addElement(form_makeCheckboxField('autoskip', '1', $this->getLang('autoskip'), '', 'block', ($this->getConf('autoskip') ? array('checked' => 'checked') : array()))); - $form->addElement(form_makeCheckboxField('autorewrite', '1', $this->getLang('autorewrite'), '', 'block', ($this->getConf('autorewrite') ? array('checked' => 'checked') : array()))); + $form->addElement(form_makeCheckboxField('autoskip', '1', $this->getLang('autoskip'), '', 'block', ($this->getConf('autoskip') ? ['checked' => 'checked'] : []))); + $form->addElement(form_makeCheckboxField('autorewrite', '1', $this->getLang('autorewrite'), '', 'block', ($this->getConf('autorewrite') ? ['checked' => 'checked'] : []))); $form->addElement(form_makeButton('submit', 'admin', $this->getLang('btn_start'))); $form->endFieldset(); @@ -192,14 +203,15 @@ protected function GUI_simpleForm() { /** * Display the GUI while the move progresses */ - protected function GUI_progress() { + protected function GUI_progress() + { echo '
'; echo $this->locale_xhtml('progress'); $progress = $this->plan->getProgress(); - if(!$this->plan->inProgress()) { + if (!$this->plan->inProgress()) { echo '
'; echo '

'; echo '' . $this->getLang('intro') . ' '; @@ -207,13 +219,12 @@ protected function GUI_progress() { echo '

'; echo $this->plan->previewHTML(); echo '
'; - } echo '
' . $progress . '%
'; echo '
'; - if($this->plan->getLastError()) { + if ($this->plan->getLastError()) { echo '

' . $this->plan->getLastError() . '

'; } elseif ($this->plan->inProgress()) { echo '

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

'; @@ -244,27 +255,28 @@ protected function GUI_progress() { * @param string $control * @param bool $show should this control be visible? */ - protected function btn($control, $show = true) { + protected function btn($control, $show = true) + { global $ID; $skip = 0; $label = $this->getLang('btn_' . $control); $id = $control; - if($control == 'start') $control = 'continue'; - if($control == 'retry') { + if ($control == 'start') $control = 'continue'; + if ($control == 'retry') { $control = 'continue'; $skip = 0; } $class = 'move__control ctlfrm-' . $id; - if(!$show) $class .= ' hide'; + if (!$show) $class .= ' hide'; - $form = new Doku_Form(array('action' => wl($ID), 'method' => 'post', 'class' => $class)); + $form = new Doku_Form(['action' => wl($ID), 'method' => 'post', 'class' => $class]); $form->addHidden('page', 'move_main'); $form->addHidden('id', $ID); $form->addHidden('ctl', $control); $form->addHidden('skip', $skip); - $form->addElement(form_makeButton('submit', 'admin', $label, array('class' => 'btn ctl-' . $control))); + $form->addElement(form_makeButton('submit', 'admin', $label, ['class' => 'btn ctl-' . $control])); $form->printForm(); } } diff --git a/admin/tree.php b/admin/tree.php index a3482dc7..0a4f14e0 100644 --- a/admin/tree.php +++ b/admin/tree.php @@ -1,15 +1,18 @@ locale_xhtml('tree'); @@ -51,16 +57,16 @@ public function html() { /** @var helper_plugin_move_plan $plan */ $plan = plugin_load('helper', 'move_plan'); echo '
'; - if($plan->isCommited()) { + if ($plan->isCommited()) { echo '
' . $this->getLang('moveinprogress') . '
'; } else { - $form = new Doku_Form(array('action' => wl($ID), 'id' => 'plugin_move__tree_execute')); + $form = new Doku_Form(['action' => wl($ID), 'id' => 'plugin_move__tree_execute']); $form->addHidden('id', $ID); $form->addHidden('page', 'move_main'); $form->addHidden('json', ''); - $form->addElement(form_makeCheckboxField('autoskip', '1', $this->getLang('autoskip'), '', '', ($this->getConf('autoskip') ? array('checked' => 'checked') : array()))); + $form->addElement(form_makeCheckboxField('autoskip', '1', $this->getLang('autoskip'), '', '', ($this->getConf('autoskip') ? ['checked' => 'checked'] : []))); $form->addElement('
'); - $form->addElement(form_makeCheckboxField('autorewrite', '1', $this->getLang('autorewrite'), '', '', ($this->getConf('autorewrite') ? array('checked' => 'checked') : array()))); + $form->addElement(form_makeCheckboxField('autorewrite', '1', $this->getLang('autorewrite'), '', '', ($this->getConf('autorewrite') ? ['checked' => 'checked'] : []))); $form->addElement('
'); $form->addElement('
'); $form->addElement(form_makeButton('submit', 'admin', $this->getLang('btn_start'))); @@ -76,20 +82,20 @@ public function html() { * * @param int $type */ - protected function htmlTree($type = self::TYPE_PAGES) { + protected function htmlTree($type = self::TYPE_PAGES) + { $data = $this->tree($type); // wrap a list with the root level around the other namespaces array_unshift( - $data, array( - 'level' => 0, 'id' => '*', 'type' => 'd', - 'open' => 'true', 'label' => $this->getLang('root') - ) + $data, + ['level' => 0, 'id' => '*', 'type' => 'd', 'open' => 'true', 'label' => $this->getLang('root')] ); echo html_buildlist( - $data, 'tree_list idx', - array($this, 'html_list'), - array($this, 'html_li') + $data, + 'tree_list idx', + [$this, 'html_list'], + [$this, 'html_li'] ); } @@ -101,26 +107,19 @@ protected function htmlTree($type = self::TYPE_PAGES) { * @param string $base The namespace to start from * @return array */ - public function tree($type = self::TYPE_PAGES, $open = '', $base = '') { + public function tree($type = self::TYPE_PAGES, $open = '', $base = '') + { global $conf; - $opendir = utf8_encodeFN(str_replace(':', '/', $open)); + utf8_encodeFN(str_replace(':', '/', $open)); $basedir = utf8_encodeFN(str_replace(':', '/', $base)); - $opts = array( - 'pagesonly' => ($type == self::TYPE_PAGES), - 'listdirs' => true, - 'listfiles' => true, - 'sneakyacl' => $conf['sneaky_index'], - 'showmsg' => false, - 'depth' => 1, - 'showhidden' => true - ); + $opts = ['pagesonly' => ($type == self::TYPE_PAGES), 'listdirs' => true, 'listfiles' => true, 'sneakyacl' => $conf['sneaky_index'], 'showmsg' => false, 'depth' => 1, 'showhidden' => true]; - $data = array(); - if($type == self::TYPE_PAGES) { + $data = []; + if ($type == self::TYPE_PAGES) { search($data, $conf['datadir'], 'search_universal', $opts, $basedir); - } elseif($type == self::TYPE_MEDIA) { + } elseif ($type == self::TYPE_MEDIA) { search($data, $conf['mediadir'], 'search_universal', $opts, $basedir); } @@ -134,24 +133,25 @@ public function tree($type = self::TYPE_PAGES, $open = '', $base = '') { * * @author Andreas Gohr */ - function html_list($item) { + public function html_list($item) + { $ret = ''; // what to display - if(!empty($item['label'])) { + if (!empty($item['label'])) { $base = $item['label']; } else { $base = ':' . $item['id']; $base = substr($base, strrpos($base, ':') + 1); } - if($item['id'] == '*') $item['id'] = ''; + if ($item['id'] == '*') $item['id'] = ''; if ($item['id']) { $ret .= ' '; } // namespace or page? - if($item['type'] == 'd') { + if ($item['type'] == 'd') { $ret .= ''; $ret .= $base; $ret .= ''; @@ -161,7 +161,7 @@ function html_list($item) { $ret .= ''; } - if($item['id']) $ret .= ''; + if ($item['id']) $ret .= ''; else $ret .= ''; return $ret; @@ -173,17 +173,17 @@ function html_list($item) { * @param array $item * @return string */ - function html_li($item) { - if($item['id'] == '*') $item['id'] = ''; + public function html_li($item) + { + if ($item['id'] == '*') $item['id'] = ''; - $params = array(); + $params = []; $params['class'] = ' type-' . $item['type']; - if($item['type'] == 'd') $params['class'] .= ' ' . ($item['open'] ? 'open' : 'closed'); + if ($item['type'] == 'd') $params['class'] .= ' ' . ($item['open'] ? 'open' : 'closed'); $params['data-name'] = noNS($item['id']); $params['data-id'] = $item['id']; $attr = buildAttributes($params); return "
  • "; } - } diff --git a/helper/file.php b/helper/file.php index fa57101e..07be6757 100644 --- a/helper/file.php +++ b/helper/file.php @@ -1,4 +1,7 @@ * @author Andreas Gohr */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); /** * Class helper_plugin_move_file @@ -15,8 +19,8 @@ * This helps with moving files from one folder to another. It simply matches files and moves them * arround. No fancy rewriting happens here. */ -class helper_plugin_move_file extends DokuWiki_Plugin { - +class helper_plugin_move_file extends Plugin +{ /** * Move the meta files of a page * @@ -26,7 +30,8 @@ class helper_plugin_move_file extends DokuWiki_Plugin { * @param string $dst_name The basename after the move (empty for namespace moves) * @return bool If the meta files were moved successfully */ - public function movePageMeta($src_ns, $src_name, $dst_ns, $dst_name) { + public function movePageMeta($src_ns, $src_name, $dst_ns, $dst_name) + { global $conf; $regex = '\.[^.]+'; @@ -42,7 +47,8 @@ public function movePageMeta($src_ns, $src_name, $dst_ns, $dst_name) { * @param string $dst_name The basename after the move (empty for namespace moves) * @return bool If the attic files were moved successfully */ - public function movePageAttic($src_ns, $src_name, $dst_ns, $dst_name) { + public function movePageAttic($src_ns, $src_name, $dst_ns, $dst_name) + { global $conf; $regex = '\.\d+\.txt(?:\.gz|\.bz2)?'; @@ -58,7 +64,8 @@ public function movePageAttic($src_ns, $src_name, $dst_ns, $dst_name) { * @param string $dst_name The basename after the move (empty for namespace moves) * @return bool If the meta files were moved successfully */ - public function moveMediaMeta($src_ns, $src_name, $dst_ns, $dst_name) { + public function moveMediaMeta($src_ns, $src_name, $dst_ns, $dst_name) + { global $conf; $regex = '\.[^.]+'; @@ -74,17 +81,18 @@ public function moveMediaMeta($src_ns, $src_name, $dst_ns, $dst_name) { * @param string $dst_name The basename after the move (empty for namespace moves) * @return bool If the attic files were moved successfully */ - public function moveMediaAttic($src_ns, $src_name, $dst_ns, $dst_name) { + public function moveMediaAttic($src_ns, $src_name, $dst_ns, $dst_name) + { global $conf; $ext = mimetype($src_name); - if($ext[0] !== false) { + if ($ext[0] !== false) { $name = substr($src_name, 0, -1 * strlen($ext[0]) - 1); } else { $name = $src_name; } $newext = mimetype($dst_name); - if($newext[0] !== false) { + if ($newext[0] !== false) { $newname = substr($dst_name, 0, -1 * strlen($newext[0]) - 1); } else { $newname = $dst_name; @@ -101,7 +109,8 @@ public function moveMediaAttic($src_ns, $src_name, $dst_ns, $dst_name) { * @param string $dst_ns * @return bool */ - public function moveNamespaceSubscription($src_ns, $dst_ns){ + public function moveNamespaceSubscription($src_ns, $dst_ns) + { global $conf; $regex = '\.mlist'; @@ -119,28 +128,29 @@ public function moveNamespaceSubscription($src_ns, $dst_ns){ * @param string $extregex Regular expression for matching the extension of the file that shall be moved * @return bool If the files were moved successfully */ - protected function execute($dir, $src_ns, $src_name, $dst_ns, $dst_name, $extregex) { + protected function execute($dir, $src_ns, $src_name, $dst_ns, $dst_name, $extregex) + { $old_path = $dir; - if($src_ns != '') $old_path .= '/' . utf8_encodeFN(str_replace(':', '/', $src_ns)); + if ($src_ns != '') $old_path .= '/' . utf8_encodeFN(str_replace(':', '/', $src_ns)); $new_path = $dir; - if($dst_ns != '') $new_path .= '/' . utf8_encodeFN(str_replace(':', '/', $dst_ns)); + if ($dst_ns != '') $new_path .= '/' . utf8_encodeFN(str_replace(':', '/', $dst_ns)); $regex = '/^' . preg_quote(utf8_encodeFN($src_name)) . '(' . $extregex . ')$/u'; - if(!is_dir($old_path)) return true; // no media files found + if (!is_dir($old_path)) return true; // no media files found $dh = @opendir($old_path); - if($dh) { - while(($file = readdir($dh)) !== false) { - if($file == '.' || $file == '..') continue; - $match = array(); - if(is_file($old_path . '/' . $file) && preg_match($regex, $file, $match)) { - if(!is_dir($new_path)) { - if(!io_mkdir_p($new_path)) { + if ($dh) { + while (($file = readdir($dh)) !== false) { + if ($file == '.' || $file == '..') continue; + $match = []; + if (is_file($old_path . '/' . $file) && preg_match($regex, $file, $match)) { + if (!is_dir($new_path)) { + if (!io_mkdir_p($new_path)) { msg('Creating directory ' . hsc($new_path) . ' failed.', -1); return false; } } - if(!io_rename($old_path . '/' . $file, $new_path . '/' . utf8_encodeFN($dst_name . $match[1]))) { + if (!io_rename($old_path . '/' . $file, $new_path . '/' . utf8_encodeFN($dst_name . $match[1]))) { msg('Moving ' . hsc($old_path . '/' . $file) . ' to ' . hsc($new_path . '/' . utf8_encodeFN($dst_name . $match[1])) . ' failed.', -1); return false; } @@ -153,4 +163,4 @@ protected function execute($dir, $src_ns, $src_name, $dst_ns, $dst_name, $extreg } return true; } -} \ No newline at end of file +} diff --git a/helper/handler.php b/helper/handler.php index fff22542..90059fa1 100644 --- a/helper/handler.php +++ b/helper/handler.php @@ -1,4 +1,7 @@ $new * @param array $handlers Handlers for plugin content in the form $plugin_name => $callback */ - public function init($id, $original, $page_moves, $media_moves, $handlers) { + public function init($id, $original, $page_moves, $media_moves, $handlers) + { $this->id = $id; $this->ns = getNS($id); $this->origID = $original; @@ -61,18 +67,19 @@ public function init($id, $original, $page_moves, $media_moves, $handlers) { * @throws Exception on bad argument * @return string the new full qualified ID */ - public function resolveMoves($old, $type) { + public function resolveMoves($old, $type) + { global $conf; - if($type != 'media' && $type != 'page') throw new Exception('Not a valid type'); + if ($type != 'media' && $type != 'page') throw new Exception('Not a valid type'); $old = resolve_id($this->origNS, $old, false); - if($type == 'page') { + if ($type == 'page') { // FIXME this simply assumes that the link pointed to :$conf['start'], but it could also point to another page // resolve_pageid does a lot more here, but we can't really assume this as the original pages might have been // deleted already - if(substr($old, -1) === ':' || $old === '') $old .= $conf['start']; + if (substr($old, -1) === ':' || $old === '') $old .= $conf['start']; $moves = $this->page_moves; } else { @@ -81,8 +88,8 @@ public function resolveMoves($old, $type) { $old = cleanID($old); - foreach($moves as $move) { - if($move[0] == $old) { + foreach ($moves as $move) { + if ($move[0] == $old) { $old = $move[1]; } } @@ -98,13 +105,14 @@ public function resolveMoves($old, $type) { * @param $type 'media' or 'page' * @return string */ - protected function _nsStartCheck($relold, $new, $type) { + protected function _nsStartCheck($relold, $new, $type) + { global $conf; - if($type == 'page' && substr($relold, -1) == ':') { + if ($type == 'page' && substr($relold, -1) == ':') { $len = strlen($conf['start']); - if($new == $conf['start']) { + if ($new == $conf['start']) { $new = '.:'; - } else if(substr($new, -1 * ($len + 1)) == ':' . $conf['start']) { + } elseif (substr($new, -1 * ($len + 1)) === ':' . $conf['start']) { $new = substr($new, 0, -1 * $len); } } @@ -123,14 +131,15 @@ protected function _nsStartCheck($relold, $new, $type) { * @throws Exception on bad argument * @return string */ - public function relativeLink($relold, $new, $type) { + public function relativeLink($relold, $new, $type) + { global $conf; - if($type != 'media' && $type != 'page') throw new Exception('Not a valid type'); + if ($type != 'media' && $type != 'page') throw new Exception('Not a valid type'); // first check if the old link still resolves $exists = false; $old = $relold; - if($type == 'page') { + if ($type == 'page') { resolve_pageid($this->ns, $old, $exists); // Work around bug in DokuWiki 2020-07-29 where resolve_pageid doesn't append the start page to a link to // the root. @@ -140,22 +149,22 @@ public function relativeLink($relold, $new, $type) { } else { resolve_mediaid($this->ns, $old, $exists); } - if($old == $new) { + if ($old == $new) { return $relold; // old link still resolves, keep as is } - if($conf['useslash']) $relold = str_replace('/', ':', $relold); + if ($conf['useslash']) $relold = str_replace('/', ':', $relold); // check if the link was relative - if(strpos($relold, ':') === false ||$relold[0] == '.') { + if (strpos($relold, ':') === false || $relold[0] == '.') { $wasrel = true; } else { $wasrel = false; } // if it wasn't relative then, leave it absolute now, too - if(!$wasrel) { - if($this->ns && !getNS($new)) $new = ':' . $new; + if (!$wasrel) { + if ($this->ns && !getNS($new)) $new = ':' . $new; $new = $this->_nsStartCheck($relold, $new, $type); return $new; } @@ -164,30 +173,30 @@ public function relativeLink($relold, $new, $type) { $selfpath = explode(':', $this->ns); $goalpath = explode(':', getNS($new)); $min = min(count($selfpath), count($goalpath)); - for($common = 0; $common < $min; $common++) { - if($selfpath[$common] != $goalpath[$common]) break; + for ($common = 0; $common < $min; $common++) { + if ($selfpath[$common] !== $goalpath[$common]) break; } // we now have the non-common part and a number of uppers $ups = max(count($selfpath) - $common, 0); $remainder = array_slice($goalpath, $common); - $upper = $ups ? array_fill(0, $ups, '..:') : array(); + $upper = $ups ? array_fill(0, $ups, '..:') : []; // build the new relative path - $newrel = join(':', $upper); - if($remainder) $newrel .= join(':', $remainder) . ':'; + $newrel = implode(':', $upper); + if ($remainder) $newrel .= implode(':', $remainder) . ':'; $newrel .= noNS($new); $newrel = str_replace('::', ':', trim($newrel, ':')); - if($newrel[0] != '.' && $this->ns && getNS($newrel)) $newrel = '.' . $newrel; + if ($newrel[0] != '.' && $this->ns && getNS($newrel)) $newrel = '.' . $newrel; // if the old link ended with a colon and the new one is a start page, adjust - $newrel = $this->_nsStartCheck($relold,$newrel,$type); + $newrel = $this->_nsStartCheck($relold, $newrel, $type); // don't use relative paths if it is ridicoulus: - if(strlen($newrel) > strlen($new)) { + if (strlen($newrel) > strlen($new)) { $newrel = $new; - if($this->ns && !getNS($new)) $newrel = ':' . $newrel; - $newrel = $this->_nsStartCheck($relold,$newrel,$type); + if ($this->ns && !getNS($new)) $newrel = ':' . $newrel; + $newrel = $this->_nsStartCheck($relold, $newrel, $type); } return $newrel; @@ -201,22 +210,21 @@ public function relativeLink($relold, $new, $type) { * @param int $pos The position in the input * @return bool If parsing should be continued */ - public function camelcaselink($match, $state, $pos) { + public function camelcaselink($match, $state, $pos) + { $oldID = cleanID($this->origNS . ':' . $match); $newID = $this->resolveMoves($oldID, 'page'); $newNS = getNS($newID); - if($oldID == $newID || $this->origNS == $newNS) { + if ($oldID == $newID || $this->origNS == $newNS) { // link is still valid as is $this->calls .= $match; + } elseif (noNS($oldID) == noNS($newID)) { + // only namespace changed, keep CamelCase in link + $this->calls .= "[[$newNS:$match]]"; } else { - if(noNS($oldID) == noNS($newID)) { - // only namespace changed, keep CamelCase in link - $this->calls .= "[[$newNS:$match]]"; - } else { - // all new, keep CamelCase in title - $this->calls .= "[[$newID|$match]]"; - } + // all new, keep CamelCase in title + $this->calls .= "[[$newID|$match]]"; } return true; } @@ -229,15 +237,16 @@ public function camelcaselink($match, $state, $pos) { * @param int $pos The position in the input * @return bool If parsing should be continued */ - public function internallink($match, $state, $pos) { + public function internallink($match, $state, $pos) + { // Strip the opening and closing markup - $link = preg_replace(array('/^\[\[/', '/\]\]$/u'), '', $match); + $link = preg_replace(['/^\[\[/', '/\]\]$/u'], '', $match); // Split title from URL $link = explode('|', $link, 2); - if(!isset($link[1])) { + if (!isset($link[1])) { $link[1] = null; - } else if(preg_match('/^\{\{[^\}]+\}\}$/', $link[1])) { + } elseif (preg_match('/^\{\{[^\}]+\}\}$/', $link[1])) { // If the title is an image, rewrite it $old_title = $link[1]; $link[1] = $this->rewrite_media($link[1]); @@ -250,19 +259,19 @@ public function internallink($match, $state, $pos) { //decide which kind of link it is - if(preg_match('/^[a-zA-Z0-9\.]+>{1}.*$/u', $link[0])) { + if (preg_match('/^[a-zA-Z0-9\.]+>{1}.*$/u', $link[0])) { // Interwiki $this->calls .= $match; - } elseif(preg_match('/^\\\\\\\\[^\\\\]+?\\\\/u', $link[0])) { + } elseif (preg_match('/^\\\\\\\\[^\\\\]+?\\\\/u', $link[0])) { // Windows Share $this->calls .= $match; - } elseif(preg_match('#^([a-z0-9\-\.+]+?)://#i', $link[0])) { + } elseif (preg_match('#^([a-z0-9\-\.+]+?)://#i', $link[0])) { // external link (accepts all protocols) $this->calls .= $match; - } elseif(preg_match('<' . PREG_PATTERN_VALID_EMAIL . '>', $link[0])) { + } elseif (preg_match('<' . PREG_PATTERN_VALID_EMAIL . '>', $link[0])) { // E-Mail (pattern above is defined in inc/mail.php) $this->calls .= $match; - } elseif(preg_match('!^#.+!', $link[0])) { + } elseif (preg_match('!^#.+!', $link[0])) { // local hash link $this->calls .= $match; } else { @@ -270,14 +279,14 @@ public function internallink($match, $state, $pos) { $hash = ''; $parts = explode('#', $id, 2); - if(count($parts) === 2) { + if (count($parts) === 2) { $id = $parts[0]; $hash = $parts[1]; } $params = ''; $parts = explode('?', $id, 2); - if(count($parts) === 2) { + if (count($parts) === 2) { $id = $parts[0]; $params = $parts[1]; } @@ -285,24 +294,23 @@ public function internallink($match, $state, $pos) { $new_id = $this->resolveMoves($id, 'page'); $new_id = $this->relativeLink($id, $new_id, 'page'); - if($id == $new_id) { + if ($id == $new_id) { $this->calls .= $match; } else { - if($params !== '') { + if ($params !== '') { $new_id .= '?' . $params; } - if($hash !== '') { + if ($hash !== '') { $new_id .= '#' . $hash; } - if($link[1] != null) { + if ($link[1] != null) { $new_id .= '|' . $link[1]; } $this->calls .= '[[' . $new_id . ']]'; } - } return true; @@ -316,7 +324,8 @@ public function internallink($match, $state, $pos) { * @param int $pos The position in the input * @return bool If parsing should be continued */ - public function media($match, $state, $pos) { + public function media($match, $state, $pos) + { $this->calls .= $this->rewrite_media($match); return true; } @@ -327,16 +336,16 @@ public function media($match, $state, $pos) { * @param string $match The text match of the media syntax * @return string The rewritten syntax */ - protected function rewrite_media($match) { + protected function rewrite_media($match) + { $p = Doku_Handler_Parse_Media($match); - if($p['type'] == 'internalmedia') { // else: external media - + if ($p['type'] == 'internalmedia') { // else: external media $new_src = $this->resolveMoves($p['src'], 'media'); $new_src = $this->relativeLink($p['src'], $new_src, 'media'); - if($new_src !== $p['src']) { + if ($new_src !== $p['src']) { // do a simple replace of the first match so really only the id is changed and not e.g. the alignment - $srcpos = strpos($match, $p['src']); + $srcpos = strpos($match, (string) $p['src']); $srclen = strlen($p['src']); return substr_replace($match, $new_src, $srcpos, $srclen); } @@ -353,8 +362,9 @@ protected function rewrite_media($match) { * @param string $pluginname The name of the plugin * @return bool If parsing should be continued */ - public function plugin($match, $state, $pos, $pluginname) { - if(isset($this->handlers[$pluginname])) { + public function plugin($match, $state, $pos, $pluginname) + { + if (isset($this->handlers[$pluginname])) { $this->calls .= call_user_func($this->handlers[$pluginname], $match, $state, $pos, $pluginname, $this); } else { $this->calls .= $match; @@ -369,8 +379,9 @@ public function plugin($match, $state, $pos, $pluginname) { * @param array $params Original parameters * @return bool If parsing should be continue */ - public function __call($name, $params) { - if(count($params) == 3) { + public function __call($name, $params) + { + if (count($params) == 3) { $this->calls .= $params[0]; return true; } else { @@ -379,9 +390,9 @@ public function __call($name, $params) { } } - public function _finalize() { + public function _finalize() + { // remove padding that is added by the parser in parse() $this->calls = substr($this->calls, 1, -1); } - } diff --git a/helper/op.php b/helper/op.php index 48c41757..68e9682f 100644 --- a/helper/op.php +++ b/helper/op.php @@ -1,4 +1,8 @@ * @author Andreas Gohr */ -// must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); -class helper_plugin_move_op extends DokuWiki_Plugin { +// must be run within Dokuwiki +if (!defined('DOKU_INC')) die(); +class helper_plugin_move_op extends Plugin +{ /** * @var string symbol to make move operations easily recognizable in change log */ @@ -20,7 +25,7 @@ class helper_plugin_move_op extends DokuWiki_Plugin { /** * @var array stores the affected pages of the last operation */ - protected $affectedPages = array(); + protected $affectedPages = []; /** * Check if the given page can be moved to the given destination @@ -29,13 +34,14 @@ class helper_plugin_move_op extends DokuWiki_Plugin { * @param $dst * @return bool */ - public function checkPage($src, $dst) { + public function checkPage($src, $dst) + { // Check we have rights to move this document - if(!page_exists($src)) { + if (!page_exists($src)) { msg(sprintf($this->getLang('notexist'), $src), -1); return false; } - if(auth_quickaclcheck($src) < AUTH_EDIT) { + if (auth_quickaclcheck($src) < AUTH_EDIT) { msg(sprintf($this->getLang('norights'), $src), -1); return false; } @@ -44,25 +50,25 @@ public function checkPage($src, $dst) { // checklock checks if the page lock hasn't expired and the page hasn't been locked by another user // the file exists check checks if the page is reported unlocked if a lock exists which means that // the page is locked by the current user - if(checklock($src) !== false || @file_exists(wikiLockFN($src))) { + if (checklock($src) !== false || @file_exists(wikiLockFN($src))) { msg(sprintf($this->getLang('filelocked'), $src), -1); return false; } // Has the document name and/or namespace changed? - if($src == $dst) { + if ($src == $dst) { msg(sprintf($this->getLang('notchanged'), $src), -1); return false; } // Check the page does not already exist - if(page_exists($dst)) { + if (page_exists($dst)) { msg(sprintf($this->getLang('exists'), $src, $dst), -1); return false; } // Check if the current user can create the new page - if(auth_quickaclcheck($dst) < AUTH_CREATE) { + if (auth_quickaclcheck($dst) < AUTH_CREATE) { msg(sprintf($this->getLang('notargetperms'), $dst), -1); return false; } @@ -77,31 +83,32 @@ public function checkPage($src, $dst) { * @param $dst * @return bool */ - public function checkMedia($src, $dst) { + public function checkMedia($src, $dst) + { // Check we have rights to move this document - if(!file_exists(mediaFN($src))) { + if (!file_exists(mediaFN($src))) { msg(sprintf($this->getLang('medianotexist'), $src), -1); return false; } - if(auth_quickaclcheck($src) < AUTH_DELETE) { + if (auth_quickaclcheck($src) < AUTH_DELETE) { msg(sprintf($this->getLang('nomediarights'), $src), -1); return false; } // Has the document name and/or namespace changed? - if($src == $dst) { + if ($src == $dst) { msg(sprintf($this->getLang('medianotchanged'), $src), -1); return false; } // Check the page does not already exist - if(@file_exists(mediaFN($dst))) { + if (@file_exists(mediaFN($dst))) { msg(sprintf($this->getLang('mediaexists'), $src, $dst), -1); return false; } // Check if the current user can create the new page - if(auth_quickaclcheck($dst) < AUTH_UPLOAD) { + if (auth_quickaclcheck($dst) < AUTH_UPLOAD) { msg(sprintf($this->getLang('nomediatargetperms'), $dst), -1); return false; } @@ -122,8 +129,9 @@ public function checkMedia($src, $dst) { * @param string $dst new ID * @return bool */ - public function movePage($src, $dst) { - if(!$this->checkPage($src, $dst)) return false; + public function movePage($src, $dst) + { + if (!$this->checkPage($src, $dst)) return false; // lock rewrites helper_plugin_move_rewrite::addLock(); @@ -145,24 +153,19 @@ public function movePage($src, $dst) { $dst_name = noNS($dst); // pass this info on to other plugins - $eventdata = array( + $eventdata = [ // this is for compatibility to old plugin - 'opts' => array( - 'ns' => $src_ns, - 'name' => $src_name, - 'newns' => $dst_ns, - 'newname' => $dst_name, - ), + 'opts' => ['ns' => $src_ns, 'name' => $src_name, 'newns' => $dst_ns, 'newname' => $dst_name], 'affected_pages' => &$affected_pages, 'src_id' => $src, 'dst_id' => $dst, - ); + ]; // give plugins the option to add their own meta files to the list of files that need to be moved // to the oldfiles/newfiles array or to adjust their own metadata, database, ... // and to add other pages to the affected pages - $event = new Doku_Event('PLUGIN_MOVE_PAGE_RENAME', $eventdata); - if($event->advise_before()) { + $event = new Event('PLUGIN_MOVE_PAGE_RENAME', $eventdata); + if ($event->advise_before()) { lock($src); /** @var helper_plugin_move_file $FileMover */ @@ -170,21 +173,22 @@ public function movePage($src, $dst) { // Move the Subscriptions & Indexes (new feature since Spring 2013 release) $Indexer = idx_get_indexer(); - if(($idx_msg = $Indexer->renamePage($src, $dst)) !== true + if ( + ($idx_msg = $Indexer->renamePage($src, $dst)) !== true || ($idx_msg = $Indexer->renameMetaValue('relation_references', $src, $dst)) !== true ) { msg(sprintf($this->getLang('indexerror'), $idx_msg), -1); return false; } - if(!$FileMover->movePageMeta($src_ns, $src_name, $dst_ns, $dst_name)) { + if (!$FileMover->movePageMeta($src_ns, $src_name, $dst_ns, $dst_name)) { msg(sprintf($this->getLang('metamoveerror'), $src), -1); return false; } // prepare the summary for the changelog entry - if($src_ns == $dst_ns) { + if ($src_ns == $dst_ns) { $lang_key = 'renamed'; - } elseif($src_name == $dst_name) { + } elseif ($src_name == $dst_name) { $lang_key = 'moved'; } else { $lang_key = 'move_rename'; @@ -193,25 +197,25 @@ public function movePage($src, $dst) { // Wait a second when the page has just been rewritten $oldRev = filemtime(wikiFN($src)); - if($oldRev == time()) sleep(1); + if ($oldRev == time()) sleep(1); // Save the updated document in its new location $text = rawWiki($src); saveWikiText($dst, $text, $summary); // Delete the orginal file - if(@file_exists(wikiFN($dst))) { + if (@file_exists(wikiFN($dst))) { saveWikiText($src, '', $summary); } // Move the old revisions - if(!$FileMover->movePageAttic($src_ns, $src_name, $dst_ns, $dst_name)) { + if (!$FileMover->movePageAttic($src_ns, $src_name, $dst_ns, $dst_name)) { // it's too late to stop the move, so just display a message. - msg(sprintf($this->getLang('atticmoveerror'), $src ), -1); + msg(sprintf($this->getLang('atticmoveerror'), $src), -1); } // Add meta data to all affected pages, so links get updated later - foreach($affected_pages as $id) { + foreach ($affected_pages as $id) { $Rewriter->setMoveMeta($id, $src, $dst, 'pages'); } @@ -235,8 +239,9 @@ public function movePage($src, $dst) { * @param string $dst new ID * @return bool true if the move was successfully executed */ - public function moveMedia($src, $dst) { - if(!$this->checkMedia($src, $dst)) return false; + public function moveMedia($src, $dst) + { + if (!$this->checkMedia($src, $dst)) return false; // get all pages using this media $affected_pages = idx_get_indexer()->lookupKey('relation_media', $src); @@ -247,24 +252,19 @@ public function moveMedia($src, $dst) { $dst_name = noNS($dst); // pass this info on to other plugins - $eventdata = array( + $eventdata = [ // this is for compatibility to old plugin - 'opts' => array( - 'ns' => $src_ns, - 'name' => $src_name, - 'newns' => $dst_ns, - 'newname' => $dst_name, - ), + 'opts' => ['ns' => $src_ns, 'name' => $src_name, 'newns' => $dst_ns, 'newname' => $dst_name], 'affected_pages' => &$affected_pages, 'src_id' => $src, 'dst_id' => $dst, - ); + ]; // give plugins the option to add their own meta files to the list of files that need to be moved // to the oldfiles/newfiles array or to adjust their own metadata, database, ... // and to add other pages to the affected pages - $event = new Doku_Event('PLUGIN_MOVE_MEDIA_RENAME', $eventdata); - if($event->advise_before()) { + $event = new Event('PLUGIN_MOVE_MEDIA_RENAME', $eventdata); + if ($event->advise_before()) { /** @var helper_plugin_move_file $FileMover */ $FileMover = plugin_load('helper', 'move_file'); /** @var helper_plugin_move_rewrite $Rewriter */ @@ -272,11 +272,11 @@ public function moveMedia($src, $dst) { // Move the Subscriptions & Indexes (new feature since Spring 2013 release) $Indexer = idx_get_indexer(); - if(($idx_msg = $Indexer->renameMetaValue('relation_media', $src, $dst)) !== true) { + if (($idx_msg = $Indexer->renameMetaValue('relation_media', $src, $dst)) !== true) { msg(sprintf($this->getLang('indexerror'), $idx_msg), -1); return false; } - if(!$FileMover->moveMediaMeta($src_ns, $src_name, $dst_ns, $dst_name)) { + if (!$FileMover->moveMediaMeta($src_ns, $src_name, $dst_ns, $dst_name)) { msg(sprintf($this->getLang('mediametamoveerror'), $src), -1); return false; } @@ -285,7 +285,7 @@ public function moveMedia($src, $dst) { io_createNamespace($dst, 'media'); // move it FIXME this does not create a changelog entry! - if(!io_rename(mediaFN($src), mediaFN($dst))) { + if (!io_rename(mediaFN($src), mediaFN($dst))) { msg(sprintf($this->getLang('mediamoveerror'), $src), -1); return false; } @@ -294,13 +294,13 @@ public function moveMedia($src, $dst) { io_sweepNS($src, 'mediadir'); // Move the old revisions - if(!$FileMover->moveMediaAttic($src_ns, $src_name, $dst_ns, $dst_name)) { + if (!$FileMover->moveMediaAttic($src_ns, $src_name, $dst_ns, $dst_name)) { // it's too late to stop the move, so just display a message. msg(sprintf($this->getLang('mediaatticmoveerror'), $src), -1); } // Add meta data to all affected pages, so links get updated later - foreach($affected_pages as $id) { + foreach ($affected_pages as $id) { $Rewriter->setMoveMeta($id, $src, $dst, 'media'); } } @@ -317,7 +317,8 @@ public function moveMedia($src, $dst) { * * @return array */ - public function getAffectedPages() { + public function getAffectedPages() + { return $this->affectedPages; } } diff --git a/helper/plan.php b/helper/plan.php index 6d632d33..7a908a1d 100644 --- a/helper/plan.php +++ b/helper/plan.php @@ -1,4 +1,7 @@ * @author Andreas Gohr */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); /** * Class helper_plugin_move_plan @@ -25,63 +29,50 @@ * * document - refers to either a page or a media file here */ -class helper_plugin_move_plan extends DokuWiki_Plugin { +class helper_plugin_move_plan extends Plugin +{ /** Number of operations per step */ - const OPS_PER_RUN = 10; + public const OPS_PER_RUN = 10; - const TYPE_PAGES = 1; - const TYPE_MEDIA = 2; - const CLASS_NS = 4; - const CLASS_DOC = 8; + public const TYPE_PAGES = 1; + public const TYPE_MEDIA = 2; + public const CLASS_NS = 4; + public const CLASS_DOC = 8; /** * @var array the options for this move plan */ - protected $options = array(); // defaults are set in loadOptions() + protected $options = []; // defaults are set in loadOptions() /** * @var array holds the location of the different list and state files */ - protected $files = array(); + protected $files = []; /** * @var array the planned moves */ - protected $plan = array(); + protected $plan = []; /** * @var array temporary holder of document lists */ - protected $tmpstore = array( - 'pages' => array(), - 'media' => array(), - 'ns' => array(), - 'affpg' => array(), - 'miss' => array(), - 'miss_media' => array(), - ); + protected $tmpstore = ['pages' => [], 'media' => [], 'ns' => [], 'affpg' => [], 'miss' => [], 'miss_media' => []]; /** @var helper_plugin_move_op $MoveOperator */ - protected $MoveOperator = null; + protected $MoveOperator; /** * Constructor * * initializes state (if any) for continuiation of a running move op */ - public function __construct() { + public function __construct() + { global $conf; // set the file locations - $this->files = array( - 'opts' => $conf['metadir'] . '/__move_opts', - 'pagelist' => $conf['metadir'] . '/__move_pagelist', - 'medialist' => $conf['metadir'] . '/__move_medialist', - 'affected' => $conf['metadir'] . '/__move_affected', - 'namespaces' => $conf['metadir'] . '/__move_namespaces', - 'missing' => $conf['metadir'] . '/__move_missing', - 'missing_media' => $conf['metadir'] . '/__move_missing_media', - ); + $this->files = ['opts' => $conf['metadir'] . '/__move_opts', 'pagelist' => $conf['metadir'] . '/__move_pagelist', 'medialist' => $conf['metadir'] . '/__move_medialist', 'affected' => $conf['metadir'] . '/__move_affected', 'namespaces' => $conf['metadir'] . '/__move_namespaces', 'missing' => $conf['metadir'] . '/__move_missing', 'missing_media' => $conf['metadir'] . '/__move_missing_media']; $this->MoveOperator = plugin_load('helper', 'move_op'); @@ -94,13 +85,13 @@ public function __construct() { * If no options are found, the default options will be extended by any available * config options */ - protected function loadOptions() { + protected function loadOptions() + { // (re)set defaults - $this->options = array( + $this->options = [ // status 'committed' => false, 'started' => 0, - // counters 'pages_all' => 0, 'pages_run' => 0, @@ -108,18 +99,16 @@ protected function loadOptions() { 'media_run' => 0, 'affpg_all' => 0, 'affpg_run' => 0, - // options 'autoskip' => $this->getConf('autoskip'), 'autorewrite' => $this->getConf('autorewrite'), - // errors - 'lasterror' => false - ); + 'lasterror' => false, + ]; // merge whatever options are saved currently $file = $this->files['opts']; - if(file_exists($file)) { + if (file_exists($file)) { $options = unserialize(io_readFile($file, false)); $this->options = array_merge($this->options, $options); } @@ -130,7 +119,8 @@ protected function loadOptions() { * * @return bool */ - protected function saveOptions() { + protected function saveOptions() + { return io_saveFile($this->files['opts'], serialize($this->options)); } @@ -140,11 +130,9 @@ protected function saveOptions() { * @param $name * @return mixed|null */ - public function getOption($name) { - if(isset($this->options[$name])) { - return $this->options[$name]; - } - return null; + public function getOption($name) + { + return $this->options[$name] ?? null; } /** @@ -156,7 +144,8 @@ public function getOption($name) { * @param $name * @param $value */ - public function setOption($name, $value) { + public function setOption($name, $value) + { $this->options[$name] = $value; } @@ -165,7 +154,8 @@ public function setOption($name, $value) { * * @return float */ - public function getProgress() { + public function getProgress() + { $max = $this->options['pages_all'] + $this->options['media_all']; @@ -174,12 +164,12 @@ public function getProgress() { $this->options['pages_run'] + $this->options['media_run']; - if($this->options['autorewrite']) { + if ($this->options['autorewrite']) { $max += $this->options['affpg_all']; $remain += $this->options['affpg_run']; } - if($max == 0) return 0; + if ($max == 0) return 0; return round((($max - $remain) * 100) / $max, 2); } @@ -188,7 +178,8 @@ public function getProgress() { * * @return bool */ - public function inProgress() { + public function inProgress() + { return (bool) $this->options['started']; } @@ -197,7 +188,8 @@ public function inProgress() { * * @return bool */ - public function isCommited() { + public function isCommited() + { return $this->options['committed']; } @@ -207,7 +199,8 @@ public function isCommited() { * @param string $src * @param string $dst */ - public function addPageMove($src, $dst) { + public function addPageMove($src, $dst) + { $this->addMove($src, $dst, self::CLASS_DOC, self::TYPE_PAGES); } @@ -217,7 +210,8 @@ public function addPageMove($src, $dst) { * @param string $src * @param string $dst */ - public function addMediaMove($src, $dst) { + public function addMediaMove($src, $dst) + { $this->addMove($src, $dst, self::CLASS_DOC, self::TYPE_MEDIA); } @@ -227,7 +221,8 @@ public function addMediaMove($src, $dst) { * @param string $src * @param string $dst */ - public function addPageNamespaceMove($src, $dst) { + public function addPageNamespaceMove($src, $dst) + { $this->addMove($src, $dst, self::CLASS_NS, self::TYPE_PAGES); } @@ -237,7 +232,8 @@ public function addPageNamespaceMove($src, $dst) { * @param string $src * @param string $dst */ - public function addMediaNamespaceMove($src, $dst) { + public function addMediaNamespaceMove($src, $dst) + { $this->addMove($src, $dst, self::CLASS_NS, self::TYPE_MEDIA); } @@ -250,28 +246,25 @@ public function addMediaNamespaceMove($src, $dst) { * @param int $type (PLUGIN_MOVE_TYPE_PAGE|self::TYPE_MEDIA) * @throws Exception */ - protected function addMove($src, $dst, $class = self::CLASS_NS, $type = self::TYPE_PAGES) { - if($this->options['committed']) throw new Exception('plan is committed already, can not be added to'); + protected function addMove($src, $dst, $class = self::CLASS_NS, $type = self::TYPE_PAGES) + { + if ($this->options['committed']) throw new Exception('plan is committed already, can not be added to'); $src = cleanID($src); $dst = cleanID($dst); - $this->plan[] = array( - 'src' => $src, - 'dst' => $dst, - 'class' => $class, - 'type' => $type - ); + $this->plan[] = ['src' => $src, 'dst' => $dst, 'class' => $class, 'type' => $type]; } /** * Abort any move or plan in progress and reset the helper */ - public function abort() { - foreach($this->files as $file) { + public function abort() + { + foreach ($this->files as $file) { @unlink($file); } - $this->plan = array(); + $this->plan = []; $this->loadOptions(); helper_plugin_move_rewrite::removeAllLocks(); } @@ -285,55 +278,56 @@ public function abort() { * @throws Exception if you try to commit a plan twice * @return bool true if the plan was committed */ - public function commit() { + public function commit() + { global $conf; - if($this->options['committed']) throw new Exception('plan is committed already, can not be committed again'); + if ($this->options['committed']) throw new Exception('plan is committed already, can not be committed again'); helper_plugin_move_rewrite::addLock(); - usort($this->plan, array($this, 'planSorter')); + usort($this->plan, [$this, 'planSorter']); // get all the documents to be moved and store them in their lists - foreach($this->plan as $move) { - if($move['class'] == self::CLASS_DOC) { + foreach ($this->plan as $move) { + if ($move['class'] == self::CLASS_DOC) { // these can just be added $this->addToDocumentList($move['src'], $move['dst'], $move['type']); } else { // here we need a list of content first, search for it - $docs = array(); + $docs = []; $path = utf8_encodeFN(str_replace(':', '/', $move['src'])); - $opts = array('depth' => 0, 'skipacl' => true); - if($move['type'] == self::TYPE_PAGES) { + $opts = ['depth' => 0, 'skipacl' => true]; + if ($move['type'] == self::TYPE_PAGES) { search($docs, $conf['datadir'], 'search_allpages', $opts, $path); } else { search($docs, $conf['mediadir'], 'search_media', $opts, $path); } // how much namespace to strip? - if($move['src'] !== '') { + if ($move['src'] !== '') { $strip = strlen($move['src']) + 1; } else { $strip = 0; } - if($move['dst']) $move['dst'] .= ':'; + if ($move['dst']) $move['dst'] .= ':'; // now add all the found documents to our lists - foreach($docs as $doc) { + foreach ($docs as $doc) { $from = $doc['id']; $to = $move['dst'] . substr($doc['id'], $strip); $this->addToDocumentList($from, $to, $move['type']); } // remember the namespace move itself - if($move['type'] == self::TYPE_PAGES) { + if ($move['type'] == self::TYPE_PAGES) { // FIXME we use this to move namespace subscriptions later on and for now only do it on // page namespace moves, but subscriptions work for both, but what when only one of // them is moved? Should it be copied then? Complicated. This is good enough for now $this->addToDocumentList($move['src'], $move['dst'], self::CLASS_NS); } - $this->findMissingDocuments($move['src'] . ':', $move['dst'],$move['type']); + $this->findMissingDocuments($move['src'] . ':', $move['dst'], $move['type']); } // store what pages are affected by this move $this->findAffectedPages($move['src'], $move['dst'], $move['class'], $move['type']); @@ -341,7 +335,7 @@ public function commit() { $this->storeDocumentLists(); - if(!$this->options['pages_all'] && !$this->options['media_all']) { + if (!$this->options['pages_all'] && !$this->options['media_all']) { msg($this->getLang('noaction'), -1); return false; } @@ -359,49 +353,50 @@ public function commit() { * @return bool|int false on errors, otherwise the number of remaining steps * @throws Exception */ - public function nextStep($skip = false) { - if(!$this->options['committed']) throw new Exception('plan is not committed yet!'); + public function nextStep($skip = false) + { + if (!$this->options['committed']) throw new Exception('plan is not committed yet!'); // execution has started - if(!$this->options['started']) $this->options['started'] = time(); + if (!$this->options['started']) $this->options['started'] = time(); helper_plugin_move_rewrite::addLock(); - if(@filesize($this->files['pagelist']) > 1) { + if (@filesize($this->files['pagelist']) > 1) { $todo = $this->stepThroughDocuments(self::TYPE_PAGES, $skip); - if($todo === false) return $this->storeError(); + if ($todo === false) return $this->storeError(); return max($todo, 1); // force one more call } - if(@filesize($this->files['medialist']) > 1) { + if (@filesize($this->files['medialist']) > 1) { $todo = $this->stepThroughDocuments(self::TYPE_MEDIA, $skip); - if($todo === false) return $this->storeError(); + if ($todo === false) return $this->storeError(); return max($todo, 1); // force one more call } - if(@filesize($this->files['missing']) > 1 && @filesize($this->files['affected']) > 1) { + if (@filesize($this->files['missing']) > 1 && @filesize($this->files['affected']) > 1) { $todo = $this->stepThroughMissingDocuments(self::TYPE_PAGES); - if($todo === false) return $this->storeError(); + if ($todo === false) return $this->storeError(); return max($todo, 1); // force one more call } - if(@filesize($this->files['missing_media']) > 1 && @filesize($this->files['affected']) > 1) { + if (@filesize($this->files['missing_media']) > 1 && @filesize($this->files['affected']) > 1) { $todo = $this->stepThroughMissingDocuments(self::TYPE_MEDIA); - if($todo === false)return $this->storeError(); + if ($todo === false)return $this->storeError(); return max($todo, 1); // force one more call } - if(@filesize($this->files['namespaces']) > 1) { + if (@filesize($this->files['namespaces']) > 1) { $todo = $this->stepThroughNamespaces(); - if($todo === false) return $this->storeError(); + if ($todo === false) return $this->storeError(); return max($todo, 1); // force one more call } helper_plugin_move_rewrite::removeAllLocks(); - if($this->options['autorewrite'] && @filesize($this->files['affected']) > 1) { + if ($this->options['autorewrite'] && @filesize($this->files['affected']) > 1) { $todo = $this->stepThroughAffectedPages(); - if($todo === false) return $this->storeError(); + if ($todo === false) return $this->storeError(); return max($todo, 1); // force one more call } @@ -415,14 +410,15 @@ public function nextStep($skip = false) { * * @return string */ - public function previewHTML() { + public function previewHTML() + { $html = ''; $html .= '
      '; - if(@file_exists($this->files['pagelist'])) { + if (@file_exists($this->files['pagelist'])) { $pagelist = file($this->files['pagelist']); - foreach($pagelist as $line) { - list($old, $new) = explode("\t", trim($line)); + foreach ($pagelist as $line) { + [$old, $new] = explode("\t", trim($line)); $html .= '
    • '; $html .= hsc($old); @@ -431,10 +427,10 @@ public function previewHTML() { $html .= '
    • '; } } - if(@file_exists($this->files['medialist'])) { + if (@file_exists($this->files['medialist'])) { $medialist = file($this->files['medialist']); - foreach($medialist as $line) { - list($old, $new) = explode("\t", trim($line)); + foreach ($medialist as $line) { + [$old, $new] = explode("\t", trim($line)); $html .= '
    • '; $html .= hsc($old); @@ -443,9 +439,9 @@ public function previewHTML() { $html .= '
    • '; } } - if(@file_exists($this->files['affected'])) { + if (@file_exists($this->files['affected'])) { $medialist = file($this->files['affected']); - foreach($medialist as $page) { + foreach ($medialist as $page) { $html .= '
    • '; $html .= '↷'; $html .= hsc($page); @@ -464,9 +460,10 @@ public function previewHTML() { * @param bool $skip should the first item be skipped? * @return bool|int false on error, otherwise the number of remaining documents */ - protected function stepThroughDocuments($type = self::TYPE_PAGES, $skip = false) { + protected function stepThroughDocuments($type = self::TYPE_PAGES, $skip = false) + { - if($type == self::TYPE_PAGES) { + if ($type == self::TYPE_PAGES) { $file = $this->files['pagelist']; $mark = 'P'; $call = 'movePage'; @@ -480,32 +477,30 @@ protected function stepThroughDocuments($type = self::TYPE_PAGES, $skip = false) $doclist = fopen($file, 'a+'); - for($i = 0; $i < helper_plugin_move_plan::OPS_PER_RUN; $i++) { + for ($i = 0; $i < helper_plugin_move_plan::OPS_PER_RUN; $i++) { $log = ""; $line = $this->getLastLine($doclist); - if($line === false) { + if ($line === false) { break; } - list($src, $dst) = explode("\t", trim($line)); + [$src, $dst] = explode("\t", trim($line)); // should this item be skipped? - if($skip === true) { + if ($skip === true) { $skip = false; - } else { - // move the page - if(!$this->MoveOperator->$call($src, $dst)) { - $log .= $this->build_log_line($mark, $src, $dst, false); // FAILURE! - - // automatically skip this item only if wanted... - if(!$this->options['autoskip']) { - // ...otherwise abort the operation - fclose($doclist); - $return_items_run = false; - break; - } - } else { - $log .= $this->build_log_line($mark, $src, $dst, true); // SUCCESS! + } elseif (!$this->MoveOperator->$call($src, $dst)) { + // move the page + $log .= $this->build_log_line($mark, $src, $dst, false); + // FAILURE! + // automatically skip this item only if wanted... + if (!$this->options['autoskip']) { + // ...otherwise abort the operation + fclose($doclist); + $return_items_run = false; + break; } + } else { + $log .= $this->build_log_line($mark, $src, $dst, true); // SUCCESS! } /* @@ -531,15 +526,16 @@ protected function stepThroughDocuments($type = self::TYPE_PAGES, $skip = false) * * @return bool|int false on error, otherwise the number of remaining documents */ - protected function stepThroughAffectedPages() { + protected function stepThroughAffectedPages() + { /** @var helper_plugin_move_rewrite $Rewriter */ $Rewriter = plugin_load('helper', 'move_rewrite'); // handle affected pages $doclist = fopen($this->files['affected'], 'a+'); - for($i = 0; $i < helper_plugin_move_plan::OPS_PER_RUN; $i++) { + for ($i = 0; $i < helper_plugin_move_plan::OPS_PER_RUN; $i++) { $page = $this->getLastLine($doclist); - if($page === false) break; + if ($page === false) break; // rewrite it $Rewriter->rewritePage($page); @@ -568,29 +564,30 @@ protected function stepThroughAffectedPages() { * @return int always 0 * @throws Exception */ - protected function stepThroughMissingDocuments($type = self::TYPE_PAGES) { - if($type != self::TYPE_PAGES && $type != self::TYPE_MEDIA) { + protected function stepThroughMissingDocuments($type = self::TYPE_PAGES) + { + if ($type != self::TYPE_PAGES && $type != self::TYPE_MEDIA) { throw new Exception('wrong type specified'); } /** @var helper_plugin_move_rewrite $Rewriter */ $Rewriter = plugin_load('helper', 'move_rewrite'); - $miss = array(); + $miss = []; if ($type == self::TYPE_PAGES) { $missing_fn = $this->files['missing']; } else { $missing_fn = $this->files['missing_media']; } $missing = file($missing_fn); - foreach($missing as $line) { + foreach ($missing as $line) { $line = trim($line); - if($line == '') continue; - list($src, $dst) = explode("\t", $line); + if ($line == '') continue; + [$src, $dst] = explode("\t", $line); $miss[$src] = $dst; } $affected = file($this->files['affected']); - foreach($affected as $page){ + foreach ($affected as $page) { $page = trim($page); if ($type == self::TYPE_PAGES) { @@ -615,18 +612,19 @@ protected function stepThroughMissingDocuments($type = self::TYPE_PAGES) { * @todo maybe add an event so plugins can move more stuff? * @todo fixed that $src and $dst are seperated by tab, not newline. This method has no tests? */ - protected function stepThroughNamespaces() { + protected function stepThroughNamespaces() + { /** @var helper_plugin_move_file $FileMover */ $FileMover = plugin_load('helper', 'move_file'); $lines = io_readFile($this->files['namespaces']); $lines = explode("\n", $lines); - foreach($lines as $line) { + foreach ($lines as $line) { // There is an empty line at the end of the list. if ($line === '') continue; - list($src, $dst) = explode("\t", trim($line)); + [$src, $dst] = explode("\t", trim($line)); $FileMover->moveNamespaceSubscription($src, $dst); } @@ -641,10 +639,11 @@ protected function stepThroughNamespaces() { * * @return bool always false */ - protected function storeError() { + protected function storeError() + { global $MSG; - if(is_array($MSG) && count($MSG)) { + if (is_array($MSG) && count($MSG)) { $last = array_shift($MSG); $this->options['lasterror'] = $last['msg']; unset($GLOBALS['MSG']); @@ -659,7 +658,8 @@ protected function storeError() { /** * Reset the error state */ - protected function clearError() { + protected function clearError() + { $this->options['lasterror'] = false; $this->saveOptions(); } @@ -669,7 +669,8 @@ protected function clearError() { * * @return bool|string */ - public function getLastError() { + public function getLastError() + { return $this->options['lasterror']; } @@ -684,18 +685,19 @@ public function getLastError() { * @param int $type * @throws Exception */ - protected function addToDocumentList($src, $dst, $type = self::TYPE_PAGES) { - if($type == self::TYPE_PAGES) { + protected function addToDocumentList($src, $dst, $type = self::TYPE_PAGES) + { + if ($type == self::TYPE_PAGES) { $store = 'pages'; - } else if($type == self::TYPE_MEDIA) { + } elseif ($type == self::TYPE_MEDIA) { $store = 'media'; - } else if($type == self::CLASS_NS) { + } elseif ($type == self::CLASS_NS) { $store = 'ns'; } else { throw new Exception('Unknown type ' . $type); } - if(!isset($this->tmpstore[$store][$src])) { + if (!isset($this->tmpstore[$store][$src])) { $this->tmpstore[$store][$src] = $dst; } } @@ -705,11 +707,12 @@ protected function addToDocumentList($src, $dst, $type = self::TYPE_PAGES) { * * @param string|array $pages */ - protected function addToAffectedPagesList($pages) { - if(!is_array($pages)) $pages = array($pages); + protected function addToAffectedPagesList($pages) + { + if (!is_array($pages)) $pages = [$pages]; - foreach($pages as $page) { - if(!isset($this->tmpstore['affpg'][$page])) { + foreach ($pages as $page) { + if (!isset($this->tmpstore['affpg'][$page])) { $this->tmpstore['affpg'][$page] = true; } } @@ -725,26 +728,27 @@ protected function addToAffectedPagesList($pages) { * @param int $class * @param int $type */ - protected function findAffectedPages($src, $dst, $class, $type) { + protected function findAffectedPages($src, $dst, $class, $type) + { $idx = idx_get_indexer(); - if($class == self::CLASS_NS) { + if ($class == self::CLASS_NS) { $src_ = "$src:*"; // use wildcard lookup for namespaces } else { $src_ = $src; } - $pages = array(); - if($type == self::TYPE_PAGES) { + $pages = []; + if ($type == self::TYPE_PAGES) { $pages = $idx->lookupKey('relation_references', $src_); $len = strlen($src); - foreach($pages as &$page) { + foreach ($pages as &$page) { if (substr($page, 0, $len + 1) === "$src:") { $page = $dst . substr($page, $len + 1); } } unset($page); - } else if($type == self::TYPE_MEDIA) { + } elseif ($type == self::TYPE_MEDIA) { $pages = $idx->lookupKey('relation_media', $src_); } @@ -758,7 +762,8 @@ protected function findAffectedPages($src, $dst, $class, $type) { * @param string $dst destination namespace * @param int $type either self::TYPE_PAGES or self::TYPE_MEDIA */ - protected function findMissingDocuments($src, $dst, $type = self::TYPE_PAGES) { + protected function findMissingDocuments($src, $dst, $type = self::TYPE_PAGES) + { global $conf; // FIXME this duplicates Doku_Indexer::getIndex() @@ -767,27 +772,25 @@ protected function findMissingDocuments($src, $dst, $type = self::TYPE_PAGES) { } else { $fn = $conf['indexdir'] . '/relation_media_w.idx'; } - if (!@file_exists($fn)){ - $referenceidx = array(); + if (!@file_exists($fn)) { + $referenceidx = []; } else { $referenceidx = file($fn, FILE_IGNORE_NEW_LINES); } $len = strlen($src); - foreach($referenceidx as $idx => $page) { - if(substr($page, 0, $len) != "$src") continue; + foreach ($referenceidx as $page) { + if (substr($page, 0, $len) !== "$src") continue; // remember missing pages if ($type == self::TYPE_PAGES) { - if(!page_exists($page)) { + if (!page_exists($page)) { $newpage = $dst . substr($page, $len); $this->tmpstore['miss'][$page] = $newpage; } - } else { - if(!file_exists(mediaFN($page))){ - $newpage = $dst . substr($page, $len); - $this->tmpstore['miss_media'][$page] = $newpage; - } + } elseif (!file_exists(mediaFN($page))) { + $newpage = $dst . substr($page, $len); + $this->tmpstore['miss_media'][$page] = $newpage; } } } @@ -797,42 +800,35 @@ protected function findMissingDocuments($src, $dst, $type = self::TYPE_PAGES) { * * @throws Exception */ - protected function storeDocumentLists() { - $lists = array( - 'pages' => $this->files['pagelist'], - 'media' => $this->files['medialist'], - 'ns' => $this->files['namespaces'], - 'affpg' => $this->files['affected'], - 'miss' => $this->files['missing'], - 'miss_media' => $this->files['missing_media'], - ); - - foreach($lists as $store => $file) { + protected function storeDocumentLists() + { + $lists = ['pages' => $this->files['pagelist'], 'media' => $this->files['medialist'], 'ns' => $this->files['namespaces'], 'affpg' => $this->files['affected'], 'miss' => $this->files['missing'], 'miss_media' => $this->files['missing_media']]; + + foreach ($lists as $store => $file) { // anything to do? $count = count($this->tmpstore[$store]); - if(!$count) continue; + if (!$count) continue; // prepare and save content $data = ''; $this->tmpstore[$store] = array_reverse($this->tmpstore[$store]); // store in reverse order - foreach($this->tmpstore[$store] as $src => $dst) { - if($dst === true) { + foreach ($this->tmpstore[$store] as $src => $dst) { + if ($dst === true) { $data .= "$src\n"; // for affected pages only one ID is saved } else { $data .= "$src\t$dst\n"; } - } io_saveFile($file, $data); // set counters - if($store != 'ns') { + if ($store != 'ns') { $this->options[$store . '_all'] = $count; $this->options[$store . '_run'] = $count; } // reset the list - $this->tmpstore[$store] = array(); + $this->tmpstore[$store] = []; } } @@ -843,19 +839,20 @@ protected function storeDocumentLists() { * @param resource $handle The file handle to read from * @return string|bool the last id from the list or false if there is none */ - protected function getLastLine($handle) { + protected function getLastLine($handle) + { // begin the seek at the end of the file fseek($handle, 0, SEEK_END); $line = ''; // seek one backwards as long as it's possible - while(fseek($handle, -1, SEEK_CUR) >= 0) { + while (fseek($handle, -1, SEEK_CUR) >= 0) { $c = fgetc($handle); - if($c === false) return false; // EOF, i.e. the file is empty + if ($c === false) return false; // EOF, i.e. the file is empty fseek($handle, -1, SEEK_CUR); // reset the position to the character that was read - if($c == "\n") { - if($line === '') { + if ($c == "\n") { + if ($line === '') { continue; // this line was empty, continue } else { break; // we have a line, finish @@ -865,7 +862,7 @@ protected function getLastLine($handle) { $line = $c . $line; // prepend char to line } - if($line === '') return false; // beginning of file reached and no content + if ($line === '') return false; // beginning of file reached and no content return $line; } @@ -877,20 +874,21 @@ protected function getLastLine($handle) { * @param $b * @return int */ - public function planSorter($a, $b) { + public function planSorter($a, $b) + { // do page moves before namespace moves - if($a['class'] == self::CLASS_DOC && $b['class'] == self::CLASS_NS) { + if ($a['class'] == self::CLASS_DOC && $b['class'] == self::CLASS_NS) { return -1; } - if($a['class'] == self::CLASS_NS && $b['class'] == self::CLASS_DOC) { + if ($a['class'] == self::CLASS_NS && $b['class'] == self::CLASS_DOC) { return 1; } // do pages before media - if($a['type'] == self::TYPE_PAGES && $b['type'] == self::TYPE_MEDIA) { + if ($a['type'] == self::TYPE_PAGES && $b['type'] == self::TYPE_MEDIA) { return -1; } - if($a['type'] == self::TYPE_MEDIA && $b['type'] == self::TYPE_PAGES) { + if ($a['type'] == self::TYPE_MEDIA && $b['type'] == self::TYPE_PAGES) { return 1; } @@ -900,9 +898,9 @@ public function planSorter($a, $b) { $alen = substr_count($a['src'], ':'); $blen = substr_count($b['src'], ':'); - if($alen > $blen) { + if ($alen > $blen) { return -1; - } elseif($alen < $blen) { + } elseif ($alen < $blen) { return 1; } return 0; @@ -921,12 +919,13 @@ public function planSorter($a, $b) { * @author Andreas Gohr * @author Michael Große */ - public function build_log_line ($type, $from, $to, $success) { + public function build_log_line($type, $from, $to, $success) + { global $MSG; $now = time(); $date = date('Y-m-d H:i:s', $now); // for human readability - if($success) { + if ($success) { $ok = 'success'; $msg = ''; } else { @@ -943,11 +942,11 @@ public function build_log_line ($type, $from, $to, $success) { * * @param $log */ - protected function write_log ($log) { + protected function write_log($log) + { global $conf; $optime = $this->options['started']; $file = $conf['cachedir'] . '/move/' . strftime('%Y%m%d-%H%M%S', $optime) . '.log'; io_saveFile($file, $log, true); } - } diff --git a/helper/rewrite.php b/helper/rewrite.php index 73ae4716..acb5b74a 100644 --- a/helper/rewrite.php +++ b/helper/rewrite.php @@ -1,4 +1,7 @@ * @author Andreas Gohr */ + // must be run within Dokuwiki -if(!defined('DOKU_INC')) die(); +if (!defined('DOKU_INC')) die(); // load required handler class -require_once(dirname(__FILE__) . '/handler.php'); +require_once(__DIR__ . '/handler.php'); /** * Class helper_plugin_move_rewrite * * This class handles the rewriting of wiki text to update the links */ -class helper_plugin_move_rewrite extends DokuWiki_Plugin { - +class helper_plugin_move_rewrite extends Plugin +{ /** * Under what key is move data to be saved in metadata */ - const METAKEY = 'plugin_move'; + public const METAKEY = 'plugin_move'; /** * What is they filename of the lockfile */ - const LOCKFILENAME = '_plugin_move.lock'; + public const LOCKFILENAME = '_plugin_move.lock'; /** * @var string symbol to make move operations easily recognizable in change log @@ -42,7 +46,8 @@ class helper_plugin_move_rewrite extends DokuWiki_Plugin { * @param string $id The id of the page the metadata shall be loaded for * @return array|null The metadata of the page */ - public function getMoveMeta($id) { + public function getMoveMeta($id) + { $all_meta = p_get_metadata($id, '', METADATA_DONT_RENDER); /* todo migrate old move data @@ -57,15 +62,15 @@ public function getMoveMeta($id) { */ // discard missing or empty array or string - $meta = !empty($all_meta[self::METAKEY]) ? $all_meta[self::METAKEY] : array(); - if(!isset($meta['origin'])) { + $meta = empty($all_meta[self::METAKEY]) ? [] : $all_meta[self::METAKEY]; + if (!isset($meta['origin'])) { $meta['origin'] = ''; } - if(!isset($meta['pages'])) { - $meta['pages'] = array(); + if (!isset($meta['pages'])) { + $meta['pages'] = []; } - if(!isset($meta['media'])) { - $meta['media'] = array(); + if (!isset($meta['media'])) { + $meta['media'] = []; } return $meta; @@ -76,8 +81,9 @@ public function getMoveMeta($id) { * * @param $id */ - public function unsetMoveMeta($id) { - p_set_metadata($id, array(self::METAKEY => array()), false, true); + public function unsetMoveMeta($id) + { + p_set_metadata($id, [self::METAKEY => []], false, true); } /** @@ -89,8 +95,9 @@ public function unsetMoveMeta($id) { * @param string $type 'media' or 'page' * @throws Exception on wrong argument */ - public function setMoveMeta($id, $src, $dst, $type) { - $this->setMoveMetas($id, array($src => $dst), $type); + public function setMoveMeta($id, $src, $dst, $type) + { + $this->setMoveMetas($id, [$src => $dst], $type); } /** @@ -101,20 +108,21 @@ public function setMoveMeta($id, $src, $dst, $type) { * @param string $type 'media' or 'page' * @throws Exception */ - public function setMoveMetas($id, $moves, $type) { - if($type != 'pages' && $type != 'media') { + public function setMoveMetas($id, $moves, $type) + { + if ($type != 'pages' && $type != 'media') { throw new Exception('wrong type specified'); } - if(!page_exists($id, '', false)) { + if (!page_exists($id, '', false)) { return; } $meta = $this->getMoveMeta($id); - foreach($moves as $src => $dst) { - $meta[$type][] = array($src, $dst); + foreach ($moves as $src => $dst) { + $meta[$type][] = [$src, $dst]; } - p_set_metadata($id, array(self::METAKEY => $meta), false, true); + p_set_metadata($id, [self::METAKEY => $meta], false, true); } /** @@ -124,15 +132,16 @@ public function setMoveMetas($id, $moves, $type) { * * @param string $id moved page's original (and still current) id */ - public function setSelfMoveMeta($id) { + public function setSelfMoveMeta($id) + { $meta = $this->getMoveMeta($id); // was this page moved multiple times? keep the orignal name til rewriting occured - if(isset($meta['origin']) && $meta['origin'] !== '') { + if (isset($meta['origin']) && $meta['origin'] !== '') { return; } $meta['origin'] = $id; - p_set_metadata($id, array(self::METAKEY => $meta), false, true); + p_set_metadata($id, [self::METAKEY => $meta], false, true); } /** @@ -140,7 +149,8 @@ public function setSelfMoveMeta($id) { * * @return bool */ - public static function isLocked() { + public static function isLocked() + { global $PLUGIN_MOVE_WORKING; global $conf; $lockfile = $conf['lockdir'] . self::LOCKFILENAME; @@ -150,7 +160,8 @@ public static function isLocked() { /** * Do not allow any rewrites in this process right now */ - public static function addLock() { + public static function addLock() + { global $PLUGIN_MOVE_WORKING; global $conf; $PLUGIN_MOVE_WORKING = $PLUGIN_MOVE_WORKING ? $PLUGIN_MOVE_WORKING + 1 : 1; @@ -158,16 +169,17 @@ public static function addLock() { if (!file_exists($lockfile)) { io_savefile($lockfile, "1\n"); } else { - $stack = intval(file_get_contents($lockfile)); + $stack = (int) file_get_contents($lockfile); ++$stack; - io_savefile($lockfile, strval($stack)); + io_savefile($lockfile, (string) $stack); } } /** * Allow rerites in this process again, unless some other lock exists */ - public static function removeLock() { + public static function removeLock() + { global $PLUGIN_MOVE_WORKING; global $conf; $PLUGIN_MOVE_WORKING = $PLUGIN_MOVE_WORKING ? $PLUGIN_MOVE_WORKING - 1 : 0; @@ -175,12 +187,12 @@ public static function removeLock() { if (!file_exists($lockfile)) { throw new Exception("removeLock failed: lockfile missing"); } else { - $stack = intval(file_get_contents($lockfile)); - if($stack === 1) { + $stack = (int) file_get_contents($lockfile); + if ($stack === 1) { unlink($lockfile); } else { --$stack; - io_savefile($lockfile, strval($stack)); + io_savefile($lockfile, (string) $stack); } } } @@ -190,7 +202,8 @@ public static function removeLock() { * * @author Michael Große */ - public static function removeAllLocks() { + public static function removeAllLocks() + { global $conf; $lockfile = $conf['lockdir'] . self::LOCKFILENAME; if (file_exists($lockfile)) { @@ -207,22 +220,17 @@ public static function removeAllLocks() { * @param string $text The text to be rewritten * @return string The rewritten wiki text */ - public function rewrite($id, $text) { + public function rewrite($id, $text) + { $meta = $this->getMoveMeta($id); - $handlers = array(); + $handlers = []; $pages = $meta['pages']; $media = $meta['media']; $origin = $meta['origin']; - if($origin == '') $origin = $id; + if ($origin == '') $origin = $id; - $data = array( - 'id' => $id, - 'origin' => &$origin, - 'pages' => &$pages, - 'media_moves' => &$media, - 'handlers' => &$handlers - ); + $data = ['id' => $id, 'origin' => &$origin, 'pages' => &$pages, 'media_moves' => &$media, 'handlers' => &$handlers]; /* * PLUGIN_MOVE_HANDLERS REGISTER event: @@ -247,7 +255,7 @@ public function rewrite($id, $text) { $Parser->Handler->init($id, $origin, $pages, $media, $handlers); //add modes to parser - foreach($modes as $mode) { + foreach ($modes as $mode) { $Parser->addMode($mode['mode'], $mode['obj']); } @@ -261,24 +269,25 @@ public function rewrite($id, $text) { * @param string|null $text Old content of the page. When null is given the content is loaded from disk * @return string|bool The rewritten content, false on error */ - public function rewritePage($id, $text = null, $save = true) { + public function rewritePage($id, $text = null, $save = true) + { $meta = $this->getMoveMeta($id); - if(is_null($text)) { + if (is_null($text)) { $text = rawWiki($id); } - if($meta['pages'] || $meta['media']) { + if ($meta['pages'] || $meta['media']) { $old_text = $text; $text = $this->rewrite($id, $text); $changed = ($old_text != $text); $file = wikiFN($id, '', false); if ($save === true) { - if(is_writable($file) || !$changed) { - if($changed) { + if (is_writable($file) || !$changed) { + if ($changed) { // Wait a second when the page has just been rewritten $oldRev = filemtime(wikiFN($id)); - if($oldRev == time()) sleep(1); + if ($oldRev == time()) sleep(1); saveWikiText($id, $text, $this->symbol . ' ' . $this->getLang('linkchange'), $this->getConf('minor')); } @@ -293,5 +302,4 @@ public function rewritePage($id, $text = null, $save = true) { return $text; } - }