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