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