]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
1206268ed716649c3eefe57b5209c67863cb88cd
[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 DFRN_TOP_LEVEL = 0;       // Top level posting
54         const DFRN_REPLY = 1;           // Regular reply that is stored locally
55         const DFRN_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, $item, $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                         /*
2076                          * @TODO maybe one day:
2077                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
2078                         killme();
2079                         */
2080                         return false;
2081                 }
2082
2083                 $old = $r[0];
2084
2085                 // Update the gcontact entry
2086                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2087
2088                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2089                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2090                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2091                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2092                 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2093
2094                 // Update the contact table. We try to find every entry.
2095                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2096                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2097                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2098                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2099                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2100                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2101                 dba::update('contact', $fields, $condition);
2102
2103                 // @TODO No dba:update here?
2104                 dba::update('contact', $fields, $condition);
2105
2106                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2107
2108                 logger('Contacts are updated.');
2109
2110                 /// @TODO WHERE DOES $x COME FROM ???
2111                 if ($x === false) {
2112                         return false;
2113                 }
2114
2115                 // update items
2116                 // This is an extreme performance killer
2117                 Item::update(['owner-link' => $relocate["url"]], ['owner-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2118                 Item::update(['author-link' => $relocate["url"]], ['author-link' => $old["url"], 'uid' => $importer["importer_uid"]]);
2119
2120                 logger('Items are updated.');
2121
2122                 /// @TODO
2123                 /// merge with current record, current contents have priority
2124                 /// update record, set url-updated
2125                 /// update profile photos
2126                 /// schedule a scan?
2127                 return true;
2128         }
2129
2130         /**
2131          * @brief Updates an item
2132          *
2133          * @param array $current   the current item record
2134          * @param array $item      the new item record
2135          * @param array $importer  Record of the importer user mixed with contact of the content
2136          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2137          * @return mixed
2138          * @todo set proper type-hints (array?)
2139          */
2140         private static function updateContent($current, $item, $importer, $entrytype)
2141         {
2142                 $changed = false;
2143
2144                 if (self::isEditedTimestampNewer($current, $item)) {
2145                         // do not accept (ignore) an earlier edit than one we currently have.
2146                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2147                                 return false;
2148                         }
2149
2150                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2151                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2152                                         'edited' => DateTimeFormat::utc($item["edited"])];
2153
2154                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2155                         Item::update($fields, $condition);
2156
2157                         $changed = true;
2158
2159                         if ($entrytype == DFRN_REPLY_RC) {
2160                                 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2161                         }
2162                 }
2163                 return $changed;
2164         }
2165
2166         /**
2167          * @brief Detects the entry type of the item
2168          *
2169          * @param array $importer Record of the importer user mixed with contact of the content
2170          * @param array $item     the new item record
2171          *
2172          * @return int Is it a toplevel entry, a comment or a relayed comment?
2173          * @todo set proper type-hints (array?)
2174          */
2175         private static function getEntryType($importer, $item)
2176         {
2177                 if ($item["parent-uri"] != $item["uri"]) {
2178                         $community = false;
2179
2180                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2181                                 $sql_extra = "";
2182                                 $community = true;
2183                                 logger("possible community action");
2184                         } else {
2185                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2186                         }
2187
2188                         // was the top-level post for this action written by somebody on this site?
2189                         // Specifically, the recipient?
2190
2191                         $is_a_remote_action = false;
2192
2193                         $r = q(
2194                                 "SELECT `item`.`parent-uri` FROM `item`
2195                                 WHERE `item`.`uri` = '%s'
2196                                 LIMIT 1",
2197                                 dbesc($item["parent-uri"])
2198                         );
2199                         if (DBM::is_result($r)) {
2200                                 $r = q(
2201                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2202                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2203                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2204                                         AND `item`.`uid` = %d
2205                                         $sql_extra
2206                                         LIMIT 1",
2207                                         dbesc($r[0]["parent-uri"]),
2208                                         dbesc($r[0]["parent-uri"]),
2209                                         dbesc($r[0]["parent-uri"]),
2210                                         intval($importer["importer_uid"])
2211                                 );
2212                                 if (DBM::is_result($r)) {
2213                                         $is_a_remote_action = true;
2214                                 }
2215                         }
2216
2217                         /*
2218                          * Does this have the characteristics of a community or private group action?
2219                          * If it's an action to a wall post on a community/prvgroup page it's a
2220                          * valid community action. Also forum_mode makes it valid for sure.
2221                          * If neither, it's not.
2222                          */
2223                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2224                                 $is_a_remote_action = false;
2225                                 logger("not a community action");
2226                         }
2227
2228                         if ($is_a_remote_action) {
2229                                 return DFRN_REPLY_RC;
2230                         } else {
2231                                 return DFRN_REPLY;
2232                         }
2233                 } else {
2234                         return DFRN_TOP_LEVEL;
2235                 }
2236         }
2237
2238         /**
2239          * @brief Send a "poke"
2240          *
2241          * @param array $item      the new item record
2242          * @param array $importer  Record of the importer user mixed with contact of the content
2243          * @param int   $posted_id The record number of item record that was just posted
2244          * @return void
2245          * @todo set proper type-hints (array?)
2246          */
2247         private static function doPoke($item, $importer, $posted_id)
2248         {
2249                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2250                 if (!$verb) {
2251                         return;
2252                 }
2253                 $xo = XML::parseString($item["object"], false);
2254
2255                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2256                         // somebody was poked/prodded. Was it me?
2257                         foreach ($xo->link as $l) {
2258                                 $atts = $l->attributes();
2259                                 switch ($atts["rel"]) {
2260                                         case "alternate":
2261                                                 $Blink = $atts["href"];
2262                                                 break;
2263                                         default:
2264                                                 break;
2265                                 }
2266                         }
2267
2268                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2269                                 // send a notification
2270                                 notification(
2271                                         [
2272                                         "type"         => NOTIFY_POKE,
2273                                         "notify_flags" => $importer["notify-flags"],
2274                                         "language"     => $importer["language"],
2275                                         "to_name"      => $importer["username"],
2276                                         "to_email"     => $importer["email"],
2277                                         "uid"          => $importer["importer_uid"],
2278                                         "item"         => $item,
2279                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2280                                         "source_name"  => stripslashes($item["author-name"]),
2281                                         "source_link"  => $item["author-link"],
2282                                         "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2283                                                 ? $importer["thumb"] : $item["author-avatar"]),
2284                                         "verb"         => $item["verb"],
2285                                         "otype"        => "person",
2286                                         "activity"     => $verb,
2287                                         "parent"       => $item["parent"]]
2288                                 );
2289                         }
2290                 }
2291         }
2292
2293         /**
2294          * @brief Processes several actions, depending on the verb
2295          *
2296          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2297          * @param array $importer  Record of the importer user mixed with contact of the content
2298          * @param array $item      the new item record
2299          * @param bool  $is_like   Is the verb a "like"?
2300          *
2301          * @return bool Should the processing of the entries be continued?
2302          * @todo set proper type-hints (array?)
2303          */
2304         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2305         {
2306                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2307
2308                 if (($entrytype == DFRN_TOP_LEVEL)) {
2309                         // The filling of the the "contact" variable is done for legcy reasons
2310                         // The functions below are partly used by ostatus.php as well - where we have this variable
2311                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2312                         $contact = $r[0];
2313                         $nickname = $contact["nick"];
2314
2315                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2316                         // This function once was responsible for DFRN and OStatus.
2317                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2318                                 logger("New follower");
2319                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2320                                 return false;
2321                         }
2322                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2323                                 logger("Lost follower");
2324                                 Contact::removeFollower($importer, $contact, $item);
2325                                 return false;
2326                         }
2327                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2328                                 logger("New friend request");
2329                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2330                                 return false;
2331                         }
2332                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2333                                 logger("Lost sharer");
2334                                 Contact::removeSharer($importer, $contact, $item);
2335                                 return false;
2336                         }
2337                 } else {
2338                         if (($item["verb"] == ACTIVITY_LIKE)
2339                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2340                                 || ($item["verb"] == ACTIVITY_ATTEND)
2341                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2342                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2343                         ) {
2344                                 $is_like = true;
2345                                 $item["type"] = "activity";
2346                                 $item["gravity"] = GRAVITY_LIKE;
2347                                 // only one like or dislike per person
2348                                 // splitted into two queries for performance issues
2349                                 $r = q(
2350                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2351                                         intval($item["uid"]),
2352                                         dbesc($item["author-link"]),
2353                                         dbesc($item["verb"]),
2354                                         dbesc($item["parent-uri"])
2355                                 );
2356                                 if (DBM::is_result($r)) {
2357                                         return false;
2358                                 }
2359
2360                                 $r = q(
2361                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2362                                         intval($item["uid"]),
2363                                         dbesc($item["author-link"]),
2364                                         dbesc($item["verb"]),
2365                                         dbesc($item["parent-uri"])
2366                                 );
2367                                 if (DBM::is_result($r)) {
2368                                         return false;
2369                                 }
2370                         } else {
2371                                 $is_like = false;
2372                         }
2373
2374                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2375                                 $xo = XML::parseString($item["object"], false);
2376                                 $xt = XML::parseString($item["target"], false);
2377
2378                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2379                                         $r = q(
2380                                                 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2381                                                 dbesc($xt->id),
2382                                                 intval($importer["importer_uid"])
2383                                         );
2384
2385                                         if (!DBM::is_result($r)) {
2386                                                 /*
2387                                                  * @TODO maybe one day:
2388                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2389                                                 killme();
2390                                                 */
2391                                                 return false;
2392                                         }
2393
2394                                         // extract tag, if not duplicate, add to parent item
2395                                         if ($xo->content) {
2396                                                 if (!stristr($r[0]["tag"], trim($xo->content))) {
2397                                                         $tag = $r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2398                                                         Item::update(['tag' => $tag], ['id' => $r[0]["id"]]);
2399                                                 }
2400                                         }
2401                                 }
2402                         }
2403                 }
2404                 return true;
2405         }
2406
2407         /**
2408          * @brief Processes the link elements
2409          *
2410          * @param object $links link elements
2411          * @param array  $item  the item record
2412          * @return void
2413          * @todo set proper type-hints
2414          */
2415         private static function parseLinks($links, &$item)
2416         {
2417                 $rel = "";
2418                 $href = "";
2419                 $type = "";
2420                 $length = "0";
2421                 $title = "";
2422                 foreach ($links as $link) {
2423                         foreach ($link->attributes as $attributes) {
2424                                 switch ($attributes->name) {
2425                                         case "href"  : $href   = $attributes->textContent; break;
2426                                         case "rel"   : $rel    = $attributes->textContent; break;
2427                                         case "type"  : $type   = $attributes->textContent; break;
2428                                         case "length": $length = $attributes->textContent; break;
2429                                         case "title" : $title  = $attributes->textContent; break;
2430                                 }
2431                         }
2432                         if (($rel != "") && ($href != "")) {
2433                                 switch ($rel) {
2434                                         case "alternate":
2435                                                 $item["plink"] = $href;
2436                                                 break;
2437                                         case "enclosure":
2438                                                 $enclosure = $href;
2439                                                 if (strlen($item["attach"])) {
2440                                                         $item["attach"] .= ",";
2441                                                 }
2442
2443                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2444                                                 break;
2445                                 }
2446                         }
2447                 }
2448         }
2449
2450         /**
2451          * @brief Processes the entry elements which contain the items and comments
2452          *
2453          * @param array  $header   Array of the header elements that always stay the same
2454          * @param object $xpath    XPath object
2455          * @param object $entry    entry elements
2456          * @param array  $importer Record of the importer user mixed with contact of the content
2457          * @param object $xml      xml
2458          * @return void
2459          * @todo Add type-hints
2460          */
2461         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2462         {
2463                 logger("Processing entries");
2464
2465                 $item = $header;
2466
2467                 $item["protocol"] = PROTOCOL_DFRN;
2468
2469                 $item["source"] = $xml;
2470
2471                 // Get the uri
2472                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2473
2474                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2475
2476                 $current = dba::selectFirst('item',
2477                         ['id', 'uid', 'edited', 'body'],
2478                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2479                 );
2480                 // Is there an existing item?
2481                 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2482                         logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2483                         return;
2484                 }
2485
2486                 // Fetch the owner
2487                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2488
2489                 $item["owner-name"] = $owner["name"];
2490                 $item["owner-link"] = $owner["link"];
2491                 $item["owner-avatar"] = $owner["avatar"];
2492
2493                 // fetch the author
2494                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2495
2496                 $item["author-name"] = $author["name"];
2497                 $item["author-link"] = $author["link"];
2498                 $item["author-avatar"] = $author["avatar"];
2499
2500                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2501
2502                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2503
2504                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2505                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2506                 // make sure nobody is trying to sneak some html tags by us
2507                 $item["body"] = notags(base64url_decode($item["body"]));
2508
2509                 $item["body"] = BBCode::limitBodySize($item["body"]);
2510
2511                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2512                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2513                         $base_url = get_app()->get_baseurl();
2514                         $item['body'] = reltoabs($item['body'], $base_url);
2515
2516                         $item['body'] = html2bb_video($item['body']);
2517
2518                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2519
2520                         $config = HTMLPurifier_Config::createDefault();
2521                         $config->set('Cache.DefinitionImpl', null);
2522
2523                         // we shouldn't need a whitelist, because the bbcode converter
2524                         // will strip out any unsupported tags.
2525
2526                         $purifier = new HTMLPurifier($config);
2527                         $item['body'] = $purifier->purify($item['body']);
2528
2529                         $item['body'] = @HTML::toBBCode($item['body']);
2530                 }
2531
2532                 /// @todo We should check for a repeated post and if we know the repeated author.
2533
2534                 // We don't need the content element since "dfrn:env" is always present
2535                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2536
2537                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2538
2539                 $georsspoint = $xpath->query("georss:point", $entry);
2540                 if ($georsspoint) {
2541                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2542                 }
2543
2544                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2545
2546                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2547
2548                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2549                         $item["bookmark"] = true;
2550                 }
2551
2552                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2553                 if ($notice_info && ($notice_info->length > 0)) {
2554                         foreach ($notice_info->item(0)->attributes as $attributes) {
2555                                 if ($attributes->name == "source") {
2556                                         $item["app"] = strip_tags($attributes->textContent);
2557                                 }
2558                         }
2559                 }
2560
2561                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2562
2563                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2564                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2565                 if ($dsprsig != "") {
2566                         $item["dsprsig"] = $dsprsig;
2567                 }
2568
2569                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2570
2571                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2572                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2573                 }
2574
2575                 $object = $xpath->query("activity:object", $entry)->item(0);
2576                 $item["object"] = self::transformActivity($xpath, $object, "object");
2577
2578                 if (trim($item["object"]) != "") {
2579                         $r = XML::parseString($item["object"], false);
2580                         if (isset($r->type)) {
2581                                 $item["object-type"] = $r->type;
2582                         }
2583                 }
2584
2585                 $target = $xpath->query("activity:target", $entry)->item(0);
2586                 $item["target"] = self::transformActivity($xpath, $target, "target");
2587
2588                 $categories = $xpath->query("atom:category", $entry);
2589                 if ($categories) {
2590                         foreach ($categories as $category) {
2591                                 $term = "";
2592                                 $scheme = "";
2593                                 foreach ($category->attributes as $attributes) {
2594                                         if ($attributes->name == "term") {
2595                                                 $term = $attributes->textContent;
2596                                         }
2597
2598                                         if ($attributes->name == "scheme") {
2599                                                 $scheme = $attributes->textContent;
2600                                         }
2601                                 }
2602
2603                                 if (($term != "") && ($scheme != "")) {
2604                                         $parts = explode(":", $scheme);
2605                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2606                                                 $termhash = array_shift($parts);
2607                                                 $termurl = implode(":", $parts);
2608
2609                                                 if (strlen($item["tag"])) {
2610                                                         $item["tag"] .= ",";
2611                                                 }
2612
2613                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2614                                         }
2615                                 }
2616                         }
2617                 }
2618
2619                 $enclosure = "";
2620
2621                 $links = $xpath->query("atom:link", $entry);
2622                 if ($links) {
2623                         self::parseLinks($links, $item);
2624                 }
2625
2626                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2627
2628                 $conv = $xpath->query('ostatus:conversation', $entry);
2629                 if (is_object($conv->item(0))) {
2630                         foreach ($conv->item(0)->attributes as $attributes) {
2631                                 if ($attributes->name == "ref") {
2632                                         $item['conversation-uri'] = $attributes->textContent;
2633                                 }
2634                                 if ($attributes->name == "href") {
2635                                         $item['conversation-href'] = $attributes->textContent;
2636                                 }
2637                         }
2638                 }
2639
2640                 // Is it a reply or a top level posting?
2641                 $item["parent-uri"] = $item["uri"];
2642
2643                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2644                 if (is_object($inreplyto->item(0))) {
2645                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2646                                 if ($attributes->name == "ref") {
2647                                         $item["parent-uri"] = $attributes->textContent;
2648                                 }
2649                         }
2650                 }
2651
2652                 // Get the type of the item (Top level post, reply or remote reply)
2653                 $entrytype = self::getEntryType($importer, $item);
2654
2655                 // Now assign the rest of the values that depend on the type of the message
2656                 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2657                         if (!isset($item["object-type"])) {
2658                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2659                         }
2660
2661                         if ($item["contact-id"] != $owner["contact-id"]) {
2662                                 $item["contact-id"] = $owner["contact-id"];
2663                         }
2664
2665                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2666                                 $item["network"] = $owner["network"];
2667                         }
2668
2669                         if ($item["contact-id"] != $author["contact-id"]) {
2670                                 $item["contact-id"] = $author["contact-id"];
2671                         }
2672
2673                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2674                                 $item["network"] = $author["network"];
2675                         }
2676                 }
2677
2678                 if ($entrytype == DFRN_REPLY_RC) {
2679                         $item["type"] = "remote-comment";
2680                         $item["wall"] = 1;
2681                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2682                         if (!isset($item["object-type"])) {
2683                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2684                         }
2685
2686                         // Is it an event?
2687                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2688                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2689                                 $ev = Event::fromBBCode($item["body"]);
2690                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2691                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2692                                         $ev["cid"]     = $importer["id"];
2693                                         $ev["uid"]     = $importer["importer_uid"];
2694                                         $ev["uri"]     = $item["uri"];
2695                                         $ev["edited"]  = $item["edited"];
2696                                         $ev["private"] = $item["private"];
2697                                         $ev["guid"]    = $item["guid"];
2698
2699                                         $r = q(
2700                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2701                                                 dbesc($item["uri"]),
2702                                                 intval($importer["importer_uid"])
2703                                         );
2704                                         if (DBM::is_result($r)) {
2705                                                 $ev["id"] = $r[0]["id"];
2706                                         }
2707
2708                                         $event_id = Event::store($ev);
2709                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2710                                         return;
2711                                 }
2712                         }
2713                 }
2714
2715                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2716                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2717                         return;
2718                 }
2719
2720                 // Update content if 'updated' changes
2721                 if (DBM::is_result($current)) {
2722                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2723                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2724                         } else {
2725                                 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2726                         }
2727                         return;
2728                 }
2729
2730                 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2731                         $posted_id = Item::insert($item);
2732                         $parent = 0;
2733
2734                         if ($posted_id) {
2735                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2736
2737                                 if ($item['uid'] == 0) {
2738                                         Item::distribute($posted_id);
2739                                 }
2740
2741                                 $item["id"] = $posted_id;
2742
2743                                 $r = q(
2744                                         "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2745                                         intval($posted_id),
2746                                         intval($importer["importer_uid"])
2747                                 );
2748                                 if (DBM::is_result($r)) {
2749                                         $parent = $r[0]["parent"];
2750                                         $parent_uri = $r[0]["parent-uri"];
2751                                 }
2752
2753                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2754                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2755                                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2756                                 }
2757
2758                                 return true;
2759                         }
2760                 } else { // $entrytype == DFRN_TOP_LEVEL
2761                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2762                                 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2763                                 return;
2764                         }
2765                         if (!link_compare($item["owner-link"], $importer["url"])) {
2766                                 /*
2767                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2768                                  * but otherwise there's a possible data mixup on the sender's system.
2769                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2770                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2771                                  */
2772                                 logger('Correcting item owner.', LOGGER_DEBUG);
2773                                 $item["owner-name"]   = $importer["senderName"];
2774                                 $item["owner-link"]   = $importer["url"];
2775                                 $item["owner-avatar"] = $importer["thumb"];
2776                         }
2777
2778                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2779                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2780                                 return;
2781                         }
2782
2783                         // This is my contact on another system, but it's really me.
2784                         // Turn this into a wall post.
2785                         $notify = Item::isRemoteSelf($importer, $item);
2786
2787                         $posted_id = Item::insert($item, false, $notify);
2788
2789                         if ($notify) {
2790                                 $posted_id = $notify;
2791                         }
2792
2793                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2794
2795                         if ($item['uid'] == 0) {
2796                                 Item::distribute($posted_id);
2797                         }
2798
2799                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2800                                 self::doPoke($item, $importer, $posted_id);
2801                         }
2802                 }
2803         }
2804
2805         /**
2806          * @brief Deletes items
2807          *
2808          * @param object $xpath    XPath object
2809          * @param object $deletion deletion elements
2810          * @param array  $importer Record of the importer user mixed with contact of the content
2811          * @return void
2812          * @todo set proper type-hints
2813          */
2814         private static function processDeletion($xpath, $deletion, $importer)
2815         {
2816                 logger("Processing deletions");
2817                 $uri = null;
2818
2819                 foreach ($deletion->attributes as $attributes) {
2820                         if ($attributes->name == "ref") {
2821                                 $uri = $attributes->textContent;
2822                         }
2823                 }
2824
2825                 if (!$uri || !$importer["id"]) {
2826                         return false;
2827                 }
2828
2829                 $condition = ["`uri` = ? AND `uid` = ? AND NOT `file` LIKE '%[%'", $uri, $importer["importer_uid"]];
2830                 $item = dba::selectFirst('item', ['id', 'parent', 'contact-id'], $condition);
2831                 if (!DBM::is_result($item)) {
2832                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2833                         return;
2834                 }
2835
2836                 // When it is a starting post it has to belong to the person that wants to delete it
2837                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2838                         logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2839                         return;
2840                 }
2841
2842                 // Comments can be deleted by the thread owner or comment owner
2843                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2844                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2845                         if (!dba::exists('item', $condition)) {
2846                                 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2847                                 return;
2848                         }
2849                 }
2850
2851                 $entrytype = self::getEntryType($importer, $item);
2852
2853                 if (!$item["deleted"]) {
2854                         logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2855                 } else {
2856                         return;
2857                 }
2858
2859                 Item::deleteById($item["id"]);
2860
2861                 if ($entrytype != DFRN_TOP_LEVEL) {
2862                         // if this is a relayed delete, propagate it to other recipients
2863                         if ($entrytype == DFRN_REPLY_RC) {
2864                                 logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2865                                 Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2866                         }
2867                 }
2868         }
2869
2870         /**
2871          * @brief Imports a DFRN message
2872          *
2873          * @param string $xml          The DFRN message
2874          * @param array  $importer     Record of the importer user mixed with contact of the content
2875          * @param bool   $sort_by_date Is used when feeds are polled
2876          * @return integer Import status
2877          * @todo set proper type-hints
2878          */
2879         public static function import($xml, $importer, $sort_by_date = false)
2880         {
2881                 if ($xml == "") {
2882                         return 400;
2883                 }
2884
2885                 $doc = new DOMDocument();
2886                 @$doc->loadXML($xml);
2887
2888                 $xpath = new DOMXPath($doc);
2889                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2890                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2891                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2892                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2893                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2894                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2895                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2896                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2897                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2898                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2899
2900                 $header = [];
2901                 $header["uid"] = $importer["importer_uid"];
2902                 $header["network"] = NETWORK_DFRN;
2903                 $header["type"] = "remote";
2904                 $header["wall"] = 0;
2905                 $header["origin"] = 0;
2906                 $header["contact-id"] = $importer["id"];
2907
2908                 // Update the contact table if the data has changed
2909
2910                 // The "atom:author" is only present in feeds
2911                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2912                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2913                 }
2914
2915                 // Only the "dfrn:owner" in the head section contains all data
2916                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2917                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2918                 }
2919
2920                 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2921
2922                 // is it a public forum? Private forums aren't exposed with this method
2923                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2924
2925                 // The account type is new since 3.5.1
2926                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2927                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2928
2929                         if ($accounttype != $importer["contact-type"]) {
2930                                 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2931                         }
2932                         // A forum contact can either have set "forum" or "prv" - but not both
2933                         if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2934                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2935                                 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2936                         }
2937                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2938                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2939                         dba::update('contact', ['forum' => $forum], $condition);
2940                 }
2941
2942
2943                 // We are processing relocations even if we are ignoring a contact
2944                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2945                 foreach ($relocations as $relocation) {
2946                         self::processRelocation($xpath, $relocation, $importer);
2947                 }
2948
2949                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2950                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2951                         foreach ($mails as $mail) {
2952                                 self::processMail($xpath, $mail, $importer);
2953                         }
2954
2955                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2956                         foreach ($suggestions as $suggestion) {
2957                                 self::processSuggestion($xpath, $suggestion, $importer);
2958                         }
2959                 }
2960
2961                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2962                 foreach ($deletions as $deletion) {
2963                         self::processDeletion($xpath, $deletion, $importer);
2964                 }
2965
2966                 if (!$sort_by_date) {
2967                         $entries = $xpath->query("/atom:feed/atom:entry");
2968                         foreach ($entries as $entry) {
2969                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2970                         }
2971                 } else {
2972                         $newentries = [];
2973                         $entries = $xpath->query("/atom:feed/atom:entry");
2974                         foreach ($entries as $entry) {
2975                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2976                                 $newentries[strtotime($created)] = $entry;
2977                         }
2978
2979                         // Now sort after the publishing date
2980                         ksort($newentries);
2981
2982                         foreach ($newentries as $entry) {
2983                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2984                         }
2985                 }
2986                 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2987                 return 200;
2988         }
2989
2990         /**
2991          * @param App    $a            App
2992          * @param string $contact_nick contact nickname
2993          */
2994         public static function autoRedir(App $a, $contact_nick)
2995         {
2996                 // prevent looping
2997                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2998                         return;
2999                 }
3000
3001                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
3002                         return;
3003                 }
3004
3005                 if (local_user()) {
3006                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
3007                         // am a contact of that user. However, that user may have other contacts with the
3008                         // same nickname as me on other hubs or other networks. Exclude these by requiring
3009                         // that the contact have a local URL. I will be the only person with my nickname at
3010                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
3011                         //
3012                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3013
3014                         $baseurl = System::baseUrl();
3015                         $domain_st = strpos($baseurl, "://");
3016                         if ($domain_st === false) {
3017                                 return;
3018                         }
3019                         $baseurl = substr($baseurl, $domain_st + 3);
3020                         $nurl = normalise_link($baseurl);
3021
3022                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3023                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3024                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3025                                 dbesc($contact_nick),
3026                                 dbesc($a->user['nickname']),
3027                                 dbesc($baseurl),
3028                                 dbesc($nurl)
3029                         );
3030                         if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3031                                 return;
3032                         }
3033
3034                         $r = q("SELECT * FROM contact WHERE nick = '%s'
3035                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
3036                                 dbesc($contact_nick),
3037                                 dbesc(NETWORK_DFRN),
3038                                 intval(local_user()),
3039                                 dbesc($baseurl)
3040                         );
3041                         if (! DBM::is_result($r)) {
3042                                 return;
3043                         }
3044
3045                         $cid = $r[0]['id'];
3046
3047                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3048
3049                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
3050                                 $orig_id = $r[0]['issued-id'];
3051                                 $dfrn_id = '1:' . $orig_id;
3052                         }
3053                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3054                                 $orig_id = $r[0]['dfrn-id'];
3055                                 $dfrn_id = '0:' . $orig_id;
3056                         }
3057
3058                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3059                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3060
3061                         if (strlen($dfrn_id) < 3) {
3062                                 return;
3063                         }
3064
3065                         $sec = random_string();
3066
3067                         dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3068
3069                         $url = curPageURL();
3070
3071                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3072                         $dest = (($url) ? '&destination_url=' . $url : '');
3073                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3074                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3075                 }
3076
3077                 return;
3078         }
3079
3080         /**
3081          * @brief Returns the activity verb
3082          *
3083          * @param array $item Item array
3084          *
3085          * @return string activity verb
3086          */
3087         private static function constructVerb(array $item)
3088         {
3089                 if ($item['verb']) {
3090                         return $item['verb'];
3091                 }
3092                 return ACTIVITY_POST;
3093         }
3094
3095         private static function tgroupCheck($uid, $item)
3096         {
3097                 $mention = false;
3098
3099                 // check that the message originated elsewhere and is a top-level post
3100
3101                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3102                         return false;
3103                 }
3104
3105                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3106                         intval($uid)
3107                 );
3108                 if (!DBM::is_result($u)) {
3109                         return false;
3110                 }
3111
3112                 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3113                 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3114
3115                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3116
3117                 /*
3118                  * Diaspora uses their own hardwired link URL in @-tags
3119                  * instead of the one we supply with webfinger
3120                  */
3121                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3122
3123                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3124                 if ($cnt) {
3125                         foreach ($matches as $mtch) {
3126                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3127                                         $mention = true;
3128                                         logger('mention found: ' . $mtch[2]);
3129                                 }
3130                         }
3131                 }
3132
3133                 if (!$mention) {
3134                         return false;
3135                 }
3136
3137                 return $community_page || $prvgroup;
3138         }
3139
3140         /**
3141          * This function returns true if $update has an edited timestamp newer
3142          * than $existing, i.e. $update contains new data which should override
3143          * what's already there.  If there is no timestamp yet, the update is
3144          * assumed to be newer.  If the update has no timestamp, the existing
3145          * item is assumed to be up-to-date.  If the timestamps are equal it
3146          * assumes the update has been seen before and should be ignored.
3147          *
3148          */
3149         private static function isEditedTimestampNewer($existing, $update)
3150         {
3151                 if (!x($existing, 'edited') || !$existing['edited']) {
3152                         return true;
3153                 }
3154                 if (!x($update, 'edited') || !$update['edited']) {
3155                         return false;
3156                 }
3157
3158                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3159                 $update_edited = DateTimeFormat::utc($update['edited']);
3160
3161                 return (strcmp($existing_edited, $update_edited) < 0);
3162         }
3163 }