]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/WikiAdminSearchReplace.php
Use braces
[SourceForge/phpwiki.git] / lib / plugin / WikiAdminSearchReplace.php
1 <?php // -*-php-*-
2 // $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 changed:")));
107             } else {
108                 $result->pushContent(HTML::p(fmt("%d pages have been 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
124         $args = $this->getArgs($argstr, $request);
125         $this->_args = $args;
126
127         //TODO: support p from <!plugin-list !>
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),
148                                                  $post_args['from'], $post_args['to']);
149             }
150             if ($post_args['action'] == 'select') {
151                 if (!empty($post_args['from']))
152                     $next_action = 'verify';
153                 foreach ($p as $name => $c) {
154                     $pages[$name] = 1;
155                 }
156             }
157         }
158         if ($next_action == 'select' and empty($pages)) {
159             // List all pages to select from.
160             //TODO: check for permissions and list only the allowed
161             $pages = $this->collectPages($pages, $dbi, $args['sortby'],
162                                          $args['limit'], $args['exclude']);
163         }
164
165         if ($next_action == 'verify') {
166             $args['info'] = "checkbox,pagename";
167         } else {
168             $args['info'] = "checkbox,pagename,hi_content,mtime,author";
169         }
170         $pagelist = new PageList_Selectable
171             ($args['info'], $args['exclude'],
172              array_merge
173              (
174               $args,
175               array('types' => array
176                     (
177                      'hi_content' // with highlighted search for SearchReplace
178                      => new _PageList_Column_content('rev:hi_content', _("Content"))))));
179
180         $pagelist->addPageList($pages);
181
182         $header = HTML::fieldset();
183         if (empty($post_args['from']))
184             $header->pushContent(
185               HTML::p(HTML::em(_("Warning: The search string cannot be empty!"))));
186         if ($next_action == 'verify') {
187             $button_label = _("Yes");
188             $header->pushContent(
189               HTML::p(HTML::strong(
190                                    _("Are you sure you want to replace text in the selected files?"))));
191             $this->replaceForm($header, $post_args);
192         } else {
193             $button_label = _("Search & Replace");
194             $this->replaceForm($header, $post_args);
195             $header->pushContent(HTML::legend(_("Select the pages to search and replace")));
196         }
197
198         $buttons = HTML::p(Button('submit:admin_replace[replace]', $button_label, 'wikiadmin'),
199                            Button('submit:admin_replace[cancel]', _("Cancel"), 'button'));
200         $header->pushContent($buttons);
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     }
214
215     function checkBox (&$post_args, $name, $msg) {
216             $id = 'admin_replace-'.$name;
217             $checkbox = HTML::input(array('type' => 'checkbox',
218                                       'name' => 'admin_replace['.$name.']',
219                                       'id'   => $id,
220                                       'value' => 1));
221         if (!empty($post_args[$name]))
222             $checkbox->setAttr('checked', 'checked');
223         return HTML::div($checkbox, ' ', HTML::label(array('for' => $id), $msg));
224     }
225
226     function replaceForm(&$header, $post_args) {
227         $header->pushContent(HTML::div(array('class'=>'hint'),
228                                        _("Replace all occurences of the given string in the content of all pages.")),
229                              HTML::br());
230         $table = HTML::table();
231         $this->_tablePush($table, _("Replace")._(": "),
232                           HTML::input(array('name' => 'admin_replace[from]',
233                                             'size' => 90,
234                                             'value' => $post_args['from'])));
235         $this->_tablePush($table, _("by")._(": "),
236                           HTML::input(array('name' => 'admin_replace[to]',
237                                             'size' => 90,
238                                             'value' => $post_args['to'])));
239         $this->_tablePush($table, '', $this->checkBox($post_args, 'case_exact', _("Case exact?")));
240         $this->_tablePush($table, '', $this->checkBox($post_args, 'regex', _("Regex?")));
241         $header->pushContent($table);
242         return $header;
243     }
244 }
245
246 function stri_replace($find,$replace,$string) {
247     if (!is_array($find)) $find = array($find);
248     if (!is_array($replace))  {
249         if (!is_array($find))
250             $replace = array($replace);
251         else {
252             // this will duplicate the string into an array the size of $find
253             $c = count($find);
254             $rString = $replace;
255             unset($replace);
256             for ($i = 0; $i < $c; $i++) {
257                 $replace[$i] = $rString;
258             }
259         }
260     }
261     foreach ($find as $fKey => $fItem) {
262         $between = explode(strtolower($fItem),strtolower($string));
263         $pos = 0;
264         foreach($between as $bKey => $bItem) {
265             $between[$bKey] = substr($string,$pos,strlen($bItem));
266             $pos += strlen($bItem) + strlen($fItem);
267         }
268         $string = implode($replace[$fKey],$between);
269     }
270     return $string;
271 }
272
273 // Local Variables:
274 // mode: php
275 // tab-width: 8
276 // c-basic-offset: 4
277 // c-hanging-comment-ender-p: nil
278 // indent-tabs-mode: nil
279 // End:
280 ?>