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