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