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