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