]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
reenable admin check on !ENABLE_PAGEPERM, honor s=Wildcard arg, fix warning after...
[SourceForge/phpwiki.git] / lib / plugin / WikiAdminSearchReplace.php
1 <?php // -*-php-*-
2 rcs_id('$Id: WikiAdminSearchReplace.php,v 1.10 2004-06-03 22:24:48 rurban Exp $');
3 /*
4  Copyright 2004 $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  * Currently we must be Admin.
29  * Future versions will support PagePermissions.
30  * requires PHP 4.2 so far.
31  */
32 require_once('lib/PageList.php');
33 require_once('lib/plugin/WikiAdminSelect.php');
34
35 class WikiPlugin_WikiAdminSearchReplace
36 extends WikiPlugin_WikiAdminSelect
37 {
38     function getName() {
39         return _("WikiAdminSearchReplace");
40     }
41
42     function getDescription() {
43         return _("Search and replace text in selected wiki pages.");
44     }
45
46     function getVersion() {
47         return preg_replace("/[Revision: $]/", '',
48                             "\$Revision: 1.10 $");
49     }
50
51     function getDefaultArguments() {
52         return array(
53                      's'        => false,
54                      /* Pages to exclude */
55                      'exclude'  => '.',
56                      /* Columns to include in listing */
57                      'info'     => 'some',
58                      /* How to sort */
59                      'sortby'   => 'pagename',
60                      'limit'    => 0,
61                      );
62     }
63
64     function replaceHelper(&$dbi, $pagename, $from, $to, $caseexact = true) {
65         $page = $dbi->getPage($pagename);
66         if ($page->exists()) {// don't replace default contents
67             $current = $page->getCurrentRevision();
68             $version = $current->getVersion();
69             $text = $current->getPackedContent();
70             if ($caseexact) {
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             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         $caseexact = !empty($post_args['caseexact']);
95         foreach ($pages as $pagename) {
96             if (($result = $this->replaceHelper(&$dbi,$pagename,$from,$to,$caseexact))) {
97                 $ul->pushContent(HTML::li(fmt("Replaced '%s' with '%s' in page '%s'.", $from, $to, WikiLink($pagename))));
98                 $count++;
99             } else {
100                 $ul->pushContent(HTML::li(fmt("Search string '%s' not found in page '%s'.", $from, $to, WikiLink($pagename))));
101             }
102         }
103         if ($count) {
104             $dbi->touch();
105             return HTML($ul,
106                         HTML::p(fmt("%s pages changed.",$count)));
107         } else {
108             return HTML($ul,
109                         HTML::p(fmt("No pages changed.")));
110         }
111     }
112     
113     function run($dbi, $argstr, &$request, $basepage) {
114         if ($request->getArg('action') != 'browse')
115             return $this->disabled("(action != 'browse')");
116         
117         $args = $this->getArgs($argstr, $request);
118         $this->_args = $args;
119         if (!empty($args['exclude']))
120             $exclude = explodePageList($args['exclude']);
121         else
122             $exclude = false;
123         $this->preSelectS(&$args, &$request);
124
125         $p = $request->getArg('p');
126         if (!$p) $p = $this->_list;
127         $post_args = $request->getArg('admin_replace');
128         $next_action = 'select';
129         $pages = array();
130         if ($p && !$request->isPost())
131             $pages = $p;
132         if ($p && $request->isPost() &&
133             empty($post_args['cancel'])) {
134             // FIXME: check individual PagePermissions
135             if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) {
136                 $request->_notAuthorized(WIKIAUTH_ADMIN);
137                 $this->disabled("! user->isAdmin");
138             }
139
140             if ($post_args['action'] == 'verify' and !empty($post_args['from'])) {
141                 // Real action
142                 return $this->searchReplacePages($dbi, $request, array_keys($p), $post_args['from'], $post_args['to']);
143             }
144             if ($post_args['action'] == 'select') {
145                 if (!empty($post_args['from']))
146                     $next_action = 'verify';
147                 foreach ($p as $name => $c) {
148                     $pages[$name] = 1;
149                 }
150             }
151         }
152         if ($next_action == 'select' and empty($pages)) {
153             // List all pages to select from.
154             $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit']);
155         }
156
157         if ($next_action == 'verify') {
158             $args['info'] = "checkbox,pagename,hi_content";
159         }
160         $pagelist = new PageList_Selectable($args['info'], $exclude,
161                                             array('types' => array(
162                                                   'hi_content' // with highlighted search for SearchReplace
163                                                    => new _PageList_Column_content('rev:hi_content', _("Content")))));
164
165         $pagelist->addPageList($pages);
166
167         $header = HTML::p();
168         if (empty($post_args['from']))
169             $header->pushContent(
170               HTML::p(HTML::em(_("Warning: The search string cannot be empty!"))));
171         if ($next_action == 'verify') {
172             $button_label = _("Yes");
173             $header->pushContent(
174               HTML::p(HTML::strong(
175                                    _("Are you sure you want to permanently search & replace text in the selected files?"))));
176             $this->replaceForm(&$header, $post_args);
177         }
178         else {
179             $button_label = _("Search & Replace");
180             $this->replaceForm(&$header, $post_args);
181             $header->pushContent(HTML::p(_("Select the pages to search:")));
182         }
183
184
185         $buttons = HTML::p(Button('submit:admin_replace[rename]', $button_label, 'wikiadmin'),
186                            Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
187
188         return HTML::form(array('action' => $request->getPostURL(),
189                                 'method' => 'post'),
190                           $header,
191                           $pagelist->getContent(),
192                           HiddenInputs($request->getArgs(),
193                                         false,
194                                         array('admin_replace')),
195                           HiddenInputs(array('admin_replace[action]' => $next_action,
196                                              'require_authority_for_post' => WIKIAUTH_ADMIN)),
197                           $buttons);
198     }
199
200     function replaceForm(&$header, $post_args) {
201         $header->pushContent(_("Replace: "));
202         $header->pushContent(HTML::input(array('name' => 'admin_replace[from]',
203                                                'value' => $post_args['from'])));
204         $header->pushContent(' '._("by").': ');
205         $header->pushContent(HTML::input(array('name' => 'admin_replace[to]',
206                                                'value' => $post_args['to'])));
207         $header->pushContent(' '._("(no regex) Case-exact: "));
208         $checkbox = HTML::input(array('type' => 'checkbox',
209                                       'name' => 'admin_replace[caseexact]',
210                                       'value' => 1));
211         if (!empty($post_args['caseexact']))
212             $checkbox->setAttr('checked','checked');
213         $header->pushContent($checkbox);
214         $header->pushContent(HTML::br());
215         return $header;
216     }
217 }
218
219 function stri_replace($find,$replace,$string) {
220     if (!is_array($find)) $find = array($find);
221     if (!is_array($replace))  {
222         if (!is_array($find)) 
223             $replace = array($replace);
224         else {
225             // this will duplicate the string into an array the size of $find
226             $c = count($find);
227             $rString = $replace;
228             unset($replace);
229             for ($i = 0; $i < $c; $i++) {
230                 $replace[$i] = $rString;
231             }
232         }
233     }
234     foreach ($find as $fKey => $fItem) {
235         $between = explode(strtolower($fItem),strtolower($string));
236         $pos = 0;
237         foreach($between as $bKey => $bItem) {
238             $between[$bKey] = substr($string,$pos,strlen($bItem));
239             $pos += strlen($bItem) + strlen($fItem);
240         }
241         $string = implode($replace[$fKey],$between);
242     }
243     return $string;
244 }
245
246 // $Log: not supported by cvs2svn $
247 // Revision 1.9  2004/04/07 23:13:19  rurban
248 // fixed pear/File_Passwd for Windows
249 // fixed FilePassUser sessions (filehandle revive) and password update
250 //
251 // Revision 1.8  2004/03/17 20:23:44  rurban
252 // fixed p[] pagehash passing from WikiAdminSelect, fixed problem removing pages with [] in the pagename
253 //
254 // Revision 1.7  2004/03/12 13:31:43  rurban
255 // enforce PagePermissions, errormsg if not Admin
256 //
257 // Revision 1.6  2004/02/24 15:20:07  rurban
258 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
259 //
260 // Revision 1.5  2004/02/17 12:11:36  rurban
261 // added missing 4th basepage arg at plugin->run() to almost all plugins. This caused no harm so far, because it was silently dropped on normal usage. However on plugin internal ->run invocations it failed. (InterWikiSearch, IncludeSiteMap, ...)
262 //
263 // Revision 1.4  2004/02/15 21:34:37  rurban
264 // PageList enhanced and improved.
265 // fixed new WikiAdmin... plugins
266 // editpage, Theme with exp. htmlarea framework
267 //   (htmlarea yet committed, this is really questionable)
268 // WikiUser... code with better session handling for prefs
269 // enhanced UserPreferences (again)
270 // RecentChanges for show_deleted: how should pages be deleted then?
271 //
272 // Revision 1.3  2004/02/12 17:05:39  rurban
273 // WikiAdminRename:
274 //   added "Change pagename in all linked pages also"
275 // PageList:
276 //   added javascript toggle for Select
277 // WikiAdminSearchReplace:
278 //   fixed another typo
279 //
280 // Revision 1.2  2004/02/12 11:47:51  rurban
281 // typo
282 //
283 // Revision 1.1  2004/02/12 11:25:53  rurban
284 // new WikiAdminSearchReplace plugin (requires currently Admin)
285 // removed dead comments from WikiDB
286 //
287 //
288
289 // Local Variables:
290 // mode: php
291 // tab-width: 8
292 // c-basic-offset: 4
293 // c-hanging-comment-ender-p: nil
294 // indent-tabs-mode: nil
295 // End:
296 ?>