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