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