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