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