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