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