]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
Removed history
[SourceForge/phpwiki.git] / lib / plugin / WikiAdminSearchReplace.php
1 <?php // -*-php-*-
2 rcs_id('$Id$');
3 /*
4  Copyright 2004,2007 $ThePhpWikiProgrammingTeam
5
6  This file is part of PhpWiki.
7
8  PhpWiki is free software; you can redistribute it and/or modify
9  it under the terms of the GNU General Public License as published by
10  the Free Software Foundation; either version 2 of the License, or
11  (at your option) any later version.
12
13  PhpWiki is distributed in the hope that it will be useful,
14  but WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  GNU General Public License for more details.
17
18  You should have received a copy of the GNU General Public License
19  along with PhpWiki; if not, write to the Free Software
20  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
22
23 /**
24  * Usage:   <?plugin WikiAdminSearchReplace ?> or called via WikiAdminSelect
25  * Author:  Reini Urban <rurban@x-ray.at>
26  *
27  * KNOWN ISSUES:
28  *   Requires PHP 4.2 so far.
29  */
30 require_once('lib/PageList.php');
31 require_once('lib/plugin/WikiAdminSelect.php');
32
33 class WikiPlugin_WikiAdminSearchReplace
34 extends WikiPlugin_WikiAdminSelect
35 {
36     function getName() {
37         return _("WikiAdminSearchReplace");
38     }
39
40     function getDescription() {
41         return _("Search and replace text in selected wiki pages.");
42     }
43
44     function getVersion() {
45         return preg_replace("/[Revision: $]/", '',
46                             "\$Revision$");
47     }
48
49     function getDefaultArguments() {
50         return array_merge
51             (
52              PageList::supportedArgs(),
53              array(
54                    's'  => false,
55                    /* Columns to include in listing */
56                    'info'     => 'some',
57                    ));
58     }
59
60     function replaceHelper(&$dbi, $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(_("WikiAdminSearchReplace %s by %s"),$from,$to);
83                 return $page->save($newtext, $version + 1, $meta);
84             }
85         }
86         return false;
87     }
88
89     function searchReplacePages(&$dbi, &$request, $pages, $from, $to) {
90         if (empty($from)) return HTML::p(HTML::strong(fmt("Error: Empty search string.")));
91         $ul = HTML::ul();
92         $count = 0;
93         $post_args = $request->getArg('admin_replace');
94         $case_exact = !empty($post_args['case_exact']);
95         $regex = !empty($post_args['regex']);
96         foreach ($pages as $pagename) {
97             if (!mayAccessPage('edit', $pagename)) {
98                 $ul->pushContent(HTML::li(fmt("Access denied to change page '%s'.",$pagename)));
99             } elseif (($result = $this->replaceHelper($dbi, $pagename, $from, $to, 
100                                                       $case_exact, $regex))) 
101             {
102                 $ul->pushContent(HTML::li(fmt("Replaced '%s' with '%s' in page '%s'.", 
103                                               $from, $to, WikiLink($pagename))));
104                 $count++;
105             } else {
106                 $ul->pushContent(HTML::li(fmt("Search string '%s' not found in content of page '%s'.", 
107                                               $from, WikiLink($pagename))));
108             }
109         }
110         if ($count) {
111             $dbi->touch();
112             return HTML($ul,
113                         HTML::p(fmt("%s pages changed.",$count)));
114         } else {
115             return HTML($ul,
116                         HTML::p(fmt("No pages changed.")));
117         }
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,hi_content";
168         }
169         $pagelist = new PageList_Selectable
170             ($args['info'], $args['exclude'],
171              array_merge
172              (
173               $args,
174               array('types' => array
175                     (
176                      'hi_content' // with highlighted search for SearchReplace
177                      => new _PageList_Column_content('rev:hi_content', _("Content"))))));
178
179         $pagelist->addPageList($pages);
180
181         $header = HTML::p();
182         if (empty($post_args['from']))
183             $header->pushContent(
184               HTML::p(HTML::em(_("Warning: The search string cannot be empty!"))));
185         if ($next_action == 'verify') {
186             $button_label = _("Yes");
187             $header->pushContent(
188               HTML::p(HTML::strong(
189                                    _("Are you sure you want to permanently search & replace text in the selected files?"))));
190             $this->replaceForm($header, $post_args);
191         }
192         else {
193             $button_label = _("Search & Replace");
194             $this->replaceForm($header, $post_args);
195             $header->pushContent(HTML::p(_("Select the pages to search:")));
196         }
197
198
199         $buttons = HTML::p(Button('submit:admin_replace[rename]', $button_label, 'wikiadmin'),
200                            Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
201
202         return HTML::form(array('action' => $request->getPostURL(),
203                                 'method' => 'post'),
204                           $header,
205                           $pagelist->getContent(),
206                           HiddenInputs($request->getArgs(),
207                                         false,
208                                         array('admin_replace')),
209                           HiddenInputs(array('admin_replace[action]' => $next_action)),
210                           ENABLE_PAGEPERM
211                           ? ''
212                           : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
213                           $buttons);
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         $header->pushContent(HTML::br());
244         return $header;
245     }
246 }
247
248 function stri_replace($find,$replace,$string) {
249     if (!is_array($find)) $find = array($find);
250     if (!is_array($replace))  {
251         if (!is_array($find)) 
252             $replace = array($replace);
253         else {
254             // this will duplicate the string into an array the size of $find
255             $c = count($find);
256             $rString = $replace;
257             unset($replace);
258             for ($i = 0; $i < $c; $i++) {
259                 $replace[$i] = $rString;
260             }
261         }
262     }
263     foreach ($find as $fKey => $fItem) {
264         $between = explode(strtolower($fItem),strtolower($string));
265         $pos = 0;
266         foreach($between as $bKey => $bItem) {
267             $between[$bKey] = substr($string,$pos,strlen($bItem));
268             $pos += strlen($bItem) + strlen($fItem);
269         }
270         $string = implode($replace[$fKey],$between);
271     }
272     return $string;
273 }
274
275 // Local Variables:
276 // mode: php
277 // tab-width: 8
278 // c-basic-offset: 4
279 // c-hanging-comment-ender-p: nil
280 // indent-tabs-mode: nil
281 // End:
282 ?>