]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
new support for arguments owner, author, creator in most relevant
[SourceForge/phpwiki.git] / lib / plugin / WikiAdminSearchReplace.php
1 <?php // -*-php-*-
2 rcs_id('$Id: WikiAdminSearchReplace.php,v 1.14 2004-06-13 15:33:20 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  *   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: 1.14 $");
47     }
48
49     function getDefaultArguments() {
50         return array(
51                      's'        => false,
52                      /* select pages by meta-data: */
53                      'author'   => false,
54                      'owner'    => false,
55                      'creator'  => false,
56                      /* Pages to exclude */
57                      'exclude'  => '.',
58                      /* Columns to include in listing */
59                      'info'     => 'some',
60                      /* How to sort */
61                      'sortby'   => 'pagename',
62                      'limit'    => 0,
63                      );
64     }
65
66     function replaceHelper(&$dbi, $pagename, $from, $to, $caseexact = true) {
67         $page = $dbi->getPage($pagename);
68         if ($page->exists()) {// don't replace default contents
69             $current = $page->getCurrentRevision();
70             $version = $current->getVersion();
71             $text = $current->getPackedContent();
72             if ($caseexact) {
73                 $newtext = str_replace($from, $to, $text);
74             } else {
75                 //not all PHP have this enabled. use a workaround
76                 if (function_exists('str_ireplace'))
77                     $newtext = str_ireplace($from, $to, $text);
78                 else { // see eof
79                     $newtext = stri_replace($from, $to, $text);
80                 }
81             }
82             if ($text != $newtext) {
83                 $meta = $current->_data;
84                 $meta['summary'] = sprintf(_("WikiAdminSearchReplace %s by %s"),$from,$to);
85                 return $page->save($newtext, $version + 1, $meta);
86             }
87         }
88         return false;
89     }
90
91     function searchReplacePages(&$dbi, &$request, $pages, $from, $to) {
92         if (empty($from)) return HTML::p(HTML::strong(fmt("Error: Empty search string.")));
93         $ul = HTML::ul();
94         $count = 0;
95         $post_args = $request->getArg('admin_replace');
96         $caseexact = !empty($post_args['caseexact']);
97         foreach ($pages as $pagename) {
98             if (!mayAccessPage('edit',$pagename)) {
99                 $ul->pushContent(HTML::li(fmt("Access denied to change page '%s'.",$pagename)));
100             } elseif (($result = $this->replaceHelper(&$dbi,$pagename,$from,$to,$caseexact))) {
101                 $ul->pushContent(HTML::li(fmt("Replaced '%s' with '%s' in page '%s'.", $from, $to, WikiLink($pagename))));
102                 $count++;
103             } else {
104                 $ul->pushContent(HTML::li(fmt("Search string '%s' not found in content of page '%s'.", $from, WikiLink($pagename))));
105             }
106         }
107         if ($count) {
108             $dbi->touch();
109             return HTML($ul,
110                         HTML::p(fmt("%s pages changed.",$count)));
111         } else {
112             return HTML($ul,
113                         HTML::p(fmt("No pages changed.")));
114         }
115     }
116     
117     function run($dbi, $argstr, &$request, $basepage) {
118         // no action=replace support yet
119         if ($request->getArg('action') != 'browse')
120             return $this->disabled("(action != 'browse')");
121         
122         $args = $this->getArgs($argstr, $request);
123         $this->_args = $args;
124         if (!empty($args['exclude']))
125             $exclude = explodePageList($args['exclude']);
126         else
127             $exclude = false;
128         $this->preSelectS(&$args, &$request);
129
130         $p = $request->getArg('p');
131         if (!$p) $p = $this->_list;
132         $post_args = $request->getArg('admin_replace');
133         $next_action = 'select';
134         $pages = array();
135         if ($p && !$request->isPost())
136             $pages = $p;
137         if ($p && $request->isPost() &&
138             empty($post_args['cancel'])) {
139             // without individual PagePermissions:
140             if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) {
141                 $request->_notAuthorized(WIKIAUTH_ADMIN);
142                 $this->disabled("! user->isAdmin");
143             }
144
145             if ($post_args['action'] == 'verify' and !empty($post_args['from'])) {
146                 // Real action
147                 return $this->searchReplacePages($dbi, $request, array_keys($p), $post_args['from'], $post_args['to']);
148             }
149             if ($post_args['action'] == 'select') {
150                 if (!empty($post_args['from']))
151                     $next_action = 'verify';
152                 foreach ($p as $name => $c) {
153                     $pages[$name] = 1;
154                 }
155             }
156         }
157         if ($next_action == 'select' and empty($pages)) {
158             // List all pages to select from.
159             //TODO: check for permissions and list only the allowed
160             $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit']);
161         }
162
163         if ($next_action == 'verify') {
164             $args['info'] = "checkbox,pagename,hi_content";
165         }
166         $pagelist = new PageList_Selectable($args['info'], $exclude,
167                                             array('types' => array(
168                                                   'hi_content' // with highlighted search for SearchReplace
169                                                    => new _PageList_Column_content('rev:hi_content', _("Content")))));
170
171         $pagelist->addPageList($pages);
172
173         $header = HTML::p();
174         if (empty($post_args['from']))
175             $header->pushContent(
176               HTML::p(HTML::em(_("Warning: The search string cannot be empty!"))));
177         if ($next_action == 'verify') {
178             $button_label = _("Yes");
179             $header->pushContent(
180               HTML::p(HTML::strong(
181                                    _("Are you sure you want to permanently search & replace text in the selected files?"))));
182             $this->replaceForm(&$header, $post_args);
183         }
184         else {
185             $button_label = _("Search & Replace");
186             $this->replaceForm(&$header, $post_args);
187             $header->pushContent(HTML::p(_("Select the pages to search:")));
188         }
189
190
191         $buttons = HTML::p(Button('submit:admin_replace[rename]', $button_label, 'wikiadmin'),
192                            Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
193
194         return HTML::form(array('action' => $request->getPostURL(),
195                                 'method' => 'post'),
196                           $header,
197                           $pagelist->getContent(),
198                           HiddenInputs($request->getArgs(),
199                                         false,
200                                         array('admin_replace')),
201                           HiddenInputs(array('admin_replace[action]' => $next_action)),
202                           ENABLE_PAGEPERM
203                           ? ''
204                           : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)),
205                           $buttons);
206     }
207
208     function replaceForm(&$header, $post_args) {
209         $header->pushContent(_("Replace: "));
210         $header->pushContent(HTML::input(array('name' => 'admin_replace[from]',
211                                                'value' => $post_args['from'])));
212         $header->pushContent(' '._("by").': ');
213         $header->pushContent(HTML::input(array('name' => 'admin_replace[to]',
214                                                'value' => $post_args['to'])));
215         $header->pushContent(' '._("(no regex) Case-exact: "));
216         $checkbox = HTML::input(array('type' => 'checkbox',
217                                       'name' => 'admin_replace[caseexact]',
218                                       'value' => 1));
219         if (!empty($post_args['caseexact']))
220             $checkbox->setAttr('checked','checked');
221         $header->pushContent($checkbox);
222         $header->pushContent(HTML::br());
223         return $header;
224     }
225 }
226
227 function stri_replace($find,$replace,$string) {
228     if (!is_array($find)) $find = array($find);
229     if (!is_array($replace))  {
230         if (!is_array($find)) 
231             $replace = array($replace);
232         else {
233             // this will duplicate the string into an array the size of $find
234             $c = count($find);
235             $rString = $replace;
236             unset($replace);
237             for ($i = 0; $i < $c; $i++) {
238                 $replace[$i] = $rString;
239             }
240         }
241     }
242     foreach ($find as $fKey => $fItem) {
243         $between = explode(strtolower($fItem),strtolower($string));
244         $pos = 0;
245         foreach($between as $bKey => $bItem) {
246             $between[$bKey] = substr($string,$pos,strlen($bItem));
247             $pos += strlen($bItem) + strlen($fItem);
248         }
249         $string = implode($replace[$fKey],$between);
250     }
251     return $string;
252 }
253
254 // $Log: not supported by cvs2svn $
255 // Revision 1.13  2004/06/13 14:30:26  rurban
256 // security fix: check permissions in SearchReplace
257 //
258 // Revision 1.12  2004/06/08 10:05:12  rurban
259 // simplified admin action shortcuts
260 //
261 // Revision 1.11  2004/06/04 20:32:54  rurban
262 // Several locale related improvements suggested by Pierrick Meignen
263 // LDAP fix by John Cole
264 // reanable admin check without ENABLE_PAGEPERM in the admin plugins
265 //
266 // Revision 1.10  2004/06/03 22:24:48  rurban
267 // reenable admin check on !ENABLE_PAGEPERM, honor s=Wildcard arg, fix warning after Remove
268 //
269 // Revision 1.9  2004/04/07 23:13:19  rurban
270 // fixed pear/File_Passwd for Windows
271 // fixed FilePassUser sessions (filehandle revive) and password update
272 //
273 // Revision 1.8  2004/03/17 20:23:44  rurban
274 // fixed p[] pagehash passing from WikiAdminSelect, fixed problem removing pages with [] in the pagename
275 //
276 // Revision 1.7  2004/03/12 13:31:43  rurban
277 // enforce PagePermissions, errormsg if not Admin
278 //
279 // Revision 1.6  2004/02/24 15:20:07  rurban
280 // fixed minor warnings: unchecked args, POST => Get urls for sortby e.g.
281 //
282 // Revision 1.5  2004/02/17 12:11:36  rurban
283 // 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, ...)
284 //
285 // Revision 1.4  2004/02/15 21:34:37  rurban
286 // PageList enhanced and improved.
287 // fixed new WikiAdmin... plugins
288 // editpage, Theme with exp. htmlarea framework
289 //   (htmlarea yet committed, this is really questionable)
290 // WikiUser... code with better session handling for prefs
291 // enhanced UserPreferences (again)
292 // RecentChanges for show_deleted: how should pages be deleted then?
293 //
294 // Revision 1.3  2004/02/12 17:05:39  rurban
295 // WikiAdminRename:
296 //   added "Change pagename in all linked pages also"
297 // PageList:
298 //   added javascript toggle for Select
299 // WikiAdminSearchReplace:
300 //   fixed another typo
301 //
302 // Revision 1.2  2004/02/12 11:47:51  rurban
303 // typo
304 //
305 // Revision 1.1  2004/02/12 11:25:53  rurban
306 // new WikiAdminSearchReplace plugin (requires currently Admin)
307 // removed dead comments from WikiDB
308 //
309 //
310
311 // Local Variables:
312 // mode: php
313 // tab-width: 8
314 // c-basic-offset: 4
315 // c-hanging-comment-ender-p: nil
316 // indent-tabs-mode: nil
317 // End:
318 ?>