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