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