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