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