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