]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
31c12405f65aecd9c0bd9b3bf682663ab2aeff9c
[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                         $condition = ['uid' => $owner["uid"], 'nurl' => normalise_link($mention)];
1060                         $contact = DBA::selectFirst('contact', ['forum', 'prv'], $condition);
1061
1062                         if (DBA::isResult($contact) && ($contact["forum"] || $contact["prv"])) {
1063                                 XML::addElement(
1064                                         $doc,
1065                                         $entry,
1066                                         "link",
1067                                         "",
1068                                         ["rel" => "mentioned",
1069                                                         "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
1070                                                         "href" => $mention]
1071                                 );
1072                         } else {
1073                                 XML::addElement(
1074                                         $doc,
1075                                         $entry,
1076                                         "link",
1077                                         "",
1078                                         ["rel" => "mentioned",
1079                                                         "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
1080                                                         "href" => $mention]
1081                                 );
1082                         }
1083                 }
1084
1085                 self::getAttachment($doc, $entry, $item);
1086
1087                 return $entry;
1088         }
1089
1090         /**
1091          * @brief encrypts data via AES
1092          *
1093          * @param string $data The data that is to be encrypted
1094          * @param string $key  The AES key
1095          *
1096          * @return string encrypted data
1097          */
1098         private static function aesEncrypt($data, $key)
1099         {
1100                 return openssl_encrypt($data, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1101         }
1102
1103         /**
1104          * @brief decrypts data via AES
1105          *
1106          * @param string $encrypted The encrypted data
1107          * @param string $key       The AES key
1108          *
1109          * @return string decrypted data
1110          */
1111         public static function aesDecrypt($encrypted, $key)
1112         {
1113                 return openssl_decrypt($encrypted, 'aes-128-ecb', $key, OPENSSL_RAW_DATA);
1114         }
1115
1116         /**
1117          * @brief Delivers the atom content to the contacts
1118          *
1119          * @param array  $owner    Owner record
1120          * @param array  $contact  Contact record of the receiver
1121          * @param string $atom     Content that will be transmitted
1122          * @param bool   $dissolve (to be documented)
1123          *
1124          * @return int Deliver status. Negative values mean an error.
1125          * @todo Add array type-hint for $owner, $contact
1126          */
1127         public static function deliver($owner, $contact, $atom, $dissolve = false)
1128         {
1129                 $a = get_app();
1130
1131                 // At first try the Diaspora transport layer
1132                 $ret = self::transmit($owner, $contact, $atom);
1133                 if ($ret >= 200) {
1134                         logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1135                         return $ret;
1136                 }
1137
1138                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1139
1140                 if ($contact['duplex'] && $contact['dfrn-id']) {
1141                         $idtosend = '0:' . $orig_id;
1142                 }
1143                 if ($contact['duplex'] && $contact['issued-id']) {
1144                         $idtosend = '1:' . $orig_id;
1145                 }
1146
1147                 $rino = Config::get('system', 'rino_encrypt');
1148                 $rino = intval($rino);
1149
1150                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1151
1152                 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1153                 $ssl_policy = '';
1154
1155                 switch ($ssl_val) {
1156                         case SSL_POLICY_FULL:
1157                                 $ssl_policy = 'full';
1158                                 break;
1159                         case SSL_POLICY_SELFSIGN:
1160                                 $ssl_policy = 'self';
1161                                 break;
1162                         case SSL_POLICY_NONE:
1163                         default:
1164                                 $ssl_policy = 'none';
1165                                 break;
1166                 }
1167
1168                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1169
1170                 logger('dfrn_deliver: ' . $url);
1171
1172                 $ret = Network::curl($url);
1173
1174                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1175                         Contact::markForArchival($contact);
1176                         return -2; // timed out
1177                 }
1178
1179                 $xml = $ret['body'];
1180
1181                 $curl_stat = $a->get_curl_code();
1182                 if (empty($curl_stat)) {
1183                         Contact::markForArchival($contact);
1184                         return -3; // timed out
1185                 }
1186
1187                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1188
1189                 if (empty($xml)) {
1190                         Contact::markForArchival($contact);
1191                         return 3;
1192                 }
1193
1194                 if (strpos($xml, '<?xml') === false) {
1195                         logger('dfrn_deliver: no valid XML returned');
1196                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1197                         Contact::markForArchival($contact);
1198                         return 3;
1199                 }
1200
1201                 $res = XML::parseString($xml);
1202
1203                 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1204                         Contact::markForArchival($contact);
1205
1206                         if (empty($res->status)) {
1207                                 $status = 3;
1208                         } else {
1209                                 $status = $res->status;
1210                         }
1211
1212                         return $status;
1213                 }
1214
1215                 $postvars     = [];
1216                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1217                 $challenge    = hex2bin((string) $res->challenge);
1218                 $perm         = (($res->perm) ? $res->perm : null);
1219                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1220                 $rino_remote_version = intval($res->rino);
1221                 $page         = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1222
1223                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1224
1225                 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1226                         $page = 2;
1227                 }
1228
1229                 $final_dfrn_id = '';
1230
1231                 if ($perm) {
1232                         if ((($perm == 'rw') && !intval($contact['writable']))
1233                                 || (($perm == 'r') && intval($contact['writable']))
1234                         ) {
1235                                 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1236
1237                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1238                         }
1239                 }
1240
1241                 if (($contact['duplex'] && strlen($contact['pubkey']))
1242                         || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1243                         || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1244                 ) {
1245                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1246                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1247                 } else {
1248                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1249                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1250                 }
1251
1252                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1253
1254                 if (strpos($final_dfrn_id, ':') == 1) {
1255                         $final_dfrn_id = substr($final_dfrn_id, 2);
1256                 }
1257
1258                 if ($final_dfrn_id != $orig_id) {
1259                         logger('dfrn_deliver: wrong dfrn_id.');
1260                         // did not decode properly - cannot trust this site
1261                         Contact::markForArchival($contact);
1262                         return 3;
1263                 }
1264
1265                 $postvars['dfrn_id']      = $idtosend;
1266                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1267                 if ($dissolve) {
1268                         $postvars['dissolve'] = '1';
1269                 }
1270
1271                 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1272                         $postvars['data'] = $atom;
1273                         $postvars['perm'] = 'rw';
1274                 } else {
1275                         $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1276                         $postvars['perm'] = 'r';
1277                 }
1278
1279                 $postvars['ssl_policy'] = $ssl_policy;
1280
1281                 if ($page) {
1282                         $postvars['page'] = $page;
1283                 }
1284
1285
1286                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1287                         logger('rino version: '. $rino_remote_version);
1288
1289                         switch ($rino_remote_version) {
1290                                 case 1:
1291                                         $key = openssl_random_pseudo_bytes(16);
1292                                         $data = self::aesEncrypt($postvars['data'], $key);
1293                                         break;
1294                                 default:
1295                                         logger("rino: invalid requested version '$rino_remote_version'");
1296                                         Contact::markForArchival($contact);
1297                                         return -8;
1298                         }
1299
1300                         $postvars['rino'] = $rino_remote_version;
1301                         $postvars['data'] = bin2hex($data);
1302
1303                         if ($dfrn_version >= 2.1) {
1304                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1305                                         || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1306                                         || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1307                                 ) {
1308                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1309                                 } else {
1310                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1311                                 }
1312                         } else {
1313                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1314                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1315                                 } else {
1316                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1317                                 }
1318                         }
1319
1320                         logger('md5 rawkey ' . md5($postvars['key']));
1321
1322                         $postvars['key'] = bin2hex($postvars['key']);
1323                 }
1324
1325
1326                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1327
1328                 $xml = Network::post($contact['notify'], $postvars);
1329
1330                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1331
1332                 $curl_stat = $a->get_curl_code();
1333                 if (empty($curl_stat) || empty($xml)) {
1334                         Contact::markForArchival($contact);
1335                         return -9; // timed out
1336                 }
1337
1338                 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1339                         Contact::markForArchival($contact);
1340                         return -10;
1341                 }
1342
1343                 if (strpos($xml, '<?xml') === false) {
1344                         logger('dfrn_deliver: phase 2: no valid XML returned');
1345                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1346                         Contact::markForArchival($contact);
1347                         return 3;
1348                 }
1349
1350                 $res = XML::parseString($xml);
1351
1352                 if (!isset($res->status)) {
1353                         Contact::markForArchival($contact);
1354                         return -11;
1355                 }
1356
1357                 // Possibly old servers had returned an empty value when everything was okay
1358                 if (empty($res->status)) {
1359                         $res->status = 200;
1360                 }
1361
1362                 if (!empty($res->message)) {
1363                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1364                 }
1365
1366                 if (($res->status >= 200) && ($res->status <= 299)) {
1367                         Contact::unmarkForArchival($contact);
1368                 }
1369
1370                 return intval($res->status);
1371         }
1372
1373         /**
1374          * @brief Transmits atom content to the contacts via the Diaspora transport layer
1375          *
1376          * @param array  $owner    Owner record
1377          * @param array  $contact  Contact record of the receiver
1378          * @param string $atom     Content that will be transmitted
1379          *
1380          * @return int Deliver status. Negative values mean an error.
1381          */
1382         public static function transmit($owner, $contact, $atom, $public_batch = false)
1383         {
1384                 $a = get_app();
1385
1386                 if (!$public_batch) {
1387                         if (empty($contact['addr'])) {
1388                                 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1389                                 if (Contact::updateFromProbe($contact['id'])) {
1390                                         $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1391                                         $contact['addr'] = $new_contact['addr'];
1392                                 }
1393
1394                                 if (empty($contact['addr'])) {
1395                                         logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1396                                         Contact::markForArchival($contact);
1397                                         return -21;
1398                                 }
1399                         }
1400
1401                         $fcontact = Diaspora::personByHandle($contact['addr']);
1402                         if (empty($fcontact)) {
1403                                 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1404                                 Contact::markForArchival($contact);
1405                                 return -22;
1406                         }
1407                         $pubkey = $fcontact['pubkey'];
1408                 } else {
1409                         $pubkey = '';
1410                 }
1411
1412                 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1413
1414                 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1415                 if ($public_batch && empty($contact["batch"])) {
1416                         $parts = parse_url($contact["notify"]);
1417                         $path_parts = explode('/', $parts['path']);
1418                         array_pop($path_parts);
1419                         $parts['path'] =  implode('/', $path_parts);
1420                         $contact["batch"] = Network::unparseURL($parts);
1421                 }
1422
1423                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1424
1425                 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1426
1427                 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1428
1429                 $curl_stat = $a->get_curl_code();
1430                 if (empty($curl_stat) || empty($xml)) {
1431                         logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1432                         Contact::markForArchival($contact);
1433                         return -9; // timed out
1434                 }
1435
1436                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1437                         Contact::markForArchival($contact);
1438                         return -10;
1439                 }
1440
1441                 if (strpos($xml, '<?xml') === false) {
1442                         logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1443                         logger('Returned XML: ' . $xml, LOGGER_DATA);
1444                         Contact::markForArchival($contact);
1445                         return 3;
1446                 }
1447
1448                 $res = XML::parseString($xml);
1449
1450                 if (empty($res->status)) {
1451                         Contact::markForArchival($contact);
1452                         return -23;
1453                 }
1454
1455                 if (!empty($res->message)) {
1456                         logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1457                 }
1458
1459                 if (($res->status >= 200) && ($res->status <= 299)) {
1460                         Contact::unmarkForArchival($contact);
1461                 }
1462
1463                 return intval($res->status);
1464         }
1465
1466         /**
1467          * @brief Add new birthday event for this person
1468          *
1469          * @param array  $contact  Contact record
1470          * @param string $birthday Birthday of the contact
1471          * @return void
1472          * @todo Add array type-hint for $contact
1473          */
1474         private static function birthdayEvent($contact, $birthday)
1475         {
1476                 // Check for duplicates
1477                 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1478                         'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1479                 if (DBA::exists('event', $condition)) {
1480                         return;
1481                 }
1482
1483                 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1484
1485                 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1486                 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1487
1488                 $r = q(
1489                         "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1490                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1491                         intval($contact['uid']),
1492                         intval($contact['id']),
1493                         DBA::escape(DateTimeFormat::utcNow()),
1494                         DBA::escape(DateTimeFormat::utcNow()),
1495                         DBA::escape(DateTimeFormat::utc($birthday)),
1496                         DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1497                         DBA::escape($bdtext),
1498                         DBA::escape($bdtext2),
1499                         DBA::escape('birthday')
1500                 );
1501         }
1502
1503         /**
1504          * @brief Fetch the author data from head or entry items
1505          *
1506          * @param object $xpath     XPath object
1507          * @param object $context   In which context should the data be searched
1508          * @param array  $importer  Record of the importer user mixed with contact of the content
1509          * @param string $element   Element name from which the data is fetched
1510          * @param bool   $onlyfetch Should the data only be fetched or should it update the contact record as well
1511          * @param string $xml       optional, default empty
1512          *
1513          * @return array Relevant data of the author
1514          * @todo Find good type-hints for all parameter
1515          */
1516         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1517         {
1518                 $author = [];
1519                 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1520                 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1521
1522                 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1523                         'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1524                 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1525                         $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1526                 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1527
1528                 if (DBA::isResult($contact_old)) {
1529                         $author["contact-id"] = $contact_old["id"];
1530                         $author["network"] = $contact_old["network"];
1531                 } else {
1532                         if (!$onlyfetch) {
1533                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1534                         }
1535
1536                         $author["contact-unknown"] = true;
1537                         $author["contact-id"] = $importer["id"];
1538                         $author["network"] = $importer["network"];
1539                         $onlyfetch = true;
1540                 }
1541
1542                 // Until now we aren't serving different sizes - but maybe later
1543                 $avatarlist = [];
1544                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1545                 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1546                 foreach ($avatars as $avatar) {
1547                         $href = "";
1548                         $width = 0;
1549                         foreach ($avatar->attributes as $attributes) {
1550                                 /// @TODO Rewrite these similar if() to one switch
1551                                 if ($attributes->name == "href") {
1552                                         $href = $attributes->textContent;
1553                                 }
1554                                 if ($attributes->name == "width") {
1555                                         $width = $attributes->textContent;
1556                                 }
1557                                 if ($attributes->name == "updated") {
1558                                         $author["avatar-date"] = $attributes->textContent;
1559                                 }
1560                         }
1561                         if (($width > 0) && ($href != "")) {
1562                                 $avatarlist[$width] = $href;
1563                         }
1564                 }
1565
1566                 if (count($avatarlist) > 0) {
1567                         krsort($avatarlist);
1568                         $author["avatar"] = current($avatarlist);
1569                 }
1570
1571                 if (empty($author['avatar']) && !empty($author['link'])) {
1572                         $cid = Contact::getIdForURL($author['link'], 0);
1573                         if (!empty($cid)) {
1574                                 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1575                                 if (DBA::isResult($contact)) {
1576                                         $author['avatar'] = $contact['avatar'];
1577                                 }
1578                         }
1579                 }
1580
1581                 if (DBA::isResult($contact_old) && !$onlyfetch) {
1582                         logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1583
1584                         $poco = ["url" => $contact_old["url"]];
1585
1586                         // When was the last change to name or uri?
1587                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1588                         foreach ($name_element->attributes as $attributes) {
1589                                 if ($attributes->name == "updated") {
1590                                         $poco["name-date"] = $attributes->textContent;
1591                                 }
1592                         }
1593
1594                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1595                         foreach ($link_element->attributes as $attributes) {
1596                                 if ($attributes->name == "updated") {
1597                                         $poco["uri-date"] = $attributes->textContent;
1598                                 }
1599                         }
1600
1601                         // Update contact data
1602                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1603                         if ($value != "") {
1604                                 $poco["addr"] = $value;
1605                         }
1606
1607                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1608                         if ($value != "") {
1609                                 $poco["name"] = $value;
1610                         }
1611
1612                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1613                         if ($value != "") {
1614                                 $poco["nick"] = $value;
1615                         }
1616
1617                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1618                         if ($value != "") {
1619                                 $poco["about"] = $value;
1620                         }
1621
1622                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1623                         if ($value != "") {
1624                                 $poco["location"] = $value;
1625                         }
1626
1627                         /// @todo Only search for elements with "poco:type" = "xmpp"
1628                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1629                         if ($value != "") {
1630                                 $poco["xmpp"] = $value;
1631                         }
1632
1633                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1634                         /// - poco:utcOffset
1635                         /// - poco:urls
1636                         /// - poco:locality
1637                         /// - poco:region
1638                         /// - poco:country
1639
1640                         // If the "hide" element is present then the profile isn't searchable.
1641                         $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1642
1643                         logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1644
1645                         // If the contact isn't searchable then set the contact to "hidden".
1646                         // Problem: This can be manually overridden by the user.
1647                         if ($hide) {
1648                                 $contact_old["hidden"] = true;
1649                         }
1650
1651                         // Save the keywords into the contact table
1652                         $tags = [];
1653                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1654                         foreach ($tagelements as $tag) {
1655                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1656                         }
1657
1658                         if (count($tags)) {
1659                                 $poco["keywords"] = implode(", ", $tags);
1660                         }
1661
1662                         // "dfrn:birthday" contains the birthday converted to UTC
1663                         $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1664
1665                         if (strtotime($birthday) > time()) {
1666                                 $bd_timestamp = strtotime($birthday);
1667
1668                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1669                         }
1670
1671                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1672                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1673
1674                         if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1675                                 $bdyear = date("Y");
1676                                 $value = str_replace("0000", $bdyear, $value);
1677
1678                                 if (strtotime($value) < time()) {
1679                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1680                                         $bdyear = $bdyear + 1;
1681                                 }
1682
1683                                 $poco["bd"] = $value;
1684                         }
1685
1686                         $contact = array_merge($contact_old, $poco);
1687
1688                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1689                                 self::birthdayEvent($contact, $birthday);
1690                         }
1691
1692                         // Get all field names
1693                         $fields = [];
1694                         foreach ($contact_old as $field => $data) {
1695                                 $fields[$field] = $data;
1696                         }
1697
1698                         unset($fields["id"]);
1699                         unset($fields["uid"]);
1700                         unset($fields["url"]);
1701                         unset($fields["avatar-date"]);
1702                         unset($fields["avatar"]);
1703                         unset($fields["name-date"]);
1704                         unset($fields["uri-date"]);
1705
1706                         $update = false;
1707                         // Update check for this field has to be done differently
1708                         $datefields = ["name-date", "uri-date"];
1709                         foreach ($datefields as $field) {
1710                                 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1711                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1712                                         $update = true;
1713                                 }
1714                         }
1715
1716                         foreach ($fields as $field => $data) {
1717                                 if ($contact[$field] != $contact_old[$field]) {
1718                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1719                                         $update = true;
1720                                 }
1721                         }
1722
1723                         if ($update) {
1724                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1725
1726                                 q(
1727                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1728                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1729                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1730                                         WHERE `id` = %d AND `network` = '%s'",
1731                                         DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]),   DBA::escape($contact["location"]),
1732                                         DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1733                                         DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1734                                         DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1735                                         intval($contact["id"]), DBA::escape($contact["network"])
1736                                 );
1737                         }
1738
1739                         Contact::updateAvatar(
1740                                 $author['avatar'],
1741                                 $importer['importer_uid'],
1742                                 $contact['id'],
1743                                 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1744                         );
1745
1746                         /*
1747                          * The generation is a sign for the reliability of the provided data.
1748                          * It is used in the socgraph.php to prevent that old contact data
1749                          * that was relayed over several servers can overwrite contact
1750                          * data that we received directly.
1751                          */
1752
1753                         $poco["generation"] = 2;
1754                         $poco["photo"] = $author["avatar"];
1755                         $poco["hide"] = $hide;
1756                         $poco["contact-type"] = $contact["contact-type"];
1757                         $gcid = GContact::update($poco);
1758
1759                         GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1760                 }
1761
1762                 return $author;
1763         }
1764
1765         /**
1766          * @brief Transforms activity objects into an XML string
1767          *
1768          * @param object $xpath    XPath object
1769          * @param object $activity Activity object
1770          * @param string $element  element name
1771          *
1772          * @return string XML string
1773          * @todo Find good type-hints for all parameter
1774          */
1775         private static function transformActivity($xpath, $activity, $element)
1776         {
1777                 if (!is_object($activity)) {
1778                         return "";
1779                 }
1780
1781                 $obj_doc = new DOMDocument("1.0", "utf-8");
1782                 $obj_doc->formatOutput = true;
1783
1784                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1785
1786                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1787                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1788
1789                 $id = $xpath->query("atom:id", $activity)->item(0);
1790                 if (is_object($id)) {
1791                         $obj_element->appendChild($obj_doc->importNode($id, true));
1792                 }
1793
1794                 $title = $xpath->query("atom:title", $activity)->item(0);
1795                 if (is_object($title)) {
1796                         $obj_element->appendChild($obj_doc->importNode($title, true));
1797                 }
1798
1799                 $links = $xpath->query("atom:link", $activity);
1800                 if (is_object($links)) {
1801                         foreach ($links as $link) {
1802                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1803                         }
1804                 }
1805
1806                 $content = $xpath->query("atom:content", $activity)->item(0);
1807                 if (is_object($content)) {
1808                         $obj_element->appendChild($obj_doc->importNode($content, true));
1809                 }
1810
1811                 $obj_doc->appendChild($obj_element);
1812
1813                 $objxml = $obj_doc->saveXML($obj_element);
1814
1815                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1816                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1817                 return($objxml);
1818         }
1819
1820         /**
1821          * @brief Processes the mail elements
1822          *
1823          * @param object $xpath    XPath object
1824          * @param object $mail     mail elements
1825          * @param array  $importer Record of the importer user mixed with contact of the content
1826          * @return void
1827          * @todo Find good type-hints for all parameter
1828          */
1829         private static function processMail($xpath, $mail, $importer)
1830         {
1831                 logger("Processing mails");
1832
1833                 /// @TODO Rewrite this to one statement
1834                 $msg = [];
1835                 $msg["uid"] = $importer["importer_uid"];
1836                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1837                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1838                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1839                 $msg["contact-id"] = $importer["id"];
1840                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1841                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1842                 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1843                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1844                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1845                 $msg["seen"] = 0;
1846                 $msg["replied"] = 0;
1847
1848                 DBA::insert('mail', $msg);
1849
1850                 $msg["id"] = DBA::lastInsertId();
1851
1852                 // send notifications.
1853                 /// @TODO Arange this mess
1854                 $notif_params = [
1855                         "type" => NOTIFY_MAIL,
1856                         "notify_flags" => $importer["notify-flags"],
1857                         "language" => $importer["language"],
1858                         "to_name" => $importer["username"],
1859                         "to_email" => $importer["email"],
1860                         "uid" => $importer["importer_uid"],
1861                         "item" => $msg,
1862                         "source_name" => $msg["from-name"],
1863                         "source_link" => $importer["url"],
1864                         "source_photo" => $importer["thumb"],
1865                         "verb" => ACTIVITY_POST,
1866                         "otype" => "mail"
1867                 ];
1868
1869                 notification($notif_params);
1870
1871                 logger("Mail is processed, notification was sent.");
1872         }
1873
1874         /**
1875          * @brief Processes the suggestion elements
1876          *
1877          * @param object $xpath      XPath object
1878          * @param object $suggestion suggestion elements
1879          * @param array  $importer   Record of the importer user mixed with contact of the content
1880          * @return boolean
1881          * @todo Find good type-hints for all parameter
1882          */
1883         private static function processSuggestion($xpath, $suggestion, $importer)
1884         {
1885                 $a = get_app();
1886
1887                 logger("Processing suggestions");
1888
1889                 /// @TODO Rewrite this to one statement
1890                 $suggest = [];
1891                 $suggest["uid"] = $importer["importer_uid"];
1892                 $suggest["cid"] = $importer["id"];
1893                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1894                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1895                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1896                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1897                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1898
1899                 // Does our member already have a friend matching this description?
1900
1901                 /*
1902                  * The valid result means the friend we're about to send a friend
1903                  * suggestion already has them in their contact, which means no further
1904                  * action is required.
1905                  *
1906                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1907                  */
1908                 $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
1909                         'uid' => $suggest["uid"]];
1910                 if (DBA::exists('contact', $condition)) {
1911                         return false;
1912                 }
1913
1914                 // Do we already have an fcontact record for this person?
1915
1916                 $fid = 0;
1917                 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1918                 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1919                 if (DBA::isResult($fcontact)) {
1920                         $fid = $fcontact["id"];
1921
1922                         // OK, we do. Do we already have an introduction for this person?
1923                         if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1924                                 /*
1925                                  * The valid result means the friend we're about to send a friend
1926                                  * suggestion already has them in their contact, which means no further
1927                                  * action is required.
1928                                  *
1929                                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1930                                  */
1931                                 return false;
1932                         }
1933                 }
1934                 if (!$fid) {
1935                         $r = q(
1936                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1937                                 DBA::escape($suggest["name"]),
1938                                 DBA::escape($suggest["url"]),
1939                                 DBA::escape($suggest["photo"]),
1940                                 DBA::escape($suggest["request"])
1941                         );
1942                 }
1943
1944                 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1945                 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1946
1947                 /*
1948                  * If no record in fcontact is found, below INSERT statement will not
1949                  * link an introduction to it.
1950                  */
1951                 if (!DBA::isResult($fcontact)) {
1952                         // Database record did not get created. Quietly give up.
1953                         killme();
1954                 }
1955
1956                 $fid = $r[0]["id"];
1957
1958                 $hash = random_string();
1959
1960                 $r = q(
1961                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1962                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1963                         intval($suggest["uid"]),
1964                         intval($fid),
1965                         intval($suggest["cid"]),
1966                         DBA::escape($suggest["body"]),
1967                         DBA::escape($hash),
1968                         DBA::escape(DateTimeFormat::utcNow()),
1969                         intval(0)
1970                 );
1971
1972                 notification(
1973                         [
1974                                 "type"         => NOTIFY_SUGGEST,
1975                                 "notify_flags" => $importer["notify-flags"],
1976                                 "language"     => $importer["language"],
1977                                 "to_name"      => $importer["username"],
1978                                 "to_email"     => $importer["email"],
1979                                 "uid"          => $importer["importer_uid"],
1980                                 "item"         => $suggest,
1981                                 "link"         => System::baseUrl()."/notifications/intros",
1982                                 "source_name"  => $importer["name"],
1983                                 "source_link"  => $importer["url"],
1984                                 "source_photo" => $importer["photo"],
1985                                 "verb"         => ACTIVITY_REQ_FRIEND,
1986                                 "otype"        => "intro"]
1987                 );
1988
1989                 return true;
1990         }
1991
1992         /**
1993          * @brief Processes the relocation elements
1994          *
1995          * @param object $xpath      XPath object
1996          * @param object $relocation relocation elements
1997          * @param array  $importer   Record of the importer user mixed with contact of the content
1998          * @return boolean
1999          * @todo Find good type-hints for all parameter
2000          */
2001         private static function processRelocation($xpath, $relocation, $importer)
2002         {
2003                 logger("Processing relocations");
2004
2005                 /// @TODO Rewrite this to one statement
2006                 $relocate = [];
2007                 $relocate["uid"] = $importer["importer_uid"];
2008                 $relocate["cid"] = $importer["id"];
2009                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2010                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2011                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2012                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2013                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2014                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2015                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2016                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2017                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2018                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2019                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2020                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2021
2022                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2023                         $relocate["avatar"] = $relocate["photo"];
2024                 }
2025
2026                 if ($relocate["addr"] == "") {
2027                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2028                 }
2029
2030                 // update contact
2031                 $r = q(
2032                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2033                         intval($importer["id"]),
2034                         intval($importer["importer_uid"])
2035                 );
2036
2037                 if (!DBA::isResult($r)) {
2038                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
2039                         return false;
2040                 }
2041
2042                 $old = $r[0];
2043
2044                 // Update the gcontact entry
2045                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2046
2047                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2048                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2049                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2050                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2051                 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2052
2053                 // Update the contact table. We try to find every entry.
2054                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2055                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2056                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2057                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2058                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2059                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2060
2061                 DBA::update('contact', $fields, $condition);
2062
2063                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2064
2065                 logger('Contacts are updated.');
2066
2067                 /// @TODO
2068                 /// merge with current record, current contents have priority
2069                 /// update record, set url-updated
2070                 /// update profile photos
2071                 /// schedule a scan?
2072                 return true;
2073         }
2074
2075         /**
2076          * @brief Updates an item
2077          *
2078          * @param array $current   the current item record
2079          * @param array $item      the new item record
2080          * @param array $importer  Record of the importer user mixed with contact of the content
2081          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2082          * @return mixed
2083          * @todo set proper type-hints (array?)
2084          */
2085         private static function updateContent($current, $item, $importer, $entrytype)
2086         {
2087                 $changed = false;
2088
2089                 if (self::isEditedTimestampNewer($current, $item)) {
2090                         // do not accept (ignore) an earlier edit than one we currently have.
2091                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2092                                 return false;
2093                         }
2094
2095                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2096                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2097                                         'edited' => DateTimeFormat::utc($item["edited"])];
2098
2099                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2100                         Item::update($fields, $condition);
2101
2102                         $changed = true;
2103                 }
2104                 return $changed;
2105         }
2106
2107         /**
2108          * @brief Detects the entry type of the item
2109          *
2110          * @param array $importer Record of the importer user mixed with contact of the content
2111          * @param array $item     the new item record
2112          *
2113          * @return int Is it a toplevel entry, a comment or a relayed comment?
2114          * @todo set proper type-hints (array?)
2115          */
2116         private static function getEntryType($importer, $item)
2117         {
2118                 if ($item["parent-uri"] != $item["uri"]) {
2119                         $community = false;
2120
2121                         if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2122                                 $sql_extra = "";
2123                                 $community = true;
2124                                 logger("possible community action");
2125                         } else {
2126                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2127                         }
2128
2129                         // was the top-level post for this action written by somebody on this site?
2130                         // Specifically, the recipient?
2131
2132                         $is_a_remote_action = false;
2133
2134                         $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2135                         if (DBA::isResult($parent)) {
2136                                 $r = q(
2137                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2138                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2139                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2140                                         AND `item`.`uid` = %d
2141                                         $sql_extra
2142                                         LIMIT 1",
2143                                         DBA::escape($parent["parent-uri"]),
2144                                         DBA::escape($parent["parent-uri"]),
2145                                         DBA::escape($parent["parent-uri"]),
2146                                         intval($importer["importer_uid"])
2147                                 );
2148                                 if (DBA::isResult($r)) {
2149                                         $is_a_remote_action = true;
2150                                 }
2151                         }
2152
2153                         /*
2154                          * Does this have the characteristics of a community or private group action?
2155                          * If it's an action to a wall post on a community/prvgroup page it's a
2156                          * valid community action. Also forum_mode makes it valid for sure.
2157                          * If neither, it's not.
2158                          */
2159                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2160                                 $is_a_remote_action = false;
2161                                 logger("not a community action");
2162                         }
2163
2164                         if ($is_a_remote_action) {
2165                                 return DFRN::REPLY_RC;
2166                         } else {
2167                                 return DFRN::REPLY;
2168                         }
2169                 } else {
2170                         return DFRN::TOP_LEVEL;
2171                 }
2172         }
2173
2174         /**
2175          * @brief Send a "poke"
2176          *
2177          * @param array $item      the new item record
2178          * @param array $importer  Record of the importer user mixed with contact of the content
2179          * @param int   $posted_id The record number of item record that was just posted
2180          * @return void
2181          * @todo set proper type-hints (array?)
2182          */
2183         private static function doPoke($item, $importer, $posted_id)
2184         {
2185                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2186                 if (!$verb) {
2187                         return;
2188                 }
2189                 $xo = XML::parseString($item["object"], false);
2190
2191                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2192                         // somebody was poked/prodded. Was it me?
2193                         foreach ($xo->link as $l) {
2194                                 $atts = $l->attributes();
2195                                 switch ($atts["rel"]) {
2196                                         case "alternate":
2197                                                 $Blink = $atts["href"];
2198                                                 break;
2199                                         default:
2200                                                 break;
2201                                 }
2202                         }
2203
2204                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2205                                 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2206
2207                                 // send a notification
2208                                 notification(
2209                                         [
2210                                         "type"         => NOTIFY_POKE,
2211                                         "notify_flags" => $importer["notify-flags"],
2212                                         "language"     => $importer["language"],
2213                                         "to_name"      => $importer["username"],
2214                                         "to_email"     => $importer["email"],
2215                                         "uid"          => $importer["importer_uid"],
2216                                         "item"         => $item,
2217                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2218                                         "source_name"  => $author["name"],
2219                                         "source_link"  => $author["url"],
2220                                         "source_photo" => $author["thumb"],
2221                                         "verb"         => $item["verb"],
2222                                         "otype"        => "person",
2223                                         "activity"     => $verb,
2224                                         "parent"       => $item["parent"]]
2225                                 );
2226                         }
2227                 }
2228         }
2229
2230         /**
2231          * @brief Processes several actions, depending on the verb
2232          *
2233          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2234          * @param array $importer  Record of the importer user mixed with contact of the content
2235          * @param array $item      the new item record
2236          * @param bool  $is_like   Is the verb a "like"?
2237          *
2238          * @return bool Should the processing of the entries be continued?
2239          * @todo set proper type-hints (array?)
2240          */
2241         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2242         {
2243                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2244
2245                 if (($entrytype == DFRN::TOP_LEVEL)) {
2246                         // The filling of the the "contact" variable is done for legcy reasons
2247                         // The functions below are partly used by ostatus.php as well - where we have this variable
2248                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2249                         $contact = $r[0];
2250                         $nickname = $contact["nick"];
2251
2252                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2253                         // This function once was responsible for DFRN and OStatus.
2254                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2255                                 logger("New follower");
2256                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2257                                 return false;
2258                         }
2259                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2260                                 logger("Lost follower");
2261                                 Contact::removeFollower($importer, $contact, $item);
2262                                 return false;
2263                         }
2264                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2265                                 logger("New friend request");
2266                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2267                                 return false;
2268                         }
2269                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2270                                 logger("Lost sharer");
2271                                 Contact::removeSharer($importer, $contact, $item);
2272                                 return false;
2273                         }
2274                 } else {
2275                         if (($item["verb"] == ACTIVITY_LIKE)
2276                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2277                                 || ($item["verb"] == ACTIVITY_ATTEND)
2278                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2279                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2280                         ) {
2281                                 $is_like = true;
2282                                 $item["gravity"] = GRAVITY_ACTIVITY;
2283                                 // only one like or dislike per person
2284                                 // splitted into two queries for performance issues
2285                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2286                                         'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2287                                 if (Item::exists($condition)) {
2288                                         return false;
2289                                 }
2290
2291                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2292                                         'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2293                                 if (Item::exists($condition)) {
2294                                         return false;
2295                                 }
2296                         } else {
2297                                 $is_like = false;
2298                         }
2299
2300                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2301                                 $xo = XML::parseString($item["object"], false);
2302                                 $xt = XML::parseString($item["target"], false);
2303
2304                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2305                                         $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2306
2307                                         if (!DBA::isResult($item_tag)) {
2308                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2309                                                 return false;
2310                                         }
2311
2312                                         // extract tag, if not duplicate, add to parent item
2313                                         if ($xo->content) {
2314                                                 if (!stristr($item_tag["tag"], trim($xo->content))) {
2315                                                         $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2316                                                         Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2317                                                 }
2318                                         }
2319                                 }
2320                         }
2321                 }
2322                 return true;
2323         }
2324
2325         /**
2326          * @brief Processes the link elements
2327          *
2328          * @param object $links link elements
2329          * @param array  $item  the item record
2330          * @return void
2331          * @todo set proper type-hints
2332          */
2333         private static function parseLinks($links, &$item)
2334         {
2335                 $rel = "";
2336                 $href = "";
2337                 $type = "";
2338                 $length = "0";
2339                 $title = "";
2340                 foreach ($links as $link) {
2341                         foreach ($link->attributes as $attributes) {
2342                                 switch ($attributes->name) {
2343                                         case "href"  : $href   = $attributes->textContent; break;
2344                                         case "rel"   : $rel    = $attributes->textContent; break;
2345                                         case "type"  : $type   = $attributes->textContent; break;
2346                                         case "length": $length = $attributes->textContent; break;
2347                                         case "title" : $title  = $attributes->textContent; break;
2348                                 }
2349                         }
2350                         if (($rel != "") && ($href != "")) {
2351                                 switch ($rel) {
2352                                         case "alternate":
2353                                                 $item["plink"] = $href;
2354                                                 break;
2355                                         case "enclosure":
2356                                                 $enclosure = $href;
2357                                                 if (strlen($item["attach"])) {
2358                                                         $item["attach"] .= ",";
2359                                                 }
2360
2361                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2362                                                 break;
2363                                 }
2364                         }
2365                 }
2366         }
2367
2368         /**
2369          * @brief Processes the entry elements which contain the items and comments
2370          *
2371          * @param array  $header   Array of the header elements that always stay the same
2372          * @param object $xpath    XPath object
2373          * @param object $entry    entry elements
2374          * @param array  $importer Record of the importer user mixed with contact of the content
2375          * @param object $xml      xml
2376          * @return void
2377          * @todo Add type-hints
2378          */
2379         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2380         {
2381                 logger("Processing entries");
2382
2383                 $item = $header;
2384
2385                 $item["protocol"] = Conversation::PARCEL_DFRN;
2386
2387                 $item["source"] = $xml;
2388
2389                 // Get the uri
2390                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2391
2392                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2393
2394                 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2395                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2396                 );
2397                 // Is there an existing item?
2398                 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2399                         logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2400                         return;
2401                 }
2402
2403                 // Fetch the owner
2404                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2405
2406                 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2407
2408                 $item["owner-name"] = $owner["name"];
2409                 $item["owner-link"] = $owner["link"];
2410                 $item["owner-avatar"] = $owner["avatar"];
2411                 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2412
2413                 // fetch the author
2414                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2415
2416                 $item["author-name"] = $author["name"];
2417                 $item["author-link"] = $author["link"];
2418                 $item["author-avatar"] = $author["avatar"];
2419                 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2420
2421                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2422
2423                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2424
2425                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2426                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2427                 // make sure nobody is trying to sneak some html tags by us
2428                 $item["body"] = notags(base64url_decode($item["body"]));
2429
2430                 $item["body"] = BBCode::limitBodySize($item["body"]);
2431
2432                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2433                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2434                         $base_url = get_app()->get_baseurl();
2435                         $item['body'] = reltoabs($item['body'], $base_url);
2436
2437                         $item['body'] = html2bb_video($item['body']);
2438
2439                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2440
2441                         $config = HTMLPurifier_Config::createDefault();
2442                         $config->set('Cache.DefinitionImpl', null);
2443
2444                         // we shouldn't need a whitelist, because the bbcode converter
2445                         // will strip out any unsupported tags.
2446
2447                         $purifier = new HTMLPurifier($config);
2448                         $item['body'] = $purifier->purify($item['body']);
2449
2450                         $item['body'] = @HTML::toBBCode($item['body']);
2451                 }
2452
2453                 /// @todo We should check for a repeated post and if we know the repeated author.
2454
2455                 // We don't need the content element since "dfrn:env" is always present
2456                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2457
2458                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2459
2460                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2461
2462                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2463
2464                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2465
2466                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2467                         $item["post-type"] = Item::PT_PAGE;
2468                 }
2469
2470                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2471                 if ($notice_info && ($notice_info->length > 0)) {
2472                         foreach ($notice_info->item(0)->attributes as $attributes) {
2473                                 if ($attributes->name == "source") {
2474                                         $item["app"] = strip_tags($attributes->textContent);
2475                                 }
2476                         }
2477                 }
2478
2479                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2480
2481                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2482                 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2483                 if ($dsprsig != "") {
2484                         $item["dsprsig"] = $dsprsig;
2485                 }
2486
2487                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2488
2489                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2490                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2491                 }
2492
2493                 $object = $xpath->query("activity:object", $entry)->item(0);
2494                 $item["object"] = self::transformActivity($xpath, $object, "object");
2495
2496                 if (trim($item["object"]) != "") {
2497                         $r = XML::parseString($item["object"], false);
2498                         if (isset($r->type)) {
2499                                 $item["object-type"] = $r->type;
2500                         }
2501                 }
2502
2503                 $target = $xpath->query("activity:target", $entry)->item(0);
2504                 $item["target"] = self::transformActivity($xpath, $target, "target");
2505
2506                 $categories = $xpath->query("atom:category", $entry);
2507                 if ($categories) {
2508                         foreach ($categories as $category) {
2509                                 $term = "";
2510                                 $scheme = "";
2511                                 foreach ($category->attributes as $attributes) {
2512                                         if ($attributes->name == "term") {
2513                                                 $term = $attributes->textContent;
2514                                         }
2515
2516                                         if ($attributes->name == "scheme") {
2517                                                 $scheme = $attributes->textContent;
2518                                         }
2519                                 }
2520
2521                                 if (($term != "") && ($scheme != "")) {
2522                                         $parts = explode(":", $scheme);
2523                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2524                                                 $termhash = array_shift($parts);
2525                                                 $termurl = implode(":", $parts);
2526
2527                                                 if (!empty($item["tag"])) {
2528                                                         $item["tag"] .= ",";
2529                                                 } else {
2530                                                         $item["tag"] = "";
2531                                                 }
2532
2533                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2534                                         }
2535                                 }
2536                         }
2537                 }
2538
2539                 $enclosure = "";
2540
2541                 $links = $xpath->query("atom:link", $entry);
2542                 if ($links) {
2543                         self::parseLinks($links, $item);
2544                 }
2545
2546                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2547
2548                 $conv = $xpath->query('ostatus:conversation', $entry);
2549                 if (is_object($conv->item(0))) {
2550                         foreach ($conv->item(0)->attributes as $attributes) {
2551                                 if ($attributes->name == "ref") {
2552                                         $item['conversation-uri'] = $attributes->textContent;
2553                                 }
2554                                 if ($attributes->name == "href") {
2555                                         $item['conversation-href'] = $attributes->textContent;
2556                                 }
2557                         }
2558                 }
2559
2560                 // Is it a reply or a top level posting?
2561                 $item["parent-uri"] = $item["uri"];
2562
2563                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2564                 if (is_object($inreplyto->item(0))) {
2565                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2566                                 if ($attributes->name == "ref") {
2567                                         $item["parent-uri"] = $attributes->textContent;
2568                                 }
2569                         }
2570                 }
2571
2572                 // Get the type of the item (Top level post, reply or remote reply)
2573                 $entrytype = self::getEntryType($importer, $item);
2574
2575                 // Now assign the rest of the values that depend on the type of the message
2576                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2577                         if (!isset($item["object-type"])) {
2578                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2579                         }
2580
2581                         if ($item["contact-id"] != $owner["contact-id"]) {
2582                                 $item["contact-id"] = $owner["contact-id"];
2583                         }
2584
2585                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2586                                 $item["network"] = $owner["network"];
2587                         }
2588
2589                         if ($item["contact-id"] != $author["contact-id"]) {
2590                                 $item["contact-id"] = $author["contact-id"];
2591                         }
2592
2593                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2594                                 $item["network"] = $author["network"];
2595                         }
2596                 }
2597
2598                 if ($entrytype == DFRN::REPLY_RC) {
2599                         $item["wall"] = 1;
2600                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2601                         if (!isset($item["object-type"])) {
2602                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2603                         }
2604
2605                         // Is it an event?
2606                         if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2607                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2608                                 $ev = Event::fromBBCode($item["body"]);
2609                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2610                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2611                                         $ev["cid"]     = $importer["id"];
2612                                         $ev["uid"]     = $importer["importer_uid"];
2613                                         $ev["uri"]     = $item["uri"];
2614                                         $ev["edited"]  = $item["edited"];
2615                                         $ev["private"] = $item["private"];
2616                                         $ev["guid"]    = $item["guid"];
2617                                         $ev["plink"]   = $item["plink"];
2618
2619                                         $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2620                                         $event = DBA::selectFirst('event', ['id'], $condition);
2621                                         if (DBA::isResult($event)) {
2622                                                 $ev["id"] = $event["id"];
2623                                         }
2624
2625                                         $event_id = Event::store($ev);
2626                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2627                                         return;
2628                                 }
2629                         }
2630                 }
2631
2632                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2633                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2634                         return;
2635                 }
2636
2637                 // This check is done here to be able to receive connection requests in "processVerbs"
2638                 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2639                         logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2640                         return;
2641                 }
2642
2643
2644                 // Update content if 'updated' changes
2645                 if (DBA::isResult($current)) {
2646                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2647                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2648                         } else {
2649                                 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2650                         }
2651                         return;
2652                 }
2653
2654                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2655                         $posted_id = Item::insert($item);
2656                         $parent = 0;
2657
2658                         if ($posted_id) {
2659                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2660
2661                                 if ($item['uid'] == 0) {
2662                                         Item::distribute($posted_id);
2663                                 }
2664
2665                                 return true;
2666                         }
2667                 } else { // $entrytype == DFRN::TOP_LEVEL
2668                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2669                                 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2670                                 return;
2671                         }
2672                         if (!link_compare($item["owner-link"], $importer["url"])) {
2673                                 /*
2674                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2675                                  * but otherwise there's a possible data mixup on the sender's system.
2676                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2677                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2678                                  */
2679                                 logger('Correcting item owner.', LOGGER_DEBUG);
2680                                 $item["owner-link"] = $importer["url"];
2681                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2682                         }
2683
2684                         if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2685                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2686                                 return;
2687                         }
2688
2689                         // This is my contact on another system, but it's really me.
2690                         // Turn this into a wall post.
2691                         $notify = Item::isRemoteSelf($importer, $item);
2692
2693                         $posted_id = Item::insert($item, false, $notify);
2694
2695                         if ($notify) {
2696                                 $posted_id = $notify;
2697                         }
2698
2699                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2700
2701                         if ($item['uid'] == 0) {
2702                                 Item::distribute($posted_id);
2703                         }
2704
2705                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2706                                 self::doPoke($item, $importer, $posted_id);
2707                         }
2708                 }
2709         }
2710
2711         /**
2712          * @brief Deletes items
2713          *
2714          * @param object $xpath    XPath object
2715          * @param object $deletion deletion elements
2716          * @param array  $importer Record of the importer user mixed with contact of the content
2717          * @return void
2718          * @todo set proper type-hints
2719          */
2720         private static function processDeletion($xpath, $deletion, $importer)
2721         {
2722                 logger("Processing deletions");
2723                 $uri = null;
2724
2725                 foreach ($deletion->attributes as $attributes) {
2726                         if ($attributes->name == "ref") {
2727                                 $uri = $attributes->textContent;
2728                         }
2729                 }
2730
2731                 if (!$uri || !$importer["id"]) {
2732                         return false;
2733                 }
2734
2735                 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2736                 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2737                 if (!DBA::isResult($item)) {
2738                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2739                         return;
2740                 }
2741
2742                 if (strstr($item['file'], '[')) {
2743                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2744                         return;
2745                 }
2746
2747                 // When it is a starting post it has to belong to the person that wants to delete it
2748                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2749                         logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2750                         return;
2751                 }
2752
2753                 // Comments can be deleted by the thread owner or comment owner
2754                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2755                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2756                         if (!Item::exists($condition)) {
2757                                 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2758                                 return;
2759                         }
2760                 }
2761
2762                 if ($item["deleted"]) {
2763                         return;
2764                 }
2765
2766                 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2767
2768                 Item::delete(['id' => $item['id']]);
2769         }
2770
2771         /**
2772          * @brief Imports a DFRN message
2773          *
2774          * @param string $xml          The DFRN message
2775          * @param array  $importer     Record of the importer user mixed with contact of the content
2776          * @param bool   $sort_by_date Is used when feeds are polled
2777          * @return integer Import status
2778          * @todo set proper type-hints
2779          */
2780         public static function import($xml, $importer, $sort_by_date = false)
2781         {
2782                 if ($xml == "") {
2783                         return 400;
2784                 }
2785
2786                 $doc = new DOMDocument();
2787                 @$doc->loadXML($xml);
2788
2789                 $xpath = new DOMXPath($doc);
2790                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2791                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2792                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2793                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2794                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2795                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2796                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2797                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2798                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2799                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2800
2801                 $header = [];
2802                 $header["uid"] = $importer["importer_uid"];
2803                 $header["network"] = Protocol::DFRN;
2804                 $header["wall"] = 0;
2805                 $header["origin"] = 0;
2806                 $header["contact-id"] = $importer["id"];
2807
2808                 // Update the contact table if the data has changed
2809
2810                 // The "atom:author" is only present in feeds
2811                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2812                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2813                 }
2814
2815                 // Only the "dfrn:owner" in the head section contains all data
2816                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2817                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2818                 }
2819
2820                 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2821
2822                 // is it a public forum? Private forums aren't exposed with this method
2823                 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2824
2825                 // The account type is new since 3.5.1
2826                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2827                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2828
2829                         if ($accounttype != $importer["contact-type"]) {
2830                                 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2831                         }
2832                         // A forum contact can either have set "forum" or "prv" - but not both
2833                         if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2834                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2835                                 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2836                         }
2837                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2838                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2839                         DBA::update('contact', ['forum' => $forum], $condition);
2840                 }
2841
2842
2843                 // We are processing relocations even if we are ignoring a contact
2844                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2845                 foreach ($relocations as $relocation) {
2846                         self::processRelocation($xpath, $relocation, $importer);
2847                 }
2848
2849                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2850                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2851                         foreach ($mails as $mail) {
2852                                 self::processMail($xpath, $mail, $importer);
2853                         }
2854
2855                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2856                         foreach ($suggestions as $suggestion) {
2857                                 self::processSuggestion($xpath, $suggestion, $importer);
2858                         }
2859                 }
2860
2861                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2862                 foreach ($deletions as $deletion) {
2863                         self::processDeletion($xpath, $deletion, $importer);
2864                 }
2865
2866                 if (!$sort_by_date) {
2867                         $entries = $xpath->query("/atom:feed/atom:entry");
2868                         foreach ($entries as $entry) {
2869                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2870                         }
2871                 } else {
2872                         $newentries = [];
2873                         $entries = $xpath->query("/atom:feed/atom:entry");
2874                         foreach ($entries as $entry) {
2875                                 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2876                                 $newentries[strtotime($created)] = $entry;
2877                         }
2878
2879                         // Now sort after the publishing date
2880                         ksort($newentries);
2881
2882                         foreach ($newentries as $entry) {
2883                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2884                         }
2885                 }
2886                 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2887                 return 200;
2888         }
2889
2890         /**
2891          * @param App    $a            App
2892          * @param string $contact_nick contact nickname
2893          */
2894         public static function autoRedir(App $a, $contact_nick)
2895         {
2896                 // prevent looping
2897                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2898                         return;
2899                 }
2900
2901                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2902                         return;
2903                 }
2904
2905                 if (local_user()) {
2906                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
2907                         // am a contact of that user. However, that user may have other contacts with the
2908                         // same nickname as me on other hubs or other networks. Exclude these by requiring
2909                         // that the contact have a local URL. I will be the only person with my nickname at
2910                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2911                         //
2912                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2913
2914                         $baseurl = System::baseUrl();
2915                         $domain_st = strpos($baseurl, "://");
2916                         if ($domain_st === false) {
2917                                 return;
2918                         }
2919                         $baseurl = substr($baseurl, $domain_st + 3);
2920                         $nurl = normalise_link($baseurl);
2921
2922                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2923                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2924                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2925                                 DBA::escape($contact_nick),
2926                                 DBA::escape($a->user['nickname']),
2927                                 DBA::escape($baseurl),
2928                                 DBA::escape($nurl)
2929                         );
2930                         if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2931                                 return;
2932                         }
2933
2934                         $r = q("SELECT * FROM contact WHERE nick = '%s'
2935                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
2936                                 DBA::escape($contact_nick),
2937                                 DBA::escape(Protocol::DFRN),
2938                                 intval(local_user()),
2939                                 DBA::escape($baseurl)
2940                         );
2941                         if (! DBA::isResult($r)) {
2942                                 return;
2943                         }
2944
2945                         $cid = $r[0]['id'];
2946
2947                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2948
2949                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
2950                                 $orig_id = $r[0]['issued-id'];
2951                                 $dfrn_id = '1:' . $orig_id;
2952                         }
2953                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2954                                 $orig_id = $r[0]['dfrn-id'];
2955                                 $dfrn_id = '0:' . $orig_id;
2956                         }
2957
2958                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2959                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2960
2961                         if (strlen($dfrn_id) < 3) {
2962                                 return;
2963                         }
2964
2965                         $sec = random_string();
2966
2967                         DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2968
2969                         $url = curPageURL();
2970
2971                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2972                         $dest = (($url) ? '&destination_url=' . $url : '');
2973                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2974                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2975                 }
2976
2977                 return;
2978         }
2979
2980         /**
2981          * @brief Returns the activity verb
2982          *
2983          * @param array $item Item array
2984          *
2985          * @return string activity verb
2986          */
2987         private static function constructVerb(array $item)
2988         {
2989                 if ($item['verb']) {
2990                         return $item['verb'];
2991                 }
2992                 return ACTIVITY_POST;
2993         }
2994
2995         private static function tgroupCheck($uid, $item)
2996         {
2997                 $mention = false;
2998
2999                 // check that the message originated elsewhere and is a top-level post
3000
3001                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3002                         return false;
3003                 }
3004
3005                 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3006                 if (!DBA::isResult($user)) {
3007                         return false;
3008                 }
3009
3010                 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3011                 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3012
3013                 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
3014
3015                 /*
3016                  * Diaspora uses their own hardwired link URL in @-tags
3017                  * instead of the one we supply with webfinger
3018                  */
3019                 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
3020
3021                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3022                 if ($cnt) {
3023                         foreach ($matches as $mtch) {
3024                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3025                                         $mention = true;
3026                                         logger('mention found: ' . $mtch[2]);
3027                                 }
3028                         }
3029                 }
3030
3031                 if (!$mention) {
3032                         return false;
3033                 }
3034
3035                 return $community_page || $prvgroup;
3036         }
3037
3038         /**
3039          * This function returns true if $update has an edited timestamp newer
3040          * than $existing, i.e. $update contains new data which should override
3041          * what's already there.  If there is no timestamp yet, the update is
3042          * assumed to be newer.  If the update has no timestamp, the existing
3043          * item is assumed to be up-to-date.  If the timestamps are equal it
3044          * assumes the update has been seen before and should be ignored.
3045          *
3046          */
3047         private static function isEditedTimestampNewer($existing, $update)
3048         {
3049                 if (!x($existing, 'edited') || !$existing['edited']) {
3050                         return true;
3051                 }
3052                 if (!x($update, 'edited') || !$update['edited']) {
3053                         return false;
3054                 }
3055
3056                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3057                 $update_edited = DateTimeFormat::utc($update['edited']);
3058
3059                 return (strcmp($existing_edited, $update_edited) < 0);
3060         }
3061 }