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