]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
0efb07cbbcb3d1c67d194d30ea2a2192cfeb98e7
[friendica.git] / src / Protocol / DFRN.php
1 <?php
2 namespace Friendica\Protocol;
3 /**
4  * @file include/dfrn.php
5  * @brief The implementation of the dfrn protocol
6  *
7  * @see https://github.com/friendica/friendica/wiki/Protocol and
8  * https://github.com/friendica/friendica/blob/master/spec/dfrn2.pdf
9  */
10
11 use Friendica\App;
12 use Friendica\Core\Config;
13 use Friendica\Core\System;
14 use Friendica\Core\Worker;
15 use Friendica\Database\DBM;
16
17 use dba;
18 use DOMDocument;
19 use DomXPath;
20
21 require_once("include/Contact.php");
22 require_once("include/ostatus.php");
23 require_once("include/enotify.php");
24 require_once("include/threads.php");
25 require_once("include/socgraph.php");
26 require_once("include/items.php");
27 require_once("include/tags.php");
28 require_once("include/files.php");
29 require_once("include/event.php");
30 require_once("include/text.php");
31 require_once("include/oembed.php");
32 require_once("include/html2bbcode.php");
33 require_once("include/bbcode.php");
34 require_once("include/xml.php");
35
36 /**
37  * @brief This class contain functions to create and send DFRN XML files
38  *
39  */
40 class DFRN {
41
42         const DFRN_TOP_LEVEL = 0;       // Top level posting
43         const DFRN_REPLY = 1;           // Regular reply that is stored locally
44         const DFRN_REPLY_RC = 2;        // Reply that will be relayed
45
46         /**
47          * @brief Generates the atom entries for delivery.php
48          *
49          * This function is used whenever content is transmitted via DFRN.
50          *
51          * @param array $items Item elements
52          * @param array $owner Owner record
53          *
54          * @return string DFRN entries
55          * @todo Add type-hints
56          */
57         public static function entries($items,$owner) {
58
59                 $doc = new DOMDocument('1.0', 'utf-8');
60                 $doc->formatOutput = true;
61
62                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
63
64                 if (! count($items)) {
65                         return trim($doc->saveXML());
66                 }
67
68                 foreach ($items as $item) {
69                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
70                         $root->appendChild($entry);
71                 }
72
73                 return(trim($doc->saveXML()));
74         }
75
76         /**
77          * @brief Generate an atom feed for the given user
78          *
79          * This function is called when another server is pulling data from the user feed.
80          *
81          * @param string $dfrn_id DFRN ID from the requesting party
82          * @param string $owner_nick Owner nick name
83          * @param string $last_update Date of the last update
84          * @param int $direction Can be -1, 0 or 1.
85          * @param boolean $onlyheader Output only the header without content? (Default is "no")
86          *
87          * @return string DFRN feed entries
88          */
89         public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false) {
90
91                 $a = get_app();
92
93                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
94                 $public_feed = (($dfrn_id) ? false : true);
95                 $starred     = false;   // not yet implemented, possible security issues
96                 $converse    = false;
97
98                 if ($public_feed && $a->argc > 2) {
99                         for ($x = 2; $x < $a->argc; $x++) {
100                                 if ($a->argv[$x] == 'converse') {
101                                         $converse = true;
102                                 }
103                                 if ($a->argv[$x] == 'starred') {
104                                         $starred = true;
105                                 }
106                                 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
107                                         $category = $a->argv[$x+1];
108                                 }
109                         }
110                 }
111
112
113
114                 // default permissions - anonymous user
115
116                 $sql_extra = " AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' ";
117
118                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
119                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
120                         WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
121                         dbesc($owner_nick)
122                 );
123
124                 if (! DBM::is_result($r)) {
125                         killme();
126                 }
127
128                 $owner = $r[0];
129                 $owner_id = $owner['uid'];
130                 $owner_nick = $owner['nickname'];
131
132                 $sql_post_table = "";
133
134                 if (! $public_feed) {
135
136                         $sql_extra = '';
137                         switch($direction) {
138                                 case (-1):
139                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", dbesc($dfrn_id));
140                                         $my_id = $dfrn_id;
141                                         break;
142                                 case 0:
143                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
144                                         $my_id = '1:' . $dfrn_id;
145                                         break;
146                                 case 1:
147                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", dbesc($dfrn_id));
148                                         $my_id = '0:' . $dfrn_id;
149                                         break;
150                                 default:
151                                         return false;
152                                         break; // NOTREACHED
153                         }
154
155                         $r = q("SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
156                                 intval($owner_id)
157                         );
158
159                         if (! DBM::is_result($r)) {
160                                 killme();
161                         }
162
163                         $contact = $r[0];
164                         require_once('include/security.php');
165                         $groups = init_groups_visitor($contact['id']);
166
167                         if (count($groups)) {
168                                 for ($x = 0; $x < count($groups); $x ++)
169                                         $groups[$x] = '<' . intval($groups[$x]) . '>' ;
170                                 $gs = implode('|', $groups);
171                         } else {
172                                 $gs = '<<>>' ; // Impossible to match
173                         }
174
175                         $sql_extra = sprintf("
176                                 AND ( `allow_cid` = '' OR     `allow_cid` REGEXP '<%d>' )
177                                 AND ( `deny_cid`  = '' OR NOT `deny_cid`  REGEXP '<%d>' )
178                                 AND ( `allow_gid` = '' OR     `allow_gid` REGEXP '%s' )
179                                 AND ( `deny_gid`  = '' OR NOT `deny_gid`  REGEXP '%s')
180                         ",
181                                 intval($contact['id']),
182                                 intval($contact['id']),
183                                 dbesc($gs),
184                                 dbesc($gs)
185                         );
186                 }
187
188                 if ($public_feed) {
189                         $sort = 'DESC';
190                 } else {
191                         $sort = 'ASC';
192                 }
193
194                 if (! strlen($last_update)) {
195                         $last_update = 'now -30 days';
196                 }
197
198                 if (isset($category)) {
199                         $sql_post_table = sprintf("INNER JOIN (SELECT `oid` FROM `term` WHERE `term` = '%s' AND `otype` = %d AND `type` = %d AND `uid` = %d ORDER BY `tid` DESC) AS `term` ON `item`.`id` = `term`.`oid` ",
200                                         dbesc(protect_sprintf($category)), intval(TERM_OBJ_POST), intval(TERM_CATEGORY), intval($owner_id));
201                         //$sql_extra .= file_tag_file_query('item',$category,'category');
202                 }
203
204                 if ($public_feed) {
205                         if (! $converse) {
206                                 $sql_extra .= " AND `contact`.`self` = 1 ";
207                         }
208                 }
209
210                 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
211
212                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
213                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
214                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
215                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
216                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
217                         FROM `item` USE INDEX (`uid_wall_changed`) $sql_post_table
218                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
219                         AND (NOT `contact`.`blocked` OR `contact`.`pending`)
220                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
221                         WHERE `item`.`uid` = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
222                         AND `item`.`wall` AND `item`.`changed` > '%s'
223                         $sql_extra
224                         ORDER BY `item`.`parent` ".$sort.", `item`.`created` ASC LIMIT 0, 300",
225                         intval($owner_id),
226                         dbesc($check_date),
227                         dbesc($sort)
228                 );
229
230                 /*
231                  * Will check further below if this actually returned results.
232                  * We will provide an empty feed if that is the case.
233                  */
234
235                 $items = $r;
236
237                 $doc = new DOMDocument('1.0', 'utf-8');
238                 $doc->formatOutput = true;
239
240                 $alternatelink = $owner['url'];
241
242                 if (isset($category)) {
243                         $alternatelink .= "/category/".$category;
244                 }
245
246                 if ($public_feed) {
247                         $author = "dfrn:owner";
248                 } else {
249                         $author = "author";
250                 }
251
252                 $root = self::add_header($doc, $owner, $author, $alternatelink, true);
253
254                 /// @TODO This hook can't work anymore
255                 //      call_hooks('atom_feed', $atom);
256
257                 if (!DBM::is_result($items) || $onlyheader) {
258                         $atom = trim($doc->saveXML());
259
260                         call_hooks('atom_feed_end', $atom);
261
262                         return $atom;
263                 }
264
265                 foreach ($items as $item) {
266
267                         // prevent private email from leaking.
268                         if ($item['network'] == NETWORK_MAIL) {
269                                 continue;
270                         }
271
272                         // public feeds get html, our own nodes use bbcode
273
274                         if ($public_feed) {
275                                 $type = 'html';
276                                 // catch any email that's in a public conversation and make sure it doesn't leak
277                                 if ($item['private']) {
278                                         continue;
279                                 }
280                         } else {
281                                 $type = 'text';
282                         }
283
284                         $entry = self::entry($doc, $type, $item, $owner, true);
285                         $root->appendChild($entry);
286
287                 }
288
289                 $atom = trim($doc->saveXML());
290
291                 call_hooks('atom_feed_end', $atom);
292
293                 return $atom;
294         }
295
296         /**
297          * @brief Generate an atom entry for a given item id
298          *
299          * @param int $item_id The item id
300          * @param boolean $conversation Show the conversation. If false show the single post.
301          *
302          * @return string DFRN feed entry
303          */
304         public static function itemFeed($item_id, $conversation = false) {
305                 if ($conversation) {
306                         $condition = '`item`.`parent`';
307                 } else {
308                         $condition = '`item`.`id`';
309                 }
310
311                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
312                         `contact`.`name`, `contact`.`network`, `contact`.`photo`, `contact`.`url`,
313                         `contact`.`name-date`, `contact`.`uri-date`, `contact`.`avatar-date`,
314                         `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
315                         `sign`.`signed_text`, `sign`.`signature`, `sign`.`signer`
316                         FROM `item`
317                         STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
318                                 AND (NOT `contact`.`blocked` OR `contact`.`pending`)
319                         LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id`
320                         WHERE %s = %d AND `item`.`visible` AND NOT `item`.`moderated` AND `item`.`parent` != 0
321                         AND NOT `item`.`private`",
322                         $condition,
323                         intval($item_id)
324                 );
325
326                 if (!DBM::is_result($r)) {
327                         killme();
328                 }
329
330                 $items = $r;
331                 $item = $r[0];
332
333                 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
334                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
335                         WHERE `contact`.`self` AND `user`.`uid` = %d LIMIT 1",
336                         intval($item['uid'])
337                 );
338
339                 if (!DBM::is_result($r)) {
340                         killme();
341                 }
342
343                 $owner = $r[0];
344
345                 $doc = new DOMDocument('1.0', 'utf-8');
346                 $doc->formatOutput = true;
347                 $type = 'html';
348
349                 if ($conversation) {
350                         $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
351                         $doc->appendChild($root);
352
353                         $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
354                         $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
355                         $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
356                         $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
357                         $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
358                         $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
359                         $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
360                         $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
361                         $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
362
363                         //$root = self::add_header($doc, $owner, "dfrn:owner", "", false);
364
365                         foreach ($items as $item) {
366                                 $entry = self::entry($doc, $type, $item, $owner, true, 0);
367                                 $root->appendChild($entry);
368                         }
369                 } else {
370                         $root = self::entry($doc, $type, $item, $owner, true, 0, true);
371                 }
372
373                 $atom = trim($doc->saveXML());
374                 return $atom;
375         }
376
377         /**
378          * @brief Create XML text for DFRN mails
379          *
380          * @param array $item message elements
381          * @param array $owner Owner record
382          *
383          * @return string DFRN mail
384          * @todo Add type-hints
385          */
386         public static function mail($item, $owner) {
387                 $doc = new DOMDocument('1.0', 'utf-8');
388                 $doc->formatOutput = true;
389
390                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
391
392                 $mail = $doc->createElement("dfrn:mail");
393                 $sender = $doc->createElement("dfrn:sender");
394
395                 xml::add_element($doc, $sender, "dfrn:name", $owner['name']);
396                 xml::add_element($doc, $sender, "dfrn:uri", $owner['url']);
397                 xml::add_element($doc, $sender, "dfrn:avatar", $owner['thumb']);
398
399                 $mail->appendChild($sender);
400
401                 xml::add_element($doc, $mail, "dfrn:id", $item['uri']);
402                 xml::add_element($doc, $mail, "dfrn:in-reply-to", $item['parent-uri']);
403                 xml::add_element($doc, $mail, "dfrn:sentdate", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME));
404                 xml::add_element($doc, $mail, "dfrn:subject", $item['title']);
405                 xml::add_element($doc, $mail, "dfrn:content", $item['body']);
406
407                 $root->appendChild($mail);
408
409                 return(trim($doc->saveXML()));
410         }
411
412         /**
413          * @brief Create XML text for DFRN friend suggestions
414          *
415          * @param array $item suggestion elements
416          * @param array $owner Owner record
417          *
418          * @return string DFRN suggestions
419          * @todo Add type-hints
420          */
421         public static function fsuggest($item, $owner) {
422                 $doc = new DOMDocument('1.0', 'utf-8');
423                 $doc->formatOutput = true;
424
425                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
426
427                 $suggest = $doc->createElement("dfrn:suggest");
428
429                 xml::add_element($doc, $suggest, "dfrn:url", $item['url']);
430                 xml::add_element($doc, $suggest, "dfrn:name", $item['name']);
431                 xml::add_element($doc, $suggest, "dfrn:photo", $item['photo']);
432                 xml::add_element($doc, $suggest, "dfrn:request", $item['request']);
433                 xml::add_element($doc, $suggest, "dfrn:note", $item['note']);
434
435                 $root->appendChild($suggest);
436
437                 return(trim($doc->saveXML()));
438         }
439
440         /**
441          * @brief Create XML text for DFRN relocations
442          *
443          * @param array $owner Owner record
444          * @param int $uid User ID
445          *
446          * @return string DFRN relocations
447          * @todo Add type-hints
448          */
449         public static function relocate($owner, $uid) {
450
451                 /* get site pubkey. this could be a new installation with no site keys*/
452                 $pubkey = Config::get('system','site_pubkey');
453                 if (! $pubkey) {
454                         $res = new_keypair(1024);
455                         Config::set('system','site_prvkey', $res['prvkey']);
456                         Config::set('system','site_pubkey', $res['pubkey']);
457                 }
458
459                 $rp = q("SELECT `resource-id` , `scale`, type FROM `photo`
460                                 WHERE `profile` = 1 AND `uid` = %d ORDER BY scale;", $uid);
461                 $photos = array();
462                 $ext = Photo::supportedTypes();
463
464                 foreach ($rp as $p) {
465                         $photos[$p['scale']] = System::baseUrl().'/photo/'.$p['resource-id'].'-'.$p['scale'].'.'.$ext[$p['type']];
466                 }
467
468                 unset($rp, $ext);
469
470                 $doc = new DOMDocument('1.0', 'utf-8');
471                 $doc->formatOutput = true;
472
473                 $root = self::add_header($doc, $owner, "dfrn:owner", "", false);
474
475                 $relocate = $doc->createElement("dfrn:relocate");
476
477                 xml::add_element($doc, $relocate, "dfrn:url", $owner['url']);
478                 xml::add_element($doc, $relocate, "dfrn:name", $owner['name']);
479                 xml::add_element($doc, $relocate, "dfrn:addr", $owner['addr']);
480                 xml::add_element($doc, $relocate, "dfrn:avatar", $owner['avatar']);
481                 xml::add_element($doc, $relocate, "dfrn:photo", $photos[4]);
482                 xml::add_element($doc, $relocate, "dfrn:thumb", $photos[5]);
483                 xml::add_element($doc, $relocate, "dfrn:micro", $photos[6]);
484                 xml::add_element($doc, $relocate, "dfrn:request", $owner['request']);
485                 xml::add_element($doc, $relocate, "dfrn:confirm", $owner['confirm']);
486                 xml::add_element($doc, $relocate, "dfrn:notify", $owner['notify']);
487                 xml::add_element($doc, $relocate, "dfrn:poll", $owner['poll']);
488                 xml::add_element($doc, $relocate, "dfrn:sitepubkey", Config::get('system','site_pubkey'));
489
490                 $root->appendChild($relocate);
491
492                 return(trim($doc->saveXML()));
493         }
494
495         /**
496          * @brief Adds the header elements for the DFRN protocol
497          *
498          * @param object $doc XML document
499          * @param array $owner Owner record
500          * @param string $authorelement Element name for the author
501          * @param string $alternatelink link to profile or category
502          * @param bool $public Is it a header for public posts?
503          *
504          * @return object XML root object
505          * @todo Add type-hints
506          */
507         private static function add_header($doc, $owner, $authorelement, $alternatelink = "", $public = false) {
508
509                 if ($alternatelink == "") {
510                         $alternatelink = $owner['url'];
511                 }
512
513                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
514                 $doc->appendChild($root);
515
516                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
517                 $root->setAttribute("xmlns:at", NAMESPACE_TOMB);
518                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
519                 $root->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
520                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
521                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
522                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
523                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
524                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
525
526                 xml::add_element($doc, $root, "id", System::baseUrl()."/profile/".$owner["nick"]);
527                 xml::add_element($doc, $root, "title", $owner["name"]);
528
529                 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
530                 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
531
532                 $attributes = array("rel" => "license", "href" => "http://creativecommons.org/licenses/by/3.0/");
533                 xml::add_element($doc, $root, "link", "", $attributes);
534
535                 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $alternatelink);
536                 xml::add_element($doc, $root, "link", "", $attributes);
537
538
539                 if ($public) {
540                         // DFRN itself doesn't uses this. But maybe someone else wants to subscribe to the public feed.
541                         ostatus::hublinks($doc, $root, $owner["nick"]);
542
543                         $attributes = array("rel" => "salmon", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
544                         xml::add_element($doc, $root, "link", "", $attributes);
545
546                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-replies", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
547                         xml::add_element($doc, $root, "link", "", $attributes);
548
549                         $attributes = array("rel" => "http://salmon-protocol.org/ns/salmon-mention", "href" => System::baseUrl()."/salmon/".$owner["nick"]);
550                         xml::add_element($doc, $root, "link", "", $attributes);
551                 }
552
553                 // For backward compatibility we keep this element
554                 if ($owner['page-flags'] == PAGE_COMMUNITY) {
555                         xml::add_element($doc, $root, "dfrn:community", 1);
556                 }
557
558                 // The former element is replaced by this one
559                 xml::add_element($doc, $root, "dfrn:account_type", $owner["account-type"]);
560
561                 /// @todo We need a way to transmit the different page flags like "PAGE_PRVGROUP"
562
563                 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
564
565                 $author = self::add_author($doc, $owner, $authorelement, $public);
566                 $root->appendChild($author);
567
568                 return $root;
569         }
570
571         /**
572          * @brief Adds the author element in the header for the DFRN protocol
573          *
574          * @param object $doc XML document
575          * @param array $owner Owner record
576          * @param string $authorelement Element name for the author
577          *
578          * @return object XML author object
579          * @todo Add type-hints
580          */
581         private static function add_author($doc, $owner, $authorelement, $public) {
582
583                 // Is the profile hidden or shouldn't be published in the net? Then add the "hide" element
584                 $r = q("SELECT `id` FROM `profile` INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
585                                 WHERE (`hidewall` OR NOT `net-publish`) AND `user`.`uid` = %d",
586                         intval($owner['uid']));
587                 if (DBM::is_result($r)) {
588                         $hidewall = true;
589                 } else {
590                         $hidewall = false;
591                 }
592
593                 $author = $doc->createElement($authorelement);
594
595                 $namdate = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
596                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
597                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
598
599                 $attributes = array();
600
601                 if (!$public || !$hidewall) {
602                         $attributes = array("dfrn:updated" => $namdate);
603                 }
604
605                 xml::add_element($doc, $author, "name", $owner["name"], $attributes);
606                 xml::add_element($doc, $author, "uri", System::baseUrl().'/profile/'.$owner["nickname"], $attributes);
607                 xml::add_element($doc, $author, "dfrn:handle", $owner["addr"], $attributes);
608
609                 $attributes = array("rel" => "photo", "type" => "image/jpeg",
610                                         "media:width" => 175, "media:height" => 175, "href" => $owner['photo']);
611
612                 if (!$public || !$hidewall) {
613                         $attributes["dfrn:updated"] = $picdate;
614                 }
615
616                 xml::add_element($doc, $author, "link", "", $attributes);
617
618                 $attributes["rel"] = "avatar";
619                 xml::add_element($doc, $author, "link", "", $attributes);
620
621                 if ($hidewall) {
622                         xml::add_element($doc, $author, "dfrn:hide", "true");
623                 }
624
625                 // The following fields will only be generated if the data isn't meant for a public feed
626                 if ($public) {
627                         return $author;
628                 }
629
630                 $birthday = feed_birthday($owner['uid'], $owner['timezone']);
631
632                 if ($birthday)
633                         xml::add_element($doc, $author, "dfrn:birthday", $birthday);
634
635                 // Only show contact details when we are allowed to
636                 $r = q("SELECT `profile`.`about`, `profile`.`name`, `profile`.`homepage`, `user`.`nickname`,
637                                 `user`.`timezone`, `profile`.`locality`, `profile`.`region`, `profile`.`country-name`,
638                                 `profile`.`pub_keywords`, `profile`.`xmpp`, `profile`.`dob`
639                         FROM `profile`
640                                 INNER JOIN `user` ON `user`.`uid` = `profile`.`uid`
641                                 WHERE `profile`.`is-default` AND NOT `user`.`hidewall` AND `user`.`uid` = %d",
642                         intval($owner['uid']));
643                 if (DBM::is_result($r)) {
644                         $profile = $r[0];
645
646                         xml::add_element($doc, $author, "poco:displayName", $profile["name"]);
647                         xml::add_element($doc, $author, "poco:updated", $namdate);
648
649                         if (trim($profile["dob"]) > '0001-01-01') {
650                                 xml::add_element($doc, $author, "poco:birthday", "0000-".date("m-d", strtotime($profile["dob"])));
651                         }
652
653                         xml::add_element($doc, $author, "poco:note", $profile["about"]);
654                         xml::add_element($doc, $author, "poco:preferredUsername", $profile["nickname"]);
655
656                         $savetz = date_default_timezone_get();
657                         date_default_timezone_set($profile["timezone"]);
658                         xml::add_element($doc, $author, "poco:utcOffset", date("P"));
659                         date_default_timezone_set($savetz);
660
661                         if (trim($profile["homepage"]) != "") {
662                                 $urls = $doc->createElement("poco:urls");
663                                 xml::add_element($doc, $urls, "poco:type", "homepage");
664                                 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
665                                 xml::add_element($doc, $urls, "poco:primary", "true");
666                                 $author->appendChild($urls);
667                         }
668
669                         if (trim($profile["pub_keywords"]) != "") {
670                                 $keywords = explode(",", $profile["pub_keywords"]);
671
672                                 foreach ($keywords AS $keyword) {
673                                         xml::add_element($doc, $author, "poco:tags", trim($keyword));
674                                 }
675
676                         }
677
678                         if (trim($profile["xmpp"]) != "") {
679                                 $ims = $doc->createElement("poco:ims");
680                                 xml::add_element($doc, $ims, "poco:type", "xmpp");
681                                 xml::add_element($doc, $ims, "poco:value", $profile["xmpp"]);
682                                 xml::add_element($doc, $ims, "poco:primary", "true");
683                                 $author->appendChild($ims);
684                         }
685
686                         if (trim($profile["locality"].$profile["region"].$profile["country-name"]) != "") {
687                                 $element = $doc->createElement("poco:address");
688
689                                 xml::add_element($doc, $element, "poco:formatted", formatted_location($profile));
690
691                                 if (trim($profile["locality"]) != "") {
692                                         xml::add_element($doc, $element, "poco:locality", $profile["locality"]);
693                                 }
694
695                                 if (trim($profile["region"]) != "") {
696                                         xml::add_element($doc, $element, "poco:region", $profile["region"]);
697                                 }
698
699                                 if (trim($profile["country-name"]) != "") {
700                                         xml::add_element($doc, $element, "poco:country", $profile["country-name"]);
701                                 }
702
703                                 $author->appendChild($element);
704                         }
705                 }
706
707                 return $author;
708         }
709
710         /**
711          * @brief Adds the author elements in the "entry" elements of the DFRN protocol
712          *
713          * @param object $doc XML document
714          * @param string $element Element name for the author
715          * @param string $contact_url Link of the contact
716          * @param array $items Item elements
717          *
718          * @return object XML author object
719          * @todo Add type-hints
720          */
721         private static function add_entry_author($doc, $element, $contact_url, $item) {
722
723                 $contact = get_contact_details_by_url($contact_url, $item["uid"]);
724
725                 $author = $doc->createElement($element);
726                 xml::add_element($doc, $author, "name", $contact["name"]);
727                 xml::add_element($doc, $author, "uri", $contact["url"]);
728                 xml::add_element($doc, $author, "dfrn:handle", $contact["addr"]);
729
730                 /// @Todo
731                 /// - Check real image type and image size
732                 /// - Check which of these boths elements we should use
733                 $attributes = array(
734                                 "rel" => "photo",
735                                 "type" => "image/jpeg",
736                                 "media:width" => 80,
737                                 "media:height" => 80,
738                                 "href" => $contact["photo"]);
739                 xml::add_element($doc, $author, "link", "", $attributes);
740
741                 $attributes = array(
742                                 "rel" => "avatar",
743                                 "type" => "image/jpeg",
744                                 "media:width" => 80,
745                                 "media:height" => 80,
746                                 "href" => $contact["photo"]);
747                 xml::add_element($doc, $author, "link", "", $attributes);
748
749                 return $author;
750         }
751
752         /**
753          * @brief Adds the activity elements
754          *
755          * @param object $doc XML document
756          * @param string $element Element name for the activity
757          * @param string $activity activity value
758          *
759          * @return object XML activity object
760          * @todo Add type-hints
761          */
762         private static function create_activity($doc, $element, $activity) {
763
764                 if ($activity) {
765                         $entry = $doc->createElement($element);
766
767                         $r = parse_xml_string($activity, false);
768                         if (!$r) {
769                                 return false;
770                         }
771                         if ($r->type) {
772                                 xml::add_element($doc, $entry, "activity:object-type", $r->type);
773                         }
774                         if ($r->id) {
775                                 xml::add_element($doc, $entry, "id", $r->id);
776                         }
777                         if ($r->title) {
778                                 xml::add_element($doc, $entry, "title", $r->title);
779                         }
780
781                         if ($r->link) {
782                                 if (substr($r->link, 0, 1) == '<') {
783                                         if (strstr($r->link, '&') && (! strstr($r->link, '&amp;'))) {
784                                                 $r->link = str_replace('&', '&amp;', $r->link);
785                                         }
786
787                                         $r->link = preg_replace('/\<link(.*?)\"\>/', '<link$1"/>', $r->link);
788
789                                         // XML does need a single element as root element so we add a dummy element here
790                                         $data = parse_xml_string("<dummy>" . $r->link . "</dummy>", false);
791                                         if (is_object($data)) {
792                                                 foreach ($data->link AS $link) {
793                                                         $attributes = array();
794                                                         foreach ($link->attributes() AS $parameter => $value) {
795                                                                 $attributes[$parameter] = $value;
796                                                         }
797                                                         xml::add_element($doc, $entry, "link", "", $attributes);
798                                                 }
799                                         }
800                                 } else {
801                                         $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $r->link);
802                                         xml::add_element($doc, $entry, "link", "", $attributes);
803                                 }
804                         }
805                         if ($r->content) {
806                                 xml::add_element($doc, $entry, "content", bbcode($r->content), array("type" => "html"));
807                         }
808
809                         return $entry;
810                 }
811
812                 return false;
813         }
814
815         /**
816          * @brief Adds the elements for attachments
817          *
818          * @param object $doc XML document
819          * @param object $root XML root
820          * @param array $item Item element
821          *
822          * @return object XML attachment object
823          * @todo Add type-hints
824          */
825         private static function get_attachment($doc, $root, $item) {
826                 $arr = explode('[/attach],',$item['attach']);
827                 if (count($arr)) {
828                         foreach ($arr as $r) {
829                                 $matches = false;
830                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|',$r,$matches);
831                                 if ($cnt) {
832                                         $attributes = array("rel" => "enclosure",
833                                                         "href" => $matches[1],
834                                                         "type" => $matches[3]);
835
836                                         if (intval($matches[2])) {
837                                                 $attributes["length"] = intval($matches[2]);
838                                         }
839
840                                         if (trim($matches[4]) != "") {
841                                                 $attributes["title"] = trim($matches[4]);
842                                         }
843
844                                         xml::add_element($doc, $root, "link", "", $attributes);
845                                 }
846                         }
847                 }
848         }
849
850         /**
851          * @brief Adds the "entry" elements for the DFRN protocol
852          *
853          * @param object $doc XML document
854          * @param string $type "text" or "html"
855          * @param array $item Item element
856          * @param array $owner Owner record
857          * @param bool $comment Trigger the sending of the "comment" element
858          * @param int $cid Contact ID of the recipient
859          * @param bool $single If set, the entry is created as an XML document with a single "entry" element
860          *
861          * @return object XML entry object
862          * @todo Add type-hints
863          */
864         private static function entry($doc, $type, $item, $owner, $comment = false, $cid = 0, $single = false) {
865
866                 $mentioned = array();
867
868                 if (!$item['parent']) {
869                         return;
870                 }
871
872                 if ($item['deleted']) {
873                         $attributes = array("ref" => $item['uri'], "when" => datetime_convert('UTC','UTC',$item['edited'] . '+00:00',ATOM_TIME));
874                         return xml::create_element($doc, "at:deleted-entry", "", $attributes);
875                 }
876
877                 if (!$single) {
878                         $entry = $doc->createElement("entry");
879                 } else {
880                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, 'entry');
881                         $doc->appendChild($entry);
882
883                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
884                         $entry->setAttribute("xmlns:at", NAMESPACE_TOMB);
885                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
886                         $entry->setAttribute("xmlns:dfrn", NAMESPACE_DFRN);
887                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
888                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
889                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
890                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
891                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
892                 }
893
894                 if ($item['allow_cid'] || $item['allow_gid'] || $item['deny_cid'] || $item['deny_gid']) {
895                         $body = fix_private_photos($item['body'],$owner['uid'],$item,$cid);
896                 } else {
897                         $body = $item['body'];
898                 }
899
900                 // Remove the abstract element. It is only locally important.
901                 $body = remove_abstract($body);
902
903                 if ($type == 'html') {
904                         $htmlbody = $body;
905
906                         if ($item['title'] != "") {
907                                 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
908                         }
909
910                         $htmlbody = bbcode($htmlbody, false, false, 7);
911                 }
912
913                 $author = self::add_entry_author($doc, "author", $item["author-link"], $item);
914                 $entry->appendChild($author);
915
916                 $dfrnowner = self::add_entry_author($doc, "dfrn:owner", $item["owner-link"], $item);
917                 $entry->appendChild($dfrnowner);
918
919                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
920                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
921                         $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
922                         $attributes = array("ref" => $parent_item, "type" => "text/html",
923                                                 "href" => $parent[0]['plink'],
924                                                 "dfrn:diaspora_guid" => $parent[0]['guid']);
925                         xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
926                 }
927
928                 // Add conversation data. This is used for OStatus
929                 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
930                 $conversation_uri = $conversation_href;
931
932                 if (isset($parent_item)) {
933                         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
934                         if (DBM::is_result($r)) {
935                                 if ($r['conversation-uri'] != '') {
936                                         $conversation_uri = $r['conversation-uri'];
937                                 }
938                                 if ($r['conversation-href'] != '') {
939                                         $conversation_href = $r['conversation-href'];
940                                 }
941                         }
942                 }
943
944                 $attributes = array(
945                                 "href" => $conversation_href,
946                                 "ref" => $conversation_uri);
947
948                 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
949
950                 xml::add_element($doc, $entry, "id", $item["uri"]);
951                 xml::add_element($doc, $entry, "title", $item["title"]);
952
953                 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
954                 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
955
956                 // "dfrn:env" is used to read the content
957                 xml::add_element($doc, $entry, "dfrn:env", base64url_encode($body, true));
958
959                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
960                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
961                 xml::add_element($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), array("type" => $type));
962
963                 // We save this value in "plink". Maybe we should read it from there as well?
964                 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
965                                                                 "href" => System::baseUrl()."/display/".$item["guid"]));
966
967                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
968                 // It is included in the rewritten code for completeness
969                 if ($comment) {
970                         xml::add_element($doc, $entry, "dfrn:comment-allow", intval($item['last-child']));
971                 }
972
973                 if ($item['location']) {
974                         xml::add_element($doc, $entry, "dfrn:location", $item['location']);
975                 }
976
977                 if ($item['coord']) {
978                         xml::add_element($doc, $entry, "georss:point", $item['coord']);
979                 }
980
981                 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
982                         xml::add_element($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
983                 }
984
985                 if ($item['extid']) {
986                         xml::add_element($doc, $entry, "dfrn:extid", $item['extid']);
987                 }
988
989                 if ($item['bookmark']) {
990                         xml::add_element($doc, $entry, "dfrn:bookmark", "true");
991                 }
992
993                 if ($item['app']) {
994                         xml::add_element($doc, $entry, "statusnet:notice_info", "", array("local_id" => $item['id'], "source" => $item['app']));
995                 }
996
997                 xml::add_element($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
998
999                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1000                 // It is needed for relayed comments to Diaspora.
1001                 if ($item['signed_text']) {
1002                         $sign = base64_encode(json_encode(array('signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer'])));
1003                         xml::add_element($doc, $entry, "dfrn:diaspora_signature", $sign);
1004                 }
1005
1006                 xml::add_element($doc, $entry, "activity:verb", construct_verb($item));
1007
1008                 if ($item['object-type'] != "") {
1009                         xml::add_element($doc, $entry, "activity:object-type", $item['object-type']);
1010                 } elseif ($item['id'] == $item['parent']) {
1011                         xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1012                 } else {
1013                         xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1014                 }
1015
1016                 $actobj = self::create_activity($doc, "activity:object", $item['object']);
1017                 if ($actobj) {
1018                         $entry->appendChild($actobj);
1019                 }
1020
1021                 $actarg = self::create_activity($doc, "activity:target", $item['target']);
1022                 if ($actarg) {
1023                         $entry->appendChild($actarg);
1024                 }
1025
1026                 $tags = item_getfeedtags($item);
1027
1028                 if (count($tags)) {
1029                         foreach ($tags as $t) {
1030                                 if (($type != 'html') || ($t[0] != "@")) {
1031                                         xml::add_element($doc, $entry, "category", "", array("scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]));
1032                                 }
1033                         }
1034                 }
1035
1036                 if (count($tags)) {
1037                         foreach ($tags as $t) {
1038                                 if ($t[0] == "@") {
1039                                         $mentioned[$t[1]] = $t[1];
1040                                 }
1041                         }
1042                 }
1043
1044                 foreach ($mentioned AS $mention) {
1045                         $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1046                                 intval($owner["uid"]),
1047                                 dbesc(normalise_link($mention)));
1048
1049                         if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1050                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1051                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1052                                                                                         "href" => $mention));
1053                         } else {
1054                                 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
1055                                                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1056                                                                                         "href" => $mention));
1057                         }
1058                 }
1059
1060                 self::get_attachment($doc, $entry, $item);
1061
1062                 return $entry;
1063         }
1064
1065         /**
1066          * @brief encrypts data via AES
1067          *
1068          * @param string $data The data that is to be encrypted
1069          * @param string $key The AES key
1070          *
1071          * @return string encrypted data
1072          */
1073         private static function aes_encrypt($data, $key) {
1074                 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1075         }
1076
1077         /**
1078          * @brief decrypts data via AES
1079          *
1080          * @param string $encrypted The encrypted data
1081          * @param string $key The AES key
1082          *
1083          * @return string decrypted data
1084          */
1085         public static function aes_decrypt($encrypted, $key) {
1086                 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1087         }
1088
1089         /**
1090          * @brief Delivers the atom content to the contacts
1091          *
1092          * @param array $owner Owner record
1093          * @param array $contactr Contact record of the receiver
1094          * @param string $atom Content that will be transmitted
1095          * @param bool $dissolve (to be documented)
1096          *
1097          * @return int Deliver status. -1 means an error.
1098          * @todo Add array type-hint for $owner, $contact
1099          */
1100         public static function deliver($owner,$contact,$atom, $dissolve = false) {
1101
1102                 $a = get_app();
1103
1104                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1105
1106                 if ($contact['duplex'] && $contact['dfrn-id']) {
1107                         $idtosend = '0:' . $orig_id;
1108                 }
1109                 if ($contact['duplex'] && $contact['issued-id']) {
1110                         $idtosend = '1:' . $orig_id;
1111                 }
1112
1113                 $rino = Config::get('system', 'rino_encrypt');
1114                 $rino = intval($rino);
1115
1116                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1117
1118                 $ssl_val = intval(Config::get('system','ssl_policy'));
1119                 $ssl_policy = '';
1120
1121                 switch ($ssl_val) {
1122                         case SSL_POLICY_FULL:
1123                                 $ssl_policy = 'full';
1124                                 break;
1125                         case SSL_POLICY_SELFSIGN:
1126                                 $ssl_policy = 'self';
1127                                 break;
1128                         case SSL_POLICY_NONE:
1129                         default:
1130                                 $ssl_policy = 'none';
1131                                 break;
1132                 }
1133
1134                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1135
1136                 logger('dfrn_deliver: ' . $url);
1137
1138                 $ret = z_fetch_url($url);
1139
1140                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1141                         return -2; // timed out
1142                 }
1143
1144                 $xml = $ret['body'];
1145
1146                 $curl_stat = $a->get_curl_code();
1147                 if (!$curl_stat) {
1148                         return -3; // timed out
1149                 }
1150
1151                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1152
1153                 if (! $xml) {
1154                         return 3;
1155                 }
1156
1157                 if (strpos($xml,'<?xml') === false) {
1158                         logger('dfrn_deliver: no valid XML returned');
1159                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1160                         return 3;
1161                 }
1162
1163                 $res = parse_xml_string($xml);
1164
1165                 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1166                         return (($res->status) ? $res->status : 3);
1167                 }
1168
1169                 $postvars     = array();
1170                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1171                 $challenge    = hex2bin((string) $res->challenge);
1172                 $perm         = (($res->perm) ? $res->perm : null);
1173                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1174                 $rino_remote_version = intval($res->rino);
1175                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1176
1177                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1178
1179                 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1180                         $page = 2;
1181                 }
1182
1183                 $final_dfrn_id = '';
1184
1185                 if ($perm) {
1186                         if ((($perm == 'rw') && (! intval($contact['writable'])))
1187                                 || (($perm == 'r') && (intval($contact['writable'])))) {
1188                                 q("update contact set writable = %d where id = %d",
1189                                         intval(($perm == 'rw') ? 1 : 0),
1190                                         intval($contact['id'])
1191                                 );
1192                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1193                         }
1194                 }
1195
1196                 if (($contact['duplex'] && strlen($contact['pubkey']))
1197                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1198                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1199                         openssl_public_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['pubkey']);
1200                         openssl_public_decrypt($challenge,$postvars['challenge'],$contact['pubkey']);
1201                 } else {
1202                         openssl_private_decrypt($sent_dfrn_id,$final_dfrn_id,$contact['prvkey']);
1203                         openssl_private_decrypt($challenge,$postvars['challenge'],$contact['prvkey']);
1204                 }
1205
1206                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1207
1208                 if (strpos($final_dfrn_id,':') == 1) {
1209                         $final_dfrn_id = substr($final_dfrn_id,2);
1210                 }
1211
1212                 if ($final_dfrn_id != $orig_id) {
1213                         logger('dfrn_deliver: wrong dfrn_id.');
1214                         // did not decode properly - cannot trust this site
1215                         return 3;
1216                 }
1217
1218                 $postvars['dfrn_id']      = $idtosend;
1219                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1220                 if ($dissolve) {
1221                         $postvars['dissolve'] = '1';
1222                 }
1223
1224
1225                 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1226                         $postvars['data'] = $atom;
1227                         $postvars['perm'] = 'rw';
1228                 } else {
1229                         $postvars['data'] = str_replace('<dfrn:comment-allow>1','<dfrn:comment-allow>0',$atom);
1230                         $postvars['perm'] = 'r';
1231                 }
1232
1233                 $postvars['ssl_policy'] = $ssl_policy;
1234
1235                 if ($page) {
1236                         $postvars['page'] = $page;
1237                 }
1238
1239
1240                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1241                         logger('rino version: '. $rino_remote_version);
1242
1243                         switch ($rino_remote_version) {
1244                                 case 1:
1245                                         // Deprecated rino version!
1246                                         $key = openssl_random_pseudo_bytes(16);
1247                                         $data = self::aes_encrypt($postvars['data'], $key);
1248                                         break;
1249                                 case 2:
1250                                         // RINO 2 based on php-encryption
1251                                         try {
1252                                                 $key = Crypto::createNewRandomKey();
1253                                         } catch (CryptoTestFailed $ex) {
1254                                                 logger('Cannot safely create a key');
1255                                                 return -4;
1256                                         } catch (CannotPerformOperation $ex) {
1257                                                 logger('Cannot safely create a key');
1258                                                 return -5;
1259                                         }
1260                                         try {
1261                                                 $data = Crypto::encrypt($postvars['data'], $key);
1262                                         } catch (CryptoTestFailed $ex) {
1263                                                 logger('Cannot safely perform encryption');
1264                                                 return -6;
1265                                         } catch (CannotPerformOperation $ex) {
1266                                                 logger('Cannot safely perform encryption');
1267                                                 return -7;
1268                                         }
1269                                         break;
1270                                 default:
1271                                         logger("rino: invalid requested verision '$rino_remote_version'");
1272                                         return -8;
1273                         }
1274
1275                         $postvars['rino'] = $rino_remote_version;
1276                         $postvars['data'] = bin2hex($data);
1277
1278                         //logger('rino: sent key = ' . $key, LOGGER_DEBUG);
1279
1280
1281                         if ($dfrn_version >= 2.1) {
1282                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1283                                                 || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1284                                                 || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))) {
1285                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1286                                 } else {
1287                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1288                                 }
1289
1290                         } else {
1291                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1292                                         openssl_private_encrypt($key,$postvars['key'],$contact['prvkey']);
1293                                 } else {
1294                                         openssl_public_encrypt($key,$postvars['key'],$contact['pubkey']);
1295                                 }
1296
1297                         }
1298
1299                         logger('md5 rawkey ' . md5($postvars['key']));
1300
1301                         $postvars['key'] = bin2hex($postvars['key']);
1302                 }
1303
1304
1305                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars,true), LOGGER_DATA);
1306
1307                 $xml = post_url($contact['notify'], $postvars);
1308
1309                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1310
1311                 $curl_stat = $a->get_curl_code();
1312                 if ((!$curl_stat) || (!strlen($xml))) {
1313                         return -9; // timed out
1314                 }
1315
1316                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(),'retry-after'))) {
1317                         return -10;
1318                 }
1319
1320                 if (strpos($xml,'<?xml') === false) {
1321                         logger('dfrn_deliver: phase 2: no valid XML returned');
1322                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1323                         return 3;
1324                 }
1325
1326                 if ($contact['term-date'] > NULL_DATE) {
1327                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1328                         require_once('include/Contact.php');
1329                         unmark_for_death($contact);
1330                 }
1331
1332                 $res = parse_xml_string($xml);
1333
1334                 if (!isset($res->status)) {
1335                         return -11;
1336                 }
1337
1338                 if (!empty($res->message)) {
1339                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1340                 }
1341
1342                 return intval($res->status);
1343         }
1344
1345         /**
1346          * @brief Add new birthday event for this person
1347          *
1348          * @param array $contact Contact record
1349          * @param string $birthday Birthday of the contact
1350          * @todo Add array type-hint for $contact
1351          */
1352         private static function birthday_event($contact, $birthday) {
1353
1354                 // Check for duplicates
1355                 $r = q("SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1356                         intval($contact["uid"]),
1357                         intval($contact["id"]),
1358                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1359                         dbesc("birthday"));
1360
1361                 if (DBM::is_result($r)) {
1362                         return;
1363                 }
1364
1365                 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1366
1367                 $bdtext = sprintf(t("%s\'s birthday"), $contact["name"]);
1368                 $bdtext2 = sprintf(t("Happy Birthday %s"), " [url=".$contact["url"]."]".$contact["name"]."[/url]") ;
1369
1370                 $r = q("INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1371                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1372                         intval($contact["uid"]),
1373                         intval($contact["id"]),
1374                         dbesc(datetime_convert()),
1375                         dbesc(datetime_convert()),
1376                         dbesc(datetime_convert("UTC","UTC", $birthday)),
1377                         dbesc(datetime_convert("UTC","UTC", $birthday." + 1 day ")),
1378                         dbesc($bdtext),
1379                         dbesc($bdtext2),
1380                         dbesc("birthday")
1381                 );
1382         }
1383
1384         /**
1385          * @brief Fetch the author data from head or entry items
1386          *
1387          * @param object $xpath XPath object
1388          * @param object $context In which context should the data be searched
1389          * @param array $importer Record of the importer user mixed with contact of the content
1390          * @param string $element Element name from which the data is fetched
1391          * @param bool $onlyfetch Should the data only be fetched or should it update the contact record as well
1392          *
1393          * @return Returns an array with relevant data of the author
1394          * @todo Find good type-hints for all parameter
1395          */
1396         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "") {
1397
1398                 $author = array();
1399                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1400                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1401
1402                 $r = q("SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1403                                 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1404                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1405                         intval($importer["uid"]), dbesc(normalise_link($author["link"])), dbesc(NETWORK_STATUSNET));
1406
1407                 if (DBM::is_result($r)) {
1408                         $contact = $r[0];
1409                         $author["contact-id"] = $r[0]["id"];
1410                         $author["network"] = $r[0]["network"];
1411                 } else {
1412                         if (!$onlyfetch) {
1413                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1414                         }
1415
1416                         $author["contact-id"] = $importer["id"];
1417                         $author["network"] = $importer["network"];
1418                         $onlyfetch = true;
1419                 }
1420
1421                 // Until now we aren't serving different sizes - but maybe later
1422                 $avatarlist = array();
1423                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1424                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1425                 foreach ($avatars AS $avatar) {
1426                         $href = "";
1427                         $width = 0;
1428                         foreach ($avatar->attributes AS $attributes) {
1429                                 /// @TODO Rewrite these similar if () to one switch
1430                                 if ($attributes->name == "href") {
1431                                         $href = $attributes->textContent;
1432                                 }
1433                                 if ($attributes->name == "width") {
1434                                         $width = $attributes->textContent;
1435                                 }
1436                                 if ($attributes->name == "updated") {
1437                                         $contact["avatar-date"] = $attributes->textContent;
1438                                 }
1439                         }
1440                         if (($width > 0) && ($href != "")) {
1441                                 $avatarlist[$width] = $href;
1442                         }
1443                 }
1444                 if (count($avatarlist) > 0) {
1445                         krsort($avatarlist);
1446                         $author["avatar"] = current($avatarlist);
1447                 }
1448
1449                 if (DBM::is_result($r) && !$onlyfetch) {
1450                         logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1451
1452                         $poco = array("url" => $contact["url"]);
1453
1454                         // When was the last change to name or uri?
1455                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1456                         foreach ($name_element->attributes AS $attributes) {
1457                                 if ($attributes->name == "updated") {
1458                                         $poco["name-date"] = $attributes->textContent;
1459                                 }
1460                         }
1461
1462                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1463                         foreach ($link_element->attributes AS $attributes) {
1464                                 if ($attributes->name == "updated") {
1465                                         $poco["uri-date"] = $attributes->textContent;
1466                                 }
1467                         }
1468
1469                         // Update contact data
1470                         $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1471                         if ($value != "") {
1472                                 $poco["addr"] = $value;
1473                         }
1474
1475                         $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1476                         if ($value != "") {
1477                                 $poco["name"] = $value;
1478                         }
1479
1480                         $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1481                         if ($value != "") {
1482                                 $poco["nick"] = $value;
1483                         }
1484
1485                         $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1486                         if ($value != "") {
1487                                 $poco["about"] = $value;
1488                         }
1489
1490                         $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1491                         if ($value != "") {
1492                                 $poco["location"] = $value;
1493                         }
1494
1495                         /// @todo Only search for elements with "poco:type" = "xmpp"
1496                         $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1497                         if ($value != "") {
1498                                 $poco["xmpp"] = $value;
1499                         }
1500
1501                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1502                         /// - poco:utcOffset
1503                         /// - poco:urls
1504                         /// - poco:locality
1505                         /// - poco:region
1506                         /// - poco:country
1507
1508                         // If the "hide" element is present then the profile isn't searchable.
1509                         $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1510
1511                         logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1512
1513                         // If the contact isn't searchable then set the contact to "hidden".
1514                         // Problem: This can be manually overridden by the user.
1515                         if ($hide) {
1516                                 $contact["hidden"] = true;
1517                         }
1518
1519                         // Save the keywords into the contact table
1520                         $tags = array();
1521                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1522                         foreach ($tagelements AS $tag) {
1523                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1524                         }
1525
1526                         if (count($tags)) {
1527                                 $poco["keywords"] = implode(", ", $tags);
1528                         }
1529
1530                         // "dfrn:birthday" contains the birthday converted to UTC
1531                         $old_bdyear = $contact["bdyear"];
1532
1533                         $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1534
1535                         if (strtotime($birthday) > time()) {
1536                                 $bd_timestamp = strtotime($birthday);
1537
1538                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1539                         }
1540
1541                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1542                         $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1543
1544                         if (!in_array($value, array("", "0000-00-00", "0001-01-01"))) {
1545                                 $bdyear = date("Y");
1546                                 $value = str_replace("0000", $bdyear, $value);
1547
1548                                 if (strtotime($value) < time()) {
1549                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1550                                         $bdyear = $bdyear + 1;
1551                                 }
1552
1553                                 $poco["bd"] = $value;
1554                         }
1555
1556                         $contact = array_merge($contact, $poco);
1557
1558                         if ($old_bdyear != $contact["bdyear"]) {
1559                                 self::birthday_event($contact, $birthday);
1560                         }
1561
1562                         // Get all field names
1563                         $fields = array();
1564                         foreach ($r[0] AS $field => $data) {
1565                                 $fields[$field] = $data;
1566                         }
1567
1568                         unset($fields["id"]);
1569                         unset($fields["uid"]);
1570                         unset($fields["url"]);
1571                         unset($fields["avatar-date"]);
1572                         unset($fields["name-date"]);
1573                         unset($fields["uri-date"]);
1574
1575                         // Update check for this field has to be done differently
1576                         $datefields = array("name-date", "uri-date");
1577                         foreach ($datefields AS $field) {
1578                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1579                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1580                                         $update = true;
1581                                 }
1582                         }
1583
1584                         foreach ($fields AS $field => $data) {
1585                                 if ($contact[$field] != $r[0][$field]) {
1586                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1587                                         $update = true;
1588                                 }
1589                         }
1590
1591                         if ($update) {
1592                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1593
1594                                 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1595                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1596                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1597                                         WHERE `id` = %d AND `network` = '%s'",
1598                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]), dbesc($contact["location"]),
1599                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1600                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1601                                         dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1602                                         intval($contact["id"]), dbesc($contact["network"]));
1603                         }
1604
1605                         update_contact_avatar($author["avatar"], $importer["uid"], $contact["id"],
1606                                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"])));
1607
1608                         /*
1609                          * The generation is a sign for the reliability of the provided data.
1610                          * It is used in the socgraph.php to prevent that old contact data
1611                          * that was relayed over several servers can overwrite contact
1612                          * data that we received directly.
1613                          */
1614
1615                         $poco["generation"] = 2;
1616                         $poco["photo"] = $author["avatar"];
1617                         $poco["hide"] = $hide;
1618                         $poco["contact-type"] = $contact["contact-type"];
1619                         $gcid = update_gcontact($poco);
1620
1621                         link_gcontact($gcid, $importer["uid"], $contact["id"]);
1622                 }
1623
1624                 return($author);
1625         }
1626
1627         /**
1628          * @brief Transforms activity objects into an XML string
1629          *
1630          * @param object $xpath XPath object
1631          * @param object $activity Activity object
1632          * @param text $element element name
1633          *
1634          * @return string XML string
1635          * @todo Find good type-hints for all parameter
1636          */
1637         private static function transform_activity($xpath, $activity, $element) {
1638                 if (!is_object($activity)) {
1639                         return "";
1640                 }
1641
1642                 $obj_doc = new DOMDocument("1.0", "utf-8");
1643                 $obj_doc->formatOutput = true;
1644
1645                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1646
1647                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1648                 xml::add_element($obj_doc, $obj_element, "type", $activity_type);
1649
1650                 $id = $xpath->query("atom:id", $activity)->item(0);
1651                 if (is_object($id)) {
1652                         $obj_element->appendChild($obj_doc->importNode($id, true));
1653                 }
1654
1655                 $title = $xpath->query("atom:title", $activity)->item(0);
1656                 if (is_object($title)) {
1657                         $obj_element->appendChild($obj_doc->importNode($title, true));
1658                 }
1659
1660                 $links = $xpath->query("atom:link", $activity);
1661                 if (is_object($links)) {
1662                         foreach ($links AS $link) {
1663                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1664                         }
1665                 }
1666
1667                 $content = $xpath->query("atom:content", $activity)->item(0);
1668                 if (is_object($content)) {
1669                         $obj_element->appendChild($obj_doc->importNode($content, true));
1670                 }
1671
1672                 $obj_doc->appendChild($obj_element);
1673
1674                 $objxml = $obj_doc->saveXML($obj_element);
1675
1676                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1677                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1678                 return($objxml);
1679         }
1680
1681         /**
1682          * @brief Processes the mail elements
1683          *
1684          * @param object $xpath XPath object
1685          * @param object $mail mail elements
1686          * @param array $importer Record of the importer user mixed with contact of the content
1687          * @todo Find good type-hints for all parameter
1688          */
1689         private static function process_mail($xpath, $mail, $importer) {
1690
1691                 logger("Processing mails");
1692
1693                 /// @TODO Rewrite this to one statement
1694                 $msg = array();
1695                 $msg["uid"] = $importer["importer_uid"];
1696                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1697                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1698                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1699                 $msg["contact-id"] = $importer["id"];
1700                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1701                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1702                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1703                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1704                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1705                 $msg["seen"] = 0;
1706                 $msg["replied"] = 0;
1707
1708                 dba::insert('mail', $msg);
1709
1710                 // send notifications.
1711                 /// @TODO Arange this mess
1712                 $notif_params = array(
1713                         "type" => NOTIFY_MAIL,
1714                         "notify_flags" => $importer["notify-flags"],
1715                         "language" => $importer["language"],
1716                         "to_name" => $importer["username"],
1717                         "to_email" => $importer["email"],
1718                         "uid" => $importer["importer_uid"],
1719                         "item" => $msg,
1720                         "source_name" => $msg["from-name"],
1721                         "source_link" => $importer["url"],
1722                         "source_photo" => $importer["thumb"],
1723                         "verb" => ACTIVITY_POST,
1724                         "otype" => "mail"
1725                 );
1726
1727                 notification($notif_params);
1728
1729                 logger("Mail is processed, notification was sent.");
1730         }
1731
1732         /**
1733          * @brief Processes the suggestion elements
1734          *
1735          * @param object $xpath XPath object
1736          * @param object $suggestion suggestion elements
1737          * @param array $importer Record of the importer user mixed with contact of the content
1738          * @todo Find good type-hints for all parameter
1739          */
1740         private static function process_suggestion($xpath, $suggestion, $importer) {
1741                 $a = get_app();
1742
1743                 logger("Processing suggestions");
1744
1745                 /// @TODO Rewrite this to one statement
1746                 $suggest = array();
1747                 $suggest["uid"] = $importer["importer_uid"];
1748                 $suggest["cid"] = $importer["id"];
1749                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1750                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1751                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1752                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1753                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1754
1755                 // Does our member already have a friend matching this description?
1756
1757                 $r = q("SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1758                         dbesc($suggest["name"]),
1759                         dbesc(normalise_link($suggest["url"])),
1760                         intval($suggest["uid"])
1761                 );
1762
1763                 /*
1764                  * The valid result means the friend we're about to send a friend
1765                  * suggestion already has them in their contact, which means no further
1766                  * action is required.
1767                  *
1768                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1769                  */
1770                 if (DBM::is_result($r)) {
1771                         return false;
1772                 }
1773
1774                 // Do we already have an fcontact record for this person?
1775
1776                 $fid = 0;
1777                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1778                         dbesc($suggest["url"]),
1779                         dbesc($suggest["name"]),
1780                         dbesc($suggest["request"])
1781                 );
1782                 if (DBM::is_result($r)) {
1783                         $fid = $r[0]["id"];
1784
1785                         // OK, we do. Do we already have an introduction for this person ?
1786                         $r = q("SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1787                                 intval($suggest["uid"]),
1788                                 intval($fid)
1789                         );
1790
1791                         /*
1792                          * The valid result means the friend we're about to send a friend
1793                          * suggestion already has them in their contact, which means no further
1794                          * action is required.
1795                          *
1796                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1797                          */
1798                         if (DBM::is_result($r)) {
1799                                 return false;
1800                         }
1801                 }
1802                 if (!$fid) {
1803                         $r = q("INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1804                                 dbesc($suggest["name"]),
1805                                 dbesc($suggest["url"]),
1806                                 dbesc($suggest["photo"]),
1807                                 dbesc($suggest["request"])
1808                         );
1809                 }
1810                 $r = q("SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1811                         dbesc($suggest["url"]),
1812                         dbesc($suggest["name"]),
1813                         dbesc($suggest["request"])
1814                 );
1815
1816                 /*
1817                  * If no record in fcontact is found, below INSERT statement will not
1818                  * link an introduction to it.
1819                  */
1820                 if (!DBM::is_result($r)) {
1821                         // database record did not get created. Quietly give up.
1822                         killme();
1823                 }
1824
1825                 $fid = $r[0]["id"];
1826
1827                 $hash = random_string();
1828
1829                 $r = q("INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1830                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1831                         intval($suggest["uid"]),
1832                         intval($fid),
1833                         intval($suggest["cid"]),
1834                         dbesc($suggest["body"]),
1835                         dbesc($hash),
1836                         dbesc(datetime_convert()),
1837                         intval(0)
1838                 );
1839
1840                 notification(array(
1841                         "type"         => NOTIFY_SUGGEST,
1842                         "notify_flags" => $importer["notify-flags"],
1843                         "language"     => $importer["language"],
1844                         "to_name"      => $importer["username"],
1845                         "to_email"     => $importer["email"],
1846                         "uid"          => $importer["importer_uid"],
1847                         "item"         => $suggest,
1848                         "link"         => System::baseUrl()."/notifications/intros",
1849                         "source_name"  => $importer["name"],
1850                         "source_link"  => $importer["url"],
1851                         "source_photo" => $importer["photo"],
1852                         "verb"         => ACTIVITY_REQ_FRIEND,
1853                         "otype"        => "intro"
1854                 ));
1855
1856                 return true;
1857
1858         }
1859
1860         /**
1861          * @brief Processes the relocation elements
1862          *
1863          * @param object $xpath XPath object
1864          * @param object $relocation relocation elements
1865          * @param array $importer Record of the importer user mixed with contact of the content
1866          * @todo Find good type-hints for all parameter
1867          */
1868         private static function process_relocation($xpath, $relocation, $importer) {
1869
1870                 logger("Processing relocations");
1871
1872                 /// @TODO Rewrite this to one statement
1873                 $relocate = array();
1874                 $relocate["uid"] = $importer["importer_uid"];
1875                 $relocate["cid"] = $importer["id"];
1876                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1877                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1878                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1879                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1880                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1881                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1882                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1883                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1884                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1885                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1886                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1887                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1888
1889                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1890                         $relocate["avatar"] = $relocate["photo"];
1891                 }
1892
1893                 if ($relocate["addr"] == "") {
1894                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1895                 }
1896
1897                 // update contact
1898                 $r = q("SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1899                         intval($importer["id"]),
1900                         intval($importer["importer_uid"]));
1901
1902                 if (!DBM::is_result($r)) {
1903                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
1904                         return false;
1905                 }
1906
1907                 $old = $r[0];
1908
1909                 // Update the gcontact entry
1910                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1911
1912                 $x = q("UPDATE `gcontact` SET
1913                                         `name` = '%s',
1914                                         `photo` = '%s',
1915                                         `url` = '%s',
1916                                         `nurl` = '%s',
1917                                         `addr` = '%s',
1918                                         `connect` = '%s',
1919                                         `notify` = '%s',
1920                                         `server_url` = '%s'
1921                         WHERE `nurl` = '%s';",
1922                                         dbesc($relocate["name"]),
1923                                         dbesc($relocate["avatar"]),
1924                                         dbesc($relocate["url"]),
1925                                         dbesc(normalise_link($relocate["url"])),
1926                                         dbesc($relocate["addr"]),
1927                                         dbesc($relocate["addr"]),
1928                                         dbesc($relocate["notify"]),
1929                                         dbesc($relocate["server_url"]),
1930                                         dbesc(normalise_link($old["url"])));
1931
1932                 // Update the contact table. We try to find every entry.
1933                 $x = q("UPDATE `contact` SET
1934                                         `name` = '%s',
1935                                         `avatar` = '%s',
1936                                         `url` = '%s',
1937                                         `nurl` = '%s',
1938                                         `addr` = '%s',
1939                                         `request` = '%s',
1940                                         `confirm` = '%s',
1941                                         `notify` = '%s',
1942                                         `poll` = '%s',
1943                                         `site-pubkey` = '%s'
1944                         WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
1945                                         dbesc($relocate["name"]),
1946                                         dbesc($relocate["avatar"]),
1947                                         dbesc($relocate["url"]),
1948                                         dbesc(normalise_link($relocate["url"])),
1949                                         dbesc($relocate["addr"]),
1950                                         dbesc($relocate["request"]),
1951                                         dbesc($relocate["confirm"]),
1952                                         dbesc($relocate["notify"]),
1953                                         dbesc($relocate["poll"]),
1954                                         dbesc($relocate["sitepubkey"]),
1955                                         intval($importer["id"]),
1956                                         intval($importer["importer_uid"]),
1957                                         dbesc(normalise_link($old["url"])));
1958
1959                 update_contact_avatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
1960
1961                 if ($x === false) {
1962                         return false;
1963                 }
1964
1965                 // update items
1966                 /// @todo This is an extreme performance killer
1967                 $fields = array(
1968                         'owner-link' => array($old["url"], $relocate["url"]),
1969                         'author-link' => array($old["url"], $relocate["url"]),
1970                         //'owner-avatar' => array($old["photo"], $relocate["photo"]),
1971                         //'author-avatar' => array($old["photo"], $relocate["photo"]),
1972                 );
1973                 foreach ($fields as $n=>$f) {
1974                         $r = q("SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
1975                                         $n, dbesc($f[0]),
1976                                         intval($importer["importer_uid"]));
1977
1978                         if (DBM::is_result($r)) {
1979                                 $x = q("UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
1980                                                 $n, dbesc($f[1]),
1981                                                 $n, dbesc($f[0]),
1982                                                 intval($importer["importer_uid"]));
1983
1984                                         if ($x === false) {
1985                                                 return false;
1986                                         }
1987                         }
1988                 }
1989
1990                 /// @TODO
1991                 /// merge with current record, current contents have priority
1992                 /// update record, set url-updated
1993                 /// update profile photos
1994                 /// schedule a scan?
1995                 return true;
1996         }
1997
1998         /**
1999          * @brief Updates an item
2000          *
2001          * @param array $current the current item record
2002          * @param array $item the new item record
2003          * @param array $importer Record of the importer user mixed with contact of the content
2004          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2005          * @todo set proper type-hints (array?)
2006          */
2007         private static function update_content($current, $item, $importer, $entrytype) {
2008                 $changed = false;
2009
2010                 if (edited_timestamp_is_newer($current, $item)) {
2011
2012                         // do not accept (ignore) an earlier edit than one we currently have.
2013                         if (datetime_convert("UTC","UTC",$item["edited"]) < $current["edited"]) {
2014                                 return false;
2015                         }
2016
2017                         $fields = array('title' => $item["title"], 'body' => $item["body"],
2018                                         'tag' => $item["tag"], 'changed' => datetime_convert(),
2019                                         'edited' => datetime_convert("UTC", "UTC", $item["edited"]));
2020
2021                         $condition = array("`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]);
2022                         dba::update('item', $fields, $condition);
2023
2024                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2025                         update_thread_uri($item["uri"], $importer["importer_uid"]);
2026
2027                         $changed = true;
2028
2029                         if ($entrytype == DFRN_REPLY_RC) {
2030                                 Worker::add(PRIORITY_HIGH, "notifier","comment-import", $current["id"]);
2031                         }
2032                 }
2033
2034                 // update last-child if it changes
2035                 if ($item["last-child"] && ($item["last-child"] != $current["last-child"])) {
2036                         $r = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2037                                 dbesc(datetime_convert()),
2038                                 dbesc($item["parent-uri"]),
2039                                 intval($importer["importer_uid"])
2040                         );
2041                         $r = q("UPDATE `item` SET `last-child` = %d , `changed` = '%s' WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2042                                 intval($item["last-child"]),
2043                                 dbesc(datetime_convert()),
2044                                 dbesc($item["uri"]),
2045                                 intval($importer["importer_uid"])
2046                         );
2047                 }
2048                 return $changed;
2049         }
2050
2051         /**
2052          * @brief Detects the entry type of the item
2053          *
2054          * @param array $importer Record of the importer user mixed with contact of the content
2055          * @param array $item the new item record
2056          *
2057          * @return int Is it a toplevel entry, a comment or a relayed comment?
2058          * @todo set proper type-hints (array?)
2059          */
2060         private static function get_entry_type($importer, $item) {
2061                 if ($item["parent-uri"] != $item["uri"]) {
2062                         $community = false;
2063
2064                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2065                                 $sql_extra = "";
2066                                 $community = true;
2067                                 logger("possible community action");
2068                         } else {
2069                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2070                         }
2071
2072                         // was the top-level post for this action written by somebody on this site?
2073                         // Specifically, the recipient?
2074
2075                         $is_a_remote_action = false;
2076
2077                         $r = q("SELECT `item`.`parent-uri` FROM `item`
2078                                 WHERE `item`.`uri` = '%s'
2079                                 LIMIT 1",
2080                                 dbesc($item["parent-uri"])
2081                         );
2082                         if (DBM::is_result($r)) {
2083                                 $r = q("SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2084                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2085                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2086                                         AND `item`.`uid` = %d
2087                                         $sql_extra
2088                                         LIMIT 1",
2089                                         dbesc($r[0]["parent-uri"]),
2090                                         dbesc($r[0]["parent-uri"]),
2091                                         dbesc($r[0]["parent-uri"]),
2092                                         intval($importer["importer_uid"])
2093                                 );
2094                                 if (DBM::is_result($r)) {
2095                                         $is_a_remote_action = true;
2096                                 }
2097                         }
2098
2099                         /*
2100                          * Does this have the characteristics of a community or private group action?
2101                          * If it's an action to a wall post on a community/prvgroup page it's a
2102                          * valid community action. Also forum_mode makes it valid for sure.
2103                          * If neither, it's not.
2104                          */
2105
2106                         /// @TODO Maybe merge these if() blocks into one?
2107                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2108                                 $is_a_remote_action = false;
2109                                 logger("not a community action");
2110                         }
2111
2112                         if ($is_a_remote_action) {
2113                                 return DFRN_REPLY_RC;
2114                         } else {
2115                                 return DFRN_REPLY;
2116                         }
2117                 } else {
2118                         return DFRN_TOP_LEVEL;
2119                 }
2120
2121         }
2122
2123         /**
2124          * @brief Send a "poke"
2125          *
2126          * @param array $item the new item record
2127          * @param array $importer Record of the importer user mixed with contact of the content
2128          * @param int $posted_id The record number of item record that was just posted
2129          * @todo set proper type-hints (array?)
2130          */
2131         private static function do_poke($item, $importer, $posted_id) {
2132                 $verb = urldecode(substr($item["verb"],strpos($item["verb"], "#")+1));
2133                 if (!$verb) {
2134                         return;
2135                 }
2136                 $xo = parse_xml_string($item["object"],false);
2137
2138                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2139
2140                         // somebody was poked/prodded. Was it me?
2141                         foreach ($xo->link as $l) {
2142                                 $atts = $l->attributes();
2143                                 switch ($atts["rel"]) {
2144                                         case "alternate":
2145                                                 $Blink = $atts["href"];
2146                                                 break;
2147                                         default:
2148                                                 break;
2149                                 }
2150                         }
2151
2152                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2153
2154                                 // send a notification
2155                                 notification(array(
2156                                         "type"         => NOTIFY_POKE,
2157                                         "notify_flags" => $importer["notify-flags"],
2158                                         "language"     => $importer["language"],
2159                                         "to_name"      => $importer["username"],
2160                                         "to_email"     => $importer["email"],
2161                                         "uid"          => $importer["importer_uid"],
2162                                         "item"         => $item,
2163                                         "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2164                                         "source_name"  => stripslashes($item["author-name"]),
2165                                         "source_link"  => $item["author-link"],
2166                                         "source_photo" => ((link_compare($item["author-link"],$importer["url"]))
2167                                                 ? $importer["thumb"] : $item["author-avatar"]),
2168                                         "verb"         => $item["verb"],
2169                                         "otype"        => "person",
2170                                         "activity"     => $verb,
2171                                         "parent"       => $item["parent"]
2172                                 ));
2173                         }
2174                 }
2175         }
2176
2177         /**
2178          * @brief Processes several actions, depending on the verb
2179          *
2180          * @param int $entrytype Is it a toplevel entry, a comment or a relayed comment?
2181          * @param array $importer Record of the importer user mixed with contact of the content
2182          * @param array $item the new item record
2183          * @param bool $is_like Is the verb a "like"?
2184          *
2185          * @return bool Should the processing of the entries be continued?
2186          * @todo set proper type-hints (array?)
2187          */
2188         private static function process_verbs($entrytype, $importer, &$item, &$is_like) {
2189
2190                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2191
2192                 if (($entrytype == DFRN_TOP_LEVEL)) {
2193                         // The filling of the the "contact" variable is done for legcy reasons
2194                         // The functions below are partly used by ostatus.php as well - where we have this variable
2195                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2196                         $contact = $r[0];
2197                         $nickname = $contact["nick"];
2198
2199                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2200                         // This function once was responsible for DFRN and OStatus.
2201                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2202                                 logger("New follower");
2203                                 new_follower($importer, $contact, $item, $nickname);
2204                                 return false;
2205                         }
2206                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW))  {
2207                                 logger("Lost follower");
2208                                 lose_follower($importer, $contact, $item);
2209                                 return false;
2210                         }
2211                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2212                                 logger("New friend request");
2213                                 new_follower($importer, $contact, $item, $nickname, true);
2214                                 return false;
2215                         }
2216                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND))  {
2217                                 logger("Lost sharer");
2218                                 lose_sharer($importer, $contact, $item);
2219                                 return false;
2220                         }
2221                 } else {
2222                         if (($item["verb"] == ACTIVITY_LIKE)
2223                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2224                                 || ($item["verb"] == ACTIVITY_ATTEND)
2225                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2226                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)) {
2227                                 $is_like = true;
2228                                 $item["type"] = "activity";
2229                                 $item["gravity"] = GRAVITY_LIKE;
2230                                 // only one like or dislike per person
2231                                 // splitted into two queries for performance issues
2232                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2233                                         intval($item["uid"]),
2234                                         dbesc($item["author-link"]),
2235                                         dbesc($item["verb"]),
2236                                         dbesc($item["parent-uri"])
2237                                 );
2238                                 if (DBM::is_result($r)) {
2239                                         return false;
2240                                 }
2241
2242                                 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2243                                         intval($item["uid"]),
2244                                         dbesc($item["author-link"]),
2245                                         dbesc($item["verb"]),
2246                                         dbesc($item["parent-uri"])
2247                                 );
2248                                 if (DBM::is_result($r)) {
2249                                         return false;
2250                                 }
2251                         } else {
2252                                 $is_like = false;
2253                         }
2254
2255                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2256
2257                                 $xo = parse_xml_string($item["object"],false);
2258                                 $xt = parse_xml_string($item["target"],false);
2259
2260                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2261                                         $r = q("SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2262                                                 dbesc($xt->id),
2263                                                 intval($importer["importer_uid"])
2264                                         );
2265
2266                                         if (!DBM::is_result($r)) {
2267                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2268                                                 return false;
2269                                         }
2270
2271                                         // extract tag, if not duplicate, add to parent item
2272                                         if ($xo->content) {
2273                                                 if (!(stristr($r[0]["tag"],trim($xo->content)))) {
2274                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2275                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2276                                                                 intval($r[0]["id"])
2277                                                         );
2278                                                         create_tags_from_item($r[0]["id"]);
2279                                                 }
2280                                         }
2281                                 }
2282                         }
2283                 }
2284                 return true;
2285         }
2286
2287         /**
2288          * @brief Processes the link elements
2289          *
2290          * @param object $links link elements
2291          * @param array $item the item record
2292          * @todo set proper type-hints
2293          */
2294         private static function parse_links($links, &$item) {
2295                 $rel = "";
2296                 $href = "";
2297                 $type = "";
2298                 $length = "0";
2299                 $title = "";
2300                 foreach ($links AS $link) {
2301                         foreach ($link->attributes AS $attributes) {
2302                                 /// @TODO Rewrite these repeated (same) if () statements to a switch()
2303                                 if ($attributes->name == "href") {
2304                                         $href = $attributes->textContent;
2305                                 }
2306                                 if ($attributes->name == "rel") {
2307                                         $rel = $attributes->textContent;
2308                                 }
2309                                 if ($attributes->name == "type") {
2310                                         $type = $attributes->textContent;
2311                                 }
2312                                 if ($attributes->name == "length") {
2313                                         $length = $attributes->textContent;
2314                                 }
2315                                 if ($attributes->name == "title") {
2316                                         $title = $attributes->textContent;
2317                                 }
2318                         }
2319                         if (($rel != "") && ($href != "")) {
2320                                 switch ($rel) {
2321                                         case "alternate":
2322                                                 $item["plink"] = $href;
2323                                                 break;
2324                                         case "enclosure":
2325                                                 $enclosure = $href;
2326                                                 if (strlen($item["attach"])) {
2327                                                         $item["attach"] .= ",";
2328                                                 }
2329
2330                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2331                                                 break;
2332                                 }
2333                         }
2334                 }
2335         }
2336
2337         /**
2338          * @brief Processes the entry elements which contain the items and comments
2339          *
2340          * @param array $header Array of the header elements that always stay the same
2341          * @param object $xpath XPath object
2342          * @param object $entry entry elements
2343          * @param array $importer Record of the importer user mixed with contact of the content
2344          * @todo Add type-hints
2345          */
2346         private static function process_entry($header, $xpath, $entry, $importer, $xml) {
2347
2348                 logger("Processing entries");
2349
2350                 $item = $header;
2351
2352                 $item["protocol"] = PROTOCOL_DFRN;
2353
2354                 $item["source"] = $xml;
2355
2356                 // Get the uri
2357                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2358
2359                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2360
2361                 $current = q("SELECT `id`, `uid`, `last-child`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2362                         dbesc($item["uri"]),
2363                         intval($importer["importer_uid"])
2364                 );
2365
2366                 // Is there an existing item?
2367                 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item) &&
2368                         (datetime_convert("UTC","UTC",$item["edited"]) < $current[0]["edited"])) {
2369                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2370                         return;
2371                 }
2372
2373                 // Fetch the owner
2374                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2375
2376                 $item["owner-name"] = $owner["name"];
2377                 $item["owner-link"] = $owner["link"];
2378                 $item["owner-avatar"] = $owner["avatar"];
2379
2380                 // fetch the author
2381                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2382
2383                 $item["author-name"] = $author["name"];
2384                 $item["author-link"] = $author["link"];
2385                 $item["author-avatar"] = $author["avatar"];
2386
2387                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2388
2389                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2390
2391                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2392                 $item["body"] = str_replace(array(' ',"\t","\r","\n"), array('','','',''),$item["body"]);
2393                 // make sure nobody is trying to sneak some html tags by us
2394                 $item["body"] = notags(base64url_decode($item["body"]));
2395
2396                 $item["body"] = limit_body_size($item["body"]);
2397
2398                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2399                 if ((strpos($item['body'],'<') !== false) && (strpos($item['body'],'>') !== false)) {
2400
2401                         $item['body'] = reltoabs($item['body'],$base_url);
2402
2403                         $item['body'] = html2bb_video($item['body']);
2404
2405                         $item['body'] = oembed_html2bbcode($item['body']);
2406
2407                         $config = HTMLPurifier_Config::createDefault();
2408                         $config->set('Cache.DefinitionImpl', null);
2409
2410                         // we shouldn't need a whitelist, because the bbcode converter
2411                         // will strip out any unsupported tags.
2412
2413                         $purifier = new HTMLPurifier($config);
2414                         $item['body'] = $purifier->purify($item['body']);
2415
2416                         $item['body'] = @html2bbcode($item['body']);
2417                 }
2418
2419                 /// @todo We should check for a repeated post and if we know the repeated author.
2420
2421                 // We don't need the content element since "dfrn:env" is always present
2422                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2423
2424                 $item["last-child"] = $xpath->query("dfrn:comment-allow/text()", $entry)->item(0)->nodeValue;
2425                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2426
2427                 $georsspoint = $xpath->query("georss:point", $entry);
2428                 if ($georsspoint) {
2429                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2430                 }
2431
2432                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2433
2434                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2435
2436                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2437                         $item["bookmark"] = true;
2438                 }
2439
2440                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2441                 if ($notice_info && ($notice_info->length > 0)) {
2442                         foreach ($notice_info->item(0)->attributes AS $attributes) {
2443                                 if ($attributes->name == "source") {
2444                                         $item["app"] = strip_tags($attributes->textContent);
2445                                 }
2446                         }
2447                 }
2448
2449                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2450
2451                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2452                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2453                 if ($dsprsig != "") {
2454                         $item["dsprsig"] = $dsprsig;
2455                 }
2456
2457                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2458
2459                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2460                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2461                 }
2462
2463                 $object = $xpath->query("activity:object", $entry)->item(0);
2464                 $item["object"] = self::transform_activity($xpath, $object, "object");
2465
2466                 if (trim($item["object"]) != "") {
2467                         $r = parse_xml_string($item["object"], false);
2468                         if (isset($r->type)) {
2469                                 $item["object-type"] = $r->type;
2470                         }
2471                 }
2472
2473                 $target = $xpath->query("activity:target", $entry)->item(0);
2474                 $item["target"] = self::transform_activity($xpath, $target, "target");
2475
2476                 $categories = $xpath->query("atom:category", $entry);
2477                 if ($categories) {
2478                         foreach ($categories AS $category) {
2479                                 $term = "";
2480                                 $scheme = "";
2481                                 foreach ($category->attributes AS $attributes) {
2482                                         if ($attributes->name == "term") {
2483                                                 $term = $attributes->textContent;
2484                                         }
2485
2486                                         if ($attributes->name == "scheme") {
2487                                                 $scheme = $attributes->textContent;
2488                                         }
2489                                 }
2490
2491                                 if (($term != "") && ($scheme != "")) {
2492                                         $parts = explode(":", $scheme);
2493                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2494                                                 $termhash = array_shift($parts);
2495                                                 $termurl = implode(":", $parts);
2496
2497                                                 if (strlen($item["tag"])) {
2498                                                         $item["tag"] .= ",";
2499                                                 }
2500
2501                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2502                                         }
2503                                 }
2504                         }
2505                 }
2506
2507                 $enclosure = "";
2508
2509                 $links = $xpath->query("atom:link", $entry);
2510                 if ($links) {
2511                         self::parse_links($links, $item);
2512                 }
2513
2514                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2515
2516                 $conv = $xpath->query('ostatus:conversation', $entry);
2517                 if (is_object($conv->item(0))) {
2518                         foreach ($conv->item(0)->attributes AS $attributes) {
2519                                 if ($attributes->name == "ref") {
2520                                         $item['conversation-uri'] = $attributes->textContent;
2521                                 }
2522                                 if ($attributes->name == "href") {
2523                                         $item['conversation-href'] = $attributes->textContent;
2524                                 }
2525                         }
2526                 }
2527
2528                 // Is it a reply or a top level posting?
2529                 $item["parent-uri"] = $item["uri"];
2530
2531                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2532                 if (is_object($inreplyto->item(0))) {
2533                         foreach ($inreplyto->item(0)->attributes AS $attributes) {
2534                                 if ($attributes->name == "ref") {
2535                                         $item["parent-uri"] = $attributes->textContent;
2536                                 }
2537                         }
2538                 }
2539
2540                 // Get the type of the item (Top level post, reply or remote reply)
2541                 $entrytype = self::get_entry_type($importer, $item);
2542
2543                 // Now assign the rest of the values that depend on the type of the message
2544                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2545                         if (!isset($item["object-type"])) {
2546                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2547                         }
2548
2549                         if ($item["contact-id"] != $owner["contact-id"]) {
2550                                 $item["contact-id"] = $owner["contact-id"];
2551                         }
2552
2553                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2554                                 $item["network"] = $owner["network"];
2555                         }
2556
2557                         if ($item["contact-id"] != $author["contact-id"]) {
2558                                 $item["contact-id"] = $author["contact-id"];
2559                         }
2560
2561                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2562                                 $item["network"] = $author["network"];
2563                         }
2564
2565                         /// @TODO maybe remove this old-lost code then?
2566                         // This code was taken from the old DFRN code
2567                         // When activated, forums don't work.
2568                         // And: Why should we disallow commenting by followers?
2569                         // the behaviour is now similar to the Diaspora part.
2570                         //if ($importer["rel"] == CONTACT_IS_FOLLOWER) {
2571                         //      logger("Contact ".$importer["id"]." is only follower. Quitting", LOGGER_DEBUG);
2572                         //      return;
2573                         //}
2574                 }
2575
2576                 if ($entrytype == DFRN_REPLY_RC) {
2577                         $item["type"] = "remote-comment";
2578                         $item["wall"] = 1;
2579                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2580                         if (!isset($item["object-type"])) {
2581                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2582                         }
2583
2584                         // Is it an event?
2585                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2586                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2587                                 $ev = bbtoevent($item["body"]);
2588                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2589                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2590                                         /// @TODO Mixure of "/' ahead ...
2591                                         $ev["cid"] = $importer["id"];
2592                                         $ev["uid"] = $importer["uid"];
2593                                         $ev["uri"] = $item["uri"];
2594                                         $ev["edited"] = $item["edited"];
2595                                         $ev['private'] = $item['private'];
2596                                         $ev["guid"] = $item["guid"];
2597
2598                                         $r = q("SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2599                                                 dbesc($item["uri"]),
2600                                                 intval($importer["uid"])
2601                                         );
2602                                         if (DBM::is_result($r)) {
2603                                                 $ev["id"] = $r[0]["id"];
2604                                         }
2605
2606                                         $event_id = event_store($ev);
2607                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2608                                         return;
2609                                 }
2610                         }
2611                 }
2612
2613                 if (!self::process_verbs($entrytype, $importer, $item, $is_like)) {
2614                         logger("Exiting because 'process_verbs' told us so", LOGGER_DEBUG);
2615                         return;
2616                 }
2617
2618                 // Update content if 'updated' changes
2619                 if (DBM::is_result($current)) {
2620                         if (self::update_content($r[0], $item, $importer, $entrytype)) {
2621                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2622                         } else {
2623                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2624                         }
2625                         return;
2626                 }
2627
2628                 if (in_array($entrytype, array(DFRN_REPLY, DFRN_REPLY_RC))) {
2629                         $posted_id = item_store($item);
2630                         $parent = 0;
2631
2632                         if ($posted_id) {
2633
2634                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2635
2636                                 $item["id"] = $posted_id;
2637
2638                                 $r = q("SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2639                                         intval($posted_id),
2640                                         intval($importer["importer_uid"])
2641                                 );
2642                                 if (DBM::is_result($r)) {
2643                                         $parent = $r[0]["parent"];
2644                                         $parent_uri = $r[0]["parent-uri"];
2645                                 }
2646
2647                                 if (!$is_like) {
2648                                         $r1 = q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `uid` = %d AND `parent` = %d",
2649                                                 dbesc(datetime_convert()),
2650                                                 intval($importer["importer_uid"]),
2651                                                 intval($r[0]["parent"])
2652                                         );
2653
2654                                         $r2 = q("UPDATE `item` SET `last-child` = 1, `changed` = '%s' WHERE `uid` = %d AND `id` = %d",
2655                                                 dbesc(datetime_convert()),
2656                                                 intval($importer["importer_uid"]),
2657                                                 intval($posted_id)
2658                                         );
2659                                 }
2660
2661                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2662                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2663                                         Worker::add(PRIORITY_HIGH, "notifier", "comment-import", $posted_id);
2664                                 }
2665
2666                                 return true;
2667                         }
2668                 } else { // $entrytype == DFRN_TOP_LEVEL
2669                         if (!link_compare($item["owner-link"],$importer["url"])) {
2670                                 /*
2671                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2672                                  * but otherwise there's a possible data mixup on the sender's system.
2673                                  * the tgroup delivery code called from item_store will correct it if it's a forum,
2674                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2675                                  */
2676                                 logger('Correcting item owner.', LOGGER_DEBUG);
2677                                 $item["owner-name"]   = $importer["senderName"];
2678                                 $item["owner-link"]   = $importer["url"];
2679                                 $item["owner-avatar"] = $importer["thumb"];
2680                         }
2681
2682                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2683                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2684                                 return;
2685                         }
2686
2687                         // This is my contact on another system, but it's really me.
2688                         // Turn this into a wall post.
2689                         $notify = item_is_remote_self($importer, $item);
2690
2691                         $posted_id = item_store($item, false, $notify);
2692
2693                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2694
2695                         if (stristr($item["verb"],ACTIVITY_POKE))
2696                                 self::do_poke($item, $importer, $posted_id);
2697                 }
2698         }
2699
2700         /**
2701          * @brief Deletes items
2702          *
2703          * @param object $xpath XPath object
2704          * @param object $deletion deletion elements
2705          * @param array $importer Record of the importer user mixed with contact of the content
2706          * @todo set proper type-hints
2707          */
2708         private static function process_deletion($xpath, $deletion, $importer) {
2709
2710                 logger("Processing deletions");
2711
2712                 foreach ($deletion->attributes AS $attributes) {
2713                         if ($attributes->name == "ref") {
2714                                 $uri = $attributes->textContent;
2715                         }
2716                         if ($attributes->name == "when") {
2717                                 $when = $attributes->textContent;
2718                         }
2719                 }
2720                 if ($when) {
2721                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2722                 } else {
2723                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2724                 }
2725
2726                 if (!$uri || !$importer["id"]) {
2727                         return false;
2728                 }
2729
2730                 /// @todo Only select the used fields
2731                 $r = q("SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2732                                 WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2733                                 dbesc($uri),
2734                                 intval($importer["uid"]),
2735                                 intval($importer["id"])
2736                         );
2737                 if (!DBM::is_result($r)) {
2738                         logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2739                         return;
2740                 } else {
2741
2742                         $item = $r[0];
2743
2744                         $entrytype = self::get_entry_type($importer, $item);
2745
2746                         if (!$item["deleted"]) {
2747                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2748                         } else {
2749                                 return;
2750                         }
2751
2752                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2753                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2754                                 event_delete($item["event-id"]);
2755                         }
2756
2757                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2758
2759                                 $xo = parse_xml_string($item["object"],false);
2760                                 $xt = parse_xml_string($item["target"],false);
2761
2762                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2763                                         $i = q("SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2764                                                 dbesc($xt->id),
2765                                                 intval($importer["importer_uid"])
2766                                         );
2767                                         if (DBM::is_result($i)) {
2768
2769                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2770
2771                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2772                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2773                                                 $author_copy = (($item["origin"]) ? true : false);
2774
2775                                                 if ($owner_remove && $author_copy) {
2776                                                         return;
2777                                                 }
2778                                                 if ($author_remove || $owner_remove) {
2779                                                         $tags = explode(',',$i[0]["tag"]);
2780                                                         $newtags = array();
2781                                                         if (count($tags)) {
2782                                                                 foreach ($tags as $tag) {
2783                                                                         if (trim($tag) !== trim($xo->body)) {
2784                                                                                 $newtags[] = trim($tag);
2785                                                                         }
2786                                                                 }
2787                                                         }
2788                                                         q("UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2789                                                                 dbesc(implode(',', $newtags)),
2790                                                                 intval($i[0]["id"])
2791                                                         );
2792                                                         create_tags_from_item($i[0]["id"]);
2793                                                 }
2794                                         }
2795                                 }
2796                         }
2797
2798                         if ($entrytype == DFRN_TOP_LEVEL) {
2799                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2800                                                 `body` = '', `title` = ''
2801                                         WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2802                                                 dbesc($when),
2803                                                 dbesc(datetime_convert()),
2804                                                 dbesc($uri),
2805                                                 intval($importer["uid"])
2806                                         );
2807                                 create_tags_from_itemuri($uri, $importer["uid"]);
2808                                 create_files_from_itemuri($uri, $importer["uid"]);
2809                                 update_thread_uri($uri, $importer["uid"]);
2810                         } else {
2811                                 $r = q("UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2812                                                 `body` = '', `title` = ''
2813                                         WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2814                                                 dbesc($when),
2815                                                 dbesc(datetime_convert()),
2816                                                 dbesc($uri),
2817                                                 intval($importer["uid"])
2818                                         );
2819                                 create_tags_from_itemuri($uri, $importer["uid"]);
2820                                 create_files_from_itemuri($uri, $importer["uid"]);
2821                                 update_thread_uri($uri, $importer["importer_uid"]);
2822                                 if ($item["last-child"]) {
2823                                         // ensure that last-child is set in case the comment that had it just got wiped.
2824                                         q("UPDATE `item` SET `last-child` = 0, `changed` = '%s' WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2825                                                 dbesc(datetime_convert()),
2826                                                 dbesc($item["parent-uri"]),
2827                                                 intval($item["uid"])
2828                                         );
2829                                         // who is the last child now?
2830                                         $r = q("SELECT `id` FROM `item` WHERE `parent-uri` = '%s' AND `type` != 'activity' AND `deleted` = 0 AND `moderated` = 0 AND `uid` = %d
2831                                                 ORDER BY `created` DESC LIMIT 1",
2832                                                         dbesc($item["parent-uri"]),
2833                                                         intval($importer["uid"])
2834                                         );
2835                                         if (DBM::is_result($r)) {
2836                                                 q("UPDATE `item` SET `last-child` = 1 WHERE `id` = %d",
2837                                                         intval($r[0]["id"])
2838                                                 );
2839                                         }
2840                                 }
2841                                 // if this is a relayed delete, propagate it to other recipients
2842
2843                                 if ($entrytype == DFRN_REPLY_RC) {
2844                                         logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2845                                         Worker::add(PRIORITY_HIGH, "notifier","drop", $item["id"]);
2846                                 }
2847                         }
2848                 }
2849         }
2850
2851         /**
2852          * @brief Imports a DFRN message
2853          *
2854          * @param text $xml The DFRN message
2855          * @param array $importer Record of the importer user mixed with contact of the content
2856          * @param bool $sort_by_date Is used when feeds are polled
2857          * @return integer Import status
2858          * @todo set proper type-hints
2859          */
2860         public static function import($xml, $importer, $sort_by_date = false) {
2861
2862                 if ($xml == "") {
2863                         return 400;
2864                 }
2865
2866                 $doc = new DOMDocument();
2867                 @$doc->loadXML($xml);
2868
2869                 $xpath = new DomXPath($doc);
2870                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2871                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2872                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2873                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2874                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2875                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2876                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2877                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2878                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2879                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2880
2881                 $header = array();
2882                 $header["uid"] = $importer["uid"];
2883                 $header["network"] = NETWORK_DFRN;
2884                 $header["type"] = "remote";
2885                 $header["wall"] = 0;
2886                 $header["origin"] = 0;
2887                 $header["contact-id"] = $importer["id"];
2888
2889                 // Update the contact table if the data has changed
2890
2891                 // The "atom:author" is only present in feeds
2892                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2893                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2894                 }
2895
2896                 // Only the "dfrn:owner" in the head section contains all data
2897                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2898                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2899                 }
2900
2901                 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2902
2903                 // The account type is new since 3.5.1
2904                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2905                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()", $context)->item(0)->nodeValue);
2906
2907                         if ($accounttype != $importer["contact-type"]) {
2908                                 dba::update('contact', array('contact-type' => $accounttype), array('id' => $importer["id"]));
2909                         }
2910                 }
2911
2912                 // is it a public forum? Private forums aren't supported with this method
2913                 // This is deprecated since 3.5.1
2914                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()", $context)->item(0)->nodeValue);
2915
2916                 if ($forum != $importer["forum"]) {
2917                         $condition = array('`forum` != ? AND `id` = ?', $forum, $importer["id"]);
2918                         dba::update('contact', array('forum' => $forum), $condition);
2919                 }
2920
2921                 // We are processing relocations even if we are ignoring a contact
2922                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2923                 foreach ($relocations AS $relocation) {
2924                         self::process_relocation($xpath, $relocation, $importer);
2925                 }
2926
2927                 if ($importer["readonly"]) {
2928                         // We aren't receiving stuff from this person. But we will quietly ignore them
2929                         // rather than a blatant "go away" message.
2930                         logger('ignoring contact '.$importer["id"]);
2931                         return 403;
2932                 }
2933
2934                 $mails = $xpath->query("/atom:feed/dfrn:mail");
2935                 foreach ($mails AS $mail) {
2936                         self::process_mail($xpath, $mail, $importer);
2937                 }
2938
2939                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2940                 foreach ($suggestions AS $suggestion) {
2941                         self::process_suggestion($xpath, $suggestion, $importer);
2942                 }
2943
2944                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2945                 foreach ($deletions AS $deletion) {
2946                         self::process_deletion($xpath, $deletion, $importer);
2947                 }
2948
2949                 if (!$sort_by_date) {
2950                         $entries = $xpath->query("/atom:feed/atom:entry");
2951                         foreach ($entries AS $entry) {
2952                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
2953                         }
2954                 } else {
2955                         $newentries = array();
2956                         $entries = $xpath->query("/atom:feed/atom:entry");
2957                         foreach ($entries AS $entry) {
2958                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2959                                 $newentries[strtotime($created)] = $entry;
2960                         }
2961
2962                         // Now sort after the publishing date
2963                         ksort($newentries);
2964
2965                         foreach ($newentries AS $entry) {
2966                                 self::process_entry($header, $xpath, $entry, $importer, $xml);
2967                         }
2968                 }
2969                 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2970                 return 200;
2971         }
2972 }