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