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