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