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