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