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