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