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