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