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