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