]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
[Database version 1499] Create new paradigm classes for Diaspora Contact
[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\App;
29 use Friendica\Content\Text\BBCode;
30 use Friendica\Core\Logger;
31 use Friendica\Core\Protocol;
32 use Friendica\Database\DBA;
33 use Friendica\DI;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Event;
37 use Friendica\Model\FContact;
38 use Friendica\Model\GServer;
39 use Friendica\Model\Item;
40 use Friendica\Model\ItemURI;
41 use Friendica\Model\Mail;
42 use Friendica\Model\Notification;
43 use Friendica\Model\Photo;
44 use Friendica\Model\Post;
45 use Friendica\Model\Profile;
46 use Friendica\Model\Tag;
47 use Friendica\Model\User;
48 use Friendica\Network\HTTPException;
49 use Friendica\Network\Probe;
50 use Friendica\Util\Crypto;
51 use Friendica\Util\DateTimeFormat;
52 use Friendica\Util\Images;
53 use Friendica\Util\Proxy;
54 use Friendica\Util\Strings;
55 use Friendica\Util\XML;
56 use GuzzleHttp\Psr7\Uri;
57
58 /**
59  * This class contain functions to create and send DFRN XML files
60  */
61 class DFRN
62 {
63
64         const TOP_LEVEL = 0; // Top level posting
65         const REPLY     = 1; // Regular reply that is stored locally
66         const REPLY_RC  = 2; // Reply that will be relayed
67
68         /**
69          * Generates an array of contact and user for DFRN imports
70          *
71          * This array contains not only the receiver but also the sender of the message.
72          *
73          * @param integer $cid Contact id
74          * @param integer $uid User id
75          *
76          * @return array importer
77          * @throws \Exception
78          */
79         public static function getImporter(int $cid, int $uid = 0): array
80         {
81                 $condition = ['id' => $cid, 'blocked' => false, 'pending' => false];
82                 $contact = DBA::selectFirst('contact', [], $condition);
83                 if (!DBA::isResult($contact)) {
84                         return [];
85                 }
86
87                 $contact['cpubkey'] = $contact['pubkey'];
88                 $contact['cprvkey'] = $contact['prvkey'];
89                 $contact['senderName'] = $contact['name'];
90
91                 if ($uid != 0) {
92                         $condition = ['uid' => $uid, 'account_expired' => false, 'account_removed' => false];
93                         $user = DBA::selectFirst('user', [], $condition);
94                         if (!DBA::isResult($user)) {
95                                 return [];
96                         }
97
98                         $user['importer_uid'] = $user['uid'];
99                         $user['uprvkey'] = $user['prvkey'];
100                 } else {
101                         $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
102                                 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
103                                 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
104                 }
105
106                 return array_merge($contact, $user);
107         }
108
109         /**
110          * Generates the atom entries for delivery.php
111          *
112          * This function is used whenever content is transmitted via DFRN.
113          *
114          * @param array $items Item elements
115          * @param array $owner Owner record
116          *
117          * @return string DFRN entries
118          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
119          * @throws \ImagickException
120          * @todo  Find proper type-hints
121          */
122         public static function entries(array $items, array $owner): string
123         {
124                 $doc = new DOMDocument('1.0', 'utf-8');
125                 $doc->formatOutput = true;
126
127                 $root = self::addHeader($doc, $owner, 'dfrn:owner', '', false);
128
129                 if (! count($items)) {
130                         return trim($doc->saveXML());
131                 }
132
133                 foreach ($items as $item) {
134                         // These values aren't sent when sending from the queue.
135                         /// @todo Check if we can set these values from the queue or if they are needed at all.
136                         $item['entry:comment-allow'] = ($item['entry:comment-allow'] ?? '') ?: true;
137                         $item['entry:cid'] = $item['entry:cid'] ?? 0;
138
139                         $entry = self::entry($doc, 'text', $item, $owner, $item['entry:comment-allow'], $item['entry:cid']);
140                         if (isset($entry)) {
141                                 $root->appendChild($entry);
142                         }
143                 }
144
145                 return trim($doc->saveXML());
146         }
147
148         /**
149          * Generate an atom entry for a given uri id and user
150          *
151          * @param int     $uri_id       The uri id
152          * @param int     $uid          The user id
153          * @param boolean $conversation Show the conversation. If false show the single post.
154          *
155          * @return string DFRN feed entry
156          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
157          * @throws \ImagickException
158          */
159         public static function itemFeed(int $uri_id, int $uid, bool $conversation = false): string
160         {
161                 if ($conversation) {
162                         $condition = ['parent-uri-id' => $uri_id];
163                 } else {
164                         $condition = ['uri-id' => $uri_id];
165                 }
166
167                 $condition['uid'] = $uid;
168
169                 $items = Post::selectToArray(Item::DELIVER_FIELDLIST, $condition);
170                 if (!DBA::isResult($items)) {
171                         return '';
172                 }
173
174                 $item = $items[0];
175
176                 if ($item['uid'] != 0) {
177                         $owner = User::getOwnerDataById($item['uid']);
178                         if (!$owner) {
179                                 return '';
180                         }
181                 } else {
182                         $owner = ['uid' => 0, 'nick' => 'feed-item'];
183                 }
184
185                 $doc = new DOMDocument('1.0', 'utf-8');
186                 $doc->formatOutput = true;
187                 $type = 'html';
188
189                 if ($conversation) {
190                         $root = $doc->createElementNS(ActivityNamespace::ATOM1, 'feed');
191                         $doc->appendChild($root);
192
193                         $root->setAttribute('xmlns:thr', ActivityNamespace::THREAD);
194                         $root->setAttribute('xmlns:at', ActivityNamespace::TOMB);
195                         $root->setAttribute('xmlns:media', ActivityNamespace::MEDIA);
196                         $root->setAttribute('xmlns:dfrn', ActivityNamespace::DFRN);
197                         $root->setAttribute('xmlns:activity', ActivityNamespace::ACTIVITY);
198                         $root->setAttribute('xmlns:georss', ActivityNamespace::GEORSS);
199                         $root->setAttribute('xmlns:poco', ActivityNamespace::POCO);
200                         $root->setAttribute('xmlns:ostatus', ActivityNamespace::OSTATUS);
201                         $root->setAttribute('xmlns:statusnet', ActivityNamespace::STATUSNET);
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' => App::VERSION . '-' . DB_UPDATE_VERSION];
375                 XML::addElement($doc, $root, 'generator', App::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::warning('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'], DI::contentItem()->addSharedPost($item));
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'] != Item::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                 $attributes = [
816                         'href' => $item['conversation'],
817                         'ref' => $item['conversation'],
818                 ];
819
820                 XML::addElement($doc, $entry, 'ostatus:conversation', $item['conversation'], $attributes);
821
822                 XML::addElement($doc, $entry, 'id', $item['uri']);
823                 XML::addElement($doc, $entry, 'title', $item['title']);
824
825                 XML::addElement($doc, $entry, 'published', DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM));
826                 XML::addElement($doc, $entry, 'updated', DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM));
827
828                 // "dfrn:env" is used to read the content
829                 XML::addElement($doc, $entry, 'dfrn:env', Strings::base64UrlEncode($body, true));
830
831                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
832                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
833                 XML::addElement($doc, $entry, 'content', (($type == 'html') ? $htmlbody : $body), ['type' => $type]);
834
835                 // We save this value in "plink". Maybe we should read it from there as well?
836                 XML::addElement(
837                         $doc,
838                         $entry,
839                         'link',
840                         '',
841                         [
842                                 'rel' => 'alternate',
843                                 'type' => 'text/html',
844                                 'href' => DI::baseUrl() . '/display/' . $item['guid']
845                         ],
846                 );
847
848                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
849                 // It is included in the rewritten code for completeness
850                 if ($comment) {
851                         XML::addElement($doc, $entry, 'dfrn:comment-allow', 1);
852                 }
853
854                 if ($item['location']) {
855                         XML::addElement($doc, $entry, 'dfrn:location', $item['location']);
856                 }
857
858                 if ($item['coord']) {
859                         XML::addElement($doc, $entry, 'georss:point', $item['coord']);
860                 }
861
862                 if ($item['private']) {
863                         // Friendica versions prior to 2020.3 can't handle "unlisted" properly. So we can only transmit public and private
864                         XML::addElement($doc, $entry, 'dfrn:private', ($item['private'] == Item::PRIVATE ? Item::PRIVATE : Item::PUBLIC));
865                         XML::addElement($doc, $entry, 'dfrn:unlisted', $item['private'] == Item::UNLISTED);
866                 }
867
868                 if ($item['extid']) {
869                         XML::addElement($doc, $entry, 'dfrn:extid', $item['extid']);
870                 }
871
872                 if ($item['post-type'] == Item::PT_PAGE) {
873                         XML::addElement($doc, $entry, 'dfrn:bookmark', 'true');
874                 }
875
876                 if ($item['app']) {
877                         XML::addElement($doc, $entry, 'statusnet:notice_info', '', ['local_id' => $item['id'], 'source' => $item['app']]);
878                 }
879
880                 XML::addElement($doc, $entry, 'dfrn:diaspora_guid', $item['guid']);
881
882                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
883                 // It is needed for relayed comments to Diaspora.
884                 if ($item['signed_text']) {
885                         $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => '','signer' => '']));
886                         XML::addElement($doc, $entry, 'dfrn:diaspora_signature', $sign);
887                 }
888
889                 XML::addElement($doc, $entry, 'activity:verb', self::constructVerb($item));
890
891                 if ($item['object-type'] != '') {
892                         XML::addElement($doc, $entry, 'activity:object-type', $item['object-type']);
893                 } elseif ($item['gravity'] == Item::GRAVITY_PARENT) {
894                         XML::addElement($doc, $entry, 'activity:object-type', Activity\ObjectType::NOTE);
895                 } else {
896                         XML::addElement($doc, $entry, 'activity:object-type', Activity\ObjectType::COMMENT);
897                 }
898
899                 $actobj = self::createActivity($doc, 'activity:object', $item['object'] ?? '', $item['uri-id']);
900                 if ($actobj) {
901                         $entry->appendChild($actobj);
902                 }
903
904                 $actarg = self::createActivity($doc, 'activity:target', $item['target'] ?? '', $item['uri-id']);
905                 if ($actarg) {
906                         $entry->appendChild($actarg);
907                 }
908
909                 $tags = Tag::getByURIId($item['uri-id']);
910
911                 if (count($tags)) {
912                         foreach ($tags as $tag) {
913                                 if (($type != 'html') || ($tag['type'] == Tag::HASHTAG)) {
914                                         XML::addElement($doc, $entry, 'category', '', ['scheme' => 'X-DFRN:' . Tag::TAG_CHARACTER[$tag['type']] . ':' . $tag['url'], 'term' => $tag['name']]);
915                                 }
916                                 if ($tag['type'] != Tag::HASHTAG) {
917                                         $mentioned[$tag['url']] = $tag['url'];
918                                 }
919                         }
920                 }
921
922                 foreach ($mentioned as $mention) {
923                         $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
924                         $contact = DBA::selectFirst('contact', ['contact-type'], $condition);
925
926                         if (DBA::isResult($contact) && ($contact['contact-type'] == Contact::TYPE_COMMUNITY)) {
927                                 XML::addElement(
928                                         $doc,
929                                         $entry,
930                                         'link',
931                                         '',
932                                         [
933                                                 'rel' => 'mentioned',
934                                                 'ostatus:object-type' => Activity\ObjectType::GROUP,
935                                                 'href' => $mention,
936                                         ],
937                                 );
938                         } else {
939                                 XML::addElement(
940                                         $doc,
941                                         $entry,
942                                         'link',
943                                         '',
944                                         [
945                                                 'rel' => 'mentioned',
946                                                 'ostatus:object-type' => Activity\ObjectType::PERSON,
947                                                 'href' => $mention,
948                                         ],
949                                 );
950                         }
951                 }
952
953                 self::getAttachment($doc, $entry, $item);
954
955                 return $entry;
956         }
957
958         /**
959          * Transmits atom content to the contacts via the Diaspora transport layer
960          *
961          * @param array  $owner   Owner record
962          * @param array  $contact Contact record of the receiver
963          * @param string $atom    Content that will be transmitted
964          * @param bool   $public_batch
965          * @return int Deliver status. Negative values mean an error.
966          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
967          * @throws \ImagickException
968          */
969         public static function transmit(array $owner, array $contact, string $atom, bool $public_batch = false)
970         {
971                 if (!$public_batch) {
972                         if (empty($contact['addr'])) {
973                                 Logger::notice('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
974                                 if (Contact::updateFromProbe($contact['id'])) {
975                                         $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
976                                         $contact['addr'] = $new_contact['addr'];
977                                 }
978
979                                 if (empty($contact['addr'])) {
980                                         Logger::notice('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
981                                         return -21;
982                                 }
983                         }
984
985                         try {
986                                 $pubkey = DI::dsprContact()->getByAddr(WebFingerUri::fromString($contact['addr']))->pubKey;
987                         } catch (HTTPException\NotFoundException|\InvalidArgumentException $e) {
988                                 Logger::notice('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
989                                 return -22;
990                         }
991                 } else {
992                         $pubkey = '';
993                 }
994
995                 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
996
997                 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
998                 if ($public_batch && empty($contact['batch'])) {
999                         $parts = parse_url($contact['notify']);
1000                         $path_parts = explode('/', $parts['path']);
1001                         array_pop($path_parts);
1002                         $parts['path'] =  implode('/', $path_parts);
1003                         $contact['batch'] = (string)Uri::fromParts($parts);
1004                 }
1005
1006                 $dest_url = ($public_batch ? $contact['batch'] : $contact['notify']);
1007
1008                 if (empty($dest_url)) {
1009                         Logger::info('Empty destination', ['public' => $public_batch, 'contact' => $contact]);
1010                         return -24;
1011                 }
1012
1013                 $content_type = ($public_batch ? 'application/magic-envelope+xml' : 'application/json');
1014
1015                 $postResult = DI::httpClient()->post($dest_url, $envelope, ['Content-Type' => $content_type]);
1016                 $xml = $postResult->getBody();
1017
1018                 $curl_stat = $postResult->getReturnCode();
1019                 if (empty($curl_stat) || empty($xml)) {
1020                         Logger::notice('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1021                         return -9; // timed out
1022                 }
1023
1024                 if (($curl_stat == 503) && $postResult->inHeader('retry-after')) {
1025                         return -10;
1026                 }
1027
1028                 if (strpos($xml, '<?xml') === false) {
1029                         Logger::notice('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1030                         Logger::debug('Returned XML: ' . $xml);
1031                         return 3;
1032                 }
1033
1034                 $res = XML::parseString($xml);
1035
1036                 if (empty($res->status)) {
1037                         return -23;
1038                 }
1039
1040                 if (!empty($res->message)) {
1041                         Logger::info('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message);
1042                 }
1043
1044                 return intval($res->status);
1045         }
1046
1047         /**
1048          * Fetch the author data from head or entry items
1049          *
1050          * @param \DOMXPath $xpath     XPath object
1051          * @param \DOMNode  $context   In which context should the data be searched
1052          * @param array     $importer  Record of the importer user mixed with contact of the content
1053          * @param string    $element   Element name from which the data is fetched
1054          * @param bool      $onlyfetch Should the data only be fetched or should it update the contact record as well
1055          * @param string    $xml       optional, default empty
1056          *
1057          * @return array Relevant data of the author
1058          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1059          * @throws \ImagickException
1060          * @todo  Find good type-hints for all parameter
1061          */
1062         private static function fetchauthor(\DOMXPath $xpath, \DOMNode $context, array $importer, string $element, bool $onlyfetch, string $xml = ''): array
1063         {
1064                 $author = [];
1065                 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1066                 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1067
1068                 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1069                         'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1070                 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ? AND NOT `pending` AND NOT `blocked`",
1071                         $importer["importer_uid"], Strings::normaliseLink($author["link"]), Protocol::STATUSNET];
1072
1073                 if ($importer['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
1074                         $condition = DBA::mergeConditions($condition, ['rel' => [Contact::SHARING, Contact::FRIEND]]);
1075                 }
1076
1077                 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1078
1079                 if (DBA::isResult($contact_old)) {
1080                         $author["contact-id"] = $contact_old["id"];
1081                         $author["network"] = $contact_old["network"];
1082                 } else {
1083                         Logger::info('Contact not found', ['condition' => $condition]);
1084
1085                         $author["contact-unknown"] = true;
1086                         $contact = Contact::getByURL($author["link"], null, ["id", "network"]);
1087                         $author["contact-id"] = $contact["id"] ?? $importer["id"];
1088                         $author["network"] = $contact["network"] ?? $importer["network"];
1089                         $onlyfetch = true;
1090                 }
1091
1092                 // Until now we aren't serving different sizes - but maybe later
1093                 $avatarlist = [];
1094                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1095                 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1096                 foreach ($avatars as $avatar) {
1097                         $href = "";
1098                         $width = 0;
1099                         foreach ($avatar->attributes as $attributes) {
1100                                 /// @TODO Rewrite these similar if() to one switch
1101                                 if ($attributes->name == "href") {
1102                                         $href = $attributes->textContent;
1103                                 }
1104                                 if ($attributes->name == "width") {
1105                                         $width = $attributes->textContent;
1106                                 }
1107                                 if ($attributes->name == "updated") {
1108                                         $author["avatar-date"] = $attributes->textContent;
1109                                 }
1110                         }
1111                         if (($width > 0) && ($href != "")) {
1112                                 $avatarlist[$width] = $href;
1113                         }
1114                 }
1115
1116                 if (count($avatarlist) > 0) {
1117                         krsort($avatarlist);
1118                         $author["avatar"] = current($avatarlist);
1119                 }
1120
1121                 if (empty($author['avatar']) && !empty($author['link'])) {
1122                         $cid = Contact::getIdForURL($author['link'], 0);
1123                         if (!empty($cid)) {
1124                                 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1125                                 if (DBA::isResult($contact)) {
1126                                         $author['avatar'] = $contact['avatar'];
1127                                 }
1128                         }
1129                 }
1130
1131                 if (empty($author['avatar'])) {
1132                         Logger::notice('Empty author: ' . $xml);
1133                         $author['avatar'] = '';
1134                 }
1135
1136                 if (DBA::isResult($contact_old) && !$onlyfetch) {
1137                         Logger::info("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.");
1138
1139                         $poco = ["url" => $contact_old["url"], "network" => $contact_old["network"]];
1140
1141                         // When was the last change to name or uri?
1142                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1143                         foreach ($name_element->attributes as $attributes) {
1144                                 if ($attributes->name == "updated") {
1145                                         $poco["name-date"] = $attributes->textContent;
1146                                 }
1147                         }
1148
1149                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1150                         foreach ($link_element->attributes as $attributes) {
1151                                 if ($attributes->name == "updated") {
1152                                         $poco["uri-date"] = $attributes->textContent;
1153                                 }
1154                         }
1155
1156                         // Update contact data
1157                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1158                         if ($value != "") {
1159                                 $poco["addr"] = $value;
1160                         }
1161
1162                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1163                         if ($value != "") {
1164                                 $poco["name"] = $value;
1165                         }
1166
1167                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1168                         if ($value != "") {
1169                                 $poco["nick"] = $value;
1170                         }
1171
1172                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1173                         if ($value != "") {
1174                                 $poco["about"] = $value;
1175                         }
1176
1177                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1178                         if ($value != "") {
1179                                 $poco["location"] = $value;
1180                         }
1181
1182                         /// @todo Only search for elements with "poco:type" = "xmpp"
1183                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1184                         if ($value != "") {
1185                                 $poco["xmpp"] = $value;
1186                         }
1187
1188                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1189                         /// - poco:utcOffset
1190                         /// - poco:urls
1191                         /// - poco:locality
1192                         /// - poco:region
1193                         /// - poco:country
1194
1195                         // If the "hide" element is present then the profile isn't searchable.
1196                         $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1197
1198                         Logger::info("Hidden status for contact " . $contact_old["url"] . ": " . $hide);
1199
1200                         // If the contact isn't searchable then set the contact to "hidden".
1201                         // Problem: This can be manually overridden by the user.
1202                         if ($hide) {
1203                                 $contact_old["hidden"] = true;
1204                         }
1205
1206                         // Save the keywords into the contact table
1207                         $tags = [];
1208                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1209                         foreach ($tagelements as $tag) {
1210                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1211                         }
1212
1213                         if (count($tags)) {
1214                                 $poco["keywords"] = implode(", ", $tags);
1215                         }
1216
1217                         // "dfrn:birthday" contains the birthday converted to UTC
1218                         $birthday = XML::getFirstNodeValue($xpath, $element . "/dfrn:birthday/text()", $context);
1219                         try {
1220                                 $birthday_date = new \DateTime($birthday);
1221                                 if ($birthday_date > new \DateTime()) {
1222                                         $poco["bdyear"] = $birthday_date->format("Y");
1223                                 }
1224                         } catch (\Exception $e) {
1225                                 // Invalid birthday
1226                         }
1227
1228                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1229                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1230
1231                         if (!in_array($value, ["", "0000-00-00", DBA::NULL_DATE])) {
1232                                 $bdyear = date("Y");
1233                                 $value = str_replace(["0000", "0001"], $bdyear, $value);
1234
1235                                 if (strtotime($value) < time()) {
1236                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1237                                 }
1238
1239                                 $poco["bd"] = $value;
1240                         }
1241
1242                         $contact = array_merge($contact_old, $poco);
1243
1244                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1245                                 Event::createBirthday($contact, $birthday);
1246                         }
1247
1248                         $fields = ['name' => $contact['name'], 'nick' => $contact['nick'], 'about' => $contact['about'],
1249                                 'location' => $contact['location'], 'addr' => $contact['addr'], 'keywords' => $contact['keywords'],
1250                                 'bdyear' => $contact['bdyear'], 'bd' => $contact['bd'], 'hidden' => $contact['hidden'],
1251                                 'xmpp' => $contact['xmpp'], 'name-date' => DateTimeFormat::utc($contact['name-date']),
1252                                 'unsearchable' => $contact['hidden'], 'uri-date' => DateTimeFormat::utc($contact['uri-date'])];
1253
1254                         Contact::update($fields, ['id' => $contact['id'], 'network' => $contact['network']], $contact_old);
1255
1256                         // Update the public contact. Don't set the "hidden" value, this is used differently for public contacts
1257                         unset($fields['hidden']);
1258                         $condition = ['uid' => 0, 'nurl' => Strings::normaliseLink($contact_old['url'])];
1259                         Contact::update($fields, $condition, true);
1260
1261                         Contact::updateAvatar($contact['id'], $author['avatar']);
1262
1263                         $pcid = Contact::getIdForURL($contact_old['url']);
1264                         if (!empty($pcid)) {
1265                                 Contact::updateAvatar($pcid, $author['avatar']);
1266                         }
1267                 }
1268
1269                 return $author;
1270         }
1271
1272         /**
1273          * Transforms activity objects into an XML string
1274          *
1275          * @param object $xpath    XPath object
1276          * @param object $activity Activity object
1277          * @param string $element  element name
1278          *
1279          * @return string XML string
1280          * @todo Find good type-hints for all parameter
1281          */
1282         private static function transformActivity($xpath, $activity, string $element): string
1283         {
1284                 if (!is_object($activity)) {
1285                         return "";
1286                 }
1287
1288                 $obj_doc = new DOMDocument("1.0", "utf-8");
1289                 $obj_doc->formatOutput = true;
1290
1291                 $obj_element = $obj_doc->createElementNS( ActivityNamespace::ATOM1, $element);
1292
1293                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1294                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1295
1296                 $id = $xpath->query("atom:id", $activity)->item(0);
1297                 if (is_object($id)) {
1298                         $obj_element->appendChild($obj_doc->importNode($id, true));
1299                 }
1300
1301                 $title = $xpath->query("atom:title", $activity)->item(0);
1302                 if (is_object($title)) {
1303                         $obj_element->appendChild($obj_doc->importNode($title, true));
1304                 }
1305
1306                 $links = $xpath->query("atom:link", $activity);
1307                 if (is_object($links)) {
1308                         foreach ($links as $link) {
1309                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1310                         }
1311                 }
1312
1313                 $content = $xpath->query("atom:content", $activity)->item(0);
1314                 if (is_object($content)) {
1315                         $obj_element->appendChild($obj_doc->importNode($content, true));
1316                 }
1317
1318                 $obj_doc->appendChild($obj_element);
1319
1320                 $objxml = $obj_doc->saveXML($obj_element);
1321
1322                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1323                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1324                 return($objxml);
1325         }
1326
1327         /**
1328          * Processes the mail elements
1329          *
1330          * @param DOMXPath $xpath    XPath object
1331          * @param DOMNode  $mail     mail elements
1332          * @param array    $importer Record of the importer user mixed with contact of the content
1333          * @return void
1334          * @throws \Exception
1335          */
1336         private static function processMail(DOMXPath $xpath, DOMNode $mail, array $importer)
1337         {
1338                 Logger::notice("Processing mails");
1339
1340                 $msg = [];
1341                 $msg['uid'] = $importer['importer_uid'];
1342                 $msg['from-name'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:name/text()', $mail);
1343                 $msg['from-url'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:uri/text()', $mail);
1344                 $msg['from-photo'] = XML::getFirstValue($xpath, 'dfrn:sender/dfrn:avatar/text()', $mail);
1345                 $msg['contact-id'] = $importer['id'];
1346                 $msg['uri'] = XML::getFirstValue($xpath, 'dfrn:id/text()', $mail);
1347                 $msg['parent-uri'] = XML::getFirstValue($xpath, 'dfrn:in-reply-to/text()', $mail);
1348                 $msg['created'] = DateTimeFormat::utc(XML::getFirstValue($xpath, 'dfrn:sentdate/text()', $mail));
1349                 $msg['title'] = XML::getFirstValue($xpath, 'dfrn:subject/text()', $mail);
1350                 $msg['body'] = XML::getFirstValue($xpath, 'dfrn:content/text()', $mail);
1351
1352                 Mail::insert($msg);
1353         }
1354
1355         /**
1356          * Processes the suggestion elements
1357          *
1358          * @param DOMXPath $xpath      XPath object
1359          * @param DOMNode  $suggestion suggestion elements
1360          * @param array    $importer   Record of the importer user mixed with contact of the content
1361          * @return boolean
1362          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363          */
1364         private static function processSuggestion(DOMXPath $xpath, DOMNode $suggestion, array $importer)
1365         {
1366                 Logger::notice('Processing suggestions');
1367
1368                 $url = $xpath->evaluate('string(dfrn:url[1]/text())', $suggestion);
1369                 $cid = Contact::getIdForURL($url);
1370                 $note = $xpath->evaluate('string(dfrn:note[1]/text())', $suggestion);
1371
1372                 return self::addSuggestion($importer['importer_uid'], $cid, $importer['id'], $note);
1373         }
1374
1375         /**
1376          * Suggest a given contact to a given user from a given contact
1377          *
1378          * @param integer $uid
1379          * @param integer $cid
1380          * @param integer $from_cid
1381          * @return bool   Was the adding successful?
1382          */
1383         private static function addSuggestion(int $uid, int $cid, int $from_cid, string $note = ''): bool
1384         {
1385                 $owner = User::getOwnerDataById($uid);
1386                 $contact = Contact::getById($cid);
1387                 $from_contact = Contact::getById($from_cid);
1388
1389                 if (DBA::exists('contact', ['nurl' => Strings::normaliseLink($contact['url']), 'uid' => $uid])) {
1390                         return false;
1391                 }
1392
1393                 // Quit if we already have an introduction for this person
1394                 if (DI::intro()->suggestionExistsForUser($cid, $uid)) {
1395                         return false;
1396                 }
1397
1398                 $suggest = [];
1399                 $suggest['uid'] = $uid;
1400                 $suggest['cid'] = $from_cid;
1401                 $suggest['url'] = $contact['url'];
1402                 $suggest['name'] = $contact['name'];
1403                 $suggest['photo'] = $contact['photo'];
1404                 $suggest['request'] = $contact['request'];
1405                 $suggest['title'] = '';
1406                 $suggest['body'] = $note;
1407
1408                 DI::intro()->save(DI::introFactory()->createNew(
1409                         $suggest['uid'],
1410                         $suggest['cid'],
1411                         $suggest['body'],
1412                         null,
1413                         $cid
1414                 ));
1415
1416                 DI::notify()->createFromArray([
1417                         'type'  => Notification\Type::SUGGEST,
1418                         'otype' => Notification\ObjectType::INTRO,
1419                         'verb'  => Activity::REQ_FRIEND,
1420                         'uid'   => $owner['uid'],
1421                         'cid'   => $from_contact['uid'],
1422                         'item'  => $suggest,
1423                         'link'  => DI::baseUrl().'/notifications/intros',
1424                 ]);
1425
1426                 return true;
1427         }
1428
1429         /**
1430          * Processes the relocation elements
1431          *
1432          * @param DOMXPath $xpath      XPath object
1433          * @param DOMNode  $relocation relocation elements
1434          * @param array    $importer   Record of the importer user mixed with contact of the content
1435          * @return boolean
1436          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1437          * @throws \ImagickException
1438          * @todo  Find good type-hints for all parameter
1439          */
1440         private static function processRelocation(DOMXPath $xpath, DOMNode $relocation, array $importer): bool
1441         {
1442                 Logger::notice("Processing relocations");
1443
1444                 /// @TODO Rewrite this to one statement
1445                 $relocate = [];
1446                 $relocate['uid'] = $importer['importer_uid'];
1447                 $relocate['cid'] = $importer['id'];
1448                 $relocate['url'] = $xpath->query('dfrn:url/text()', $relocation)->item(0)->nodeValue;
1449                 $relocate['addr'] = $xpath->query('dfrn:addr/text()', $relocation)->item(0)->nodeValue;
1450                 $relocate['name'] = $xpath->query('dfrn:name/text()', $relocation)->item(0)->nodeValue;
1451                 $relocate['avatar'] = $xpath->query('dfrn:avatar/text()', $relocation)->item(0)->nodeValue;
1452                 $relocate['photo'] = $xpath->query('dfrn:photo/text()', $relocation)->item(0)->nodeValue;
1453                 $relocate['thumb'] = $xpath->query('dfrn:thumb/text()', $relocation)->item(0)->nodeValue;
1454                 $relocate['micro'] = $xpath->query('dfrn:micro/text()', $relocation)->item(0)->nodeValue;
1455                 $relocate['request'] = $xpath->query('dfrn:request/text()', $relocation)->item(0)->nodeValue;
1456                 $relocate['confirm'] = $xpath->query('dfrn:confirm/text()', $relocation)->item(0)->nodeValue;
1457                 $relocate['notify'] = $xpath->query('dfrn:notify/text()', $relocation)->item(0)->nodeValue;
1458                 $relocate['poll'] = $xpath->query('dfrn:poll/text()', $relocation)->item(0)->nodeValue;
1459                 $relocate['sitepubkey'] = $xpath->query('dfrn:sitepubkey/text()', $relocation)->item(0)->nodeValue;
1460
1461                 if (($relocate['avatar'] == '') && ($relocate['photo'] != '')) {
1462                         $relocate['avatar'] = $relocate['photo'];
1463                 }
1464
1465                 if ($relocate['addr'] == '') {
1466                         $relocate['addr'] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", '$3@$2', $relocate['url']);
1467                 }
1468
1469                 // update contact
1470                 $old = Contact::selectFirst(['photo', 'url'], ['id' => $importer['id'], 'uid' => $importer['importer_uid']]);
1471                 if (!DBA::isResult($old)) {
1472                         Logger::warning('Existing contact had not been fetched', ['id' => $importer['id']]);
1473                         return false;
1474                 }
1475
1476                 // Update the contact table. We try to find every entry.
1477                 $fields = [
1478                         'name' => $relocate['name'],
1479                         'avatar' => $relocate['avatar'],
1480                         'url' => $relocate['url'],
1481                         'nurl' => Strings::normaliseLink($relocate['url']),
1482                         'addr' => $relocate['addr'],
1483                         'request' => $relocate['request'],
1484                         'confirm' => $relocate['confirm'],
1485                         'notify' => $relocate['notify'],
1486                         'poll' => $relocate['poll'],
1487                         'site-pubkey' => $relocate['sitepubkey'],
1488                 ];
1489                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer['id'], Strings::normaliseLink($old['url'])];
1490
1491                 Contact::update($fields, $condition);
1492
1493                 Contact::updateAvatar($importer['id'], $relocate['avatar'], true);
1494
1495                 Logger::notice('Contacts are updated.');
1496
1497                 /// @TODO
1498                 /// merge with current record, current contents have priority
1499                 /// update record, set url-updated
1500                 /// update profile photos
1501                 /// schedule a scan?
1502                 return true;
1503         }
1504
1505         /**
1506          * Updates an item
1507          *
1508          * @param array $current   the current item record
1509          * @param array $item      the new item record
1510          * @param array $importer  Record of the importer user mixed with contact of the content
1511          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
1512          * @return mixed
1513          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1514          * @todo  set proper type-hints (array?)
1515          */
1516         private static function updateContent(array $current, array $item, array $importer, int $entrytype)
1517         {
1518                 $changed = false;
1519
1520                 if (self::isEditedTimestampNewer($current, $item)) {
1521                         // do not accept (ignore) an earlier edit than one we currently have.
1522                         if (DateTimeFormat::utc($item['edited']) < $current['edited']) {
1523                                 return false;
1524                         }
1525
1526                         $fields = [
1527                                 'title' => $item['title'] ?? '',
1528                                 'body' => $item['body'] ?? '',
1529                                 'changed' => DateTimeFormat::utcNow(),
1530                                 'edited' => DateTimeFormat::utc($item['edited']),
1531                         ];
1532
1533                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item['uri'], $importer['importer_uid']];
1534                         Item::update($fields, $condition);
1535
1536                         $changed = true;
1537                 }
1538                 return $changed;
1539         }
1540
1541         /**
1542          * Detects the entry type of the item
1543          *
1544          * @param array $importer Record of the importer user mixed with contact of the content
1545          * @param array $item     the new item record
1546          *
1547          * @return int Is it a toplevel entry, a comment or a relayed comment?
1548          * @throws \Exception
1549          * @todo  set proper type-hints (array?)
1550          */
1551         private static function getEntryType(array $importer, array $item): int
1552         {
1553                 if ($item['thr-parent'] != $item['uri']) {
1554                         // was the top-level post for this action written by somebody on this site?
1555                         // Specifically, the recipient?
1556                         if (Post::exists(['uri' => $item['thr-parent'], 'uid' => $importer['importer_uid'], 'self' => true, 'wall' => true])) {
1557                                 return self::REPLY_RC;
1558                         } else {
1559                                 return self::REPLY;
1560                         }
1561                 } else {
1562                         return self::TOP_LEVEL;
1563                 }
1564         }
1565
1566         /**
1567          * Processes several actions, depending on the verb
1568          *
1569          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
1570          * @param array $importer  Record of the importer user mixed with contact of the content
1571          * @param array $item      the new item record
1572          *
1573          * @return bool Should the processing of the entries be continued?
1574          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1575          */
1576         private static function processVerbs(int $entrytype, array $importer, array &$item)
1577         {
1578                 Logger::info('Process verb ' . $item['verb'] . ' and object-type ' . $item['object-type'] . ' for entrytype ' . $entrytype);
1579
1580                 if (($entrytype == self::TOP_LEVEL) && !empty($importer['id'])) {
1581                         // The filling of the the "contact" variable is done for legcy reasons
1582                         // The functions below are partly used by ostatus.php as well - where we have this variable
1583                         $contact = Contact::selectFirst([], ['id' => $importer['id']]);
1584
1585                         $activity = DI::activity();
1586
1587                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
1588                         // This function once was responsible for DFRN and OStatus.
1589                         if ($activity->match($item['verb'], Activity::FOLLOW)) {
1590                                 Logger::notice("New follower");
1591                                 Contact::addRelationship($importer, $contact, $item);
1592                                 return false;
1593                         }
1594                         if ($activity->match($item['verb'], Activity::UNFOLLOW)) {
1595                                 Logger::notice("Lost follower");
1596                                 Contact::removeFollower($contact);
1597                                 return false;
1598                         }
1599                         if ($activity->match($item['verb'], Activity::REQ_FRIEND)) {
1600                                 Logger::notice("New friend request");
1601                                 Contact::addRelationship($importer, $contact, $item, true);
1602                                 return false;
1603                         }
1604                         if ($activity->match($item['verb'], Activity::UNFRIEND)) {
1605                                 Logger::notice("Lost sharer");
1606                                 Contact::removeSharer($contact);
1607                                 return false;
1608                         }
1609                 } else {
1610                         if (($item['verb'] == Activity::LIKE)
1611                                 || ($item['verb'] == Activity::DISLIKE)
1612                                 || ($item['verb'] == Activity::ATTEND)
1613                                 || ($item['verb'] == Activity::ATTENDNO)
1614                                 || ($item['verb'] == Activity::ATTENDMAYBE)
1615                                 || ($item['verb'] == Activity::ANNOUNCE)
1616                         ) {
1617                                 $item['gravity'] = Item::GRAVITY_ACTIVITY;
1618                                 // only one like or dislike per person
1619                                 // split into two queries for performance issues
1620                                 $condition = [
1621                                         'uid'        => $item['uid'],
1622                                         'author-id'  => $item['author-id'],
1623                                         'gravity'    => Item::GRAVITY_ACTIVITY,
1624                                         'verb'       => $item['verb'],
1625                                         'parent-uri' => $item['thr-parent'],
1626                                 ];
1627                                 if (Post::exists($condition)) {
1628                                         return false;
1629                                 }
1630
1631                                 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'gravity' => Item::GRAVITY_ACTIVITY,
1632                                         'verb' => $item['verb'], 'thr-parent' => $item['thr-parent']];
1633                                 if (Post::exists($condition)) {
1634                                         return false;
1635                                 }
1636
1637                                 // The owner of an activity must be the author
1638                                 $item['owner-name'] = $item['author-name'];
1639                                 $item['owner-link'] = $item['author-link'];
1640                                 $item['owner-avatar'] = $item['author-avatar'];
1641                                 $item['owner-id'] = $item['author-id'];
1642                         }
1643
1644                         if (($item['verb'] == Activity::TAG) && ($item['object-type'] == Activity\ObjectType::TAGTERM)) {
1645                                 $xo = XML::parseString($item['object']);
1646                                 $xt = XML::parseString($item['target']);
1647
1648                                 if ($xt->type == Activity\ObjectType::NOTE) {
1649                                         $item_tag = Post::selectFirst(['id', 'uri-id'], ['uri' => $xt->id, 'uid' => $importer['importer_uid']]);
1650                                         if (!DBA::isResult($item_tag)) {
1651                                                 Logger::warning('Post had not been fetched', ['uri' => $xt->id, 'uid' => $importer['importer_uid']]);
1652                                                 return false;
1653                                         }
1654
1655                                         // extract tag, if not duplicate, add to parent item
1656                                         if ($xo->content) {
1657                                                 Tag::store($item_tag['uri-id'], Tag::HASHTAG, $xo->content);
1658                                         }
1659                                 }
1660                         }
1661                 }
1662                 return true;
1663         }
1664
1665         /**
1666          * Processes the link elements
1667          *
1668          * @param object $links link elements
1669          * @param array  $item  the item record
1670          * @return void
1671          * @todo set proper type-hints
1672          */
1673         private static function parseLinks($links, array &$item)
1674         {
1675                 $rel = '';
1676                 $href = '';
1677                 $type = null;
1678                 $length = null;
1679                 $title = null;
1680                 foreach ($links as $link) {
1681                         foreach ($link->attributes as $attributes) {
1682                                 switch ($attributes->name) {
1683                                         case 'href'  : $href   = $attributes->textContent; break;
1684                                         case 'rel'   : $rel    = $attributes->textContent; break;
1685                                         case 'type'  : $type   = $attributes->textContent; break;
1686                                         case 'length': $length = $attributes->textContent; break;
1687                                         case 'title' : $title  = $attributes->textContent; break;
1688                                 }
1689                         }
1690                         if (($rel != '') && ($href != '')) {
1691                                 switch ($rel) {
1692                                         case 'alternate':
1693                                                 $item['plink'] = $href;
1694                                                 break;
1695
1696                                         case 'enclosure':
1697                                                 Post\Media::insert(['uri-id' => $item['uri-id'], 'type' => Post\Media::DOCUMENT,
1698                                                         'url' => $href, 'mimetype' => $type, 'size' => $length, 'description' => $title]);
1699                                                 break;
1700                                 }
1701                         }
1702                 }
1703         }
1704
1705         /**
1706          * Checks if an incoming message is wanted
1707          *
1708          * @param array $item
1709          * @param array $imporer
1710          * @return boolean Is the message wanted?
1711          */
1712         private static function isSolicitedMessage(array $item, array $importer): bool
1713         {
1714                 if (DBA::exists('contact', ["`nurl` = ? AND `uid` != ? AND `rel` IN (?, ?)",
1715                         Strings::normaliseLink($item["author-link"]), 0, Contact::FRIEND, Contact::SHARING])) {
1716                         Logger::debug('Author has got followers - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'author' => $item["author-link"]]);
1717                         return true;
1718                 }
1719
1720                 if ($importer['importer_uid'] != 0) {
1721                         Logger::debug('Message is directed to a user - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri'], 'importer' => $importer['importer_uid']]);
1722                         return true;
1723                 }
1724
1725                 if ($item['uri'] != $item['thr-parent']) {
1726                         Logger::debug('Message is no parent - accepted', ['uri-id' => $item['uri-id'], 'guid' => $item['guid'], 'url' => $item['uri']]);
1727                         return true;
1728                 }
1729
1730                 $tags = array_column(Tag::getByURIId($item['uri-id'], [Tag::HASHTAG]), 'name');
1731                 if (Relay::isSolicitedPost($tags, $item['body'], $item['author-id'], $item['uri'], Protocol::DFRN)) {
1732                         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"]]);
1733                         return true;
1734                 } else {
1735                         return false;
1736                 }
1737         }
1738
1739         /**
1740          * Processes the entry elements which contain the items and comments
1741          *
1742          * @param array    $header   Array of the header elements that always stay the same
1743          * @param DOMXPath $xpath    XPath object
1744          * @param DOMNode  $entry    entry elements
1745          * @param array    $importer Record of the importer user mixed with contact of the content
1746          * @param string   $xml      XML
1747          * @param int $protocol Protocol
1748          * @return void
1749          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1750          * @throws \ImagickException
1751          * @todo  Add type-hints
1752          */
1753         private static function processEntry(array $header, DOMXPath $xpath, DOMNode $entry, array $importer, string $xml, int $protocol)
1754         {
1755                 Logger::notice("Processing entries");
1756
1757                 $item = $header;
1758
1759                 $item['source'] = $xml;
1760
1761                 // Get the uri
1762                 $item['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
1763
1764                 $item['edited'] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
1765
1766                 $current = Post::selectFirst(['id', 'uid', 'edited', 'body'],
1767                         ['uri' => $item['uri'], 'uid' => $importer['importer_uid']]
1768                 );
1769                 // Is there an existing item?
1770                 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
1771                         Logger::info("Item " . $item['uri'] . " (" . $item['edited'] . ") already existed.");
1772                         return;
1773                 }
1774
1775                 // Fetch the owner
1776                 $owner = self::fetchauthor($xpath, $entry, $importer, 'dfrn:owner', true, $xml);
1777
1778                 $owner_unknown = (isset($owner['contact-unknown']) && $owner['contact-unknown']);
1779
1780                 $item['owner-name'] = $owner['name'];
1781                 $item['owner-link'] = $owner['link'];
1782                 $item['owner-avatar'] = $owner['avatar'];
1783                 $item['owner-id'] = Contact::getIdForURL($owner['link'], 0);
1784
1785                 // fetch the author
1786                 $author = self::fetchauthor($xpath, $entry, $importer, 'atom:author', true, $xml);
1787
1788                 $item['author-name'] = $author['name'];
1789                 $item['author-link'] = $author['link'];
1790                 $item['author-avatar'] = $author['avatar'];
1791                 $item['author-id'] = Contact::getIdForURL($author['link'], 0);
1792
1793                 $item['title'] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
1794
1795                 if (!empty($item['title'])) {
1796                         $item['post-type'] = Item::PT_ARTICLE;
1797                 } else {
1798                         $item['post-type'] = Item::PT_NOTE;
1799                 }
1800
1801                 $item['created'] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
1802
1803                 $item['body'] = XML::getFirstNodeValue($xpath, 'dfrn:env/text()', $entry);
1804                 $item['body'] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item['body']);
1805
1806                 $item['body'] = Strings::base64UrlDecode($item['body']);
1807
1808                 $item['body'] = BBCode::limitBodySize($item['body']);
1809
1810                 /// @todo We should check for a repeated post and if we know the repeated author.
1811
1812                 // We don't need the content element since "dfrn:env" is always present
1813                 //$item['body'] = $xpath->query('atom:content/text()', $entry)->item(0)->nodeValue;
1814                 $item['location'] = XML::getFirstNodeValue($xpath, 'dfrn:location/text()', $entry);
1815                 $item['coord'] = XML::getFirstNodeValue($xpath, 'georss:point', $entry);
1816                 $item['private'] = XML::getFirstNodeValue($xpath, 'dfrn:private/text()', $entry);
1817
1818                 $unlisted = XML::getFirstNodeValue($xpath, 'dfrn:unlisted/text()', $entry);
1819                 if (!empty($unlisted) && ($item['private'] != Item::PRIVATE)) {
1820                         $item['private'] = Item::UNLISTED;
1821                 }
1822
1823                 $item['extid'] = XML::getFirstNodeValue($xpath, 'dfrn:extid/text()', $entry);
1824
1825                 if (XML::getFirstNodeValue($xpath, 'dfrn:bookmark/text()', $entry) == 'true') {
1826                         $item['post-type'] = Item::PT_PAGE;
1827                 }
1828
1829                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
1830                 if ($notice_info && ($notice_info->length > 0)) {
1831                         foreach ($notice_info->item(0)->attributes as $attributes) {
1832                                 if ($attributes->name == 'source') {
1833                                         $item['app'] = strip_tags($attributes->textContent);
1834                                 }
1835                         }
1836                 }
1837
1838                 $item['guid'] = XML::getFirstNodeValue($xpath, 'dfrn:diaspora_guid/text()', $entry);
1839
1840                 $item['uri-id'] = ItemURI::insert(['uri' => $item['uri'], 'guid' => $item['guid']]);
1841
1842                 $quote_uri_id = Item::getQuoteUriId($item['body'], $item['uid']);
1843                 if (!empty($quote_uri_id)) {
1844                         $item['quote-uri-id'] = $quote_uri_id;
1845                         $item['body']         = BBCode::removeSharedData($item['body']);
1846                 }
1847
1848                 Tag::storeFromBody($item['uri-id'], $item['body']);
1849
1850                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
1851                 $dsprsig = XML::unescape(XML::getFirstNodeValue($xpath, 'dfrn:diaspora_signature/text()', $entry));
1852                 if ($dsprsig != '') {
1853                         $signature = json_decode(base64_decode($dsprsig));
1854                         // We don't store the old style signatures anymore that also contained the "signature" and "signer"
1855                         if (!empty($signature->signed_text) && empty($signature->signature) && empty($signature->signer)) {
1856                                 $item['diaspora_signed_text'] = $signature->signed_text;
1857                         }
1858                 }
1859
1860                 $item['verb'] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
1861
1862                 if (XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry) != '') {
1863                         $item['object-type'] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
1864                 }
1865
1866                 $object = $xpath->query('activity:object', $entry)->item(0);
1867                 $item['object'] = self::transformActivity($xpath, $object, 'object');
1868
1869                 if (trim($item['object']) != '') {
1870                         $r = XML::parseString($item['object']);
1871                         if (isset($r->type)) {
1872                                 $item['object-type'] = $r->type;
1873                         }
1874                 }
1875
1876                 $target = $xpath->query('activity:target', $entry)->item(0);
1877                 $item['target'] = self::transformActivity($xpath, $target, 'target');
1878
1879                 $categories = $xpath->query('atom:category', $entry);
1880                 if ($categories) {
1881                         foreach ($categories as $category) {
1882                                 $term = '';
1883                                 $scheme = '';
1884                                 foreach ($category->attributes as $attributes) {
1885                                         if ($attributes->name == 'term') {
1886                                                 $term = $attributes->textContent;
1887                                         }
1888
1889                                         if ($attributes->name == 'scheme') {
1890                                                 $scheme = $attributes->textContent;
1891                                         }
1892                                 }
1893
1894                                 if (($term != '') && ($scheme != '')) {
1895                                         $parts = explode(':', $scheme);
1896                                         if ((count($parts) >= 4) && (array_shift($parts) == 'X-DFRN')) {
1897                                                 $termurl = array_pop($parts);
1898                                                 $termurl = array_pop($parts) . ':' . $termurl;
1899                                                 Tag::store($item['uri-id'], Tag::IMPLICIT_MENTION, $term, $termurl);
1900                                         }
1901                                 }
1902                         }
1903                 }
1904
1905                 $links = $xpath->query('atom:link', $entry);
1906                 if ($links) {
1907                         self::parseLinks($links, $item);
1908                 }
1909
1910                 $item['conversation'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
1911
1912                 $conv = $xpath->query('ostatus:conversation', $entry);
1913                 if (is_object($conv->item(0))) {
1914                         foreach ($conv->item(0)->attributes as $attributes) {
1915                                 if ($attributes->name == 'ref') {
1916                                         $item['conversation'] = $attributes->textContent;
1917                                 }
1918                                 if ($attributes->name == 'href') {
1919                                         $item['conversation'] = $attributes->textContent;
1920                                 }
1921                         }
1922                 }
1923
1924                 // Is it a reply or a top level posting?
1925                 $item['thr-parent'] = $item['uri'];
1926
1927                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
1928                 if (is_object($inreplyto->item(0))) {
1929                         foreach ($inreplyto->item(0)->attributes as $attributes) {
1930                                 if ($attributes->name == 'ref') {
1931                                         $item['thr-parent'] = $attributes->textContent;
1932                                 }
1933                         }
1934                 }
1935
1936                 // Check if the message is wanted
1937                 if (!self::isSolicitedMessage($item, $importer)) {
1938                         DBA::delete('item-uri', ['uri' => $item['uri']]);
1939                         return 403;
1940                 }
1941
1942                 // Get the type of the item (Top level post, reply or remote reply)
1943                 $entrytype = self::getEntryType($importer, $item);
1944
1945                 // Now assign the rest of the values that depend on the type of the message
1946                 if (in_array($entrytype, [self::REPLY, self::REPLY_RC])) {
1947                         $item['gravity'] = Item::GRAVITY_COMMENT;
1948
1949                         if (!isset($item['object-type'])) {
1950                                 $item['object-type'] = Activity\ObjectType::COMMENT;
1951                         }
1952
1953                         if ($item['contact-id'] != $owner['contact-id']) {
1954                                 $item['contact-id'] = $owner['contact-id'];
1955                         }
1956
1957                         if (($item['network'] != $owner['network']) && ($owner['network'] != '')) {
1958                                 $item['network'] = $owner['network'];
1959                         }
1960
1961                         if ($item['contact-id'] != $author['contact-id']) {
1962                                 $item['contact-id'] = $author['contact-id'];
1963                         }
1964
1965                         if (($item['network'] != $author['network']) && ($author['network'] != '')) {
1966                                 $item['network'] = $author['network'];
1967                         }
1968                 }
1969
1970                 if ($entrytype == self::REPLY_RC) {
1971                         $item['wall'] = 1;
1972                 } elseif ($entrytype == self::TOP_LEVEL) {
1973                         $item['gravity'] = Item::GRAVITY_PARENT;
1974
1975                         if (!isset($item['object-type'])) {
1976                                 $item['object-type'] = Activity\ObjectType::NOTE;
1977                         }
1978
1979                         // Is it an event?
1980                         if (($item['object-type'] == Activity\ObjectType::EVENT) && !$owner_unknown) {
1981                                 Logger::info("Item " . $item['uri'] . " seems to contain an event.");
1982                                 $ev = Event::fromBBCode($item['body']);
1983                                 if ((!empty($ev['desc']) || !empty($ev['summary'])) && !empty($ev['start'])) {
1984                                         Logger::info("Event in item " . $item['uri'] . " was found.");
1985                                         $ev['cid']       = $importer['id'];
1986                                         $ev['uid']       = $importer['importer_uid'];
1987                                         $ev['uri']       = $item['uri'];
1988                                         $ev['edited']    = $item['edited'];
1989                                         $ev['private']   = $item['private'];
1990                                         $ev['guid']      = $item['guid'];
1991                                         $ev['plink']     = $item['plink'];
1992                                         $ev['network']   = $item['network'];
1993                                         $ev['protocol']  = $item['protocol'];
1994                                         $ev['direction'] = $item['direction'];
1995                                         $ev['source']    = $item['source'];
1996
1997                                         $condition = ['uri' => $item['uri'], 'uid' => $importer['importer_uid']];
1998                                         $event = DBA::selectFirst('event', ['id'], $condition);
1999                                         if (DBA::isResult($event)) {
2000                                                 $ev['id'] = $event['id'];
2001                                         }
2002
2003                                         $event_id = Event::store($ev);
2004                                         Logger::info('Event was stored', ['id' => $event_id]);
2005
2006                                         $item = Event::getItemArrayForImportedId($event_id, $item);
2007                                 }
2008                         }
2009                 }
2010
2011                 if (!self::processVerbs($entrytype, $importer, $item)) {
2012                         Logger::info("Exiting because 'processVerbs' told us so");
2013                         return;
2014                 }
2015
2016                 // This check is done here to be able to receive connection requests in "processVerbs"
2017                 if (($entrytype == self::TOP_LEVEL) && $owner_unknown) {
2018                         Logger::info("Item won't be stored because user " . $importer['importer_uid'] . " doesn't follow " . $item['owner-link'] . ".");
2019                         return;
2020                 }
2021
2022
2023                 // Update content if 'updated' changes
2024                 if (DBA::isResult($current)) {
2025                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2026                                 Logger::info("Item " . $item['uri'] . " was updated.");
2027                         } else {
2028                                 Logger::info("Item " . $item['uri'] . " already existed.");
2029                         }
2030                         return;
2031                 }
2032
2033                 if (in_array($entrytype, [self::REPLY, self::REPLY_RC])) {
2034                         if (($item['uid'] != 0) && !Post::exists(['uid' => $item['uid'], 'uri' => $item['thr-parent']])) {
2035                                 if (DI::pConfig()->get($item['uid'], 'system', 'accept_only_sharer') == Item::COMPLETION_NONE) {
2036                                         Logger::info('Completion is set to "none", so we stop here.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]);
2037                                         return;
2038                                 }
2039                                 if (!Contact::isSharing($item['owner-id'], $item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
2040                                         Logger::info('Contact is not sharing with the user', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]);
2041                                         return;
2042                                 }
2043                                 if (($item['gravity'] == Item::GRAVITY_ACTIVITY) && DI::pConfig()->get($item['uid'], 'system', 'accept_only_sharer') == Item::COMPLETION_COMMENT) {
2044                                         Logger::info('Completion is set to "comment", but this is an activity. so we stop here.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]);
2045                                         return;
2046                                 }
2047                                 Logger::debug('Post is accepted.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]);
2048                         } else {
2049                                 Logger::debug('Thread parent exists.', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]);
2050                         }
2051
2052                         // Will be overwritten for sharing accounts in Item::insert
2053                         if (empty($item['post-reason']) && ($entrytype == self::REPLY)) {
2054                                 $item['post-reason'] = Item::PR_COMMENT;
2055                         }
2056
2057                         $posted_id = Item::insert($item);
2058                         if ($posted_id) {
2059                                 Logger::info("Reply from contact " . $item['contact-id'] . " was stored with id " . $posted_id);
2060
2061                                 if ($item['uid'] == 0) {
2062                                         Item::distribute($posted_id);
2063                                 }
2064
2065                                 return true;
2066                         }
2067                 } else { // $entrytype == self::TOP_LEVEL
2068                         if (($item['uid'] != 0) && !Contact::isSharing($item['owner-id'], $item['uid']) && !Contact::isSharing($item['author-id'], $item['uid'])) {
2069                                 Logger::info('Contact is not sharing with the user', ['uid' => $item['uid'], 'owner-id' => $item['owner-id'], 'author-id' => $item['author-id'], 'gravity' => $item['gravity'], 'uri' => $item['uri']]);
2070                                 return;
2071                         }
2072
2073                         // This is my contact on another system, but it's really me.
2074                         // Turn this into a wall post.
2075                         $notify = Item::isRemoteSelf($importer, $item);
2076
2077                         $posted_id = Item::insert($item, $notify);
2078
2079                         if ($notify) {
2080                                 $posted_id = $notify;
2081                         }
2082
2083                         Logger::info("Item was stored with id " . $posted_id);
2084
2085                         if ($item['uid'] == 0) {
2086                                 Item::distribute($posted_id);
2087                         }
2088                 }
2089         }
2090
2091         /**
2092          * Deletes items
2093          *
2094          * @param DOMXPath $xpath XPath object
2095          * @param DOMNode  $deletion deletion elements
2096          * @param array   $importer Record of the importer user mixed with contact of the content
2097          * @return void
2098          * @throws \Exception
2099          */
2100         private static function processDeletion(DOMXPath $xpath, DOMNode $deletion, array $importer)
2101         {
2102                 Logger::notice("Processing deletions");
2103                 $uri = null;
2104
2105                 foreach ($deletion->attributes as $attributes) {
2106                         if ($attributes->name == 'ref') {
2107                                 $uri = $attributes->textContent;
2108                         }
2109                 }
2110
2111                 if (!$uri || !$importer['id']) {
2112                         return false;
2113                 }
2114
2115                 $condition = ['uri' => $uri, 'uid' => $importer['importer_uid']];
2116                 $item = Post::selectFirst(['id', 'parent', 'contact-id', 'uri-id', 'deleted', 'gravity'], $condition);
2117                 if (!DBA::isResult($item)) {
2118                         Logger::info('Item with URI ' . $uri . ' for user ' . $importer['importer_uid'] . ' was not found.');
2119                         return;
2120                 }
2121
2122                 if (DBA::exists('post-category', ['uri-id' => $item['uri-id'], 'uid' => $importer['importer_uid'], 'type' => Post\Category::FILE])) {
2123                         Logger::notice('Item is filed. It will not be deleted.', ['uri' => $uri, 'uri-id' => $item['uri_id'], 'uid' => $importer['importer_uid']]);
2124                         return;
2125                 }
2126
2127                 // When it is a starting post it has to belong to the person that wants to delete it
2128                 if (($item['gravity'] == Item::GRAVITY_PARENT) && ($item['contact-id'] != $importer['id'])) {
2129                         Logger::info('Item with URI ' . $uri . ' do not belong to contact ' . $importer['id'] . ' - ignoring deletion.');
2130                         return;
2131                 }
2132
2133                 // Comments can be deleted by the thread owner or comment owner
2134                 if (($item['gravity'] != Item::GRAVITY_PARENT) && ($item['contact-id'] != $importer['id'])) {
2135                         $condition = ['id' => $item['parent'], 'contact-id' => $importer['id']];
2136                         if (!Post::exists($condition)) {
2137                                 Logger::info('Item with URI ' . $uri . ' was not found or must not be deleted by contact ' . $importer['id'] . ' - ignoring deletion.');
2138                                 return;
2139                         }
2140                 }
2141
2142                 if ($item['deleted']) {
2143                         return;
2144                 }
2145
2146                 Logger::info('deleting item '.$item['id'].' uri='.$uri);
2147
2148                 Item::markForDeletion(['id' => $item['id']]);
2149         }
2150
2151         /**
2152          * Imports a DFRN message
2153          *
2154          * @param string $xml       The DFRN message
2155          * @param array  $importer  Record of the importer user mixed with contact of the content
2156          * @param int    $protocol  Transport protocol
2157          * @param int    $direction Is the message pushed or pulled?
2158          * @return integer Import status
2159          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2160          * @throws \ImagickException
2161          */
2162         public static function import(string $xml, array $importer, int $protocol, int $direction): int
2163         {
2164                 if ($xml == '') {
2165                         return 400;
2166                 }
2167
2168                 $doc = new DOMDocument();
2169                 @$doc->loadXML($xml);
2170
2171                 $xpath = new DOMXPath($doc);
2172                 $xpath->registerNamespace('atom', ActivityNamespace::ATOM1);
2173                 $xpath->registerNamespace('thr', ActivityNamespace::THREAD);
2174                 $xpath->registerNamespace('at', ActivityNamespace::TOMB);
2175                 $xpath->registerNamespace('media', ActivityNamespace::MEDIA);
2176                 $xpath->registerNamespace('dfrn', ActivityNamespace::DFRN);
2177                 $xpath->registerNamespace('activity', ActivityNamespace::ACTIVITY);
2178                 $xpath->registerNamespace('georss', ActivityNamespace::GEORSS);
2179                 $xpath->registerNamespace('poco', ActivityNamespace::POCO);
2180                 $xpath->registerNamespace('ostatus', ActivityNamespace::OSTATUS);
2181                 $xpath->registerNamespace('statusnet', ActivityNamespace::STATUSNET);
2182
2183                 $header = [];
2184                 $header['uid'] = $importer['importer_uid'];
2185                 $header['network'] = Protocol::DFRN;
2186                 $header['protocol'] = $protocol;
2187                 $header['wall'] = 0;
2188                 $header['origin'] = 0;
2189                 $header['contact-id'] = $importer['id'];
2190
2191                 $header = Diaspora::setDirection($header, $direction);
2192
2193                 if ($direction === Conversation::RELAY) {
2194                         $header['post-reason'] = Item::PR_RELAY;
2195                 }
2196
2197                 // Update the contact table if the data has changed
2198
2199                 // The "atom:author" is only present in feeds
2200                 if ($xpath->query('/atom:feed/atom:author')->length > 0) {
2201                         self::fetchauthor($xpath, $doc->firstChild, $importer, 'atom:author', false, $xml);
2202                 }
2203
2204                 // Only the "dfrn:owner" in the head section contains all data
2205                 if ($xpath->query('/atom:feed/dfrn:owner')->length > 0) {
2206                         self::fetchauthor($xpath, $doc->firstChild, $importer, 'dfrn:owner', false, $xml);
2207                 }
2208
2209                 Logger::info("Import DFRN message for user " . $importer['importer_uid'] . " from contact " . $importer['id']);
2210
2211                 if (!empty($importer['gsid']) && ($protocol == Conversation::PARCEL_DIASPORA_DFRN)) {
2212                         GServer::setProtocol($importer['gsid'], Post\DeliveryData::DFRN);
2213                 }
2214
2215                 // is it a public forum? Private forums aren't exposed with this method
2216                 $forum = intval(XML::getFirstNodeValue($xpath, '/atom:feed/dfrn:community/text()'));
2217
2218                 // The account type is new since 3.5.1
2219                 if ($xpath->query('/atom:feed/dfrn:account_type')->length > 0) {
2220                         // Hint: We are using separate update calls for uid=0 and uid!=0 since a combined call is bad for the database performance
2221
2222                         $accounttype = intval(XML::getFirstNodeValue($xpath, '/atom:feed/dfrn:account_type/text()'));
2223
2224                         if ($accounttype != $importer['contact-type']) {
2225                                 Contact::update(['contact-type' => $accounttype], ['id' => $importer['id']]);
2226
2227                                 // Updating the public contact as well
2228                                 Contact::update(['contact-type' => $accounttype], ['uid' => 0, 'nurl' => $importer['nurl']]);
2229                         }
2230                         // A forum contact can either have set "forum" or "prv" - but not both
2231                         if ($accounttype == User::ACCOUNT_TYPE_COMMUNITY) {
2232                                 // It's a forum, so either set the public or private forum flag
2233                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer['id']];
2234                                 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2235
2236                                 // Updating the public contact as well
2237                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `uid` = 0 AND `nurl` = ?', $forum, !$forum, $importer['nurl']];
2238                                 Contact::update(['forum' => $forum, 'prv' => !$forum], $condition);
2239                         } else {
2240                                 // It's not a forum, so remove the flags
2241                                 $condition = ['(`forum` OR `prv`) AND `id` = ?', $importer['id']];
2242                                 Contact::update(['forum' => false, 'prv' => false], $condition);
2243
2244                                 // Updating the public contact as well
2245                                 $condition = ['(`forum` OR `prv`) AND `uid` = 0 AND `nurl` = ?', $importer['nurl']];
2246                                 Contact::update(['forum' => false, 'prv' => false], $condition);
2247                         }
2248                 } elseif ($forum != $importer['forum']) { // Deprecated since 3.5.1
2249                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer['id']];
2250                         Contact::update(['forum' => $forum], $condition);
2251
2252                         // Updating the public contact as well
2253                         $condition = ['`forum` != ? AND `uid` = 0 AND `nurl` = ?', $forum, $importer['nurl']];
2254                         Contact::update(['forum' => $forum], $condition);
2255                 }
2256
2257
2258                 // We are processing relocations even if we are ignoring a contact
2259                 $relocations = $xpath->query('/atom:feed/dfrn:relocate');
2260                 foreach ($relocations as $relocation) {
2261                         self::processRelocation($xpath, $relocation, $importer);
2262                 }
2263
2264                 if (($importer['uid'] != 0) && !$importer['readonly']) {
2265                         $mails = $xpath->query('/atom:feed/dfrn:mail');
2266                         foreach ($mails as $mail) {
2267                                 self::processMail($xpath, $mail, $importer);
2268                         }
2269
2270                         $suggestions = $xpath->query('/atom:feed/dfrn:suggest');
2271                         foreach ($suggestions as $suggestion) {
2272                                 self::processSuggestion($xpath, $suggestion, $importer);
2273                         }
2274                 }
2275
2276                 $deletions = $xpath->query('/atom:feed/at:deleted-entry');
2277                 if (!empty($deletions)) {
2278                         foreach ($deletions as $deletion) {
2279                                 self::processDeletion($xpath, $deletion, $importer);
2280                         }
2281                         if (count($deletions) > 0) {
2282                                 Logger::notice(count($deletions) . ' deletions had been processed');
2283                                 return 200;
2284                         }
2285                 }
2286
2287                 $entries = $xpath->query('/atom:feed/atom:entry');
2288                 foreach ($entries as $entry) {
2289                         self::processEntry($header, $xpath, $entry, $importer, $xml, $protocol);
2290                 }
2291
2292                 Logger::info("Import done for user " . $importer['importer_uid'] . " from contact " . $importer['id']);
2293                 return 200;
2294         }
2295
2296         /**
2297          * Returns the activity verb
2298          *
2299          * @param array $item Item array
2300          *
2301          * @return string activity verb
2302          */
2303         private static function constructVerb(array $item): string
2304         {
2305                 if ($item['verb']) {
2306                         return $item['verb'];
2307                 }
2308                 return Activity::POST;
2309         }
2310
2311         /**
2312          * This function returns true if $update has an edited timestamp newer
2313          * than $existing, i.e. $update contains new data which should override
2314          * what's already there.  If there is no timestamp yet, the update is
2315          * assumed to be newer.  If the update has no timestamp, the existing
2316          * item is assumed to be up-to-date.  If the timestamps are equal it
2317          * assumes the update has been seen before and should be ignored.
2318          *
2319          * @param array $existing
2320          * @param array $update
2321          * @return bool
2322          * @throws \Exception
2323          */
2324         private static function isEditedTimestampNewer(array $existing, array $update): bool
2325         {
2326                 if (empty($existing['edited'])) {
2327                         return true;
2328                 }
2329                 if (empty($update['edited'])) {
2330                         return false;
2331                 }
2332
2333                 $existing_edited = DateTimeFormat::utc($existing['edited']);
2334                 $update_edited = DateTimeFormat::utc($update['edited']);
2335
2336                 return (strcmp($existing_edited, $update_edited) < 0);
2337         }
2338
2339         /**
2340          * Checks if the given contact url does support DFRN
2341          *
2342          * @param string  $url    profile url
2343          * @return boolean
2344          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2345          * @throws \ImagickException
2346          */
2347         public static function isSupportedByContactUrl(string $url): bool
2348         {
2349                 $probe = Probe::uri($url, Protocol::DFRN);
2350                 return $probe['network'] == Protocol::DFRN;
2351         }
2352 }