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