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