]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
private
[SourceForge/phpwiki.git] / lib / plugin / WikiAdminSearchReplace.php
1 <?php
2
3 /*
4  * Copyright 2004,2007 $ThePhpWikiProgrammingTeam
5  * Copyright 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
6  *
7  * This file is part of PhpWiki.
8  *
9  * PhpWiki is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * PhpWiki is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License along
20  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
21  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22  */
23
24 /**
25  * Usage:   <<WikiAdminSearchReplace >> or called via WikiAdminSelect
26  * Author:  Reini Urban <rurban@x-ray.at>
27  *
28  */
29 require_once 'lib/PageList.php';
30 require_once 'lib/plugin/WikiAdminSelect.php';
31
32 class WikiPlugin_WikiAdminSearchReplace
33     extends WikiPlugin_WikiAdminSelect
34 {
35     function getName()
36     {
37         return _("WikiAdminSearchReplace");
38     }
39
40     function getDescription()
41     {
42         return _("Search and replace text in selected wiki pages.");
43     }
44
45     function getDefaultArguments()
46     {
47         return array_merge
48         (
49             WikiPlugin_WikiAdminSelect::getDefaultArguments(),
50             array(
51                 /* Columns to include in listing */
52                 'info' => 'some',
53             ));
54     }
55
56     private function replaceHelper(&$dbi, &$request, $pagename, $from, $to, $case_exact = true, $regex = false)
57     {
58         $page = $dbi->getPage($pagename);
59         if ($page->exists()) { // don't replace default contents
60             $current = $page->getCurrentRevision();
61             $version = $current->getVersion();
62             $text = $current->getPackedContent();
63             if ($regex) {
64                 $newtext = preg_replace("/" . $from . "/" . ($case_exact ? '' : 'i'), $to, $text);
65             } else {
66                 if ($case_exact) {
67                     $newtext = str_replace($from, $to, $text);
68                 } else {
69                     //not all PHP have this enabled. use a workaround
70                     if (function_exists('str_ireplace'))
71                         $newtext = str_ireplace($from, $to, $text);
72                     else { // see eof
73                         $newtext = stri_replace($from, $to, $text);
74                     }
75                 }
76             }
77             if ($text != $newtext) {
78                 $meta = $current->_data;
79                 $meta['summary'] = sprintf(_("Replace “%s” by “%s”"), $from, $to);
80                 $meta['is_minor_edit'] = 0;
81                 $meta['author'] = $request->_user->UserName();
82                 unset($meta['mtime']); // force new date
83                 return $page->save($newtext, $version + 1, $meta);
84             }
85         }
86         return false;
87     }
88
89     private function searchReplacePages(&$dbi, &$request, $pages, $from, $to)
90     {
91         if (empty($from)) return HTML::p(HTML::strong(fmt("Error: Empty search string.")));
92         $result = HTML::div();
93         $ul = HTML::ul();
94         $count = 0;
95         $post_args = $request->getArg('admin_replace');
96         $case_exact = !empty($post_args['case_exact']);
97         $regex = !empty($post_args['regex']);
98         foreach ($pages as $pagename) {
99             if (!mayAccessPage('edit', $pagename)) {
100                 $ul->pushContent(HTML::li(fmt("Access denied to change page “%s”.", $pagename)));
101             } elseif ($this->replaceHelper($dbi, $request, $pagename, $from, $to, $case_exact, $regex)) {
102                 $ul->pushContent(HTML::li(fmt("Replaced “%s” with “%s” in page “%s”.",
103                     $from, $to, WikiLink($pagename))));
104                 $count++;
105             }
106         }
107         if ($count) {
108             $dbi->touch();
109             $result->setAttr('class', 'feedback');
110             if ($count == 1) {
111                 $result->pushContent(HTML::p(_("One page has been changed:")));
112             } else {
113                 $result->pushContent(HTML::p(fmt("%d pages have been changed:", $count)));
114             }
115             $result->pushContent($ul);
116         } else {
117             $result->setAttr('class', 'error');
118             $result->pushContent(HTML::p(_("No pages changed.")));
119         }
120         return $result;
121     }
122
123     function run($dbi, $argstr, &$request, $basepage)
124     {
125         // no action=replace support yet
126         if ($request->getArg('action') != 'browse') {
127             return $this->disabled(_("Plugin not run: not in browse mode"));
128         }
129
130         $args = $this->getArgs($argstr, $request);
131         $this->_args = $args;
132
133         //TODO: support p from <!plugin-list !>
134         $this->preSelectS($args, $request);
135
136         $p = $request->getArg('p');
137         if (!$p) $p = $this->_list;
138         $post_args = $request->getArg('admin_replace');
139         $next_action = 'select';
140         $pages = array();
141         if ($p && !$request->isPost())
142             $pages = $p;
143         if ($p && $request->isPost() &&
144             empty($post_args['cancel'])
145         ) {
146             // without individual PagePermissions:
147             if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) {
148                 $request->_notAuthorized(WIKIAUTH_ADMIN);
149                 $this->disabled("! user->isAdmin");
150             }
151
152             if ($post_args['action'] == 'verify' and !empty($post_args['from'])) {
153                 // Real action
154                 return $this->searchReplacePages($dbi, $request, array_keys($p),
155                     $post_args['from'], $post_args['to']);
156             }
157             if ($post_args['action'] == 'select') {
158                 if (!empty($post_args['from']))
159                     $next_action = 'verify';
160                 foreach ($p as $name => $c) {
161                     $pages[$name] = 1;
162                 }
163             }
164         }
165         if ($next_action == 'select' and empty($pages)) {
166             // List all pages to select from.
167             //TODO: check for permissions and list only the allowed
168             $pages = $this->collectPages($pages, $dbi, $args['sortby'],
169                 $args['limit'], $args['exclude']);
170         }
171
172         if ($next_action == 'verify') {
173             $args['info'] = "checkbox,pagename";
174         } else {
175             // Avoid warning about "hi_content"
176             // $args['info'] = "checkbox,pagename,hi_content,mtime,author";
177             $args['info'] = "checkbox,pagename,mtime,author";
178         }
179         $pagelist = new PageList_Selectable
180         ($args['info'], $args['exclude'],
181             array_merge
182             (
183                 $args,
184                 array('types' => array
185                 (
186                     'hi_content' // with highlighted search for SearchReplace
187                     => new _PageList_Column_content('rev:hi_content', _("Content"))))));
188
189         $pagelist->addPageList($pages);
190
191         $header = HTML::fieldset();
192         if (empty($post_args['from']))
193             $header->pushContent(
194                 HTML::p(HTML::em(_("Warning: The search string cannot be empty!"))));
195         if ($next_action == 'verify') {
196             $button_label = _("Yes");
197             $header->pushContent(
198                 HTML::p(HTML::strong(
199                     _("Are you sure you want to replace text in the selected files?"))));
200             $this->replaceForm($header, $post_args);
201         } else {
202             $button_label = _("Search & Replace");
203             $this->replaceForm($header, $post_args);
204             $header->pushContent(HTML::legend(_("Select the pages to search and replace")));
205         }
206
207         $buttons = HTML::p(Button('submit:admin_replace[replace]', $button_label, 'wikiadmin'),
208             Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
209         $header->pushContent($buttons);
210
211         return HTML::form(array('action' => $request->getPostURL(),
212                 'method' => 'post'),
213             $header,
214             $pagelist->getContent(),
215             HiddenInputs($request->getArgs(),
216                 false,
217                 array('admin_replace')),
218             HiddenInputs(array('admin_replace[action]' => $next_action)),
219             ENABLE_PAGEPERM
220                 ? ''
221                 : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)));
222     }
223
224     private function checkBox(&$post_args, $name, $msg)
225     {
226         $id = 'admin_replace-' . $name;
227         $checkbox = HTML::input(array('type' => 'checkbox',
228             'name' => 'admin_replace[' . $name . ']',
229             'id' => $id,
230             'value' => 1));
231         if (!empty($post_args[$name]))
232             $checkbox->setAttr('checked', 'checked');
233         return HTML::div($checkbox, ' ', HTML::label(array('for' => $id), $msg));
234     }
235
236     private function replaceForm(&$header, $post_args)
237     {
238         $header->pushContent(HTML::div(array('class' => 'hint'),
239                 _("Replace all occurences of the given string in the content of all pages.")),
240             HTML::br());
241         $table = HTML::table();
242         $this->tablePush($table, _("Replace") . _(": "),
243             HTML::input(array('name' => 'admin_replace[from]',
244                 'size' => 90,
245                 'value' => $post_args['from'])));
246         $this->tablePush($table, _("by") . _(": "),
247             HTML::input(array('name' => 'admin_replace[to]',
248                 'size' => 90,
249                 'value' => $post_args['to'])));
250         $this->tablePush($table, '', $this->checkBox($post_args, 'case_exact', _("Case exact?")));
251         $this->tablePush($table, '', $this->checkBox($post_args, 'regex', _("Regex?")));
252         $header->pushContent($table);
253         return $header;
254     }
255 }
256
257 function stri_replace($find, $replace, $string)
258 {
259     if (!is_array($find)) $find = array($find);
260     if (!is_array($replace)) {
261         if (!is_array($find))
262             $replace = array($replace);
263         else {
264             // this will duplicate the string into an array the size of $find
265             $c = count($find);
266             $rString = $replace;
267             unset($replace);
268             for ($i = 0; $i < $c; $i++) {
269                 $replace[$i] = $rString;
270             }
271         }
272     }
273     foreach ($find as $fKey => $fItem) {
274         $between = explode(strtolower($fItem), strtolower($string));
275         $pos = 0;
276         foreach ($between as $bKey => $bItem) {
277             $between[$bKey] = substr($string, $pos, strlen($bItem));
278             $pos += strlen($bItem) + strlen($fItem);
279         }
280         $string = implode($replace[$fKey], $between);
281     }
282     return $string;
283 }
284
285 // Local Variables:
286 // mode: php
287 // tab-width: 8
288 // c-basic-offset: 4
289 // c-hanging-comment-ender-p: nil
290 // indent-tabs-mode: nil
291 // End: