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