]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
1a2e8c56954006b88f7c46704e1f97a827bc493a
[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                 $msg["id"] = DBA::lastInsertId();
1852
1853                 // send notifications.
1854                 /// @TODO Arange this mess
1855                 $notif_params = [
1856                         "type" => NOTIFY_MAIL,
1857                         "notify_flags" => $importer["notify-flags"],
1858                         "language" => $importer["language"],
1859                         "to_name" => $importer["username"],
1860                         "to_email" => $importer["email"],
1861                         "uid" => $importer["importer_uid"],
1862                         "item" => $msg,
1863                         "source_name" => $msg["from-name"],
1864                         "source_link" => $importer["url"],
1865                         "source_photo" => $importer["thumb"],
1866                         "verb" => ACTIVITY_POST,
1867                         "otype" => "mail"
1868                 ];
1869
1870                 notification($notif_params);
1871
1872                 logger("Mail is processed, notification was sent.");
1873         }
1874
1875         /**
1876          * @brief Processes the suggestion elements
1877          *
1878          * @param object $xpath      XPath object
1879          * @param object $suggestion suggestion elements
1880          * @param array  $importer   Record of the importer user mixed with contact of the content
1881          * @return boolean
1882          * @todo Find good type-hints for all parameter
1883          */
1884         private static function processSuggestion($xpath, $suggestion, $importer)
1885         {
1886                 $a = get_app();
1887
1888                 logger("Processing suggestions");
1889
1890                 /// @TODO Rewrite this to one statement
1891                 $suggest = [];
1892                 $suggest["uid"] = $importer["importer_uid"];
1893                 $suggest["cid"] = $importer["id"];
1894                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1895                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1896                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1897                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1898                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1899
1900                 // Does our member already have a friend matching this description?
1901
1902                 $r = q(
1903                         "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1904                         DBA::escape($suggest["name"]),
1905                         DBA::escape(normalise_link($suggest["url"])),
1906                         intval($suggest["uid"])
1907                 );
1908
1909                 /*
1910                  * The valid result means the friend we're about to send a friend
1911                  * suggestion already has them in their contact, which means no further
1912                  * action is required.
1913                  *
1914                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1915                  */
1916                 if (DBA::isResult($r)) {
1917                         return false;
1918                 }
1919
1920                 // Do we already have an fcontact record for this person?
1921
1922                 $fid = 0;
1923                 $r = q(
1924                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1925                         DBA::escape($suggest["url"]),
1926                         DBA::escape($suggest["name"]),
1927                         DBA::escape($suggest["request"])
1928                 );
1929                 if (DBA::isResult($r)) {
1930                         $fid = $r[0]["id"];
1931
1932                         // OK, we do. Do we already have an introduction for this person ?
1933                         $r = q(
1934                                 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1935                                 intval($suggest["uid"]),
1936                                 intval($fid)
1937                         );
1938
1939                         /*
1940                          * The valid result means the friend we're about to send a friend
1941                          * suggestion already has them in their contact, which means no further
1942                          * action is required.
1943                          *
1944                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1945                          */
1946                         if (DBA::isResult($r)) {
1947                                 return false;
1948                         }
1949                 }
1950                 if (!$fid) {
1951                         $r = q(
1952                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1953                                 DBA::escape($suggest["name"]),
1954                                 DBA::escape($suggest["url"]),
1955                                 DBA::escape($suggest["photo"]),
1956                                 DBA::escape($suggest["request"])
1957                         );
1958                 }
1959                 $r = q(
1960                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1961                         DBA::escape($suggest["url"]),
1962                         DBA::escape($suggest["name"]),
1963                         DBA::escape($suggest["request"])
1964                 );
1965
1966                 /*
1967                  * If no record in fcontact is found, below INSERT statement will not
1968                  * link an introduction to it.
1969                  */
1970                 if (!DBA::isResult($r)) {
1971                         // Database record did not get created. Quietly give up.
1972                         killme();
1973                 }
1974
1975                 $fid = $r[0]["id"];
1976
1977                 $hash = random_string();
1978
1979                 $r = q(
1980                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1981                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1982                         intval($suggest["uid"]),
1983                         intval($fid),
1984                         intval($suggest["cid"]),
1985                         DBA::escape($suggest["body"]),
1986                         DBA::escape($hash),
1987                         DBA::escape(DateTimeFormat::utcNow()),
1988                         intval(0)
1989                 );
1990
1991                 notification(
1992                         [
1993                                 "type"         => NOTIFY_SUGGEST,
1994                                 "notify_flags" => $importer["notify-flags"],
1995                                 "language"     => $importer["language"],
1996                                 "to_name"      => $importer["username"],
1997                                 "to_email"     => $importer["email"],
1998                                 "uid"          => $importer["importer_uid"],
1999                                 "item"         => $suggest,
2000                                 "link"         => System::baseUrl()."/notifications/intros",
2001                                 "source_name"  => $importer["name"],
2002                                 "source_link"  => $importer["url"],
2003                                 "source_photo" => $importer["photo"],
2004                                 "verb"         => ACTIVITY_REQ_FRIEND,
2005                                 "otype"        => "intro"]
2006                 );
2007
2008                 return true;
2009         }
2010
2011         /**
2012          * @brief Processes the relocation elements
2013          *
2014          * @param object $xpath      XPath object
2015          * @param object $relocation relocation elements
2016          * @param array  $importer   Record of the importer user mixed with contact of the content
2017          * @return boolean
2018          * @todo Find good type-hints for all parameter
2019          */
2020         private static function processRelocation($xpath, $relocation, $importer)
2021         {
2022                 logger("Processing relocations");
2023
2024                 /// @TODO Rewrite this to one statement
2025                 $relocate = [];
2026                 $relocate["uid"] = $importer["importer_uid"];
2027                 $relocate["cid"] = $importer["id"];
2028                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2029                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2030                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2031                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2032                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2033                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2034                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2035                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2036                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2037                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2038                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2039                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2040
2041                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2042                         $relocate["avatar"] = $relocate["photo"];
2043                 }
2044
2045                 if ($relocate["addr"] == "") {
2046                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2047                 }
2048
2049                 // update contact
2050                 $r = q(
2051                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2052                         intval($importer["id"]),
2053                         intval($importer["importer_uid"])
2054                 );
2055
2056                 if (!DBA::isResult($r)) {
2057                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
2058                         return false;
2059                 }
2060
2061                 $old = $r[0];
2062
2063                 // Update the gcontact entry
2064                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2065
2066                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2067                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2068                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2069                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2070                 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2071
2072                 // Update the contact table. We try to find every entry.
2073                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2074                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2075                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2076                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2077                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2078                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2079
2080                 DBA::update('contact', $fields, $condition);
2081
2082                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2083
2084                 logger('Contacts are updated.');
2085
2086                 /// @TODO
2087                 /// merge with current record, current contents have priority
2088                 /// update record, set url-updated
2089                 /// update profile photos
2090                 /// schedule a scan?
2091                 return true;
2092         }
2093
2094         /**
2095          * @brief Updates an item
2096          *
2097          * @param array $current   the current item record
2098          * @param array $item      the new item record
2099          * @param array $importer  Record of the importer user mixed with contact of the content
2100          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2101          * @return mixed
2102          * @todo set proper type-hints (array?)
2103          */
2104         private static function updateContent($current, $item, $importer, $entrytype)
2105         {
2106                 $changed = false;
2107
2108                 if (self::isEditedTimestampNewer($current, $item)) {
2109                         // do not accept (ignore) an earlier edit than one we currently have.
2110                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2111                                 return false;
2112                         }
2113
2114                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2115                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2116                                         'edited' => DateTimeFormat::utc($item["edited"])];
2117
2118                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2119                         Item::update($fields, $condition);
2120
2121                         $changed = true;
2122                 }
2123                 return $changed;
2124         }
2125
2126         /**
2127          * @brief Detects the entry type of the item
2128          *
2129          * @param array $importer Record of the importer user mixed with contact of the content
2130          * @param array $item     the new item record
2131          *
2132          * @return int Is it a toplevel entry, a comment or a relayed comment?
2133          * @todo set proper type-hints (array?)
2134          */
2135         private static function getEntryType($importer, $item)
2136         {
2137                 if ($item["parent-uri"] != $item["uri"]) {
2138                         $community = false;
2139
2140                         if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2141                                 $sql_extra = "";
2142                                 $community = true;
2143                                 logger("possible community action");
2144                         } else {
2145                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2146                         }
2147
2148                         // was the top-level post for this action written by somebody on this site?
2149                         // Specifically, the recipient?
2150
2151                         $is_a_remote_action = false;
2152
2153                         $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2154                         if (DBA::isResult($parent)) {
2155                                 $r = q(
2156                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2157                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2158                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2159                                         AND `item`.`uid` = %d
2160                                         $sql_extra
2161                                         LIMIT 1",
2162                                         DBA::escape($parent["parent-uri"]),
2163                                         DBA::escape($parent["parent-uri"]),
2164                                         DBA::escape($parent["parent-uri"]),
2165                                         intval($importer["importer_uid"])
2166                                 );
2167                                 if (DBA::isResult($r)) {
2168                                         $is_a_remote_action = true;
2169                                 }
2170                         }
2171
2172                         /*
2173                          * Does this have the characteristics of a community or private group action?
2174                          * If it's an action to a wall post on a community/prvgroup page it's a
2175                          * valid community action. Also forum_mode makes it valid for sure.
2176                          * If neither, it's not.
2177                          */
2178                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2179                                 $is_a_remote_action = false;
2180                                 logger("not a community action");
2181                         }
2182
2183                         if ($is_a_remote_action) {
2184                                 return DFRN::REPLY_RC;
2185                         } else {
2186                                 return DFRN::REPLY;
2187                         }
2188                 } else {
2189                         return DFRN::TOP_LEVEL;
2190                 }
2191         }
2192
2193         /**
2194          * @brief Send a "poke"
2195          *
2196          * @param array $item      the new item record
2197          * @param array $importer  Record of the importer user mixed with contact of the content
2198          * @param int   $posted_id The record number of item record that was just posted
2199          * @return void
2200          * @todo set proper type-hints (array?)
2201          */
2202         private static function doPoke($item, $importer, $posted_id)
2203         {
2204                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2205                 if (!$verb) {
2206                         return;
2207                 }
2208                 $xo = XML::parseString($item["object"], false);
2209
2210                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2211                         // somebody was poked/prodded. Was it me?
2212                         foreach ($xo->link as $l) {
2213                                 $atts = $l->attributes();
2214                                 switch ($atts["rel"]) {
2215                                         case "alternate":
2216                                                 $Blink = $atts["href"];
2217                                                 break;
2218                                         default:
2219                                                 break;
2220                                 }
2221                         }
2222
2223                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2224                                 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2225
2226                                 // send a notification
2227                                 notification(
2228                                         [
2229                                         "type"         => NOTIFY_POKE,
2230                                         "notify_flags" => $importer["notify-flags"],
2231                                         "language"     => $importer["language"],
2232                                         "to_name"      => $importer["username"],
2233                                         "to_email"     => $importer["email"],
2234                                         "uid"          => $importer["importer_uid"],
2235                                         "item"         => $item,
2236                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2237                                         "source_name"  => $author["name"],
2238                                         "source_link"  => $author["url"],
2239                                         "source_photo" => $author["thumb"],
2240                                         "verb"         => $item["verb"],
2241                                         "otype"        => "person",
2242                                         "activity"     => $verb,
2243                                         "parent"       => $item["parent"]]
2244                                 );
2245                         }
2246                 }
2247         }
2248
2249         /**
2250          * @brief Processes several actions, depending on the verb
2251          *
2252          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2253          * @param array $importer  Record of the importer user mixed with contact of the content
2254          * @param array $item      the new item record
2255          * @param bool  $is_like   Is the verb a "like"?
2256          *
2257          * @return bool Should the processing of the entries be continued?
2258          * @todo set proper type-hints (array?)
2259          */
2260         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2261         {
2262                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2263
2264                 if (($entrytype == DFRN::TOP_LEVEL)) {
2265                         // The filling of the the "contact" variable is done for legcy reasons
2266                         // The functions below are partly used by ostatus.php as well - where we have this variable
2267                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2268                         $contact = $r[0];
2269                         $nickname = $contact["nick"];
2270
2271                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2272                         // This function once was responsible for DFRN and OStatus.
2273                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2274                                 logger("New follower");
2275                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2276                                 return false;
2277                         }
2278                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2279                                 logger("Lost follower");
2280                                 Contact::removeFollower($importer, $contact, $item);
2281                                 return false;
2282                         }
2283                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2284                                 logger("New friend request");
2285                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2286                                 return false;
2287                         }
2288                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2289                                 logger("Lost sharer");
2290                                 Contact::removeSharer($importer, $contact, $item);
2291                                 return false;
2292                         }
2293                 } else {
2294                         if (($item["verb"] == ACTIVITY_LIKE)
2295                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2296                                 || ($item["verb"] == ACTIVITY_ATTEND)
2297                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2298                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2299                         ) {
2300                                 $is_like = true;
2301                                 $item["gravity"] = GRAVITY_ACTIVITY;
2302                                 // only one like or dislike per person
2303                                 // splitted into two queries for performance issues
2304                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2305                                         'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2306                                 if (Item::exists($condition)) {
2307                                         return false;
2308                                 }
2309
2310                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2311                                         'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2312                                 if (Item::exists($condition)) {
2313                                         return false;
2314                                 }
2315                         } else {
2316                                 $is_like = false;
2317                         }
2318
2319                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2320                                 $xo = XML::parseString($item["object"], false);
2321                                 $xt = XML::parseString($item["target"], false);
2322
2323                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2324                                         $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2325
2326                                         if (!DBA::isResult($item_tag)) {
2327                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2328                                                 return false;
2329                                         }
2330
2331                                         // extract tag, if not duplicate, add to parent item
2332                                         if ($xo->content) {
2333                                                 if (!stristr($item_tag["tag"], trim($xo->content))) {
2334                                                         $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2335                                                         Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2336                                                 }
2337                                         }
2338                                 }
2339                         }
2340                 }
2341                 return true;
2342         }
2343
2344         /**
2345          * @brief Processes the link elements
2346          *
2347          * @param object $links link elements
2348          * @param array  $item  the item record
2349          * @return void
2350          * @todo set proper type-hints
2351          */
2352         private static function parseLinks($links, &$item)
2353         {
2354                 $rel = "";
2355                 $href = "";
2356                 $type = "";
2357                 $length = "0";
2358                 $title = "";
2359                 foreach ($links as $link) {
2360                         foreach ($link->attributes as $attributes) {
2361                                 switch ($attributes->name) {
2362                                         case "href"  : $href   = $attributes->textContent; break;
2363                                         case "rel"   : $rel    = $attributes->textContent; break;
2364                                         case "type"  : $type   = $attributes->textContent; break;
2365                                         case "length": $length = $attributes->textContent; break;
2366                                         case "title" : $title  = $attributes->textContent; break;
2367                                 }
2368                         }
2369                         if (($rel != "") && ($href != "")) {
2370                                 switch ($rel) {
2371                                         case "alternate":
2372                                                 $item["plink"] = $href;
2373                                                 break;
2374                                         case "enclosure":
2375                                                 $enclosure = $href;
2376                                                 if (strlen($item["attach"])) {
2377                                                         $item["attach"] .= ",";
2378                                                 }
2379
2380                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2381                                                 break;
2382                                 }
2383                         }
2384                 }
2385         }
2386
2387         /**
2388          * @brief Processes the entry elements which contain the items and comments
2389          *
2390          * @param array  $header   Array of the header elements that always stay the same
2391          * @param object $xpath    XPath object
2392          * @param object $entry    entry elements
2393          * @param array  $importer Record of the importer user mixed with contact of the content
2394          * @param object $xml      xml
2395          * @return void
2396          * @todo Add type-hints
2397          */
2398         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2399         {
2400                 logger("Processing entries");
2401
2402                 $item = $header;
2403
2404                 $item["protocol"] = PROTOCOL_DFRN;
2405
2406                 $item["source"] = $xml;
2407
2408                 // Get the uri
2409                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2410
2411                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2412
2413                 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2414                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2415                 );
2416                 // Is there an existing item?
2417                 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2418                         logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2419                         return;
2420                 }
2421
2422                 // Fetch the owner
2423                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2424
2425                 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2426
2427                 $item["owner-name"] = $owner["name"];
2428                 $item["owner-link"] = $owner["link"];
2429                 $item["owner-avatar"] = $owner["avatar"];
2430                 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2431
2432                 // fetch the author
2433                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2434
2435                 $item["author-name"] = $author["name"];
2436                 $item["author-link"] = $author["link"];
2437                 $item["author-avatar"] = $author["avatar"];
2438                 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2439
2440                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2441
2442                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2443
2444                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2445                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2446                 // make sure nobody is trying to sneak some html tags by us
2447                 $item["body"] = notags(base64url_decode($item["body"]));
2448
2449                 $item["body"] = BBCode::limitBodySize($item["body"]);
2450
2451                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2452                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2453                         $base_url = get_app()->get_baseurl();
2454                         $item['body'] = reltoabs($item['body'], $base_url);
2455
2456                         $item['body'] = html2bb_video($item['body']);
2457
2458                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2459
2460                         $config = HTMLPurifier_Config::createDefault();
2461                         $config->set('Cache.DefinitionImpl', null);
2462
2463                         // we shouldn't need a whitelist, because the bbcode converter
2464                         // will strip out any unsupported tags.
2465
2466                         $purifier = new HTMLPurifier($config);
2467                         $item['body'] = $purifier->purify($item['body']);
2468
2469                         $item['body'] = @HTML::toBBCode($item['body']);
2470                 }
2471
2472                 /// @todo We should check for a repeated post and if we know the repeated author.
2473
2474                 // We don't need the content element since "dfrn:env" is always present
2475                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2476
2477                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2478
2479                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2480
2481                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2482
2483                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2484
2485                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2486                         $item["post-type"] = Item::PT_PAGE;
2487                 }
2488
2489                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2490                 if ($notice_info && ($notice_info->length > 0)) {
2491                         foreach ($notice_info->item(0)->attributes as $attributes) {
2492                                 if ($attributes->name == "source") {
2493                                         $item["app"] = strip_tags($attributes->textContent);
2494                                 }
2495                         }
2496                 }
2497
2498                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2499
2500                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2501                 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2502                 if ($dsprsig != "") {
2503                         $item["dsprsig"] = $dsprsig;
2504                 }
2505
2506                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2507
2508                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2509                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2510                 }
2511
2512                 $object = $xpath->query("activity:object", $entry)->item(0);
2513                 $item["object"] = self::transformActivity($xpath, $object, "object");
2514
2515                 if (trim($item["object"]) != "") {
2516                         $r = XML::parseString($item["object"], false);
2517                         if (isset($r->type)) {
2518                                 $item["object-type"] = $r->type;
2519                         }
2520                 }
2521
2522                 $target = $xpath->query("activity:target", $entry)->item(0);
2523                 $item["target"] = self::transformActivity($xpath, $target, "target");
2524
2525                 $categories = $xpath->query("atom:category", $entry);
2526                 if ($categories) {
2527                         foreach ($categories as $category) {
2528                                 $term = "";
2529                                 $scheme = "";
2530                                 foreach ($category->attributes as $attributes) {
2531                                         if ($attributes->name == "term") {
2532                                                 $term = $attributes->textContent;
2533                                         }
2534
2535                                         if ($attributes->name == "scheme") {
2536                                                 $scheme = $attributes->textContent;
2537                                         }
2538                                 }
2539
2540                                 if (($term != "") && ($scheme != "")) {
2541                                         $parts = explode(":", $scheme);
2542                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2543                                                 $termhash = array_shift($parts);
2544                                                 $termurl = implode(":", $parts);
2545
2546                                                 if (!empty($item["tag"])) {
2547                                                         $item["tag"] .= ",";
2548                                                 } else {
2549                                                         $item["tag"] = "";
2550                                                 }
2551
2552                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2553                                         }
2554                                 }
2555                         }
2556                 }
2557
2558                 $enclosure = "";
2559
2560                 $links = $xpath->query("atom:link", $entry);
2561                 if ($links) {
2562                         self::parseLinks($links, $item);
2563                 }
2564
2565                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2566
2567                 $conv = $xpath->query('ostatus:conversation', $entry);
2568                 if (is_object($conv->item(0))) {
2569                         foreach ($conv->item(0)->attributes as $attributes) {
2570                                 if ($attributes->name == "ref") {
2571                                         $item['conversation-uri'] = $attributes->textContent;
2572                                 }
2573                                 if ($attributes->name == "href") {
2574                                         $item['conversation-href'] = $attributes->textContent;
2575                                 }
2576                         }
2577                 }
2578
2579                 // Is it a reply or a top level posting?
2580                 $item["parent-uri"] = $item["uri"];
2581
2582                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2583                 if (is_object($inreplyto->item(0))) {
2584                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2585                                 if ($attributes->name == "ref") {
2586                                         $item["parent-uri"] = $attributes->textContent;
2587                                 }
2588                         }
2589                 }
2590
2591                 // Get the type of the item (Top level post, reply or remote reply)
2592                 $entrytype = self::getEntryType($importer, $item);
2593
2594                 // Now assign the rest of the values that depend on the type of the message
2595                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2596                         if (!isset($item["object-type"])) {
2597                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2598                         }
2599
2600                         if ($item["contact-id"] != $owner["contact-id"]) {
2601                                 $item["contact-id"] = $owner["contact-id"];
2602                         }
2603
2604                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2605                                 $item["network"] = $owner["network"];
2606                         }
2607
2608                         if ($item["contact-id"] != $author["contact-id"]) {
2609                                 $item["contact-id"] = $author["contact-id"];
2610                         }
2611
2612                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2613                                 $item["network"] = $author["network"];
2614                         }
2615                 }
2616
2617                 if ($entrytype == DFRN::REPLY_RC) {
2618                         $item["wall"] = 1;
2619                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2620                         if (!isset($item["object-type"])) {
2621                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2622                         }
2623
2624                         // Is it an event?
2625                         if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2626                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2627                                 $ev = Event::fromBBCode($item["body"]);
2628                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2629                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2630                                         $ev["cid"]     = $importer["id"];
2631                                         $ev["uid"]     = $importer["importer_uid"];
2632                                         $ev["uri"]     = $item["uri"];
2633                                         $ev["edited"]  = $item["edited"];
2634                                         $ev["private"] = $item["private"];
2635                                         $ev["guid"]    = $item["guid"];
2636                                         $ev["plink"]   = $item["plink"];
2637
2638                                         $r = q(
2639                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2640                                                 DBA::escape($item["uri"]),
2641                                                 intval($importer["importer_uid"])
2642                                         );
2643                                         if (DBA::isResult($r)) {
2644                                                 $ev["id"] = $r[0]["id"];
2645                                         }
2646
2647                                         $event_id = Event::store($ev);
2648                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2649                                         return;
2650                                 }
2651                         }
2652                 }
2653
2654                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2655                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2656                         return;
2657                 }
2658
2659                 // This check is done here to be able to receive connection requests in "processVerbs"
2660                 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2661                         logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2662                         return;
2663                 }
2664
2665
2666                 // Update content if 'updated' changes
2667                 if (DBA::isResult($current)) {
2668                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2669                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2670                         } else {
2671                                 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2672                         }
2673                         return;
2674                 }
2675
2676                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2677                         $posted_id = Item::insert($item);
2678                         $parent = 0;
2679
2680                         if ($posted_id) {
2681                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2682
2683                                 if ($item['uid'] == 0) {
2684                                         Item::distribute($posted_id);
2685                                 }
2686
2687                                 return true;
2688                         }
2689                 } else { // $entrytype == DFRN::TOP_LEVEL
2690                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2691                                 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2692                                 return;
2693                         }
2694                         if (!link_compare($item["owner-link"], $importer["url"])) {
2695                                 /*
2696                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2697                                  * but otherwise there's a possible data mixup on the sender's system.
2698                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2699                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2700                                  */
2701                                 logger('Correcting item owner.', LOGGER_DEBUG);
2702                                 $item["owner-link"] = $importer["url"];
2703                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2704                         }
2705
2706                         if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2707                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2708                                 return;
2709                         }
2710
2711                         // This is my contact on another system, but it's really me.
2712                         // Turn this into a wall post.
2713                         $notify = Item::isRemoteSelf($importer, $item);
2714
2715                         $posted_id = Item::insert($item, false, $notify);
2716
2717                         if ($notify) {
2718                                 $posted_id = $notify;
2719                         }
2720
2721                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2722
2723                         if ($item['uid'] == 0) {
2724                                 Item::distribute($posted_id);
2725                         }
2726
2727                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2728                                 self::doPoke($item, $importer, $posted_id);
2729                         }
2730                 }
2731         }
2732
2733         /**
2734          * @brief Deletes items
2735          *
2736          * @param object $xpath    XPath object
2737          * @param object $deletion deletion elements
2738          * @param array  $importer Record of the importer user mixed with contact of the content
2739          * @return void
2740          * @todo set proper type-hints
2741          */
2742         private static function processDeletion($xpath, $deletion, $importer)
2743         {
2744                 logger("Processing deletions");
2745                 $uri = null;
2746
2747                 foreach ($deletion->attributes as $attributes) {
2748                         if ($attributes->name == "ref") {
2749                                 $uri = $attributes->textContent;
2750                         }
2751                 }
2752
2753                 if (!$uri || !$importer["id"]) {
2754                         return false;
2755                 }
2756
2757                 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2758                 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2759                 if (!DBA::isResult($item)) {
2760                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2761                         return;
2762                 }
2763
2764                 if (strstr($item['file'], '[')) {
2765                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2766                         return;
2767                 }
2768
2769                 // When it is a starting post it has to belong to the person that wants to delete it
2770                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2771                         logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2772                         return;
2773                 }
2774
2775                 // Comments can be deleted by the thread owner or comment owner
2776                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2777                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2778                         if (!Item::exists($condition)) {
2779                                 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2780                                 return;
2781                         }
2782                 }
2783
2784                 if ($item["deleted"]) {
2785                         return;
2786                 }
2787
2788                 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2789
2790                 Item::delete(['id' => $item['id']]);
2791         }
2792
2793         /**
2794          * @brief Imports a DFRN message
2795          *
2796          * @param string $xml          The DFRN message
2797          * @param array  $importer     Record of the importer user mixed with contact of the content
2798          * @param bool   $sort_by_date Is used when feeds are polled
2799          * @return integer Import status
2800          * @todo set proper type-hints
2801          */
2802         public static function import($xml, $importer, $sort_by_date = false)
2803         {
2804                 if ($xml == "") {
2805                         return 400;
2806                 }
2807
2808                 $doc = new DOMDocument();
2809                 @$doc->loadXML($xml);
2810
2811                 $xpath = new DOMXPath($doc);
2812                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2813                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2814                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2815                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2816                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2817                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2818                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2819                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2820                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2821                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2822
2823                 $header = [];
2824                 $header["uid"] = $importer["importer_uid"];
2825                 $header["network"] = NETWORK_DFRN;
2826                 $header["wall"] = 0;
2827                 $header["origin"] = 0;
2828                 $header["contact-id"] = $importer["id"];
2829
2830                 // Update the contact table if the data has changed
2831
2832                 // The "atom:author" is only present in feeds
2833                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2834                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2835                 }
2836
2837                 // Only the "dfrn:owner" in the head section contains all data
2838                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2839                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2840                 }
2841
2842                 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2843
2844                 // is it a public forum? Private forums aren't exposed with this method
2845                 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2846
2847                 // The account type is new since 3.5.1
2848                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2849                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2850
2851                         if ($accounttype != $importer["contact-type"]) {
2852                                 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2853                         }
2854                         // A forum contact can either have set "forum" or "prv" - but not both
2855                         if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2856                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2857                                 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2858                         }
2859                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2860                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2861                         DBA::update('contact', ['forum' => $forum], $condition);
2862                 }
2863
2864
2865                 // We are processing relocations even if we are ignoring a contact
2866                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2867                 foreach ($relocations as $relocation) {
2868                         self::processRelocation($xpath, $relocation, $importer);
2869                 }
2870
2871                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2872                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2873                         foreach ($mails as $mail) {
2874                                 self::processMail($xpath, $mail, $importer);
2875                         }
2876
2877                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2878                         foreach ($suggestions as $suggestion) {
2879                                 self::processSuggestion($xpath, $suggestion, $importer);
2880                         }
2881                 }
2882
2883                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2884                 foreach ($deletions as $deletion) {
2885                         self::processDeletion($xpath, $deletion, $importer);
2886                 }
2887
2888                 if (!$sort_by_date) {
2889                         $entries = $xpath->query("/atom:feed/atom:entry");
2890                         foreach ($entries as $entry) {
2891                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2892                         }
2893                 } else {
2894                         $newentries = [];
2895                         $entries = $xpath->query("/atom:feed/atom:entry");
2896                         foreach ($entries as $entry) {
2897                                 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2898                                 $newentries[strtotime($created)] = $entry;
2899                         }
2900
2901                         // Now sort after the publishing date
2902                         ksort($newentries);
2903
2904                         foreach ($newentries as $entry) {
2905                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2906                         }
2907                 }
2908                 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2909                 return 200;
2910         }
2911
2912         /**
2913          * @param App    $a            App
2914          * @param string $contact_nick contact nickname
2915          */
2916         public static function autoRedir(App $a, $contact_nick)
2917         {
2918                 // prevent looping
2919                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2920                         return;
2921                 }
2922
2923                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2924                         return;
2925                 }
2926
2927                 if (local_user()) {
2928                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
2929                         // am a contact of that user. However, that user may have other contacts with the
2930                         // same nickname as me on other hubs or other networks. Exclude these by requiring
2931                         // that the contact have a local URL. I will be the only person with my nickname at
2932                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2933                         //
2934                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2935
2936                         $baseurl = System::baseUrl();
2937                         $domain_st = strpos($baseurl, "://");
2938                         if ($domain_st === false) {
2939                                 return;
2940                         }
2941                         $baseurl = substr($baseurl, $domain_st + 3);
2942                         $nurl = normalise_link($baseurl);
2943
2944                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2945                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2946                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2947                                 DBA::escape($contact_nick),
2948                                 DBA::escape($a->user['nickname']),
2949                                 DBA::escape($baseurl),
2950                                 DBA::escape($nurl)
2951                         );
2952                         if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2953                                 return;
2954                         }
2955
2956                         $r = q("SELECT * FROM contact WHERE nick = '%s'
2957                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
2958                                 DBA::escape($contact_nick),
2959                                 DBA::escape(NETWORK_DFRN),
2960                                 intval(local_user()),
2961                                 DBA::escape($baseurl)
2962                         );
2963                         if (! DBA::isResult($r)) {
2964                                 return;
2965                         }
2966
2967                         $cid = $r[0]['id'];
2968
2969                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2970
2971                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
2972                                 $orig_id = $r[0]['issued-id'];
2973                                 $dfrn_id = '1:' . $orig_id;
2974                         }
2975                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2976                                 $orig_id = $r[0]['dfrn-id'];
2977                                 $dfrn_id = '0:' . $orig_id;
2978                         }
2979
2980                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2981                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2982
2983                         if (strlen($dfrn_id) < 3) {
2984                                 return;
2985                         }
2986
2987                         $sec = random_string();
2988
2989                         DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2990
2991                         $url = curPageURL();
2992
2993                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2994                         $dest = (($url) ? '&destination_url=' . $url : '');
2995                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2996                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2997                 }
2998
2999                 return;
3000         }
3001
3002         /**
3003          * @brief Returns the activity verb
3004          *
3005          * @param array $item Item array
3006          *
3007          * @return string activity verb
3008          */
3009         private static function constructVerb(array $item)
3010         {
3011                 if ($item['verb']) {
3012                         return $item['verb'];
3013                 }
3014                 return ACTIVITY_POST;
3015         }
3016
3017         private static function tgroupCheck($uid, $item)
3018         {
3019                 $mention = false;
3020
3021                 // check that the message originated elsewhere and is a top-level post
3022
3023                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3024                         return false;
3025                 }
3026
3027                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3028                         intval($uid)
3029                 );
3030                 if (!DBA::isResult($u)) {
3031                         return false;
3032                 }
3033
3034                 $community_page = ($u[0]['page-flags'] == Contact::PAGE_COMMUNITY);
3035                 $prvgroup = ($u[0]['page-flags'] == Contact::PAGE_PRVGROUP);
3036
3037                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3038
3039                 /*
3040                  * Diaspora uses their own hardwired link URL in @-tags
3041                  * instead of the one we supply with webfinger
3042                  */
3043                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3044
3045                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3046                 if ($cnt) {
3047                         foreach ($matches as $mtch) {
3048                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3049                                         $mention = true;
3050                                         logger('mention found: ' . $mtch[2]);
3051                                 }
3052                         }
3053                 }
3054
3055                 if (!$mention) {
3056                         return false;
3057                 }
3058
3059                 return $community_page || $prvgroup;
3060         }
3061
3062         /**
3063          * This function returns true if $update has an edited timestamp newer
3064          * than $existing, i.e. $update contains new data which should override
3065          * what's already there.  If there is no timestamp yet, the update is
3066          * assumed to be newer.  If the update has no timestamp, the existing
3067          * item is assumed to be up-to-date.  If the timestamps are equal it
3068          * assumes the update has been seen before and should be ignored.
3069          *
3070          */
3071         private static function isEditedTimestampNewer($existing, $update)
3072         {
3073                 if (!x($existing, 'edited') || !$existing['edited']) {
3074                         return true;
3075                 }
3076                 if (!x($update, 'edited') || !$update['edited']) {
3077                         return false;
3078                 }
3079
3080                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3081                 $update_edited = DateTimeFormat::utc($update['edited']);
3082
3083                 return (strcmp($existing_edited, $update_edited) < 0);
3084         }
3085 }