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