]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
Let's assume PHP >= 4.2
[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:   <<WikiAdminSearchReplace >> or called via WikiAdminSelect
26  * Author:  Reini Urban <rurban@x-ray.at>
27  *
28  */
29 require_once('lib/PageList.php');
30 require_once('lib/plugin/WikiAdminSelect.php');
31
32 class WikiPlugin_WikiAdminSearchReplace
33 extends WikiPlugin_WikiAdminSelect
34 {
35     function getName() {
36         return _("WikiAdminSearchReplace");
37     }
38
39     function getDescription() {
40         return _("Search and replace text in selected wiki pages.");
41     }
42
43     function getDefaultArguments() {
44         return array_merge
45             (
46              WikiPlugin_WikiAdminSelect::getDefaultArguments(),
47              array(
48                    /* Columns to include in listing */
49                    'info'     => 'some',
50                    ));
51     }
52
53     function replaceHelper(&$dbi, &$request, $pagename, $from, $to, $case_exact=true, $regex=false) {
54         $page = $dbi->getPage($pagename);
55         if ($page->exists()) {// don't replace default contents
56             $current = $page->getCurrentRevision();
57             $version = $current->getVersion();
58             $text = $current->getPackedContent();
59             if ($regex) {
60                 $newtext = preg_replace("/".$from."/".($case_exact?'':'i'), $to, $text);
61             } else {
62                 if ($case_exact) {
63                     $newtext = str_replace($from, $to, $text);
64                 } else {
65                     //not all PHP have this enabled. use a workaround
66                     if (function_exists('str_ireplace'))
67                         $newtext = str_ireplace($from, $to, $text);
68                     else { // see eof
69                         $newtext = stri_replace($from, $to, $text);
70                     }
71                 }
72             }
73             if ($text != $newtext) {
74                 $meta = $current->_data;
75                 $meta['summary'] = sprintf(_("Replace '%s' by '%s'"), $from, $to);
76                 $meta['is_minor_edit'] = 0;
77                 $meta['author'] =  $request->_user->UserName();
78                 unset($meta['mtime']); // force new date
79                 return $page->save($newtext, $version + 1, $meta);
80             }
81         }
82         return false;
83     }
84
85     function searchReplacePages(&$dbi, &$request, $pages, $from, $to) {
86         if (empty($from)) return HTML::p(HTML::strong(fmt("Error: Empty search string.")));
87         $result = HTML::div();
88         $ul = HTML::ul();
89         $count = 0;
90         $post_args = $request->getArg('admin_replace');
91         $case_exact = !empty($post_args['case_exact']);
92         $regex = !empty($post_args['regex']);
93         foreach ($pages as $pagename) {
94             if (!mayAccessPage('edit', $pagename)) {
95                 $ul->pushContent(HTML::li(fmt("Access denied to change page '%s'.",$pagename)));
96             } elseif ($this->replaceHelper($dbi, $request, $pagename, $from, $to, $case_exact, $regex)) {
97                 $ul->pushContent(HTML::li(fmt("Replaced '%s' with '%s' in page '%s'.",
98                                               $from, $to, WikiLink($pagename))));
99                 $count++;
100             }
101         }
102         if ($count) {
103             $dbi->touch();
104             $result->setAttr('class', 'feedback');
105             if ($count == 1) {
106                 $result->pushContent(HTML::p("One page has been permanently changed:"));
107             } else {
108                 $result->pushContent(HTML::p(fmt("%s pages have been permanently changed:", $count)));
109             }
110             $result->pushContent($ul);
111         } else {
112             $result->setAttr('class', 'error');
113             $result->pushContent(HTML::p("No pages changed."));
114         }
115         return $result;
116     }
117
118     function run($dbi, $argstr, &$request, $basepage) {
119             // no action=replace support yet
120         if ($request->getArg('action') != 'browse')
121             return $this->disabled("(action != 'browse')");
122
123         $args = $this->getArgs($argstr, $request);
124         $this->_args = $args;
125
126         //TODO: support p from <!plugin-list !>
127         $this->preSelectS($args, $request);
128
129         $p = $request->getArg('p');
130         if (!$p) $p = $this->_list;
131         $post_args = $request->getArg('admin_replace');
132         $next_action = 'select';
133         $pages = array();
134         if ($p && !$request->isPost())
135             $pages = $p;
136         if ($p && $request->isPost() &&
137             empty($post_args['cancel'])) {
138             // without individual PagePermissions:
139             if (!ENABLE_PAGEPERM and !$request->_user->isAdmin()) {
140                 $request->_notAuthorized(WIKIAUTH_ADMIN);
141                 $this->disabled("! user->isAdmin");
142             }
143
144             if ($post_args['action'] == 'verify' and !empty($post_args['from'])) {
145                 // Real action
146                 return $this->searchReplacePages($dbi, $request, array_keys($p),
147                                                  $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'],
161                                          $args['limit'], $args['exclude']);
162         }
163
164         if ($next_action == 'verify') {
165             $args['info'] = "checkbox,pagename";
166         } else {
167             $args['info'] = "checkbox,pagename,hi_content,mtime,author";
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::fieldset();
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 replace text in the selected files?"))));
190             $this->replaceForm($header, $post_args);
191         } else {
192             $button_label = _("Search & Replace");
193             $this->replaceForm($header, $post_args);
194             $header->pushContent(HTML::legend(_("Select the pages to search and replace")));
195         }
196
197         $buttons = HTML::p(Button('submit:admin_replace[replace]', $button_label, 'wikiadmin'),
198                            Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
199         $header->pushContent($buttons);
200
201         return HTML::form(array('action' => $request->getPostURL(),
202                                 'method' => 'post'),
203                           $header,
204                           $pagelist->getContent(),
205                           HiddenInputs($request->getArgs(),
206                                         false,
207                                         array('admin_replace')),
208                           HiddenInputs(array('admin_replace[action]' => $next_action)),
209                           ENABLE_PAGEPERM
210                           ? ''
211                           : HiddenInputs(array('require_authority_for_post' => WIKIAUTH_ADMIN)));
212     }
213
214     function checkBox (&$post_args, $name, $msg) {
215             $id = 'admin_replace-'.$name;
216             $checkbox = HTML::input(array('type' => 'checkbox',
217                                       'name' => 'admin_replace['.$name.']',
218                                       'id'   => $id,
219                                       'value' => 1));
220         if (!empty($post_args[$name]))
221             $checkbox->setAttr('checked', 'checked');
222         return HTML::div($checkbox, ' ', HTML::label(array('for' => $id), $msg));
223     }
224
225     function replaceForm(&$header, $post_args) {
226         $header->pushContent(HTML::div(array('class'=>'hint'),
227                                        _("Replace all occurences of the given string in the content of all pages.")),
228                              HTML::br());
229         $table = HTML::table();
230         $this->_tablePush($table, _("Replace").": ",
231                           HTML::input(array('name' => 'admin_replace[from]',
232                                             'size' => 90,
233                                             'value' => $post_args['from'])));
234         $this->_tablePush($table, _("by").': ',
235                           HTML::input(array('name' => 'admin_replace[to]',
236                                             'size' => 90,
237                                             'value' => $post_args['to'])));
238         $this->_tablePush($table, '', $this->checkBox($post_args, 'case_exact', _("Case exact?")));
239         $this->_tablePush($table, '', $this->checkBox($post_args, 'regex', _("Regex?")));
240         $header->pushContent($table);
241         return $header;
242     }
243 }
244
245 function stri_replace($find,$replace,$string) {
246     if (!is_array($find)) $find = array($find);
247     if (!is_array($replace))  {
248         if (!is_array($find))
249             $replace = array($replace);
250         else {
251             // this will duplicate the string into an array the size of $find
252             $c = count($find);
253             $rString = $replace;
254             unset($replace);
255             for ($i = 0; $i < $c; $i++) {
256                 $replace[$i] = $rString;
257             }
258         }
259     }
260     foreach ($find as $fKey => $fItem) {
261         $between = explode(strtolower($fItem),strtolower($string));
262         $pos = 0;
263         foreach($between as $bKey => $bItem) {
264             $between[$bKey] = substr($string,$pos,strlen($bItem));
265             $pos += strlen($bItem) + strlen($fItem);
266         }
267         $string = implode($replace[$fKey],$between);
268     }
269     return $string;
270 }
271
272 // Local Variables:
273 // mode: php
274 // tab-width: 8
275 // c-basic-offset: 4
276 // c-hanging-comment-ender-p: nil
277 // indent-tabs-mode: nil
278 // End:
279 ?>