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