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