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