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