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