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