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