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