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