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