]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Bookmark/deliciousbackupimporter.php
Merge branch '1.0.x' of gitorious.org:statusnet/mainline 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         // If we can't parse it, it's no good
80
81         if (empty($doc)) {
82             return true;
83         }
84
85         $dls = $doc->getElementsByTagName('dl');
86
87         if ($dls->length != 1) {
88             // TRANS: Client exception thrown when a file upload is incorrect.
89             throw new ClientException(_m('Bad import file.'));
90         }
91
92         $dl = $dls->item(0);
93
94         $children = $dl->childNodes;
95
96         $dt = null;
97
98         for ($i = 0; $i < $children->length; $i++) {
99             try {
100                 $child = $children->item($i);
101                 if ($child->nodeType != XML_ELEMENT_NODE) {
102                     continue;
103                 }
104                 switch (strtolower($child->tagName)) {
105                 case 'dt':
106                     // <dt> nodes contain primary information about a bookmark.
107                     // We can't import the current one just yet though, since
108                     // it may be followed by a <dd>.
109                     if (!empty($dt)) {
110                         // No DD provided
111                         $this->importBookmark($user, $dt);
112                         $dt = null;
113                     }
114                     $dt = $child;
115                     break;
116                 case 'dd':
117                     $dd = $child;
118
119                     if (!empty($dt)) {
120                         // This <dd> contains a description for the bookmark in
121                         // the preceding <dt> node.
122                         $saved = $this->importBookmark($user, $dt, $dd);
123                     }
124
125                     $dt = null;
126                     $dd = null;
127                     break;
128                 case 'p':
129                     common_log(LOG_INFO, 'Skipping the <p> in the <dl>.');
130                     break;
131                 default:
132                     common_log(LOG_WARNING,
133                                "Unexpected element $child->tagName ".
134                                " found in import.");
135                 }
136             } catch (Exception $e) {
137                 common_log(LOG_ERR, $e->getMessage());
138                 $dt = $dd = null;
139             }
140         }
141         if (!empty($dt)) {
142             // There was a final bookmark without a description.
143             try {
144                 $this->importBookmark($user, $dt);
145             } catch (Exception $e) {
146                 common_log(LOG_ERR, $e->getMessage());
147             }
148         }
149
150         return true;
151     }
152
153     /**
154      * Import a single bookmark
155      *
156      * Takes a <dt>/<dd> pair. The <dt> has a single
157      * <a> in it with some non-standard attributes.
158      *
159      * A <dt><dt><dd> sequence will appear as a <dt> with
160      * anothe <dt> as a child. We handle this case recursively.
161      *
162      * @param User       $user User to import data as
163      * @param DOMElement $dt   <dt> element
164      * @param DOMElement $dd   <dd> element
165      *
166      * @return Notice imported notice
167      */
168     function importBookmark($user, $dt, $dd = null)
169     {
170         $as = $dt->getElementsByTagName('a');
171
172         if ($as->length == 0) {
173             // TRANS: Client exception thrown when a bookmark in an import file is incorrectly formatted.
174             throw new ClientException(_m("No <A> tag in a <DT>."));
175         }
176
177         $a = $as->item(0);
178
179         $private = $a->getAttribute('private');
180
181         if ($private != 0) {
182             // TRANS: Client exception thrown when a bookmark in an import file is private.
183             throw new ClientException(_m('Skipping private bookmark.'));
184         }
185
186         if (!empty($dd)) {
187             $description = $dd->nodeValue;
188         } else {
189             $description = null;
190         }
191         $addDate = $a->getAttribute('add_date');
192
193         $data = array(
194             'profile_id' => $user->id,
195             'title' => $a->nodeValue,
196             'description' => $description,
197             'url' => $a->getAttribute('href'),
198             'tags' => $a->getAttribute('tags'),
199             'created' => common_sql_date(intval($addDate))
200         );
201
202         $qm = QueueManager::get();
203         $qm->enqueue($data, 'dlcsbkmk');
204     }
205
206     /**
207      * Parse some HTML
208      *
209      * Hides the errors that the dom parser returns
210      *
211      * @param string $body Data to import
212      *
213      * @return DOMDocument parsed document
214      */
215
216     function importHTML($body)
217     {
218         // DOMDocument::loadHTML may throw warnings on unrecognized elements,
219         // and notices on unrecognized namespaces.
220         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
221         $dom = new DOMDocument();
222         $ok  = $dom->loadHTML($body);
223         error_reporting($old);
224
225         if ($ok) {
226             foreach ($dom->getElementsByTagName('body') as $node) {
227                 $this->fixListsIn($node);
228             }
229             return $dom;
230         } else {
231             return null;
232         }
233     }
234
235
236     function fixListsIn(DOMNode $body) {
237         $toFix = array();
238
239         foreach ($body->childNodes as $node) {
240             if ($node->nodeType == XML_ELEMENT_NODE) {
241                 $el = strtolower($node->nodeName);
242                 if ($el == 'dl') {
243                     $toFix[] = $node;
244                 }
245             }
246         }
247
248         foreach ($toFix as $node) {
249             $this->fixList($node);
250         }
251     }
252
253     function fixList(DOMNode $list) {
254         $toFix = array();
255
256         foreach ($list->childNodes as $node) {
257             if ($node->nodeType == XML_ELEMENT_NODE) {
258                 $el = strtolower($node->nodeName);
259                 if ($el == 'dt' || $el == 'dd') {
260                     $toFix[] = $node;
261                 }
262                 if ($el == 'dl') {
263                     // Sublist.
264                     // Technically, these can only appear inside a <dd>...
265                     $this->fixList($node);
266                 }
267             }
268         }
269
270         foreach ($toFix as $node) {
271             $this->fixListItem($node);
272         }
273     }
274
275     function fixListItem(DOMNode $item) {
276         // The HTML parser in libxml2 doesn't seem to properly handle
277         // many cases of implied close tags, apparently because it doesn't
278         // understand the nesting rules specified in the HTML DTD.
279         //
280         // This leads to sequences of adjacent <dt>s or <dd>s being incorrectly
281         // interpreted as parent->child trees instead of siblings:
282         //
283         // When parsing this input: "<dt>aaa <dt>bbb"
284         // should be equivalent to: "<dt>aaa </dt><dt>bbb</dt>"
285         // but we're seeing instead: "<dt>aaa <dt>bbb</dt></dt>"
286         //
287         // It does at least know that going from dt to dd, or dd to dt,
288         // should make a break.
289
290         $toMove = array();
291
292         foreach ($item->childNodes as $node) {
293             if ($node->nodeType == XML_ELEMENT_NODE) {
294                 $el = strtolower($node->nodeName);
295                 if ($el == 'dt' || $el == 'dd') {
296                     // dt & dd cannot contain each other;
297                     // This node was incorrectly placed; move it up a level!
298                     $toMove[] = $node;
299                 }
300                 if ($el == 'dl') {
301                     // Sublist.
302                     // Technically, these can only appear inside a <dd>.
303                     $this->fixList($node);
304                 }
305             }
306         }
307
308         $parent = $item->parentNode;
309         $next = $item->nextSibling;
310         foreach ($toMove as $node) {
311             $item->removeChild($node);
312             $parent->insertBefore($node, $next);
313             $this->fixListItem($node);
314         }
315     }
316 }