]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/plugin/SyncWiki.php
Remove unused variables
[SourceForge/phpwiki.git] / lib / plugin / SyncWiki.php
1 <?php
2
3 /**
4  * Copyright 2006 $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 along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * required argument:  url = <rpc interface to main wiki>
25  * optional arguments: noimport, noexport, noupload
26  *
27  * 1. check RPC2 interface or admin url (lang?) of external wiki
28  *    get external pagelist, only later than our last mergepoint
29  * 2. Download all externally changed sources:
30  *    If local page is older than the mergepoint, import it.
31  *    If local page does not exist (deleted?), and there is no revision, import it.
32  *    Else we deleted it. Skip the import, but don't delete the external. Should be added to conflict.
33  *    If local page is newer than the mergepoint, then add it to the conflict pages.
34  * 3. check our to_delete, to_add, to_merge
35  * 4. get our pagelist of pages only later than our last mergepoint
36  * 5. check external to_delete, to_add, to_merge
37  * 6. store log (where, how?)
38  */
39 require_once 'lib/loadsave.php';
40 include_once 'lib/plugin/WikiAdminUtils.php';
41
42 class WikiPlugin_SyncWiki
43     extends WikiPlugin_WikiAdminUtils
44 {
45     function getName()
46     {
47         return _("SyncWiki");
48     }
49
50     function getDescription()
51     {
52         return _("Synchronize pages with external PhpWiki.");
53     }
54
55     function getDefaultArguments()
56     {
57         return array('url' => '',
58             'noimport' => 0,
59             'noexport' => 0,
60             'noupload' => 0,
61             'label' => $this->getName(),
62             //'userid' => false,
63             'passwd' => false,
64             'sid' => false,
65         );
66     }
67
68     function run($dbi, $argstr, &$request, $basepage)
69     {
70         $args = $this->getArgs($argstr, $request);
71         $args['action'] = 'syncwiki';
72         extract($args);
73         if (empty($args['url'])) {
74             return $this->error(fmt("A required argument ā€œ%sā€ is missing.", "url"));
75         }
76         if ($request->getArg('action') != 'browse') {
77             return $this->disabled(_("Plugin not run: not in browse mode"));
78         }
79         $posted = $request->getArg('wikiadminutils');
80         if ($request->isPost()
81             and $posted['action'] == $action
82                 and $posted['url'] == $url
83         ) // multiple buttons
84         {
85             return $this->_do_syncwiki($request, $posted);
86         }
87         return $this->_makeButton($request, $args, $label);
88     }
89
90     function _do_syncwiki(&$request, $args)
91     {
92         longer_timeout(240);
93
94         if (!function_exists('wiki_xmlrpc_post')) {
95             include_once 'lib/XmlRpcClient.php';
96         }
97         $userid = $request->_user->_userid;
98         $dbh = $request->getDbh();
99         $merge_point = $dbh->get('mergepoint');
100         if (empty($merge_point)) {
101             $page = $dbh->getPage("ReleaseNotes"); // this is usually the latest official page
102             $last = $page->getCurrentRevision(false);
103             $merge_point = $last->get("mtime"); // for testing: 1160396075
104             $dbh->set('mergepoint', $merge_point);
105         }
106         //TODO: remote auth, set session cookie
107         $pagelist = wiki_xmlrpc_post('wiki.getRecentChanges',
108             iso8601_encode($merge_point, 1),
109             $args['url'], $args);
110         $html = HTML();
111         //$html->pushContent(HTML::div(HTML::em("check RPC2 interface...")));
112         if (gettype($pagelist) === "array") {
113             //$request->_deferredPageChangeNotification = array();
114             $request->discardOutput();
115             StartLoadDump($request, _("Syncing this PhpWiki"));
116             PrintXML(HTML::strong(fmt("Download all externally changed sources.")));
117             echo "<br />\n";
118             PrintXML(fmt("Retrieving from external url %s wiki.getRecentChanges(%s)...",
119                 $args['url'], iso8601_encode($merge_point, 1)));
120             echo "<br />\n";
121             $ouriter = $dbh->mostRecent(array('since' => $merge_point));
122             //$ol = HTML::ol();
123             $done = array();
124             foreach ($pagelist as $ext) {
125                 $reaction = _("<unknown>");
126                 // compare existance and dates with local page
127                 $extdate = iso8601_decode($ext['lastModified']->scalar, 1);
128                 // TODO: urldecode ???
129                 $name = utf8_decode($ext['name']);
130                 $our = $dbh->getPage($name);
131                 $done[$name] = 1;
132                 $ourrev = $our->getCurrentRevision(false);
133                 $rel = '<=>';
134                 if (!$our->exists()) {
135                     // we might have deleted or moved it on purpose?
136                     // check date of latest revision if there's one, and > mergepoint
137                     if (($ourrev->getVersion() > 1) and ($ourrev->get('mtime') > $merge_point)) {
138                         // our was deleted after sync, and changed after last sync.
139                         $this->_addConflict('delete', $args, $our, $extdate);
140                         $reaction = (_(" skipped") . " (" . "locally deleted or moved" . ")");
141                     } else {
142                         $reaction = $this->_import($args, $our, $extdate);
143                     }
144                 } else {
145                     $ourdate = $ourrev->get('mtime');
146                     if ($extdate > $ourdate and $ourdate < $merge_point) {
147                         $rel = '>';
148                         $reaction = $this->_import($args, $our, $extdate);
149                     } elseif ($extdate > $ourdate and $ourdate >= $merge_point) {
150                         $rel = '>';
151                         // our is older then external but newer than last sync
152                         $reaction = $this->_addConflict('import', $args, $our, $extdate);
153                     } elseif ($extdate < $ourdate and $extdate < $merge_point) {
154                         $rel = '>';
155                         $reaction = $this->_export($args, $our);
156                     } elseif ($extdate < $ourdate and $extdate >= $merge_point) {
157                         $rel = '>';
158                         // our is newer and external is also newer
159                         $reaction = $this->_addConflict('export', $args, $our, $extdate);
160                     } else {
161                         $rel = '==';
162                         $reaction = _("same date");
163                     }
164                 }
165                 /*$ol->pushContent(HTML::li(HTML::strong($name)," ",
166                                           $extdate,"<=>",$ourdate," ",
167                                           HTML::strong($reaction))); */
168                 PrintXML(HTML::strong($name), " ",
169                     $extdate, " $rel ", $ourdate, " ",
170                     HTML::strong($reaction),
171                     HTML::br());
172                 $request->chunkOutput();
173             }
174             //$html->pushContent($ol);
175         } else {
176             $html->pushContent("xmlrpc error:  wiki.getRecentChanges returned "
177                 . "(" . gettype($pagelist) . ") " . $pagelist);
178             trigger_error("xmlrpc error:  wiki.getRecentChanges returned "
179                 . "(" . gettype($pagelist) . ") " . $pagelist, E_USER_WARNING);
180             EndLoadDump($request);
181             return $this->error($html);
182         }
183
184         if (empty($args['noexport'])) {
185             PrintXML(HTML::strong(fmt("Now upload all locally newer pages.")));
186             echo "<br />\n";
187             PrintXML(fmt("Checking all local pages newer than %s...",
188                 iso8601_encode($merge_point, 1)));
189             echo "<br />\n";
190             while ($our = $ouriter->next()) {
191                 $name = $our->getName();
192                 if ($done[$name]) continue;
193                 $reaction = _(" skipped");
194                 $ext = wiki_xmlrpc_post('wiki.getPageInfo', $name, $args['url']);
195                 if (is_array($ext)) {
196                     $extdate = iso8601_decode($ext['lastModified']->scalar, 1);
197                     $ourdate = $our->get('mtime');
198                     if ($extdate < $ourdate and $extdate < $merge_point) {
199                         $reaction = $this->_export($args, $our);
200                     } elseif ($extdate < $ourdate and $extdate >= $merge_point) {
201                         // our newer and external newer
202                         $reaction = $this->_addConflict($args, $our, $extdate);
203                     }
204                 } else {
205                     $reaction = 'xmlrpc error';
206                 }
207                 PrintXML(HTML::strong($name), " ",
208                     $extdate, " < ", $ourdate, " ",
209                     HTML::strong($reaction),
210                     HTML::br());
211                 $request->chunkOutput();
212             }
213
214             PrintXML(HTML::strong(fmt("Now upload all locally newer uploads.")));
215             echo "<br />\n";
216             PrintXML(fmt("Checking all local uploads newer than %s...",
217                 iso8601_encode($merge_point, 1)));
218             echo "<br />\n";
219             $this->_fileList = array();
220             $prefix = getUploadFilePath();
221             $this->_dir($prefix);
222             $len = strlen($prefix);
223             foreach ($this->_fileList as $path) {
224                 // strip prefix
225                 $file = substr($path, $len);
226                 $ourdate = filemtime($path);
227                 $oursize = filesize($path);
228                 $reaction = _(" skipped");
229                 $ext = wiki_xmlrpc_post('wiki.getUploadedFileInfo', $file, $args['url']);
230                 if (is_array($ext)) {
231                     $extdate = iso8601_decode($ext['lastModified']->scalar, 1);
232                     $extsize = $ext['size'];
233                     if (empty($extsize) or $extdate < $ourdate) {
234                         $timeout = $oursize * 0.0002; // assume 50kb/sec upload speed
235                         $reaction = $this->_upload($args, $path, $timeout);
236                     }
237                 } else {
238                     $reaction = 'xmlrpc error wiki.getUploadedFileInfo not supported';
239                 }
240                 PrintXML(HTML::strong($name), " ",
241                     "$extdate ($extsize) < $ourdate ($oursize)",
242                     HTML::strong($reaction),
243                     HTML::br());
244                 $request->chunkOutput();
245             }
246         }
247
248         $dbh->set('mergepoint', time());
249         EndLoadDump($request);
250         return ''; //$html;
251     }
252
253     /* path must have ending slash */
254     function _dir($path)
255     {
256         $dh = @opendir($path);
257         while ($filename = readdir($dh)) {
258             if ($filename[0] == '.')
259                 continue;
260             $ft = filetype($path . $filename);
261             if ($ft == 'file')
262                 array_push($this->_fileList, $path . $filename);
263             else if ($ft == 'dir')
264                 $this->_dir($path . $filename . "/");
265         }
266         closedir($dh);
267     }
268
269     function _addConflict($what, $args, $our, $extdate = null)
270     {
271         $pagename = $our->getName();
272         $meb = Button(array('action' => $args['action'],
273                 'merge' => true,
274                 'source' => $f),
275             _("Merge Edit"),
276             $args['pagename'],
277             'wikiadmin');
278         $owb = Button(array('action' => $args['action'],
279                 'overwrite' => true,
280                 'source' => $f),
281             sprintf(_("%s force"), strtoupper(substr($what, 0, 1)) . substr($what, 1)),
282             $args['pagename'],
283             'wikiunsafe');
284         $this->_conflicts[] = $pagename;
285         return HTML(fmt(_("Postponed %s for %s."), $what, $pagename), " ", $meb, " ", $owb);
286     }
287
288     // TODO: store log or checkpoint for restauration?
289     function _import($args, $our, $extdate = null)
290     {
291         $reaction = 'import ';
292         if ($args['noimport']) return ($reaction . _("skipped"));
293         //$userid = $request->_user->_userid;
294         $name = $our->getName();
295         $pagedata = wiki_xmlrpc_post('wiki.getPage', $name, $args['url']);
296         if (is_object($pagedata)) {
297             $pagedata = $pagedata->scalar;
298             $ourrev = $our->getCurrentRevision(true);
299             $content = $ourrev->getPackedContent();
300             if ($pagedata == $content)
301                 return $reaction . _("skipped") . ' ' . _("same content");
302             if (is_null($extdate))
303                 $extdate = time();
304             $our->save(utf8_decode($pagedata), -1, array('author' => $userid,
305                 'mtime' => $extdate));
306             $reaction .= _("OK");
307         } else
308             $reaction .= (_("FAILED") . ' (' . gettype($pagedata) . ')');
309         return $reaction;
310     }
311
312     // TODO: store log or checkpoint for restauration?
313     function _export($args, $our)
314     {
315         global $request;
316         $reaction = 'export ';
317         if ($args['noexport']) return ($reaction . _("skipped"));
318         $userid = $request->_user->_userid;
319         $name = $our->getName();
320         $ourrev = $our->getCurrentRevision(true);
321         $content = $ourrev->getPackedContent();
322         $extdata = wiki_xmlrpc_post('wiki.getPage', $name, $args['url']);
323         if (is_object($extdata)) {
324             $extdata = $extdata->scalar;
325             if ($extdata == $content)
326                 return $reaction . _("skipped") . ' ' . _("same content");
327         }
328         $mypass = $request->getPref('passwd'); // this usually fails
329         $success = wiki_xmlrpc_post('wiki.putPage',
330             array($name, $content, $userid, $mypass), $args['url']);
331         if (is_array($success)) {
332             if ($success['code'] == 200)
333                 $reaction .= (_("OK") . ' ' . $success['code'] . " " . $success['message']);
334             else
335                 $reaction .= (_("FAILED") . ' ' . $success['code'] . " " . $success['message']);
336         } else
337             $reaction .= (_("FAILED"));
338         return $reaction;
339     }
340
341     // TODO: store log or checkpoint for restauration?
342     function _upload($args, $path, $timeout)
343     {
344         $reaction = 'upload ';
345         if ($args['noupload']) return ($reaction . _("skipped"));
346
347         //$userid  = $request->_user->_userid;
348         $url = $args['url'];
349         $url = str_replace("/RPC2.php", "/index.php", $url);
350         $server = parse_url($url);
351         $http = new HttpClient($server['host'], $server['port']);
352         $http->timeout = $timeout + 5;
353         $success = $http->postfile($server['url'], $path);
354         if ($success) {
355             if ($http->getStatus() == 200)
356                 $reaction .= _("OK");
357             else
358                 $reaction .= (_("FAILED") . ' ' . $http->getStatus());
359         } else
360             $reaction .= (_("FAILED") . ' ' . $http->getStatus() . " " . $http->errormsg);
361         return $reaction;
362     }
363 }
364
365 // Local Variables:
366 // mode: php
367 // tab-width: 8
368 // c-basic-offset: 4
369 // c-hanging-comment-ender-p: nil
370 // indent-tabs-mode: nil
371 // End: