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