]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Bookmark/deliciousbackupimporter.php
Merge remote-tracking branch 'gitorious/1.0.x' into 1.0.x
[quix0rs-gnu-social.git] / plugins / Bookmark / deliciousbackupimporter.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * Importer class for Delicious.com backups
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  Bookmark
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2010 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Importer class for Delicious bookmarks
39  *
40  * @category  Bookmark
41  * @package   StatusNet
42  * @author    Evan Prodromou <evan@status.net>
43  * @copyright 2010 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47 class DeliciousBackupImporter extends QueueHandler
48 {
49     /**
50      * Transport of the importer
51      *
52      * @return string transport string
53      */
54     function transport()
55     {
56         return 'dlcsback';
57     }
58
59     /**
60      * Import an in-memory bookmark list to a user's account
61      *
62      * Take a delicious.com backup file (same as Netscape bookmarks.html)
63      * and import to StatusNet as Bookmark activities.
64      *
65      * The document format is terrible. It consists of a <dl> with
66      * a bunch of <dt>'s, occasionally with <dd>'s adding descriptions.
67      * There are sometimes <p>'s lost inside.
68      *
69      * @param array $data pair of user, text
70      *
71      * @return boolean success value
72      */
73     function handle($data)
74     {
75         list($user, $body) = $data;
76
77         $doc = $this->importHTML($body);
78
79         $dls = $doc->getElementsByTagName('dl');
80
81         if ($dls->length != 1) {
82             // TRANS: Client exception thrown when a file upload is incorrect.
83             throw new ClientException(_m('Bad import file.'));
84         }
85
86         $dl = $dls->item(0);
87
88         $children = $dl->childNodes;
89
90         $dt = null;
91
92         for ($i = 0; $i < $children->length; $i++) {
93             try {
94                 $child = $children->item($i);
95                 if ($child->nodeType != XML_ELEMENT_NODE) {
96                     continue;
97                 }
98                 switch (strtolower($child->tagName)) {
99                 case 'dt':
100                     // <dt> nodes contain primary information about a bookmark.
101                     // We can't import the current one just yet though, since
102                     // it may be followed by a <dd>.
103                     if (!empty($dt)) {
104                         // No DD provided
105                         $this->importBookmark($user, $dt);
106                         $dt = null;
107                     }
108                     $dt = $child;
109                     break;
110                 case 'dd':
111                     $dd = $child;
112
113                     // This <dd> contains a description for the bookmark in
114                     // the preceding <dt> node.
115                     $saved = $this->importBookmark($user, $dt, $dd);
116
117                     $dt = null;
118                     $dd = null;
119                     break;
120                 case 'p':
121                     common_log(LOG_INFO, 'Skipping the <p> in the <dl>.');
122                     break;
123                 default:
124                     common_log(LOG_WARNING,
125                                "Unexpected element $child->tagName ".
126                                " found in import.");
127                 }
128             } catch (Exception $e) {
129                 common_log(LOG_ERR, $e->getMessage());
130                 $dt = $dd = null;
131             }
132         }
133         if (!empty($dt)) {
134             // There was a final bookmark without a description.
135             try {
136                 $this->importBookmark($user, $dt);
137             } catch (Exception $e) {
138                 common_log(LOG_ERR, $e->getMessage());
139             }
140         }
141
142         return true;
143     }
144
145     /**
146      * Import a single bookmark
147      *
148      * Takes a <dt>/<dd> pair. The <dt> has a single
149      * <a> in it with some non-standard attributes.
150      *
151      * A <dt><dt><dd> sequence will appear as a <dt> with
152      * anothe <dt> as a child. We handle this case recursively.
153      *
154      * @param User       $user User to import data as
155      * @param DOMElement $dt   <dt> element
156      * @param DOMElement $dd   <dd> element
157      *
158      * @return Notice imported notice
159      */
160     function importBookmark($user, $dt, $dd = null)
161     {
162         $as = $dt->getElementsByTagName('a');
163
164         if ($as->length == 0) {
165             // TRANS: Client exception thrown when a bookmark in an import file is incorrectly formatted.
166             throw new ClientException(_m("No <A> tag in a <DT>."));
167         }
168
169         $a = $as->item(0);
170
171         $private = $a->getAttribute('private');
172
173         if ($private != 0) {
174             // TRANS: Client exception thrown when a bookmark in an import file is private.
175             throw new ClientException(_m('Skipping private bookmark.'));
176         }
177
178         if (!empty($dd)) {
179             $description = $dd->nodeValue;
180         } else {
181             $description = null;
182         }
183         $addDate = $a->getAttribute('add_date');
184
185         $data = array(
186             'profile_id' => $user->id,
187             'title' => $a->nodeValue,
188             'description' => $description,
189             'url' => $a->getAttribute('href'),
190             'tags' => $a->getAttribute('tags'),
191             'created' => common_sql_date(intval($addDate))
192         );
193
194         $qm = QueueManager::get();
195         $qm->enqueue($data, 'dlcsbkmk');
196     }
197
198     /**
199      * Parse some HTML
200      *
201      * Hides the errors that the dom parser returns
202      *
203      * @param string $body Data to import
204      *
205      * @return DOMDocument parsed document
206      */
207
208     function importHTML($body)
209     {
210         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
211         // and notices on unrecognized namespaces.
212         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
213         $dom = new DOMDocument();
214         $ok  = $dom->loadHTML($body);
215         error_reporting($old);
216
217         if ($ok) {
218             foreach ($dom->getElementsByTagName('body') as $node) {
219                 $this->fixListsIn($node);
220             }
221             return $dom;
222         } else {
223             return null;
224         }
225     }
226
227
228     function fixListsIn(DOMNode $body) {
229         $toFix = array();
230
231         foreach ($body->childNodes as $node) {
232             if ($node->nodeType == XML_ELEMENT_NODE) {
233                 $el = strtolower($node->nodeName);
234                 if ($el == 'dl') {
235                     $toFix[] = $node;
236                 }
237             }
238         }
239
240         foreach ($toFix as $node) {
241             $this->fixList($node);
242         }
243     }
244
245     function fixList(DOMNode $list) {
246         $toFix = array();
247
248         foreach ($list->childNodes as $node) {
249             if ($node->nodeType == XML_ELEMENT_NODE) {
250                 $el = strtolower($node->nodeName);
251                 if ($el == 'dt' || $el == 'dd') {
252                     $toFix[] = $node;
253                 }
254                 if ($el == 'dl') {
255                     // Sublist.
256                     // Technically, these can only appear inside a <dd>...
257                     $this->fixList($node);
258                 }
259             }
260         }
261
262         foreach ($toFix as $node) {
263             $this->fixListItem($node);
264         }
265     }
266
267     function fixListItem(DOMNode $item) {
268         // The HTML parser in libxml2 doesn't seem to properly handle
269         // many cases of implied close tags, apparently because it doesn't
270         // understand the nesting rules specified in the HTML DTD.
271         //
272         // This leads to sequences of adjacent <dt>s or <dd>s being incorrectly
273         // interpreted as parent->child trees instead of siblings:
274         //
275         // When parsing this input: "<dt>aaa <dt>bbb"
276         // should be equivalent to: "<dt>aaa </dt><dt>bbb</dt>"
277         // but we're seeing instead: "<dt>aaa <dt>bbb</dt></dt>"
278         //
279         // It does at least know that going from dt to dd, or dd to dt,
280         // should make a break.
281
282         $toMove = array();
283
284         foreach ($item->childNodes as $node) {
285             if ($node->nodeType == XML_ELEMENT_NODE) {
286                 $el = strtolower($node->nodeName);
287                 if ($el == 'dt' || $el == 'dd') {
288                     // dt & dd cannot contain each other;
289                     // This node was incorrectly placed; move it up a level!
290                     $toMove[] = $node;
291                 }
292                 if ($el == 'dl') {
293                     // Sublist.
294                     // Technically, these can only appear inside a <dd>.
295                     $this->fixList($node);
296                 }
297             }
298         }
299
300         $parent = $item->parentNode;
301         $next = $item->nextSibling;
302         foreach ($toMove as $node) {
303             $item->removeChild($node);
304             $parent->insertBefore($node, $next);
305             $this->fixListItem($node);
306         }
307     }
308 }