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