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