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