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