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