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