]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
don't cache this at all
[SourceForge/phpwiki.git] / lib / plugin / WikiAdminSearchReplace.php
1 <?php // -*-php-*-
2 rcs_id('$Id: WikiAdminSearchReplace.php,v 1.6 2004-02-24 15:20:07 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.6 $");
49     }
50
51     function getDefaultArguments() {
52         return array(
53                      /* Pages to exclude */
54                      'exclude'  => '.',
55                      /* Columns to include in listing */
56                      'info'     => 'some',
57                      /* How to sort */
58                      'sortby'   => 'pagename',
59                      'limit'    => 0,
60                      );
61     }
62
63     function replaceHelper(&$dbi, $pagename, $from, $to, $caseexact = true) {
64         $page = $dbi->getPage($pagename);
65         if ($page->exists()) {// don't replace default contents
66             $current = $page->getCurrentRevision();
67             $version = $current->getVersion();
68             $text = $current->getPackedContent();
69             if ($caseexact) {
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             if ($text != $newtext) {
80                 $meta = $current->_data;
81                 $meta['summary'] = sprintf(_("WikiAdminSearchReplace %s by %s"),$from,$to);
82                 return $page->save($newtext, $version + 1, $meta);
83             }
84         }
85         return false;
86     }
87
88     function searchReplacePages(&$dbi, &$request, $pages, $from, $to) {
89         if (empty($from)) return HTML::p(HTML::strong(fmt("Error: Empty search string.")));
90         $ul = HTML::ul();
91         $count = 0;
92         $post_args = $request->getArg('admin_replace');
93         $caseexact = !empty($post_args['caseexact']);
94         foreach ($pages as $pagename) {
95             if (($result = $this->replaceHelper(&$dbi,$pagename,$from,$to,$caseexact))) {
96                 $ul->pushContent(HTML::li(fmt("Replaced '%s' with '%s' in page '%s'.", $from, $to, WikiLink($pagename))));
97                 $count++;
98             } else {
99                 $ul->pushContent(HTML::li(fmt("Search string '%s' not found in page '%s'.", $from, $to, WikiLink($pagename))));
100             }
101         }
102         if ($count) {
103             $dbi->touch();
104             return HTML($ul,
105                         HTML::p(fmt("%s pages changed.",$count)));
106         } else {
107             return HTML($ul,
108                         HTML::p(fmt("No pages changed.")));
109         }
110     }
111     
112     function run($dbi, $argstr, &$request, $basepage) {
113         if ($request->getArg('action') != 'browse')
114             return $this->disabled("(action != 'browse')");
115         
116         $args = $this->getArgs($argstr, $request);
117         $this->_args = $args;
118         if (!empty($args['exclude']))
119             $exclude = explodePageList($args['exclude']);
120         else
121             $exclude = false;
122
123
124         $p = $request->getArg('p');
125         $post_args = $request->getArg('admin_replace');
126         $next_action = 'select';
127         $pages = array();
128         if ($p && !$request->isPost())
129             $pages = $p;
130         if ($p && $request->isPost() && $request->_user->isAdmin()
131             && empty($post_args['cancel'])) {
132             // FIXME: error message if not admin.
133             if ($post_args['action'] == 'verify' and !empty($post_args['from'])) {
134                 // Real action
135                 return $this->searchReplacePages($dbi, $request, $p, $post_args['from'], $post_args['to']);
136             }
137             if ($post_args['action'] == 'select') {
138                 if (!empty($post_args['from']))
139                     $next_action = 'verify';
140                 if (is_array($p) and isset($p[0])) {
141                   foreach ($p as $name) {
142                     $pages[$name] = 1;
143                   }
144                 } else {
145                   $pages = $p;
146                 }
147             }
148         }
149         if ($next_action == 'select' and empty($pages)) {
150             // List all pages to select from.
151             $pages = $this->collectPages($pages, $dbi, $args['sortby'], $args['limit']);
152         }
153
154         if ($next_action == 'verify') {
155             $args['info'] = "checkbox,pagename,hi_content";
156         }
157         $pagelist = new PageList_Selectable($args['info'], $exclude);
158         $pagelist->addPageList($pages);
159
160         $header = HTML::p();
161         if (empty($post_args['from']))
162             $header->pushContent(
163               HTML::p(HTML::em(_("Warning: The search string cannot be empty!"))));
164         if ($next_action == 'verify') {
165             $button_label = _("Yes");
166             $header->pushContent(
167               HTML::p(HTML::strong(
168                                    _("Are you sure you want to permanently search & replace text in the selected files?"))));
169             $this->replaceForm(&$header, $post_args);
170         }
171         else {
172             $button_label = _("Search & Replace");
173             $this->replaceForm(&$header, $post_args);
174             $header->pushContent(HTML::p(_("Select the pages to search:")));
175         }
176
177
178         $buttons = HTML::p(Button('submit:admin_replace[rename]', $button_label, 'wikiadmin'),
179                            Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
180
181         return HTML::form(array('action' => $request->getPostURL(),
182                                 'method' => 'post'),
183                           $header,
184                           $pagelist->getContent(),
185                           HiddenInputs($request->getArgs(),
186                                         false,
187                                         array('admin_replace')),
188                           HiddenInputs(array('admin_replace[action]' => $next_action,
189                                              'require_authority_for_post' => WIKIAUTH_ADMIN)),
190                           $buttons);
191     }
192
193     function replaceForm(&$header, $post_args) {
194         $header->pushContent(_("Replace: "));
195         $header->pushContent(HTML::input(array('name' => 'admin_replace[from]',
196                                                'value' => $post_args['from'])));
197         $header->pushContent(' '._("by").': ');
198         $header->pushContent(HTML::input(array('name' => 'admin_replace[to]',
199                                                'value' => $post_args['to'])));
200         $header->pushContent(' '._("(no regex) Case-exact: "));
201         $checkbox = HTML::input(array('type' => 'checkbox',
202                                       'name' => 'admin_replace[caseexact]',
203                                       'value' => 1));
204         if (!empty($post_args['caseexact']))
205             $checkbox->setAttr('checked','checked');
206         $header->pushContent($checkbox);
207         $header->pushContent(HTML::br());
208         return $header;
209     }
210 }
211
212 function stri_replace($find,$replace,$string) {
213     if (!is_array($find)) $find = array($find);
214     if (!is_array($replace))  {
215         if (!is_array($find)) 
216             $replace = array($replace);
217         else {
218             // this will duplicate the string into an array the size of $find
219             $c = count($find);
220             $rString = $replace;
221             unset($replace);
222             for ($i = 0; $i < $c; $i++) {
223                 $replace[$i] = $rString;
224             }
225         }
226     }
227     foreach ($find as $fKey => $fItem) {
228         $between = explode(strtolower($fItem),strtolower($string));
229         $pos = 0;
230         foreach($between as $bKey => $bItem) {
231             $between[$bKey] = substr($string,$pos,strlen($bItem));
232             $pos += strlen($bItem) + strlen($fItem);
233         }
234         $string = implode($replace[$fKey],$between);
235     }
236     return $string;
237 }
238
239 // $Log: not supported by cvs2svn $
240 // Revision 1.5  2004/02/17 12:11:36  rurban
241 // 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, ...)
242 //
243 // Revision 1.4  2004/02/15 21:34:37  rurban
244 // PageList enhanced and improved.
245 // fixed new WikiAdmin... plugins
246 // editpage, Theme with exp. htmlarea framework
247 //   (htmlarea yet committed, this is really questionable)
248 // WikiUser... code with better session handling for prefs
249 // enhanced UserPreferences (again)
250 // RecentChanges for show_deleted: how should pages be deleted then?
251 //
252 // Revision 1.3  2004/02/12 17:05:39  rurban
253 // WikiAdminRename:
254 //   added "Change pagename in all linked pages also"
255 // PageList:
256 //   added javascript toggle for Select
257 // WikiAdminSearchReplace:
258 //   fixed another typo
259 //
260 // Revision 1.2  2004/02/12 11:47:51  rurban
261 // typo
262 //
263 // Revision 1.1  2004/02/12 11:25:53  rurban
264 // new WikiAdminSearchReplace plugin (requires currently Admin)
265 // removed dead comments from WikiDB
266 //
267 //
268
269 // Local Variables:
270 // mode: php
271 // tab-width: 8
272 // c-basic-offset: 4
273 // c-hanging-comment-ender-p: nil
274 // indent-tabs-mode: nil
275 // End:
276 ?>