]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Merge pull request #4312 from zeroadam/feature/L10n
[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\Core\Addon;
14 use Friendica\Core\Config;
15 use Friendica\Core\L10n;
16 use Friendica\Core\System;
17 use Friendica\Core\Worker;
18 use Friendica\Database\DBM;
19 use Friendica\Model\Contact;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Group;
22 use Friendica\Model\Profile;
23 use Friendica\Model\Term;
24 use Friendica\Model\User;
25 use Friendica\Object\Image;
26 use Friendica\Protocol\OStatus;
27 use Friendica\Util\Crypto;
28 use Friendica\Util\XML;
29
30 use dba;
31 use DOMDocument;
32 use DOMXPath;
33 use HTMLPurifier;
34 use HTMLPurifier_Config;
35
36 require_once 'boot.php';
37 require_once 'include/dba.php';
38 require_once "include/enotify.php";
39 require_once "include/threads.php";
40 require_once "include/items.php";
41 require_once "include/tags.php";
42 require_once "include/event.php";
43 require_once "include/text.php";
44 require_once "include/html2bbcode.php";
45 require_once "include/bbcode.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 = datetime_convert('UTC', 'UTC', $last_update, 'Y-m-d H:i:s');
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", datetime_convert('UTC', 'UTC', $item['created'] . '+00:00', ATOM_TIME));
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", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
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 = datetime_convert('UTC', 'UTC', $owner['name-date'].'+00:00', ATOM_TIME);
622                 $uridate = datetime_convert('UTC', 'UTC', $owner['uri-date'].'+00:00', ATOM_TIME);
623                 $picdate = datetime_convert('UTC', 'UTC', $owner['avatar-date'].'+00:00', ATOM_TIME);
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 = parse_xml_string($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 = parse_xml_string("<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($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" => datetime_convert('UTC', 'UTC', $item['edited'] . '+00:00', ATOM_TIME)];
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 = fix_private_photos($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 = remove_abstract($body);
931
932                 if ($type == 'html') {
933                         $htmlbody = $body;
934
935                         if ($item['title'] != "") {
936                                 $htmlbody = "[b]".$item['title']."[/b]\n\n".$htmlbody;
937                         }
938
939                         $htmlbody = bbcode($htmlbody, false, false, 7);
940                 }
941
942                 $author = self::addEntryAuthor($doc, "author", $item["author-link"], $item);
943                 $entry->appendChild($author);
944
945                 $dfrnowner = self::addEntryAuthor($doc, "dfrn:owner", $item["owner-link"], $item);
946                 $entry->appendChild($dfrnowner);
947
948                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
949                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
950                         $parent = q("SELECT `guid`,`plink` FROM `item` WHERE `uri` = '%s' AND `uid` = %d", dbesc($parent_item), intval($item['uid']));
951                         $attributes = ["ref" => $parent_item, "type" => "text/html",
952                                                 "href" => $parent[0]['plink'],
953                                                 "dfrn:diaspora_guid" => $parent[0]['guid']];
954                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
955                 }
956
957                 // Add conversation data. This is used for OStatus
958                 $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
959                 $conversation_uri = $conversation_href;
960
961                 if (isset($parent_item)) {
962                         $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $item['parent-uri']);
963                         if (DBM::is_result($r)) {
964                                 if ($r['conversation-uri'] != '') {
965                                         $conversation_uri = $r['conversation-uri'];
966                                 }
967                                 if ($r['conversation-href'] != '') {
968                                         $conversation_href = $r['conversation-href'];
969                                 }
970                         }
971                 }
972
973                 $attributes = [
974                                 "href" => $conversation_href,
975                                 "ref" => $conversation_uri];
976
977                 XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
978
979                 XML::addElement($doc, $entry, "id", $item["uri"]);
980                 XML::addElement($doc, $entry, "title", $item["title"]);
981
982                 XML::addElement($doc, $entry, "published", datetime_convert("UTC", "UTC", $item["created"] . "+00:00", ATOM_TIME));
983                 XML::addElement($doc, $entry, "updated", datetime_convert("UTC", "UTC", $item["edited"] . "+00:00", ATOM_TIME));
984
985                 // "dfrn:env" is used to read the content
986                 XML::addElement($doc, $entry, "dfrn:env", base64url_encode($body, true));
987
988                 // The "content" field is not read by the receiver. We could remove it when the type is "text"
989                 // We keep it at the moment, maybe there is some old version that doesn't read "dfrn:env"
990                 XML::addElement($doc, $entry, "content", (($type == 'html') ? $htmlbody : $body), ["type" => $type]);
991
992                 // We save this value in "plink". Maybe we should read it from there as well?
993                 XML::addElement(
994                         $doc,
995                         $entry,
996                         "link",
997                         "",
998                         ["rel" => "alternate", "type" => "text/html",
999                                  "href" => System::baseUrl() . "/display/" . $item["guid"]]
1000                 );
1001
1002                 // "comment-allow" is some old fashioned stuff for old Friendica versions.
1003                 // It is included in the rewritten code for completeness
1004                 if ($comment) {
1005                         XML::addElement($doc, $entry, "dfrn:comment-allow", 1);
1006                 }
1007
1008                 if ($item['location']) {
1009                         XML::addElement($doc, $entry, "dfrn:location", $item['location']);
1010                 }
1011
1012                 if ($item['coord']) {
1013                         XML::addElement($doc, $entry, "georss:point", $item['coord']);
1014                 }
1015
1016                 if (($item['private']) || strlen($item['allow_cid']) || strlen($item['allow_gid']) || strlen($item['deny_cid']) || strlen($item['deny_gid'])) {
1017                         XML::addElement($doc, $entry, "dfrn:private", (($item['private']) ? $item['private'] : 1));
1018                 }
1019
1020                 if ($item['extid']) {
1021                         XML::addElement($doc, $entry, "dfrn:extid", $item['extid']);
1022                 }
1023
1024                 if ($item['bookmark']) {
1025                         XML::addElement($doc, $entry, "dfrn:bookmark", "true");
1026                 }
1027
1028                 if ($item['app']) {
1029                         XML::addElement($doc, $entry, "statusnet:notice_info", "", ["local_id" => $item['id'], "source" => $item['app']]);
1030                 }
1031
1032                 XML::addElement($doc, $entry, "dfrn:diaspora_guid", $item["guid"]);
1033
1034                 // The signed text contains the content in Markdown, the sender handle and the signatur for the content
1035                 // It is needed for relayed comments to Diaspora.
1036                 if ($item['signed_text']) {
1037                         $sign = base64_encode(json_encode(['signed_text' => $item['signed_text'],'signature' => $item['signature'],'signer' => $item['signer']]));
1038                         XML::addElement($doc, $entry, "dfrn:diaspora_signature", $sign);
1039                 }
1040
1041                 XML::addElement($doc, $entry, "activity:verb", self::constructVerb($item));
1042
1043                 if ($item['object-type'] != "") {
1044                         XML::addElement($doc, $entry, "activity:object-type", $item['object-type']);
1045                 } elseif ($item['id'] == $item['parent']) {
1046                         XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1047                 } else {
1048                         XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_COMMENT);
1049                 }
1050
1051                 $actobj = self::createActivity($doc, "activity:object", $item['object']);
1052                 if ($actobj) {
1053                         $entry->appendChild($actobj);
1054                 }
1055
1056                 $actarg = self::createActivity($doc, "activity:target", $item['target']);
1057                 if ($actarg) {
1058                         $entry->appendChild($actarg);
1059                 }
1060
1061                 $tags = item_getfeedtags($item);
1062
1063                 if (count($tags)) {
1064                         foreach ($tags as $t) {
1065                                 if (($type != 'html') || ($t[0] != "@")) {
1066                                         XML::addElement($doc, $entry, "category", "", ["scheme" => "X-DFRN:".$t[0].":".$t[1], "term" => $t[2]]);
1067                                 }
1068                         }
1069                 }
1070
1071                 if (count($tags)) {
1072                         foreach ($tags as $t) {
1073                                 if ($t[0] == "@") {
1074                                         $mentioned[$t[1]] = $t[1];
1075                                 }
1076                         }
1077                 }
1078
1079                 foreach ($mentioned as $mention) {
1080                         $r = q(
1081                                 "SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1082                                 intval($owner["uid"]),
1083                                 dbesc(normalise_link($mention))
1084                         );
1085
1086                         if (DBM::is_result($r) && ($r[0]["forum"] || $r[0]["prv"])) {
1087                                 XML::addElement(
1088                                         $doc,
1089                                         $entry,
1090                                         "link",
1091                                         "",
1092                                         ["rel" => "mentioned",
1093                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1094                                                         "href" => $mention]
1095                                 );
1096                         } else {
1097                                 XML::addElement(
1098                                         $doc,
1099                                         $entry,
1100                                         "link",
1101                                         "",
1102                                         ["rel" => "mentioned",
1103                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1104                                                         "href" => $mention]
1105                                 );
1106                         }
1107                 }
1108
1109                 self::getAttachment($doc, $entry, $item);
1110
1111                 return $entry;
1112         }
1113
1114         /**
1115          * @brief encrypts data via AES
1116          *
1117          * @param string $data The data that is to be encrypted
1118          * @param string $key  The AES key
1119          *
1120          * @return string encrypted data
1121          */
1122         private static function aesEncrypt($data, $key)
1123         {
1124                 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1125         }
1126
1127         /**
1128          * @brief decrypts data via AES
1129          *
1130          * @param string $encrypted The encrypted data
1131          * @param string $key       The AES key
1132          *
1133          * @return string decrypted data
1134          */
1135         public static function aesDecrypt($encrypted, $key)
1136         {
1137                 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1138         }
1139
1140         /**
1141          * @brief Delivers the atom content to the contacts
1142          *
1143          * @param array  $owner    Owner record
1144          * @param array  $contact  Contact record of the receiver
1145          * @param string $atom     Content that will be transmitted
1146          * @param bool   $dissolve (to be documented)
1147          *
1148          * @return int Deliver status. -1 means an error.
1149          * @todo Add array type-hint for $owner, $contact
1150          */
1151         public static function deliver($owner, $contact, $atom, $dissolve = false)
1152         {
1153                 $a = get_app();
1154
1155                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1156
1157                 if ($contact['duplex'] && $contact['dfrn-id']) {
1158                         $idtosend = '0:' . $orig_id;
1159                 }
1160                 if ($contact['duplex'] && $contact['issued-id']) {
1161                         $idtosend = '1:' . $orig_id;
1162                 }
1163
1164                 $rino = Config::get('system', 'rino_encrypt');
1165                 $rino = intval($rino);
1166
1167                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1168
1169                 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1170                 $ssl_policy = '';
1171
1172                 switch ($ssl_val) {
1173                         case SSL_POLICY_FULL:
1174                                 $ssl_policy = 'full';
1175                                 break;
1176                         case SSL_POLICY_SELFSIGN:
1177                                 $ssl_policy = 'self';
1178                                 break;
1179                         case SSL_POLICY_NONE:
1180                         default:
1181                                 $ssl_policy = 'none';
1182                                 break;
1183                 }
1184
1185                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1186
1187                 logger('dfrn_deliver: ' . $url);
1188
1189                 $ret = z_fetch_url($url);
1190
1191                 if ($ret['errno'] == CURLE_OPERATION_TIMEDOUT) {
1192                         return -2; // timed out
1193                 }
1194
1195                 $xml = $ret['body'];
1196
1197                 $curl_stat = $a->get_curl_code();
1198                 if (!$curl_stat) {
1199                         return -3; // timed out
1200                 }
1201
1202                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1203
1204                 if (! $xml) {
1205                         return 3;
1206                 }
1207
1208                 if (strpos($xml, '<?xml') === false) {
1209                         logger('dfrn_deliver: no valid XML returned');
1210                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1211                         return 3;
1212                 }
1213
1214                 $res = parse_xml_string($xml);
1215
1216                 if ((intval($res->status) != 0) || (! strlen($res->challenge)) || (! strlen($res->dfrn_id))) {
1217                         return (($res->status) ? $res->status : 3);
1218                 }
1219
1220                 $postvars     = [];
1221                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1222                 $challenge    = hex2bin((string) $res->challenge);
1223                 $perm         = (($res->perm) ? $res->perm : null);
1224                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1225                 $rino_remote_version = intval($res->rino);
1226                 $page         = (($owner['page-flags'] == PAGE_COMMUNITY) ? 1 : 0);
1227
1228                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1229
1230                 if ($owner['page-flags'] == PAGE_PRVGROUP) {
1231                         $page = 2;
1232                 }
1233
1234                 $final_dfrn_id = '';
1235
1236                 if ($perm) {
1237                         if ((($perm == 'rw') && (! intval($contact['writable'])))
1238                                 || (($perm == 'r') && (intval($contact['writable'])))
1239                         ) {
1240                                 q(
1241                                         "update contact set writable = %d where id = %d",
1242                                         intval(($perm == 'rw') ? 1 : 0),
1243                                         intval($contact['id'])
1244                                 );
1245                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1246                         }
1247                 }
1248
1249                 if (($contact['duplex'] && strlen($contact['pubkey']))
1250                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1251                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1252                 ) {
1253                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1254                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1255                 } else {
1256                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1257                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1258                 }
1259
1260                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1261
1262                 if (strpos($final_dfrn_id, ':') == 1) {
1263                         $final_dfrn_id = substr($final_dfrn_id, 2);
1264                 }
1265
1266                 if ($final_dfrn_id != $orig_id) {
1267                         logger('dfrn_deliver: wrong dfrn_id.');
1268                         // did not decode properly - cannot trust this site
1269                         return 3;
1270                 }
1271
1272                 $postvars['dfrn_id']      = $idtosend;
1273                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1274                 if ($dissolve) {
1275                         $postvars['dissolve'] = '1';
1276                 }
1277
1278
1279                 if ((($contact['rel']) && ($contact['rel'] != CONTACT_IS_SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1280                         $postvars['data'] = $atom;
1281                         $postvars['perm'] = 'rw';
1282                 } else {
1283                         $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1284                         $postvars['perm'] = 'r';
1285                 }
1286
1287                 $postvars['ssl_policy'] = $ssl_policy;
1288
1289                 if ($page) {
1290                         $postvars['page'] = $page;
1291                 }
1292
1293
1294                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1295                         logger('rino version: '. $rino_remote_version);
1296
1297                         switch ($rino_remote_version) {
1298                                 case 1:
1299                                         $key = openssl_random_pseudo_bytes(16);
1300                                         $data = self::aesEncrypt($postvars['data'], $key);
1301                                         break;
1302                                 default:
1303                                         logger("rino: invalid requested version '$rino_remote_version'");
1304                                         return -8;
1305                         }
1306
1307                         $postvars['rino'] = $rino_remote_version;
1308                         $postvars['data'] = bin2hex($data);
1309
1310                         if ($dfrn_version >= 2.1) {
1311                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1312                                         || ($owner['page-flags'] == PAGE_COMMUNITY && strlen($contact['pubkey']))
1313                                         || ($contact['rel'] == CONTACT_IS_SHARING && strlen($contact['pubkey']))
1314                                 ) {
1315                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1316                                 } else {
1317                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1318                                 }
1319                         } else {
1320                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == PAGE_COMMUNITY)) {
1321                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1322                                 } else {
1323                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1324                                 }
1325                         }
1326
1327                         logger('md5 rawkey ' . md5($postvars['key']));
1328
1329                         $postvars['key'] = bin2hex($postvars['key']);
1330                 }
1331
1332
1333                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1334
1335                 $xml = post_url($contact['notify'], $postvars);
1336
1337                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1338
1339                 $curl_stat = $a->get_curl_code();
1340                 if ((!$curl_stat) || (!strlen($xml))) {
1341                         return -9; // timed out
1342                 }
1343
1344                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1345                         return -10;
1346                 }
1347
1348                 if (strpos($xml, '<?xml') === false) {
1349                         logger('dfrn_deliver: phase 2: no valid XML returned');
1350                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1351                         return 3;
1352                 }
1353
1354                 if ($contact['term-date'] > NULL_DATE) {
1355                         logger("dfrn_deliver: $url back from the dead - removing mark for death");
1356                         Contact::unmarkForArchival($contact);
1357                 }
1358
1359                 $res = parse_xml_string($xml);
1360
1361                 if (!isset($res->status)) {
1362                         return -11;
1363                 }
1364
1365                 if (!empty($res->message)) {
1366                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1367                 }
1368
1369                 return intval($res->status);
1370         }
1371
1372         /**
1373          * @brief Add new birthday event for this person
1374          *
1375          * @param array  $contact  Contact record
1376          * @param string $birthday Birthday of the contact
1377          * @return void
1378          * @todo Add array type-hint for $contact
1379          */
1380         private static function birthdayEvent($contact, $birthday)
1381         {
1382                 // Check for duplicates
1383                 $r = q(
1384                         "SELECT `id` FROM `event` WHERE `uid` = %d AND `cid` = %d AND `start` = '%s' AND `type` = '%s' LIMIT 1",
1385                         intval($contact["uid"]),
1386                         intval($contact["id"]),
1387                         dbesc(datetime_convert("UTC", "UTC", $birthday)),
1388                         dbesc("birthday")
1389                 );
1390
1391                 if (DBM::is_result($r)) {
1392                         return;
1393                 }
1394
1395                 logger("updating birthday: ".$birthday." for contact ".$contact["id"]);
1396
1397                 $bdtext = L10n::t("%s\'s birthday", $contact["name"]);
1398                 $bdtext2 = L10n::t("Happy Birthday %s", " [url=".$contact["url"]."]".$contact["name"]."[/url]");
1399
1400                 $r = q(
1401                         "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1402                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1403                         intval($contact["uid"]),
1404                         intval($contact["id"]),
1405                         dbesc(datetime_convert()),
1406                         dbesc(datetime_convert()),
1407                         dbesc(datetime_convert("UTC", "UTC", $birthday)),
1408                         dbesc(datetime_convert("UTC", "UTC", $birthday . " + 1 day ")),
1409                         dbesc($bdtext),
1410                         dbesc($bdtext2),
1411                         dbesc("birthday")
1412                 );
1413         }
1414
1415         /**
1416          * @brief Fetch the author data from head or entry items
1417          *
1418          * @param object $xpath     XPath object
1419          * @param object $context   In which context should the data be searched
1420          * @param array  $importer  Record of the importer user mixed with contact of the content
1421          * @param string $element   Element name from which the data is fetched
1422          * @param bool   $onlyfetch Should the data only be fetched or should it update the contact record as well
1423          * @param string $xml       optional, default empty
1424          *
1425          * @return array Relevant data of the author
1426          * @todo Find good type-hints for all parameter
1427          */
1428         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1429         {
1430                 $author = [];
1431                 $author["name"] = $xpath->evaluate($element."/atom:name/text()", $context)->item(0)->nodeValue;
1432                 $author["link"] = $xpath->evaluate($element."/atom:uri/text()", $context)->item(0)->nodeValue;
1433
1434                 $r = q(
1435                         "SELECT `id`, `uid`, `url`, `network`, `avatar-date`, `name-date`, `uri-date`, `addr`,
1436                                 `name`, `nick`, `about`, `location`, `keywords`, `xmpp`, `bdyear`, `bd`, `hidden`, `contact-type`
1437                                 FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
1438                         intval($importer["uid"]),
1439                         dbesc(normalise_link($author["link"])),
1440                         dbesc(NETWORK_STATUSNET)
1441                 );
1442
1443                 if (DBM::is_result($r)) {
1444                         $contact = $r[0];
1445                         $author["contact-id"] = $r[0]["id"];
1446                         $author["network"] = $r[0]["network"];
1447                 } else {
1448                         if (!$onlyfetch) {
1449                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["uid"]." XML: ".$xml, LOGGER_DEBUG);
1450                         }
1451
1452                         $author["contact-id"] = $importer["id"];
1453                         $author["network"] = $importer["network"];
1454                         $onlyfetch = true;
1455                 }
1456
1457                 // Until now we aren't serving different sizes - but maybe later
1458                 $avatarlist = [];
1459                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1460                 $avatars = $xpath->query($element."/atom:link[@rel='avatar']", $context);
1461                 foreach ($avatars as $avatar) {
1462                         $href = "";
1463                         $width = 0;
1464                         foreach ($avatar->attributes as $attributes) {
1465                                 /// @TODO Rewrite these similar if () to one switch
1466                                 if ($attributes->name == "href") {
1467                                         $href = $attributes->textContent;
1468                                 }
1469                                 if ($attributes->name == "width") {
1470                                         $width = $attributes->textContent;
1471                                 }
1472                                 if ($attributes->name == "updated") {
1473                                         $contact["avatar-date"] = $attributes->textContent;
1474                                 }
1475                         }
1476                         if (($width > 0) && ($href != "")) {
1477                                 $avatarlist[$width] = $href;
1478                         }
1479                 }
1480                 if (count($avatarlist) > 0) {
1481                         krsort($avatarlist);
1482                         $author["avatar"] = current($avatarlist);
1483                 }
1484
1485                 if (DBM::is_result($r) && !$onlyfetch) {
1486                         logger("Check if contact details for contact " . $r[0]["id"] . " (" . $r[0]["nick"] . ") have to be updated.", LOGGER_DEBUG);
1487
1488                         $poco = ["url" => $contact["url"]];
1489
1490                         // When was the last change to name or uri?
1491                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1492                         foreach ($name_element->attributes as $attributes) {
1493                                 if ($attributes->name == "updated") {
1494                                         $poco["name-date"] = $attributes->textContent;
1495                                 }
1496                         }
1497
1498                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1499                         foreach ($link_element->attributes as $attributes) {
1500                                 if ($attributes->name == "updated") {
1501                                         $poco["uri-date"] = $attributes->textContent;
1502                                 }
1503                         }
1504
1505                         // Update contact data
1506                         $value = $xpath->evaluate($element . "/dfrn:handle/text()", $context)->item(0)->nodeValue;
1507                         if ($value != "") {
1508                                 $poco["addr"] = $value;
1509                         }
1510
1511                         $value = $xpath->evaluate($element . "/poco:displayName/text()", $context)->item(0)->nodeValue;
1512                         if ($value != "") {
1513                                 $poco["name"] = $value;
1514                         }
1515
1516                         $value = $xpath->evaluate($element . "/poco:preferredUsername/text()", $context)->item(0)->nodeValue;
1517                         if ($value != "") {
1518                                 $poco["nick"] = $value;
1519                         }
1520
1521                         $value = $xpath->evaluate($element . "/poco:note/text()", $context)->item(0)->nodeValue;
1522                         if ($value != "") {
1523                                 $poco["about"] = $value;
1524                         }
1525
1526                         $value = $xpath->evaluate($element . "/poco:address/poco:formatted/text()", $context)->item(0)->nodeValue;
1527                         if ($value != "") {
1528                                 $poco["location"] = $value;
1529                         }
1530
1531                         /// @todo Only search for elements with "poco:type" = "xmpp"
1532                         $value = $xpath->evaluate($element . "/poco:ims/poco:value/text()", $context)->item(0)->nodeValue;
1533                         if ($value != "") {
1534                                 $poco["xmpp"] = $value;
1535                         }
1536
1537                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1538                         /// - poco:utcOffset
1539                         /// - poco:urls
1540                         /// - poco:locality
1541                         /// - poco:region
1542                         /// - poco:country
1543
1544                         // If the "hide" element is present then the profile isn't searchable.
1545                         $hide = intval($xpath->evaluate($element . "/dfrn:hide/text()", $context)->item(0)->nodeValue == "true");
1546
1547                         logger("Hidden status for contact " . $contact["url"] . ": " . $hide, LOGGER_DEBUG);
1548
1549                         // If the contact isn't searchable then set the contact to "hidden".
1550                         // Problem: This can be manually overridden by the user.
1551                         if ($hide) {
1552                                 $contact["hidden"] = true;
1553                         }
1554
1555                         // Save the keywords into the contact table
1556                         $tags = [];
1557                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1558                         foreach ($tagelements as $tag) {
1559                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1560                         }
1561
1562                         if (count($tags)) {
1563                                 $poco["keywords"] = implode(", ", $tags);
1564                         }
1565
1566                         // "dfrn:birthday" contains the birthday converted to UTC
1567                         $old_bdyear = $contact["bdyear"];
1568
1569                         $birthday = $xpath->evaluate($element . "/dfrn:birthday/text()", $context)->item(0)->nodeValue;
1570
1571                         if (strtotime($birthday) > time()) {
1572                                 $bd_timestamp = strtotime($birthday);
1573
1574                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1575                         }
1576
1577                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1578                         $value = $xpath->evaluate($element . "/poco:birthday/text()", $context)->item(0)->nodeValue;
1579
1580                         if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1581                                 $bdyear = date("Y");
1582                                 $value = str_replace("0000", $bdyear, $value);
1583
1584                                 if (strtotime($value) < time()) {
1585                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1586                                         $bdyear = $bdyear + 1;
1587                                 }
1588
1589                                 $poco["bd"] = $value;
1590                         }
1591
1592                         $contact = array_merge($contact, $poco);
1593
1594                         if ($old_bdyear != $contact["bdyear"]) {
1595                                 self::birthdayEvent($contact, $birthday);
1596                         }
1597
1598                         // Get all field names
1599                         $fields = [];
1600                         foreach ($r[0] as $field => $data) {
1601                                 $fields[$field] = $data;
1602                         }
1603
1604                         unset($fields["id"]);
1605                         unset($fields["uid"]);
1606                         unset($fields["url"]);
1607                         unset($fields["avatar-date"]);
1608                         unset($fields["name-date"]);
1609                         unset($fields["uri-date"]);
1610
1611                         // Update check for this field has to be done differently
1612                         $datefields = ["name-date", "uri-date"];
1613                         foreach ($datefields as $field) {
1614                                 if (strtotime($contact[$field]) > strtotime($r[0][$field])) {
1615                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1616                                         $update = true;
1617                                 }
1618                         }
1619
1620                         foreach ($fields as $field => $data) {
1621                                 if ($contact[$field] != $r[0][$field]) {
1622                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $r[0][$field] . "'", LOGGER_DEBUG);
1623                                         $update = true;
1624                                 }
1625                         }
1626
1627                         if ($update) {
1628                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1629
1630                                 q(
1631                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1632                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1633                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1634                                         WHERE `id` = %d AND `network` = '%s'",
1635                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]),     dbesc($contact["location"]),
1636                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1637                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1638                                         dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1639                                         intval($contact["id"]), dbesc($contact["network"])
1640                                 );
1641                         }
1642
1643                         Contact::updateAvatar(
1644                                 $author["avatar"],
1645                                 $importer["uid"],
1646                                 $contact["id"],
1647                                 (strtotime($contact["avatar-date"]) > strtotime($r[0]["avatar-date"]))
1648                         );
1649
1650                         /*
1651                          * The generation is a sign for the reliability of the provided data.
1652                          * It is used in the socgraph.php to prevent that old contact data
1653                          * that was relayed over several servers can overwrite contact
1654                          * data that we received directly.
1655                          */
1656
1657                         $poco["generation"] = 2;
1658                         $poco["photo"] = $author["avatar"];
1659                         $poco["hide"] = $hide;
1660                         $poco["contact-type"] = $contact["contact-type"];
1661                         $gcid = GContact::update($poco);
1662
1663                         GContact::link($gcid, $importer["uid"], $contact["id"]);
1664                 }
1665
1666                 return($author);
1667         }
1668
1669         /**
1670          * @brief Transforms activity objects into an XML string
1671          *
1672          * @param object $xpath    XPath object
1673          * @param object $activity Activity object
1674          * @param string $element  element name
1675          *
1676          * @return string XML string
1677          * @todo Find good type-hints for all parameter
1678          */
1679         private static function transformActivity($xpath, $activity, $element)
1680         {
1681                 if (!is_object($activity)) {
1682                         return "";
1683                 }
1684
1685                 $obj_doc = new DOMDocument("1.0", "utf-8");
1686                 $obj_doc->formatOutput = true;
1687
1688                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1689
1690                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1691                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1692
1693                 $id = $xpath->query("atom:id", $activity)->item(0);
1694                 if (is_object($id)) {
1695                         $obj_element->appendChild($obj_doc->importNode($id, true));
1696                 }
1697
1698                 $title = $xpath->query("atom:title", $activity)->item(0);
1699                 if (is_object($title)) {
1700                         $obj_element->appendChild($obj_doc->importNode($title, true));
1701                 }
1702
1703                 $links = $xpath->query("atom:link", $activity);
1704                 if (is_object($links)) {
1705                         foreach ($links as $link) {
1706                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1707                         }
1708                 }
1709
1710                 $content = $xpath->query("atom:content", $activity)->item(0);
1711                 if (is_object($content)) {
1712                         $obj_element->appendChild($obj_doc->importNode($content, true));
1713                 }
1714
1715                 $obj_doc->appendChild($obj_element);
1716
1717                 $objxml = $obj_doc->saveXML($obj_element);
1718
1719                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1720                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1721                 return($objxml);
1722         }
1723
1724         /**
1725          * @brief Processes the mail elements
1726          *
1727          * @param object $xpath    XPath object
1728          * @param object $mail     mail elements
1729          * @param array  $importer Record of the importer user mixed with contact of the content
1730          * @return void
1731          * @todo Find good type-hints for all parameter
1732          */
1733         private static function processMail($xpath, $mail, $importer)
1734         {
1735                 logger("Processing mails");
1736
1737                 /// @TODO Rewrite this to one statement
1738                 $msg = [];
1739                 $msg["uid"] = $importer["importer_uid"];
1740                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1741                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1742                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1743                 $msg["contact-id"] = $importer["id"];
1744                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1745                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1746                 $msg["created"] = $xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue;
1747                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1748                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1749                 $msg["seen"] = 0;
1750                 $msg["replied"] = 0;
1751
1752                 dba::insert('mail', $msg);
1753
1754                 // send notifications.
1755                 /// @TODO Arange this mess
1756                 $notif_params = [
1757                         "type" => NOTIFY_MAIL,
1758                         "notify_flags" => $importer["notify-flags"],
1759                         "language" => $importer["language"],
1760                         "to_name" => $importer["username"],
1761                         "to_email" => $importer["email"],
1762                         "uid" => $importer["importer_uid"],
1763                         "item" => $msg,
1764                         "source_name" => $msg["from-name"],
1765                         "source_link" => $importer["url"],
1766                         "source_photo" => $importer["thumb"],
1767                         "verb" => ACTIVITY_POST,
1768                         "otype" => "mail"
1769                 ];
1770
1771                 notification($notif_params);
1772
1773                 logger("Mail is processed, notification was sent.");
1774         }
1775
1776         /**
1777          * @brief Processes the suggestion elements
1778          *
1779          * @param object $xpath      XPath object
1780          * @param object $suggestion suggestion elements
1781          * @param array  $importer   Record of the importer user mixed with contact of the content
1782          * @return boolean
1783          * @todo Find good type-hints for all parameter
1784          */
1785         private static function processSuggestion($xpath, $suggestion, $importer)
1786         {
1787                 $a = get_app();
1788
1789                 logger("Processing suggestions");
1790
1791                 /// @TODO Rewrite this to one statement
1792                 $suggest = [];
1793                 $suggest["uid"] = $importer["importer_uid"];
1794                 $suggest["cid"] = $importer["id"];
1795                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1796                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1797                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1798                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1799                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1800
1801                 // Does our member already have a friend matching this description?
1802
1803                 $r = q(
1804                         "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1805                         dbesc($suggest["name"]),
1806                         dbesc(normalise_link($suggest["url"])),
1807                         intval($suggest["uid"])
1808                 );
1809
1810                 /*
1811                  * The valid result means the friend we're about to send a friend
1812                  * suggestion already has them in their contact, which means no further
1813                  * action is required.
1814                  *
1815                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1816                  */
1817                 if (DBM::is_result($r)) {
1818                         return false;
1819                 }
1820
1821                 // Do we already have an fcontact record for this person?
1822
1823                 $fid = 0;
1824                 $r = q(
1825                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1826                         dbesc($suggest["url"]),
1827                         dbesc($suggest["name"]),
1828                         dbesc($suggest["request"])
1829                 );
1830                 if (DBM::is_result($r)) {
1831                         $fid = $r[0]["id"];
1832
1833                         // OK, we do. Do we already have an introduction for this person ?
1834                         $r = q(
1835                                 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1836                                 intval($suggest["uid"]),
1837                                 intval($fid)
1838                         );
1839
1840                         /*
1841                          * The valid result means the friend we're about to send a friend
1842                          * suggestion already has them in their contact, which means no further
1843                          * action is required.
1844                          *
1845                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1846                          */
1847                         if (DBM::is_result($r)) {
1848                                 return false;
1849                         }
1850                 }
1851                 if (!$fid) {
1852                         $r = q(
1853                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1854                                 dbesc($suggest["name"]),
1855                                 dbesc($suggest["url"]),
1856                                 dbesc($suggest["photo"]),
1857                                 dbesc($suggest["request"])
1858                         );
1859                 }
1860                 $r = q(
1861                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1862                         dbesc($suggest["url"]),
1863                         dbesc($suggest["name"]),
1864                         dbesc($suggest["request"])
1865                 );
1866
1867                 /*
1868                  * If no record in fcontact is found, below INSERT statement will not
1869                  * link an introduction to it.
1870                  */
1871                 if (!DBM::is_result($r)) {
1872                         // database record did not get created. Quietly give up.
1873                         killme();
1874                 }
1875
1876                 $fid = $r[0]["id"];
1877
1878                 $hash = random_string();
1879
1880                 $r = q(
1881                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1882                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1883                         intval($suggest["uid"]),
1884                         intval($fid),
1885                         intval($suggest["cid"]),
1886                         dbesc($suggest["body"]),
1887                         dbesc($hash),
1888                         dbesc(datetime_convert()),
1889                         intval(0)
1890                 );
1891
1892                 notification(
1893                         [
1894                                 "type"         => NOTIFY_SUGGEST,
1895                                 "notify_flags" => $importer["notify-flags"],
1896                                 "language"     => $importer["language"],
1897                                 "to_name"      => $importer["username"],
1898                                 "to_email"     => $importer["email"],
1899                                 "uid"          => $importer["importer_uid"],
1900                                 "item"         => $suggest,
1901                                 "link"         => System::baseUrl()."/notifications/intros",
1902                                 "source_name"  => $importer["name"],
1903                                 "source_link"  => $importer["url"],
1904                                 "source_photo" => $importer["photo"],
1905                                 "verb"         => ACTIVITY_REQ_FRIEND,
1906                                 "otype"        => "intro"]
1907                 );
1908
1909                 return true;
1910         }
1911
1912         /**
1913          * @brief Processes the relocation elements
1914          *
1915          * @param object $xpath      XPath object
1916          * @param object $relocation relocation elements
1917          * @param array  $importer   Record of the importer user mixed with contact of the content
1918          * @return boolean
1919          * @todo Find good type-hints for all parameter
1920          */
1921         private static function processRelocation($xpath, $relocation, $importer)
1922         {
1923                 logger("Processing relocations");
1924
1925                 /// @TODO Rewrite this to one statement
1926                 $relocate = [];
1927                 $relocate["uid"] = $importer["importer_uid"];
1928                 $relocate["cid"] = $importer["id"];
1929                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
1930                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
1931                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
1932                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
1933                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
1934                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
1935                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
1936                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
1937                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
1938                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
1939                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
1940                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
1941
1942                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
1943                         $relocate["avatar"] = $relocate["photo"];
1944                 }
1945
1946                 if ($relocate["addr"] == "") {
1947                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
1948                 }
1949
1950                 // update contact
1951                 $r = q(
1952                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
1953                         intval($importer["id"]),
1954                         intval($importer["importer_uid"])
1955                 );
1956
1957                 if (!DBM::is_result($r)) {
1958                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
1959                         return false;
1960                 }
1961
1962                 $old = $r[0];
1963
1964                 // Update the gcontact entry
1965                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
1966
1967                 $x = q(
1968                         "UPDATE `gcontact` SET
1969                                         `name` = '%s',
1970                                         `photo` = '%s',
1971                                         `url` = '%s',
1972                                         `nurl` = '%s',
1973                                         `addr` = '%s',
1974                                         `connect` = '%s',
1975                                         `notify` = '%s',
1976                                         `server_url` = '%s'
1977                         WHERE `nurl` = '%s';",
1978                         dbesc($relocate["name"]),
1979                         dbesc($relocate["avatar"]),
1980                         dbesc($relocate["url"]),
1981                         dbesc(normalise_link($relocate["url"])),
1982                         dbesc($relocate["addr"]),
1983                         dbesc($relocate["addr"]),
1984                         dbesc($relocate["notify"]),
1985                         dbesc($relocate["server_url"]),
1986                         dbesc(normalise_link($old["url"]))
1987                 );
1988
1989                 // Update the contact table. We try to find every entry.
1990                 $x = q(
1991                         "UPDATE `contact` SET
1992                                         `name` = '%s',
1993                                         `avatar` = '%s',
1994                                         `url` = '%s',
1995                                         `nurl` = '%s',
1996                                         `addr` = '%s',
1997                                         `request` = '%s',
1998                                         `confirm` = '%s',
1999                                         `notify` = '%s',
2000                                         `poll` = '%s',
2001                                         `site-pubkey` = '%s'
2002                         WHERE (`id` = %d AND `uid` = %d) OR (`nurl` = '%s');",
2003                         dbesc($relocate["name"]),
2004                         dbesc($relocate["avatar"]),
2005                         dbesc($relocate["url"]),
2006                         dbesc(normalise_link($relocate["url"])),
2007                         dbesc($relocate["addr"]),
2008                         dbesc($relocate["request"]),
2009                         dbesc($relocate["confirm"]),
2010                         dbesc($relocate["notify"]),
2011                         dbesc($relocate["poll"]),
2012                         dbesc($relocate["sitepubkey"]),
2013                         intval($importer["id"]),
2014                         intval($importer["importer_uid"]),
2015                         dbesc(normalise_link($old["url"]))
2016                 );
2017
2018                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2019
2020                 if ($x === false) {
2021                         return false;
2022                 }
2023
2024                 // update items
2025                 /// @todo This is an extreme performance killer
2026                 $fields = [
2027                         'owner-link' => [$old["url"], $relocate["url"]],
2028                         'author-link' => [$old["url"], $relocate["url"]],
2029                         //'owner-avatar' => array($old["photo"], $relocate["photo"]),
2030                         //'author-avatar' => array($old["photo"], $relocate["photo"]),
2031                 ];
2032                 foreach ($fields as $n => $f) {
2033                         $r = q(
2034                                 "SELECT `id` FROM `item` WHERE `%s` = '%s' AND `uid` = %d LIMIT 1",
2035                                 $n,
2036                                 dbesc($f[0]),
2037                                 intval($importer["importer_uid"])
2038                         );
2039
2040                         if (DBM::is_result($r)) {
2041                                 $x = q(
2042                                         "UPDATE `item` SET `%s` = '%s' WHERE `%s` = '%s' AND `uid` = %d",
2043                                         $n,
2044                                         dbesc($f[1]),
2045                                         $n,
2046                                         dbesc($f[0]),
2047                                         intval($importer["importer_uid"])
2048                                 );
2049
2050                                 if ($x === false) {
2051                                         return false;
2052                                 }
2053                         }
2054                 }
2055
2056                 /// @TODO
2057                 /// merge with current record, current contents have priority
2058                 /// update record, set url-updated
2059                 /// update profile photos
2060                 /// schedule a scan?
2061                 return true;
2062         }
2063
2064         /**
2065          * @brief Updates an item
2066          *
2067          * @param array $current   the current item record
2068          * @param array $item      the new item record
2069          * @param array $importer  Record of the importer user mixed with contact of the content
2070          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2071          * @return mixed
2072          * @todo set proper type-hints (array?)
2073          */
2074         private static function updateContent($current, $item, $importer, $entrytype)
2075         {
2076                 $changed = false;
2077
2078                 if (edited_timestamp_is_newer($current, $item)) {
2079                         // do not accept (ignore) an earlier edit than one we currently have.
2080                         if (datetime_convert("UTC", "UTC", $item["edited"]) < $current["edited"]) {
2081                                 return false;
2082                         }
2083
2084                         $fields = ['title' => $item["title"], 'body' => $item["body"],
2085                                         'tag' => $item["tag"], 'changed' => datetime_convert(),
2086                                         'edited' => datetime_convert("UTC", "UTC", $item["edited"])];
2087
2088                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2089                         dba::update('item', $fields, $condition);
2090
2091                         create_tags_from_itemuri($item["uri"], $importer["importer_uid"]);
2092                         update_thread_uri($item["uri"], $importer["importer_uid"]);
2093
2094                         $changed = true;
2095
2096                         if ($entrytype == DFRN_REPLY_RC) {
2097                                 Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $current["id"]);
2098                         }
2099                 }
2100                 return $changed;
2101         }
2102
2103         /**
2104          * @brief Detects the entry type of the item
2105          *
2106          * @param array $importer Record of the importer user mixed with contact of the content
2107          * @param array $item     the new item record
2108          *
2109          * @return int Is it a toplevel entry, a comment or a relayed comment?
2110          * @todo set proper type-hints (array?)
2111          */
2112         private static function getEntryType($importer, $item)
2113         {
2114                 if ($item["parent-uri"] != $item["uri"]) {
2115                         $community = false;
2116
2117                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2118                                 $sql_extra = "";
2119                                 $community = true;
2120                                 logger("possible community action");
2121                         } else {
2122                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2123                         }
2124
2125                         // was the top-level post for this action written by somebody on this site?
2126                         // Specifically, the recipient?
2127
2128                         $is_a_remote_action = false;
2129
2130                         $r = q(
2131                                 "SELECT `item`.`parent-uri` FROM `item`
2132                                 WHERE `item`.`uri` = '%s'
2133                                 LIMIT 1",
2134                                 dbesc($item["parent-uri"])
2135                         );
2136                         if (DBM::is_result($r)) {
2137                                 $r = q(
2138                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2139                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2140                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2141                                         AND `item`.`uid` = %d
2142                                         $sql_extra
2143                                         LIMIT 1",
2144                                         dbesc($r[0]["parent-uri"]),
2145                                         dbesc($r[0]["parent-uri"]),
2146                                         dbesc($r[0]["parent-uri"]),
2147                                         intval($importer["importer_uid"])
2148                                 );
2149                                 if (DBM::is_result($r)) {
2150                                         $is_a_remote_action = true;
2151                                 }
2152                         }
2153
2154                         /*
2155                          * Does this have the characteristics of a community or private group action?
2156                          * If it's an action to a wall post on a community/prvgroup page it's a
2157                          * valid community action. Also forum_mode makes it valid for sure.
2158                          * If neither, it's not.
2159                          */
2160                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2161                                 $is_a_remote_action = false;
2162                                 logger("not a community action");
2163                         }
2164
2165                         if ($is_a_remote_action) {
2166                                 return DFRN_REPLY_RC;
2167                         } else {
2168                                 return DFRN_REPLY;
2169                         }
2170                 } else {
2171                         return DFRN_TOP_LEVEL;
2172                 }
2173         }
2174
2175         /**
2176          * @brief Send a "poke"
2177          *
2178          * @param array $item      the new item record
2179          * @param array $importer  Record of the importer user mixed with contact of the content
2180          * @param int   $posted_id The record number of item record that was just posted
2181          * @return void
2182          * @todo set proper type-hints (array?)
2183          */
2184         private static function doPoke($item, $importer, $posted_id)
2185         {
2186                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2187                 if (!$verb) {
2188                         return;
2189                 }
2190                 $xo = parse_xml_string($item["object"], false);
2191
2192                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2193                         // somebody was poked/prodded. Was it me?
2194                         foreach ($xo->link as $l) {
2195                                 $atts = $l->attributes();
2196                                 switch ($atts["rel"]) {
2197                                         case "alternate":
2198                                                 $Blink = $atts["href"];
2199                                                 break;
2200                                         default:
2201                                                 break;
2202                                 }
2203                         }
2204
2205                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2206                                 // send a notification
2207                                 notification(
2208                                         [
2209                                         "type"         => NOTIFY_POKE,
2210                                         "notify_flags" => $importer["notify-flags"],
2211                                         "language"     => $importer["language"],
2212                                         "to_name"      => $importer["username"],
2213                                         "to_email"     => $importer["email"],
2214                                         "uid"          => $importer["importer_uid"],
2215                                         "item"         => $item,
2216                                         "link"         => System::baseUrl()."/display/".urlencode(get_item_guid($posted_id)),
2217                                         "source_name"  => stripslashes($item["author-name"]),
2218                                         "source_link"  => $item["author-link"],
2219                                         "source_photo" => ((link_compare($item["author-link"], $importer["url"]))
2220                                                 ? $importer["thumb"] : $item["author-avatar"]),
2221                                         "verb"         => $item["verb"],
2222                                         "otype"        => "person",
2223                                         "activity"     => $verb,
2224                                         "parent"       => $item["parent"]]
2225                                 );
2226                         }
2227                 }
2228         }
2229
2230         /**
2231          * @brief Processes several actions, depending on the verb
2232          *
2233          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2234          * @param array $importer  Record of the importer user mixed with contact of the content
2235          * @param array $item      the new item record
2236          * @param bool  $is_like   Is the verb a "like"?
2237          *
2238          * @return bool Should the processing of the entries be continued?
2239          * @todo set proper type-hints (array?)
2240          */
2241         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2242         {
2243                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2244
2245                 if (($entrytype == DFRN_TOP_LEVEL)) {
2246                         // The filling of the the "contact" variable is done for legcy reasons
2247                         // The functions below are partly used by ostatus.php as well - where we have this variable
2248                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2249                         $contact = $r[0];
2250                         $nickname = $contact["nick"];
2251
2252                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2253                         // This function once was responsible for DFRN and OStatus.
2254                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2255                                 logger("New follower");
2256                                 new_follower($importer, $contact, $item, $nickname);
2257                                 return false;
2258                         }
2259                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2260                                 logger("Lost follower");
2261                                 lose_follower($importer, $contact, $item);
2262                                 return false;
2263                         }
2264                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2265                                 logger("New friend request");
2266                                 new_follower($importer, $contact, $item, $nickname, true);
2267                                 return false;
2268                         }
2269                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2270                                 logger("Lost sharer");
2271                                 lose_sharer($importer, $contact, $item);
2272                                 return false;
2273                         }
2274                 } else {
2275                         if (($item["verb"] == ACTIVITY_LIKE)
2276                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2277                                 || ($item["verb"] == ACTIVITY_ATTEND)
2278                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2279                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2280                         ) {
2281                                 $is_like = true;
2282                                 $item["type"] = "activity";
2283                                 $item["gravity"] = GRAVITY_LIKE;
2284                                 // only one like or dislike per person
2285                                 // splitted into two queries for performance issues
2286                                 $r = q(
2287                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `parent-uri` = '%s' AND NOT `deleted` LIMIT 1",
2288                                         intval($item["uid"]),
2289                                         dbesc($item["author-link"]),
2290                                         dbesc($item["verb"]),
2291                                         dbesc($item["parent-uri"])
2292                                 );
2293                                 if (DBM::is_result($r)) {
2294                                         return false;
2295                                 }
2296
2297                                 $r = q(
2298                                         "SELECT `id` FROM `item` WHERE `uid` = %d AND `author-link` = '%s' AND `verb` = '%s' AND `thr-parent` = '%s' AND NOT `deleted` LIMIT 1",
2299                                         intval($item["uid"]),
2300                                         dbesc($item["author-link"]),
2301                                         dbesc($item["verb"]),
2302                                         dbesc($item["parent-uri"])
2303                                 );
2304                                 if (DBM::is_result($r)) {
2305                                         return false;
2306                                 }
2307                         } else {
2308                                 $is_like = false;
2309                         }
2310
2311                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2312                                 $xo = parse_xml_string($item["object"], false);
2313                                 $xt = parse_xml_string($item["target"], false);
2314
2315                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2316                                         $r = q(
2317                                                 "SELECT `id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2318                                                 dbesc($xt->id),
2319                                                 intval($importer["importer_uid"])
2320                                         );
2321
2322                                         if (!DBM::is_result($r)) {
2323                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2324                                                 return false;
2325                                         }
2326
2327                                         // extract tag, if not duplicate, add to parent item
2328                                         if ($xo->content) {
2329                                                 if (!(stristr($r[0]["tag"], trim($xo->content)))) {
2330                                                         q(
2331                                                                 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2332                                                                 dbesc($r[0]["tag"] . (strlen($r[0]["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]'),
2333                                                                 intval($r[0]["id"])
2334                                                         );
2335                                                         create_tags_from_item($r[0]["id"]);
2336                                                 }
2337                                         }
2338                                 }
2339                         }
2340                 }
2341                 return true;
2342         }
2343
2344         /**
2345          * @brief Processes the link elements
2346          *
2347          * @param object $links link elements
2348          * @param array  $item  the item record
2349          * @return void
2350          * @todo set proper type-hints
2351          */
2352         private static function parseLinks($links, &$item)
2353         {
2354                 $rel = "";
2355                 $href = "";
2356                 $type = "";
2357                 $length = "0";
2358                 $title = "";
2359                 foreach ($links as $link) {
2360                         foreach ($link->attributes as $attributes) {
2361                                 switch ($attributes->name) {
2362                                         case "href"  : $href   = $attributes->textContent; break;
2363                                         case "rel"   : $rel    = $attributes->textContent; break;
2364                                         case "type"  : $type   = $attributes->textContent; break;
2365                                         case "length": $length = $attributes->textContent; break;
2366                                         case "title" : $title  = $attributes->textContent; break;
2367                                 }
2368                         }
2369                         if (($rel != "") && ($href != "")) {
2370                                 switch ($rel) {
2371                                         case "alternate":
2372                                                 $item["plink"] = $href;
2373                                                 break;
2374                                         case "enclosure":
2375                                                 $enclosure = $href;
2376                                                 if (strlen($item["attach"])) {
2377                                                         $item["attach"] .= ",";
2378                                                 }
2379
2380                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2381                                                 break;
2382                                 }
2383                         }
2384                 }
2385         }
2386
2387         /**
2388          * @brief Processes the entry elements which contain the items and comments
2389          *
2390          * @param array  $header   Array of the header elements that always stay the same
2391          * @param object $xpath    XPath object
2392          * @param object $entry    entry elements
2393          * @param array  $importer Record of the importer user mixed with contact of the content
2394          * @param object $xml      xml
2395          * @return void
2396          * @todo Add type-hints
2397          */
2398         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2399         {
2400                 logger("Processing entries");
2401
2402                 $item = $header;
2403
2404                 $item["protocol"] = PROTOCOL_DFRN;
2405
2406                 $item["source"] = $xml;
2407
2408                 // Get the uri
2409                 $item["uri"] = $xpath->query("atom:id/text()", $entry)->item(0)->nodeValue;
2410
2411                 $item["edited"] = $xpath->query("atom:updated/text()", $entry)->item(0)->nodeValue;
2412
2413                 $current = q(
2414                         "SELECT `id`, `uid`, `edited`, `body` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2415                         dbesc($item["uri"]),
2416                         intval($importer["importer_uid"])
2417                 );
2418
2419                 // Is there an existing item?
2420                 if (DBM::is_result($current) && edited_timestamp_is_newer($current[0], $item)
2421                         && (datetime_convert("UTC", "UTC", $item["edited"]) < $current[0]["edited"])
2422                 ) {
2423                         logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2424                         return;
2425                 }
2426
2427                 // Fetch the owner
2428                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2429
2430                 $item["owner-name"] = $owner["name"];
2431                 $item["owner-link"] = $owner["link"];
2432                 $item["owner-avatar"] = $owner["avatar"];
2433
2434                 // fetch the author
2435                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2436
2437                 $item["author-name"] = $author["name"];
2438                 $item["author-link"] = $author["link"];
2439                 $item["author-avatar"] = $author["avatar"];
2440
2441                 $item["title"] = $xpath->query("atom:title/text()", $entry)->item(0)->nodeValue;
2442
2443                 $item["created"] = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2444
2445                 $item["body"] = $xpath->query("dfrn:env/text()", $entry)->item(0)->nodeValue;
2446                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2447                 // make sure nobody is trying to sneak some html tags by us
2448                 $item["body"] = notags(base64url_decode($item["body"]));
2449
2450                 $item["body"] = limit_body_size($item["body"]);
2451
2452                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2453                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2454                         $base_url = get_app()->get_baseurl();
2455                         $item['body'] = reltoabs($item['body'], $base_url);
2456
2457                         $item['body'] = html2bb_video($item['body']);
2458
2459                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2460
2461                         $config = HTMLPurifier_Config::createDefault();
2462                         $config->set('Cache.DefinitionImpl', null);
2463
2464                         // we shouldn't need a whitelist, because the bbcode converter
2465                         // will strip out any unsupported tags.
2466
2467                         $purifier = new HTMLPurifier($config);
2468                         $item['body'] = $purifier->purify($item['body']);
2469
2470                         $item['body'] = @html2bbcode($item['body']);
2471                 }
2472
2473                 /// @todo We should check for a repeated post and if we know the repeated author.
2474
2475                 // We don't need the content element since "dfrn:env" is always present
2476                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2477
2478                 $item["location"] = $xpath->query("dfrn:location/text()", $entry)->item(0)->nodeValue;
2479
2480                 $georsspoint = $xpath->query("georss:point", $entry);
2481                 if ($georsspoint) {
2482                         $item["coord"] = $georsspoint->item(0)->nodeValue;
2483                 }
2484
2485                 $item["private"] = $xpath->query("dfrn:private/text()", $entry)->item(0)->nodeValue;
2486
2487                 $item["extid"] = $xpath->query("dfrn:extid/text()", $entry)->item(0)->nodeValue;
2488
2489                 if ($xpath->query("dfrn:bookmark/text()", $entry)->item(0)->nodeValue == "true") {
2490                         $item["bookmark"] = true;
2491                 }
2492
2493                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2494                 if ($notice_info && ($notice_info->length > 0)) {
2495                         foreach ($notice_info->item(0)->attributes as $attributes) {
2496                                 if ($attributes->name == "source") {
2497                                         $item["app"] = strip_tags($attributes->textContent);
2498                                 }
2499                         }
2500                 }
2501
2502                 $item["guid"] = $xpath->query("dfrn:diaspora_guid/text()", $entry)->item(0)->nodeValue;
2503
2504                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "item_store"
2505                 $dsprsig = unxmlify($xpath->query("dfrn:diaspora_signature/text()", $entry)->item(0)->nodeValue);
2506                 if ($dsprsig != "") {
2507                         $item["dsprsig"] = $dsprsig;
2508                 }
2509
2510                 $item["verb"] = $xpath->query("activity:verb/text()", $entry)->item(0)->nodeValue;
2511
2512                 if ($xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue != "") {
2513                         $item["object-type"] = $xpath->query("activity:object-type/text()", $entry)->item(0)->nodeValue;
2514                 }
2515
2516                 $object = $xpath->query("activity:object", $entry)->item(0);
2517                 $item["object"] = self::transformActivity($xpath, $object, "object");
2518
2519                 if (trim($item["object"]) != "") {
2520                         $r = parse_xml_string($item["object"], false);
2521                         if (isset($r->type)) {
2522                                 $item["object-type"] = $r->type;
2523                         }
2524                 }
2525
2526                 $target = $xpath->query("activity:target", $entry)->item(0);
2527                 $item["target"] = self::transformActivity($xpath, $target, "target");
2528
2529                 $categories = $xpath->query("atom:category", $entry);
2530                 if ($categories) {
2531                         foreach ($categories as $category) {
2532                                 $term = "";
2533                                 $scheme = "";
2534                                 foreach ($category->attributes as $attributes) {
2535                                         if ($attributes->name == "term") {
2536                                                 $term = $attributes->textContent;
2537                                         }
2538
2539                                         if ($attributes->name == "scheme") {
2540                                                 $scheme = $attributes->textContent;
2541                                         }
2542                                 }
2543
2544                                 if (($term != "") && ($scheme != "")) {
2545                                         $parts = explode(":", $scheme);
2546                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2547                                                 $termhash = array_shift($parts);
2548                                                 $termurl = implode(":", $parts);
2549
2550                                                 if (strlen($item["tag"])) {
2551                                                         $item["tag"] .= ",";
2552                                                 }
2553
2554                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2555                                         }
2556                                 }
2557                         }
2558                 }
2559
2560                 $enclosure = "";
2561
2562                 $links = $xpath->query("atom:link", $entry);
2563                 if ($links) {
2564                         self::parseLinks($links, $item);
2565                 }
2566
2567                 $item['conversation-uri'] = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
2568
2569                 $conv = $xpath->query('ostatus:conversation', $entry);
2570                 if (is_object($conv->item(0))) {
2571                         foreach ($conv->item(0)->attributes as $attributes) {
2572                                 if ($attributes->name == "ref") {
2573                                         $item['conversation-uri'] = $attributes->textContent;
2574                                 }
2575                                 if ($attributes->name == "href") {
2576                                         $item['conversation-href'] = $attributes->textContent;
2577                                 }
2578                         }
2579                 }
2580
2581                 // Is it a reply or a top level posting?
2582                 $item["parent-uri"] = $item["uri"];
2583
2584                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2585                 if (is_object($inreplyto->item(0))) {
2586                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2587                                 if ($attributes->name == "ref") {
2588                                         $item["parent-uri"] = $attributes->textContent;
2589                                 }
2590                         }
2591                 }
2592
2593                 // Get the type of the item (Top level post, reply or remote reply)
2594                 $entrytype = self::getEntryType($importer, $item);
2595
2596                 // Now assign the rest of the values that depend on the type of the message
2597                 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2598                         if (!isset($item["object-type"])) {
2599                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2600                         }
2601
2602                         if ($item["contact-id"] != $owner["contact-id"]) {
2603                                 $item["contact-id"] = $owner["contact-id"];
2604                         }
2605
2606                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2607                                 $item["network"] = $owner["network"];
2608                         }
2609
2610                         if ($item["contact-id"] != $author["contact-id"]) {
2611                                 $item["contact-id"] = $author["contact-id"];
2612                         }
2613
2614                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2615                                 $item["network"] = $author["network"];
2616                         }
2617                 }
2618
2619                 if ($entrytype == DFRN_REPLY_RC) {
2620                         $item["type"] = "remote-comment";
2621                         $item["wall"] = 1;
2622                 } elseif ($entrytype == DFRN_TOP_LEVEL) {
2623                         if (!isset($item["object-type"])) {
2624                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2625                         }
2626
2627                         // Is it an event?
2628                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2629                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2630                                 $ev = bbtoevent($item["body"]);
2631                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2632                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2633                                         $ev["cid"]     = $importer["id"];
2634                                         $ev["uid"]     = $importer["uid"];
2635                                         $ev["uri"]     = $item["uri"];
2636                                         $ev["edited"]  = $item["edited"];
2637                                         $ev["private"] = $item["private"];
2638                                         $ev["guid"]    = $item["guid"];
2639
2640                                         $r = q(
2641                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2642                                                 dbesc($item["uri"]),
2643                                                 intval($importer["uid"])
2644                                         );
2645                                         if (DBM::is_result($r)) {
2646                                                 $ev["id"] = $r[0]["id"];
2647                                         }
2648
2649                                         $event_id = event_store($ev);
2650                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2651                                         return;
2652                                 }
2653                         }
2654                 }
2655
2656                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2657                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2658                         return;
2659                 }
2660
2661                 // Update content if 'updated' changes
2662                 if (DBM::is_result($current)) {
2663                         if (self::updateContent($r[0], $item, $importer, $entrytype)) {
2664                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2665                         } else {
2666                                 logger("Item ".$item["uri"]." already existed.", LOGGER_DEBUG);
2667                         }
2668                         return;
2669                 }
2670
2671                 if (in_array($entrytype, [DFRN_REPLY, DFRN_REPLY_RC])) {
2672                         $posted_id = item_store($item);
2673                         $parent = 0;
2674
2675                         if ($posted_id) {
2676                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2677
2678                                 $item["id"] = $posted_id;
2679
2680                                 $r = q(
2681                                         "SELECT `parent`, `parent-uri` FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1",
2682                                         intval($posted_id),
2683                                         intval($importer["importer_uid"])
2684                                 );
2685                                 if (DBM::is_result($r)) {
2686                                         $parent = $r[0]["parent"];
2687                                         $parent_uri = $r[0]["parent-uri"];
2688                                 }
2689
2690                                 if ($posted_id && $parent && ($entrytype == DFRN_REPLY_RC)) {
2691                                         logger("Notifying followers about comment ".$posted_id, LOGGER_DEBUG);
2692                                         Worker::add(PRIORITY_HIGH, "Notifier", "comment-import", $posted_id);
2693                                 }
2694
2695                                 return true;
2696                         }
2697                 } else { // $entrytype == DFRN_TOP_LEVEL
2698                         if (!link_compare($item["owner-link"], $importer["url"])) {
2699                                 /*
2700                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2701                                  * but otherwise there's a possible data mixup on the sender's system.
2702                                  * the tgroup delivery code called from item_store will correct it if it's a forum,
2703                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2704                                  */
2705                                 logger('Correcting item owner.', LOGGER_DEBUG);
2706                                 $item["owner-name"]   = $importer["senderName"];
2707                                 $item["owner-link"]   = $importer["url"];
2708                                 $item["owner-avatar"] = $importer["thumb"];
2709                         }
2710
2711                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!tgroup_check($importer["importer_uid"], $item))) {
2712                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2713                                 return;
2714                         }
2715
2716                         // This is my contact on another system, but it's really me.
2717                         // Turn this into a wall post.
2718                         $notify = item_is_remote_self($importer, $item);
2719
2720                         $posted_id = item_store($item, false, $notify);
2721
2722                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2723
2724                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2725                                 self::doPoke($item, $importer, $posted_id);
2726                         }
2727                 }
2728         }
2729
2730         /**
2731          * @brief Deletes items
2732          *
2733          * @param object $xpath    XPath object
2734          * @param object $deletion deletion elements
2735          * @param array  $importer Record of the importer user mixed with contact of the content
2736          * @return void
2737          * @todo set proper type-hints
2738          */
2739         private static function processDeletion($xpath, $deletion, $importer)
2740         {
2741                 logger("Processing deletions");
2742
2743                 foreach ($deletion->attributes as $attributes) {
2744                         if ($attributes->name == "ref") {
2745                                 $uri = $attributes->textContent;
2746                         }
2747                         if ($attributes->name == "when") {
2748                                 $when = $attributes->textContent;
2749                         }
2750                 }
2751                 if ($when) {
2752                         $when = datetime_convert("UTC", "UTC", $when, "Y-m-d H:i:s");
2753                 } else {
2754                         $when = datetime_convert("UTC", "UTC", "now", "Y-m-d H:i:s");
2755                 }
2756
2757                 if (!$uri || !$importer["id"]) {
2758                         return false;
2759                 }
2760
2761                 /// @todo Only select the used fields
2762                 $r = q(
2763                         "SELECT `item`.*, `contact`.`self` FROM `item` INNER JOIN `contact` on `item`.`contact-id` = `contact`.`id`
2764                         WHERE `uri` = '%s' AND `item`.`uid` = %d AND `contact-id` = %d AND NOT `item`.`file` LIKE '%%[%%' LIMIT 1",
2765                         dbesc($uri),
2766                         intval($importer["uid"]),
2767                         intval($importer["id"])
2768                 );
2769                 if (!DBM::is_result($r)) {
2770                         logger("Item with uri " . $uri . " from contact " . $importer["id"] . " for user " . $importer["uid"] . " wasn't found.", LOGGER_DEBUG);
2771                         return;
2772                 } else {
2773                         $item = $r[0];
2774
2775                         $entrytype = self::getEntryType($importer, $item);
2776
2777                         if (!$item["deleted"]) {
2778                                 logger('deleting item '.$item["id"].' uri='.$uri, LOGGER_DEBUG);
2779                         } else {
2780                                 return;
2781                         }
2782
2783                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2784                                 logger("Deleting event ".$item["event-id"], LOGGER_DEBUG);
2785                                 event_delete($item["event-id"]);
2786                         }
2787
2788                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2789                                 $xo = parse_xml_string($item["object"], false);
2790                                 $xt = parse_xml_string($item["target"], false);
2791
2792                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2793                                         $i = q(
2794                                                 "SELECT `id`, `contact-id`, `tag` FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2795                                                 dbesc($xt->id),
2796                                                 intval($importer["importer_uid"])
2797                                         );
2798                                         if (DBM::is_result($i)) {
2799                                                 // For tags, the owner cannot remove the tag on the author's copy of the post.
2800
2801                                                 $owner_remove = (($item["contact-id"] == $i[0]["contact-id"]) ? true: false);
2802                                                 $author_remove = (($item["origin"] && $item["self"]) ? true : false);
2803                                                 $author_copy = (($item["origin"]) ? true : false);
2804
2805                                                 if ($owner_remove && $author_copy) {
2806                                                         return;
2807                                                 }
2808                                                 if ($author_remove || $owner_remove) {
2809                                                         $tags = explode(',', $i[0]["tag"]);
2810                                                         $newtags = [];
2811                                                         if (count($tags)) {
2812                                                                 foreach ($tags as $tag) {
2813                                                                         if (trim($tag) !== trim($xo->body)) {
2814                                                                                 $newtags[] = trim($tag);
2815                                                                         }
2816                                                                 }
2817                                                         }
2818                                                         q(
2819                                                                 "UPDATE `item` SET `tag` = '%s' WHERE `id` = %d",
2820                                                                 dbesc(implode(',', $newtags)),
2821                                                                 intval($i[0]["id"])
2822                                                         );
2823                                                         create_tags_from_item($i[0]["id"]);
2824                                                 }
2825                                         }
2826                                 }
2827                         }
2828
2829                         if ($entrytype == DFRN_TOP_LEVEL) {
2830                                 $r = q(
2831                                         "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2832                                                 `body` = '', `title` = ''
2833                                         WHERE `parent-uri` = '%s' AND `uid` IN (0, %d)",
2834                                         dbesc($when),
2835                                         dbesc(datetime_convert()),
2836                                         dbesc($uri),
2837                                         intval($importer["uid"])
2838                                 );
2839                                 create_tags_from_itemuri($uri, $importer["uid"]);
2840                                 Term::createFromItemURI($uri, $importer["uid"]);
2841                                 update_thread_uri($uri, $importer["uid"]);
2842                         } else {
2843                                 $r = q(
2844                                         "UPDATE `item` SET `deleted` = 1, `edited` = '%s', `changed` = '%s',
2845                                                 `body` = '', `title` = ''
2846                                         WHERE `uri` = '%s' AND `uid` IN (0, %d)",
2847                                         dbesc($when),
2848                                         dbesc(datetime_convert()),
2849                                         dbesc($uri),
2850                                         intval($importer["uid"])
2851                                 );
2852                                 create_tags_from_itemuri($uri, $importer["uid"]);
2853                                 Term::createFromItemURI($uri, $importer["uid"]);
2854                                 update_thread_uri($uri, $importer["importer_uid"]);
2855
2856                                 // if this is a relayed delete, propagate it to other recipients
2857
2858                                 if ($entrytype == DFRN_REPLY_RC) {
2859                                         logger("Notifying followers about deletion of post " . $item["id"], LOGGER_DEBUG);
2860                                         Worker::add(PRIORITY_HIGH, "Notifier", "drop", $item["id"]);
2861                                 }
2862                         }
2863                 }
2864         }
2865
2866         /**
2867          * @brief Imports a DFRN message
2868          *
2869          * @param string $xml          The DFRN message
2870          * @param array  $importer     Record of the importer user mixed with contact of the content
2871          * @param bool   $sort_by_date Is used when feeds are polled
2872          * @return integer Import status
2873          * @todo set proper type-hints
2874          */
2875         public static function import($xml, $importer, $sort_by_date = false)
2876         {
2877                 if ($xml == "") {
2878                         return 400;
2879                 }
2880
2881                 $doc = new DOMDocument();
2882                 @$doc->loadXML($xml);
2883
2884                 $xpath = new DOMXPath($doc);
2885                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2886                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2887                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2888                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2889                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2890                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2891                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2892                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2893                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2894                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2895
2896                 $header = [];
2897                 $header["uid"] = $importer["uid"];
2898                 $header["network"] = NETWORK_DFRN;
2899                 $header["type"] = "remote";
2900                 $header["wall"] = 0;
2901                 $header["origin"] = 0;
2902                 $header["contact-id"] = $importer["id"];
2903
2904                 // Update the contact table if the data has changed
2905
2906                 // The "atom:author" is only present in feeds
2907                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2908                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2909                 }
2910
2911                 // Only the "dfrn:owner" in the head section contains all data
2912                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2913                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2914                 }
2915
2916                 logger("Import DFRN message for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2917
2918                 // The account type is new since 3.5.1
2919                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2920                         $accounttype = intval($xpath->evaluate("/atom:feed/dfrn:account_type/text()")->item(0)->nodeValue);
2921
2922                         if ($accounttype != $importer["contact-type"]) {
2923                                 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2924                         }
2925                 }
2926
2927                 // is it a public forum? Private forums aren't supported with this method
2928                 // This is deprecated since 3.5.1
2929                 $forum = intval($xpath->evaluate("/atom:feed/dfrn:community/text()")->item(0)->nodeValue);
2930
2931                 if ($forum != $importer["forum"]) {
2932                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2933                         dba::update('contact', ['forum' => $forum], $condition);
2934                 }
2935
2936                 // We are processing relocations even if we are ignoring a contact
2937                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2938                 foreach ($relocations as $relocation) {
2939                         self::processRelocation($xpath, $relocation, $importer);
2940                 }
2941
2942                 if ($importer["readonly"]) {
2943                         // We aren't receiving stuff from this person. But we will quietly ignore them
2944                         // rather than a blatant "go away" message.
2945                         logger('ignoring contact '.$importer["id"]);
2946                         return 403;
2947                 }
2948
2949                 $mails = $xpath->query("/atom:feed/dfrn:mail");
2950                 foreach ($mails as $mail) {
2951                         self::processMail($xpath, $mail, $importer);
2952                 }
2953
2954                 $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2955                 foreach ($suggestions as $suggestion) {
2956                         self::processSuggestion($xpath, $suggestion, $importer);
2957                 }
2958
2959                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2960                 foreach ($deletions as $deletion) {
2961                         self::processDeletion($xpath, $deletion, $importer);
2962                 }
2963
2964                 if (!$sort_by_date) {
2965                         $entries = $xpath->query("/atom:feed/atom:entry");
2966                         foreach ($entries as $entry) {
2967                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2968                         }
2969                 } else {
2970                         $newentries = [];
2971                         $entries = $xpath->query("/atom:feed/atom:entry");
2972                         foreach ($entries as $entry) {
2973                                 $created = $xpath->query("atom:published/text()", $entry)->item(0)->nodeValue;
2974                                 $newentries[strtotime($created)] = $entry;
2975                         }
2976
2977                         // Now sort after the publishing date
2978                         ksort($newentries);
2979
2980                         foreach ($newentries as $entry) {
2981                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2982                         }
2983                 }
2984                 logger("Import done for user " . $importer["uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2985                 return 200;
2986         }
2987
2988         /**
2989          * @param App    $a            App
2990          * @param string $contact_nick contact nickname
2991          */
2992         public static function autoRedir(App $a, $contact_nick)
2993         {
2994                 // prevent looping
2995                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2996                         return;
2997                 }
2998
2999                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
3000                         return;
3001                 }
3002
3003                 if (local_user()) {
3004                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
3005                         // am a contact of that user. However, that user may have other contacts with the
3006                         // same nickname as me on other hubs or other networks. Exclude these by requiring
3007                         // that the contact have a local URL. I will be the only person with my nickname at
3008                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
3009                         //
3010                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
3011
3012                         $baseurl = System::baseUrl();
3013                         $domain_st = strpos($baseurl, "://");
3014                         if ($domain_st === false) {
3015                                 return;
3016                         }
3017                         $baseurl = substr($baseurl, $domain_st + 3);
3018                         $nurl = normalise_link($baseurl);
3019
3020                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
3021                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
3022                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
3023                                 dbesc($contact_nick),
3024                                 dbesc($a->user['nickname']),
3025                                 dbesc($baseurl),
3026                                 dbesc($nurl)
3027                         );
3028                         if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
3029                                 return;
3030                         }
3031
3032                         $r = q("SELECT * FROM contact WHERE nick = '%s'
3033                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
3034                                 dbesc($contact_nick),
3035                                 dbesc(NETWORK_DFRN),
3036                                 intval(local_user()),
3037                                 dbesc($baseurl)
3038                         );
3039                         if (! DBM::is_result($r)) {
3040                                 return;
3041                         }
3042
3043                         $cid = $r[0]['id'];
3044
3045                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
3046
3047                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
3048                                 $orig_id = $r[0]['issued-id'];
3049                                 $dfrn_id = '1:' . $orig_id;
3050                         }
3051                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
3052                                 $orig_id = $r[0]['dfrn-id'];
3053                                 $dfrn_id = '0:' . $orig_id;
3054                         }
3055
3056                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
3057                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3058
3059                         if (strlen($dfrn_id) < 3) {
3060                                 return;
3061                         }
3062
3063                         $sec = random_string();
3064
3065                         dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3066
3067                         $url = curPageURL();
3068
3069                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3070                         $dest = (($url) ? '&destination_url=' . $url : '');
3071                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3072                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3073                 }
3074
3075                 return;
3076         }
3077
3078         /**
3079          * @brief Returns the activity verb
3080          *
3081          * @param array $item Item array
3082          *
3083          * @return string activity verb
3084          */
3085         private static function constructVerb(array $item)
3086         {
3087                 if ($item['verb']) {
3088                         return $item['verb'];
3089                 }
3090                 return ACTIVITY_POST;
3091         }
3092 }