]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Several more warnings ... (#5340)
[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-id"] = $importer["id"];
1560                         $author["network"] = $importer["network"];
1561                         $onlyfetch = true;
1562                 }
1563
1564                 // Until now we aren't serving different sizes - but maybe later
1565                 $avatarlist = [];
1566                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1567                 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1568                 foreach ($avatars as $avatar) {
1569                         $href = "";
1570                         $width = 0;
1571                         foreach ($avatar->attributes as $attributes) {
1572                                 /// @TODO Rewrite these similar if() to one switch
1573                                 if ($attributes->name == "href") {
1574                                         $href = $attributes->textContent;
1575                                 }
1576                                 if ($attributes->name == "width") {
1577                                         $width = $attributes->textContent;
1578                                 }
1579                                 if ($attributes->name == "updated") {
1580                                         $author["avatar-date"] = $attributes->textContent;
1581                                 }
1582                         }
1583                         if (($width > 0) && ($href != "")) {
1584                                 $avatarlist[$width] = $href;
1585                         }
1586                 }
1587
1588                 if (count($avatarlist) > 0) {
1589                         krsort($avatarlist);
1590                         $author["avatar"] = current($avatarlist);
1591                 }
1592
1593                 if (DBM::is_result($contact_old) && !$onlyfetch) {
1594                         logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1595
1596                         $poco = ["url" => $contact_old["url"]];
1597
1598                         // When was the last change to name or uri?
1599                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1600                         foreach ($name_element->attributes as $attributes) {
1601                                 if ($attributes->name == "updated") {
1602                                         $poco["name-date"] = $attributes->textContent;
1603                                 }
1604                         }
1605
1606                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1607                         foreach ($link_element->attributes as $attributes) {
1608                                 if ($attributes->name == "updated") {
1609                                         $poco["uri-date"] = $attributes->textContent;
1610                                 }
1611                         }
1612
1613                         // Update contact data
1614                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1615                         if ($value != "") {
1616                                 $poco["addr"] = $value;
1617                         }
1618
1619                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1620                         if ($value != "") {
1621                                 $poco["name"] = $value;
1622                         }
1623
1624                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1625                         if ($value != "") {
1626                                 $poco["nick"] = $value;
1627                         }
1628
1629                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1630                         if ($value != "") {
1631                                 $poco["about"] = $value;
1632                         }
1633
1634                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1635                         if ($value != "") {
1636                                 $poco["location"] = $value;
1637                         }
1638
1639                         /// @todo Only search for elements with "poco:type" = "xmpp"
1640                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1641                         if ($value != "") {
1642                                 $poco["xmpp"] = $value;
1643                         }
1644
1645                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1646                         /// - poco:utcOffset
1647                         /// - poco:urls
1648                         /// - poco:locality
1649                         /// - poco:region
1650                         /// - poco:country
1651
1652                         // If the "hide" element is present then the profile isn't searchable.
1653                         $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1654
1655                         logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1656
1657                         // If the contact isn't searchable then set the contact to "hidden".
1658                         // Problem: This can be manually overridden by the user.
1659                         if ($hide) {
1660                                 $contact_old["hidden"] = true;
1661                         }
1662
1663                         // Save the keywords into the contact table
1664                         $tags = [];
1665                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1666                         foreach ($tagelements as $tag) {
1667                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1668                         }
1669
1670                         if (count($tags)) {
1671                                 $poco["keywords"] = implode(", ", $tags);
1672                         }
1673
1674                         // "dfrn:birthday" contains the birthday converted to UTC
1675                         $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1676
1677                         if (strtotime($birthday) > time()) {
1678                                 $bd_timestamp = strtotime($birthday);
1679
1680                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1681                         }
1682
1683                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1684                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1685
1686                         if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1687                                 $bdyear = date("Y");
1688                                 $value = str_replace("0000", $bdyear, $value);
1689
1690                                 if (strtotime($value) < time()) {
1691                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1692                                         $bdyear = $bdyear + 1;
1693                                 }
1694
1695                                 $poco["bd"] = $value;
1696                         }
1697
1698                         $contact = array_merge($contact_old, $poco);
1699
1700                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1701                                 self::birthdayEvent($contact, $birthday);
1702                         }
1703
1704                         // Get all field names
1705                         $fields = [];
1706                         foreach ($contact_old as $field => $data) {
1707                                 $fields[$field] = $data;
1708                         }
1709
1710                         unset($fields["id"]);
1711                         unset($fields["uid"]);
1712                         unset($fields["url"]);
1713                         unset($fields["avatar-date"]);
1714                         unset($fields["avatar"]);
1715                         unset($fields["name-date"]);
1716                         unset($fields["uri-date"]);
1717
1718                         $update = false;
1719                         // Update check for this field has to be done differently
1720                         $datefields = ["name-date", "uri-date"];
1721                         foreach ($datefields as $field) {
1722                                 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1723                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1724                                         $update = true;
1725                                 }
1726                         }
1727
1728                         foreach ($fields as $field => $data) {
1729                                 if ($contact[$field] != $contact_old[$field]) {
1730                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1731                                         $update = true;
1732                                 }
1733                         }
1734
1735                         if ($update) {
1736                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1737
1738                                 q(
1739                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1740                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1741                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1742                                         WHERE `id` = %d AND `network` = '%s'",
1743                                         dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["about"]),     dbesc($contact["location"]),
1744                                         dbesc($contact["addr"]), dbesc($contact["keywords"]), dbesc($contact["bdyear"]),
1745                                         dbesc($contact["bd"]), intval($contact["hidden"]), dbesc($contact["xmpp"]),
1746                                         dbesc(DBM::date($contact["name-date"])), dbesc(DBM::date($contact["uri-date"])),
1747                                         intval($contact["id"]), dbesc($contact["network"])
1748                                 );
1749                         }
1750
1751                         Contact::updateAvatar(
1752                                 $author['avatar'],
1753                                 $importer['importer_uid'],
1754                                 $contact['id'],
1755                                 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1756                         );
1757
1758                         /*
1759                          * The generation is a sign for the reliability of the provided data.
1760                          * It is used in the socgraph.php to prevent that old contact data
1761                          * that was relayed over several servers can overwrite contact
1762                          * data that we received directly.
1763                          */
1764
1765                         $poco["generation"] = 2;
1766                         $poco["photo"] = $author["avatar"];
1767                         $poco["hide"] = $hide;
1768                         $poco["contact-type"] = $contact["contact-type"];
1769                         $gcid = GContact::update($poco);
1770
1771                         GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1772                 }
1773
1774                 return $author;
1775         }
1776
1777         /**
1778          * @brief Transforms activity objects into an XML string
1779          *
1780          * @param object $xpath    XPath object
1781          * @param object $activity Activity object
1782          * @param string $element  element name
1783          *
1784          * @return string XML string
1785          * @todo Find good type-hints for all parameter
1786          */
1787         private static function transformActivity($xpath, $activity, $element)
1788         {
1789                 if (!is_object($activity)) {
1790                         return "";
1791                 }
1792
1793                 $obj_doc = new DOMDocument("1.0", "utf-8");
1794                 $obj_doc->formatOutput = true;
1795
1796                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1797
1798                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1799                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1800
1801                 $id = $xpath->query("atom:id", $activity)->item(0);
1802                 if (is_object($id)) {
1803                         $obj_element->appendChild($obj_doc->importNode($id, true));
1804                 }
1805
1806                 $title = $xpath->query("atom:title", $activity)->item(0);
1807                 if (is_object($title)) {
1808                         $obj_element->appendChild($obj_doc->importNode($title, true));
1809                 }
1810
1811                 $links = $xpath->query("atom:link", $activity);
1812                 if (is_object($links)) {
1813                         foreach ($links as $link) {
1814                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1815                         }
1816                 }
1817
1818                 $content = $xpath->query("atom:content", $activity)->item(0);
1819                 if (is_object($content)) {
1820                         $obj_element->appendChild($obj_doc->importNode($content, true));
1821                 }
1822
1823                 $obj_doc->appendChild($obj_element);
1824
1825                 $objxml = $obj_doc->saveXML($obj_element);
1826
1827                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1828                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1829                 return($objxml);
1830         }
1831
1832         /**
1833          * @brief Processes the mail elements
1834          *
1835          * @param object $xpath    XPath object
1836          * @param object $mail     mail elements
1837          * @param array  $importer Record of the importer user mixed with contact of the content
1838          * @return void
1839          * @todo Find good type-hints for all parameter
1840          */
1841         private static function processMail($xpath, $mail, $importer)
1842         {
1843                 logger("Processing mails");
1844
1845                 /// @TODO Rewrite this to one statement
1846                 $msg = [];
1847                 $msg["uid"] = $importer["importer_uid"];
1848                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1849                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1850                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1851                 $msg["contact-id"] = $importer["id"];
1852                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1853                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1854                 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1855                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1856                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1857                 $msg["seen"] = 0;
1858                 $msg["replied"] = 0;
1859
1860                 dba::insert('mail', $msg);
1861
1862                 // send notifications.
1863                 /// @TODO Arange this mess
1864                 $notif_params = [
1865                         "type" => NOTIFY_MAIL,
1866                         "notify_flags" => $importer["notify-flags"],
1867                         "language" => $importer["language"],
1868                         "to_name" => $importer["username"],
1869                         "to_email" => $importer["email"],
1870                         "uid" => $importer["importer_uid"],
1871                         "item" => $msg,
1872                         "source_name" => $msg["from-name"],
1873                         "source_link" => $importer["url"],
1874                         "source_photo" => $importer["thumb"],
1875                         "verb" => ACTIVITY_POST,
1876                         "otype" => "mail"
1877                 ];
1878
1879                 notification($notif_params);
1880
1881                 logger("Mail is processed, notification was sent.");
1882         }
1883
1884         /**
1885          * @brief Processes the suggestion elements
1886          *
1887          * @param object $xpath      XPath object
1888          * @param object $suggestion suggestion elements
1889          * @param array  $importer   Record of the importer user mixed with contact of the content
1890          * @return boolean
1891          * @todo Find good type-hints for all parameter
1892          */
1893         private static function processSuggestion($xpath, $suggestion, $importer)
1894         {
1895                 $a = get_app();
1896
1897                 logger("Processing suggestions");
1898
1899                 /// @TODO Rewrite this to one statement
1900                 $suggest = [];
1901                 $suggest["uid"] = $importer["importer_uid"];
1902                 $suggest["cid"] = $importer["id"];
1903                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1904                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1905                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1906                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1907                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1908
1909                 // Does our member already have a friend matching this description?
1910
1911                 $r = q(
1912                         "SELECT `id` FROM `contact` WHERE `name` = '%s' AND `nurl` = '%s' AND `uid` = %d LIMIT 1",
1913                         dbesc($suggest["name"]),
1914                         dbesc(normalise_link($suggest["url"])),
1915                         intval($suggest["uid"])
1916                 );
1917
1918                 /*
1919                  * The valid result means the friend we're about to send a friend
1920                  * suggestion already has them in their contact, which means no further
1921                  * action is required.
1922                  *
1923                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1924                  */
1925                 if (DBM::is_result($r)) {
1926                         return false;
1927                 }
1928
1929                 // Do we already have an fcontact record for this person?
1930
1931                 $fid = 0;
1932                 $r = q(
1933                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1934                         dbesc($suggest["url"]),
1935                         dbesc($suggest["name"]),
1936                         dbesc($suggest["request"])
1937                 );
1938                 if (DBM::is_result($r)) {
1939                         $fid = $r[0]["id"];
1940
1941                         // OK, we do. Do we already have an introduction for this person ?
1942                         $r = q(
1943                                 "SELECT `id` FROM `intro` WHERE `uid` = %d AND `fid` = %d LIMIT 1",
1944                                 intval($suggest["uid"]),
1945                                 intval($fid)
1946                         );
1947
1948                         /*
1949                          * The valid result means the friend we're about to send a friend
1950                          * suggestion already has them in their contact, which means no further
1951                          * action is required.
1952                          *
1953                          * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1954                          */
1955                         if (DBM::is_result($r)) {
1956                                 return false;
1957                         }
1958                 }
1959                 if (!$fid) {
1960                         $r = q(
1961                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1962                                 dbesc($suggest["name"]),
1963                                 dbesc($suggest["url"]),
1964                                 dbesc($suggest["photo"]),
1965                                 dbesc($suggest["request"])
1966                         );
1967                 }
1968                 $r = q(
1969                         "SELECT `id` FROM `fcontact` WHERE `url` = '%s' AND `name` = '%s' AND `request` = '%s' LIMIT 1",
1970                         dbesc($suggest["url"]),
1971                         dbesc($suggest["name"]),
1972                         dbesc($suggest["request"])
1973                 );
1974
1975                 /*
1976                  * If no record in fcontact is found, below INSERT statement will not
1977                  * link an introduction to it.
1978                  */
1979                 if (!DBM::is_result($r)) {
1980                         // database record did not get created. Quietly give up.
1981                         killme();
1982                 }
1983
1984                 $fid = $r[0]["id"];
1985
1986                 $hash = random_string();
1987
1988                 $r = q(
1989                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
1990                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
1991                         intval($suggest["uid"]),
1992                         intval($fid),
1993                         intval($suggest["cid"]),
1994                         dbesc($suggest["body"]),
1995                         dbesc($hash),
1996                         dbesc(DateTimeFormat::utcNow()),
1997                         intval(0)
1998                 );
1999
2000                 notification(
2001                         [
2002                                 "type"         => NOTIFY_SUGGEST,
2003                                 "notify_flags" => $importer["notify-flags"],
2004                                 "language"     => $importer["language"],
2005                                 "to_name"      => $importer["username"],
2006                                 "to_email"     => $importer["email"],
2007                                 "uid"          => $importer["importer_uid"],
2008                                 "item"         => $suggest,
2009                                 "link"         => System::baseUrl()."/notifications/intros",
2010                                 "source_name"  => $importer["name"],
2011                                 "source_link"  => $importer["url"],
2012                                 "source_photo" => $importer["photo"],
2013                                 "verb"         => ACTIVITY_REQ_FRIEND,
2014                                 "otype"        => "intro"]
2015                 );
2016
2017                 return true;
2018         }
2019
2020         /**
2021          * @brief Processes the relocation elements
2022          *
2023          * @param object $xpath      XPath object
2024          * @param object $relocation relocation elements
2025          * @param array  $importer   Record of the importer user mixed with contact of the content
2026          * @return boolean
2027          * @todo Find good type-hints for all parameter
2028          */
2029         private static function processRelocation($xpath, $relocation, $importer)
2030         {
2031                 logger("Processing relocations");
2032
2033                 /// @TODO Rewrite this to one statement
2034                 $relocate = [];
2035                 $relocate["uid"] = $importer["importer_uid"];
2036                 $relocate["cid"] = $importer["id"];
2037                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2038                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2039                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2040                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2041                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2042                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2043                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2044                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2045                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2046                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2047                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2048                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2049
2050                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2051                         $relocate["avatar"] = $relocate["photo"];
2052                 }
2053
2054                 if ($relocate["addr"] == "") {
2055                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2056                 }
2057
2058                 // update contact
2059                 $r = q(
2060                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d;",
2061                         intval($importer["id"]),
2062                         intval($importer["importer_uid"])
2063                 );
2064
2065                 if (!DBM::is_result($r)) {
2066                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
2067                         return false;
2068                 }
2069
2070                 $old = $r[0];
2071
2072                 // Update the gcontact entry
2073                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2074
2075                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2076                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2077                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2078                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2079                 dba::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2080
2081                 // Update the contact table. We try to find every entry.
2082                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2083                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2084                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2085                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2086                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2087                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2088
2089                 dba::update('contact', $fields, $condition);
2090
2091                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2092
2093                 logger('Contacts are updated.');
2094
2095                 /// @TODO
2096                 /// merge with current record, current contents have priority
2097                 /// update record, set url-updated
2098                 /// update profile photos
2099                 /// schedule a scan?
2100                 return true;
2101         }
2102
2103         /**
2104          * @brief Updates an item
2105          *
2106          * @param array $current   the current item record
2107          * @param array $item      the new item record
2108          * @param array $importer  Record of the importer user mixed with contact of the content
2109          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2110          * @return mixed
2111          * @todo set proper type-hints (array?)
2112          */
2113         private static function updateContent($current, $item, $importer, $entrytype)
2114         {
2115                 $changed = false;
2116
2117                 if (self::isEditedTimestampNewer($current, $item)) {
2118                         // do not accept (ignore) an earlier edit than one we currently have.
2119                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2120                                 return false;
2121                         }
2122
2123                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2124                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2125                                         'edited' => DateTimeFormat::utc($item["edited"])];
2126
2127                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2128                         Item::update($fields, $condition);
2129
2130                         $changed = true;
2131                 }
2132                 return $changed;
2133         }
2134
2135         /**
2136          * @brief Detects the entry type of the item
2137          *
2138          * @param array $importer Record of the importer user mixed with contact of the content
2139          * @param array $item     the new item record
2140          *
2141          * @return int Is it a toplevel entry, a comment or a relayed comment?
2142          * @todo set proper type-hints (array?)
2143          */
2144         private static function getEntryType($importer, $item)
2145         {
2146                 if ($item["parent-uri"] != $item["uri"]) {
2147                         $community = false;
2148
2149                         if ($importer["page-flags"] == PAGE_COMMUNITY || $importer["page-flags"] == PAGE_PRVGROUP) {
2150                                 $sql_extra = "";
2151                                 $community = true;
2152                                 logger("possible community action");
2153                         } else {
2154                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2155                         }
2156
2157                         // was the top-level post for this action written by somebody on this site?
2158                         // Specifically, the recipient?
2159
2160                         $is_a_remote_action = false;
2161
2162                         $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2163                         if (DBM::is_result($parent)) {
2164                                 $r = q(
2165                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2166                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2167                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2168                                         AND `item`.`uid` = %d
2169                                         $sql_extra
2170                                         LIMIT 1",
2171                                         dbesc($parent["parent-uri"]),
2172                                         dbesc($parent["parent-uri"]),
2173                                         dbesc($parent["parent-uri"]),
2174                                         intval($importer["importer_uid"])
2175                                 );
2176                                 if (DBM::is_result($r)) {
2177                                         $is_a_remote_action = true;
2178                                 }
2179                         }
2180
2181                         /*
2182                          * Does this have the characteristics of a community or private group action?
2183                          * If it's an action to a wall post on a community/prvgroup page it's a
2184                          * valid community action. Also forum_mode makes it valid for sure.
2185                          * If neither, it's not.
2186                          */
2187                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2188                                 $is_a_remote_action = false;
2189                                 logger("not a community action");
2190                         }
2191
2192                         if ($is_a_remote_action) {
2193                                 return DFRN::REPLY_RC;
2194                         } else {
2195                                 return DFRN::REPLY;
2196                         }
2197                 } else {
2198                         return DFRN::TOP_LEVEL;
2199                 }
2200         }
2201
2202         /**
2203          * @brief Send a "poke"
2204          *
2205          * @param array $item      the new item record
2206          * @param array $importer  Record of the importer user mixed with contact of the content
2207          * @param int   $posted_id The record number of item record that was just posted
2208          * @return void
2209          * @todo set proper type-hints (array?)
2210          */
2211         private static function doPoke($item, $importer, $posted_id)
2212         {
2213                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2214                 if (!$verb) {
2215                         return;
2216                 }
2217                 $xo = XML::parseString($item["object"], false);
2218
2219                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2220                         // somebody was poked/prodded. Was it me?
2221                         foreach ($xo->link as $l) {
2222                                 $atts = $l->attributes();
2223                                 switch ($atts["rel"]) {
2224                                         case "alternate":
2225                                                 $Blink = $atts["href"];
2226                                                 break;
2227                                         default:
2228                                                 break;
2229                                 }
2230                         }
2231
2232                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2233                                 $author = dba::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2234
2235                                 // send a notification
2236                                 notification(
2237                                         [
2238                                         "type"         => NOTIFY_POKE,
2239                                         "notify_flags" => $importer["notify-flags"],
2240                                         "language"     => $importer["language"],
2241                                         "to_name"      => $importer["username"],
2242                                         "to_email"     => $importer["email"],
2243                                         "uid"          => $importer["importer_uid"],
2244                                         "item"         => $item,
2245                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2246                                         "source_name"  => $author["name"],
2247                                         "source_link"  => $author["url"],
2248                                         "source_photo" => $author["thumb"],
2249                                         "verb"         => $item["verb"],
2250                                         "otype"        => "person",
2251                                         "activity"     => $verb,
2252                                         "parent"       => $item["parent"]]
2253                                 );
2254                         }
2255                 }
2256         }
2257
2258         /**
2259          * @brief Processes several actions, depending on the verb
2260          *
2261          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2262          * @param array $importer  Record of the importer user mixed with contact of the content
2263          * @param array $item      the new item record
2264          * @param bool  $is_like   Is the verb a "like"?
2265          *
2266          * @return bool Should the processing of the entries be continued?
2267          * @todo set proper type-hints (array?)
2268          */
2269         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2270         {
2271                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2272
2273                 if (($entrytype == DFRN::TOP_LEVEL)) {
2274                         // The filling of the the "contact" variable is done for legcy reasons
2275                         // The functions below are partly used by ostatus.php as well - where we have this variable
2276                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2277                         $contact = $r[0];
2278                         $nickname = $contact["nick"];
2279
2280                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2281                         // This function once was responsible for DFRN and OStatus.
2282                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2283                                 logger("New follower");
2284                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2285                                 return false;
2286                         }
2287                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2288                                 logger("Lost follower");
2289                                 Contact::removeFollower($importer, $contact, $item);
2290                                 return false;
2291                         }
2292                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2293                                 logger("New friend request");
2294                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2295                                 return false;
2296                         }
2297                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2298                                 logger("Lost sharer");
2299                                 Contact::removeSharer($importer, $contact, $item);
2300                                 return false;
2301                         }
2302                 } else {
2303                         if (($item["verb"] == ACTIVITY_LIKE)
2304                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2305                                 || ($item["verb"] == ACTIVITY_ATTEND)
2306                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2307                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2308                         ) {
2309                                 $is_like = true;
2310                                 $item["type"] = "activity";
2311                                 $item["gravity"] = GRAVITY_ACTIVITY;
2312                                 // only one like or dislike per person
2313                                 // splitted into two queries for performance issues
2314                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2315                                         'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2316                                 if (Item::exists($condition)) {
2317                                         return false;
2318                                 }
2319
2320                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2321                                         'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2322                                 if (Item::exists($condition)) {
2323                                         return false;
2324                                 }
2325                         } else {
2326                                 $is_like = false;
2327                         }
2328
2329                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2330                                 $xo = XML::parseString($item["object"], false);
2331                                 $xt = XML::parseString($item["target"], false);
2332
2333                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2334                                         $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2335                                         if (!DBM::is_result($item_tag)) {
2336                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2337                                                 return false;
2338                                         }
2339
2340                                         // extract tag, if not duplicate, add to parent item
2341                                         if ($xo->content) {
2342                                                 if (!stristr($item_tag["tag"], trim($xo->content))) {
2343                                                         $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2344                                                         Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2345                                                 }
2346                                         }
2347                                 }
2348                         }
2349                 }
2350                 return true;
2351         }
2352
2353         /**
2354          * @brief Processes the link elements
2355          *
2356          * @param object $links link elements
2357          * @param array  $item  the item record
2358          * @return void
2359          * @todo set proper type-hints
2360          */
2361         private static function parseLinks($links, &$item)
2362         {
2363                 $rel = "";
2364                 $href = "";
2365                 $type = "";
2366                 $length = "0";
2367                 $title = "";
2368                 foreach ($links as $link) {
2369                         foreach ($link->attributes as $attributes) {
2370                                 switch ($attributes->name) {
2371                                         case "href"  : $href   = $attributes->textContent; break;
2372                                         case "rel"   : $rel    = $attributes->textContent; break;
2373                                         case "type"  : $type   = $attributes->textContent; break;
2374                                         case "length": $length = $attributes->textContent; break;
2375                                         case "title" : $title  = $attributes->textContent; break;
2376                                 }
2377                         }
2378                         if (($rel != "") && ($href != "")) {
2379                                 switch ($rel) {
2380                                         case "alternate":
2381                                                 $item["plink"] = $href;
2382                                                 break;
2383                                         case "enclosure":
2384                                                 $enclosure = $href;
2385                                                 if (strlen($item["attach"])) {
2386                                                         $item["attach"] .= ",";
2387                                                 }
2388
2389                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2390                                                 break;
2391                                 }
2392                         }
2393                 }
2394         }
2395
2396         /**
2397          * @brief Processes the entry elements which contain the items and comments
2398          *
2399          * @param array  $header   Array of the header elements that always stay the same
2400          * @param object $xpath    XPath object
2401          * @param object $entry    entry elements
2402          * @param array  $importer Record of the importer user mixed with contact of the content
2403          * @param object $xml      xml
2404          * @return void
2405          * @todo Add type-hints
2406          */
2407         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2408         {
2409                 logger("Processing entries");
2410
2411                 $item = $header;
2412
2413                 $item["protocol"] = PROTOCOL_DFRN;
2414
2415                 $item["source"] = $xml;
2416
2417                 // Get the uri
2418                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2419
2420                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2421
2422                 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2423                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2424                 );
2425                 // Is there an existing item?
2426                 if (DBM::is_result($current) && !self::isEditedTimestampNewer($current, $item)) {
2427                         logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2428                         return;
2429                 }
2430
2431                 // Fetch the owner
2432                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2433
2434                 $item["owner-link"] = $owner["link"];
2435                 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2436
2437                 // fetch the author
2438                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2439
2440                 $item["author-link"] = $author["link"];
2441                 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2442
2443                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2444
2445                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2446
2447                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2448                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2449                 // make sure nobody is trying to sneak some html tags by us
2450                 $item["body"] = notags(base64url_decode($item["body"]));
2451
2452                 $item["body"] = BBCode::limitBodySize($item["body"]);
2453
2454                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2455                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2456                         $base_url = get_app()->get_baseurl();
2457                         $item['body'] = reltoabs($item['body'], $base_url);
2458
2459                         $item['body'] = html2bb_video($item['body']);
2460
2461                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2462
2463                         $config = HTMLPurifier_Config::createDefault();
2464                         $config->set('Cache.DefinitionImpl', null);
2465
2466                         // we shouldn't need a whitelist, because the bbcode converter
2467                         // will strip out any unsupported tags.
2468
2469                         $purifier = new HTMLPurifier($config);
2470                         $item['body'] = $purifier->purify($item['body']);
2471
2472                         $item['body'] = @HTML::toBBCode($item['body']);
2473                 }
2474
2475                 /// @todo We should check for a repeated post and if we know the repeated author.
2476
2477                 // We don't need the content element since "dfrn:env" is always present
2478                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2479
2480                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2481
2482                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2483
2484                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2485
2486                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2487
2488                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2489                         $item["bookmark"] = true;
2490                 }
2491
2492                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2493                 if ($notice_info && ($notice_info->length > 0)) {
2494                         foreach ($notice_info->item(0)->attributes as $attributes) {
2495                                 if ($attributes->name == "source") {
2496                                         $item["app"] = strip_tags($attributes->textContent);
2497                                 }
2498                         }
2499                 }
2500
2501                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2502
2503                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2504                 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2505                 if ($dsprsig != "") {
2506                         $item["dsprsig"] = $dsprsig;
2507                 }
2508
2509                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2510
2511                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2512                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2513                 }
2514
2515                 $object = $xpath->query("activity:object", $entry)->item(0);
2516                 $item["object"] = self::transformActivity($xpath, $object, "object");
2517
2518                 if (trim($item["object"]) != "") {
2519                         $r = XML::parseString($item["object"], false);
2520                         if (isset($r->type)) {
2521                                 $item["object-type"] = $r->type;
2522                         }
2523                 }
2524
2525                 $target = $xpath->query("activity:target", $entry)->item(0);
2526                 $item["target"] = self::transformActivity($xpath, $target, "target");
2527
2528                 $categories = $xpath->query("atom:category", $entry);
2529                 if ($categories) {
2530                         foreach ($categories as $category) {
2531                                 $term = "";
2532                                 $scheme = "";
2533                                 foreach ($category->attributes as $attributes) {
2534                                         if ($attributes->name == "term") {
2535                                                 $term = $attributes->textContent;
2536                                         }
2537
2538                                         if ($attributes->name == "scheme") {
2539                                                 $scheme = $attributes->textContent;
2540                                         }
2541                                 }
2542
2543                                 if (($term != "") && ($scheme != "")) {
2544                                         $parts = explode(":", $scheme);
2545                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2546                                                 $termhash = array_shift($parts);
2547                                                 $termurl = implode(":", $parts);
2548
2549                                                 if (!empty($item["tag"])) {
2550                                                         $item["tag"] .= ",";
2551                                                 } else {
2552                                                         $item["tag"] = "";
2553                                                 }
2554
2555                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2556                                         }
2557                                 }
2558                         }
2559                 }
2560
2561                 $enclosure = "";
2562
2563                 $links = $xpath->query("atom:link", $entry);
2564                 if ($links) {
2565                         self::parseLinks($links, $item);
2566                 }
2567
2568                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2569
2570                 $conv = $xpath->query('ostatus:conversation', $entry);
2571                 if (is_object($conv->item(0))) {
2572                         foreach ($conv->item(0)->attributes as $attributes) {
2573                                 if ($attributes->name == "ref") {
2574                                         $item['conversation-uri'] = $attributes->textContent;
2575                                 }
2576                                 if ($attributes->name == "href") {
2577                                         $item['conversation-href'] = $attributes->textContent;
2578                                 }
2579                         }
2580                 }
2581
2582                 // Is it a reply or a top level posting?
2583                 $item["parent-uri"] = $item["uri"];
2584
2585                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2586                 if (is_object($inreplyto->item(0))) {
2587                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2588                                 if ($attributes->name == "ref") {
2589                                         $item["parent-uri"] = $attributes->textContent;
2590                                 }
2591                         }
2592                 }
2593
2594                 // Get the type of the item (Top level post, reply or remote reply)
2595                 $entrytype = self::getEntryType($importer, $item);
2596
2597                 // Now assign the rest of the values that depend on the type of the message
2598                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2599                         if (!isset($item["object-type"])) {
2600                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2601                         }
2602
2603                         if ($item["contact-id"] != $owner["contact-id"]) {
2604                                 $item["contact-id"] = $owner["contact-id"];
2605                         }
2606
2607                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2608                                 $item["network"] = $owner["network"];
2609                         }
2610
2611                         if ($item["contact-id"] != $author["contact-id"]) {
2612                                 $item["contact-id"] = $author["contact-id"];
2613                         }
2614
2615                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2616                                 $item["network"] = $author["network"];
2617                         }
2618                 }
2619
2620                 if ($entrytype == DFRN::REPLY_RC) {
2621                         $item["type"] = "remote-comment";
2622                         $item["wall"] = 1;
2623                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2624                         if (!isset($item["object-type"])) {
2625                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2626                         }
2627
2628                         // Is it an event?
2629                         if ($item["object-type"] == ACTIVITY_OBJ_EVENT) {
2630                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2631                                 $ev = Event::fromBBCode($item["body"]);
2632                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2633                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2634                                         $ev["cid"]     = $importer["id"];
2635                                         $ev["uid"]     = $importer["importer_uid"];
2636                                         $ev["uri"]     = $item["uri"];
2637                                         $ev["edited"]  = $item["edited"];
2638                                         $ev["private"] = $item["private"];
2639                                         $ev["guid"]    = $item["guid"];
2640
2641                                         $r = q(
2642                                                 "SELECT `id` FROM `event` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
2643                                                 dbesc($item["uri"]),
2644                                                 intval($importer["importer_uid"])
2645                                         );
2646                                         if (DBM::is_result($r)) {
2647                                                 $ev["id"] = $r[0]["id"];
2648                                         }
2649
2650                                         $event_id = Event::store($ev);
2651                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2652                                         return;
2653                                 }
2654                         }
2655                 }
2656
2657                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2658                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2659                         return;
2660                 }
2661
2662                 // Update content if 'updated' changes
2663                 if (DBM::is_result($current)) {
2664                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2665                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2666                         } else {
2667                                 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2668                         }
2669                         return;
2670                 }
2671
2672                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2673                         $posted_id = Item::insert($item);
2674                         $parent = 0;
2675
2676                         if ($posted_id) {
2677                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2678
2679                                 if ($item['uid'] == 0) {
2680                                         Item::distribute($posted_id);
2681                                 }
2682
2683                                 return true;
2684                         }
2685                 } else { // $entrytype == DFRN::TOP_LEVEL
2686                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2687                                 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2688                                 return;
2689                         }
2690                         if (!link_compare($item["owner-link"], $importer["url"])) {
2691                                 /*
2692                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2693                                  * but otherwise there's a possible data mixup on the sender's system.
2694                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2695                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2696                                  */
2697                                 logger('Correcting item owner.', LOGGER_DEBUG);
2698                                 $item["owner-link"] = $importer["url"];
2699                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2700                         }
2701
2702                         if (($importer["rel"] == CONTACT_IS_FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2703                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2704                                 return;
2705                         }
2706
2707                         // This is my contact on another system, but it's really me.
2708                         // Turn this into a wall post.
2709                         $notify = Item::isRemoteSelf($importer, $item);
2710
2711                         $posted_id = Item::insert($item, false, $notify);
2712
2713                         if ($notify) {
2714                                 $posted_id = $notify;
2715                         }
2716
2717                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2718
2719                         if ($item['uid'] == 0) {
2720                                 Item::distribute($posted_id);
2721                         }
2722
2723                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2724                                 self::doPoke($item, $importer, $posted_id);
2725                         }
2726                 }
2727         }
2728
2729         /**
2730          * @brief Deletes items
2731          *
2732          * @param object $xpath    XPath object
2733          * @param object $deletion deletion elements
2734          * @param array  $importer Record of the importer user mixed with contact of the content
2735          * @return void
2736          * @todo set proper type-hints
2737          */
2738         private static function processDeletion($xpath, $deletion, $importer)
2739         {
2740                 logger("Processing deletions");
2741                 $uri = null;
2742
2743                 foreach ($deletion->attributes as $attributes) {
2744                         if ($attributes->name == "ref") {
2745                                 $uri = $attributes->textContent;
2746                         }
2747                 }
2748
2749                 if (!$uri || !$importer["id"]) {
2750                         return false;
2751                 }
2752
2753                 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2754                 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2755                 if (!DBM::is_result($item)) {
2756                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2757                         return;
2758                 }
2759
2760                 if (strstr($item['file'], '[')) {
2761                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2762                         return;
2763                 }
2764
2765                 // When it is a starting post it has to belong to the person that wants to delete it
2766                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2767                         logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2768                         return;
2769                 }
2770
2771                 // Comments can be deleted by the thread owner or comment owner
2772                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2773                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2774                         if (!Item::exists($condition)) {
2775                                 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2776                                 return;
2777                         }
2778                 }
2779
2780                 if ($item["deleted"]) {
2781                         return;
2782                 }
2783
2784                 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2785
2786                 Item::delete(['id' => $item['id']]);
2787         }
2788
2789         /**
2790          * @brief Imports a DFRN message
2791          *
2792          * @param string $xml          The DFRN message
2793          * @param array  $importer     Record of the importer user mixed with contact of the content
2794          * @param bool   $sort_by_date Is used when feeds are polled
2795          * @return integer Import status
2796          * @todo set proper type-hints
2797          */
2798         public static function import($xml, $importer, $sort_by_date = false)
2799         {
2800                 if ($xml == "") {
2801                         return 400;
2802                 }
2803
2804                 $doc = new DOMDocument();
2805                 @$doc->loadXML($xml);
2806
2807                 $xpath = new DOMXPath($doc);
2808                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2809                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2810                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2811                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2812                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2813                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2814                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2815                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2816                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2817                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2818
2819                 $header = [];
2820                 $header["uid"] = $importer["importer_uid"];
2821                 $header["network"] = NETWORK_DFRN;
2822                 $header["type"] = "remote";
2823                 $header["wall"] = 0;
2824                 $header["origin"] = 0;
2825                 $header["contact-id"] = $importer["id"];
2826
2827                 // Update the contact table if the data has changed
2828
2829                 // The "atom:author" is only present in feeds
2830                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2831                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2832                 }
2833
2834                 // Only the "dfrn:owner" in the head section contains all data
2835                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2836                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2837                 }
2838
2839                 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2840
2841                 // is it a public forum? Private forums aren't exposed with this method
2842                 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2843
2844                 // The account type is new since 3.5.1
2845                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2846                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2847
2848                         if ($accounttype != $importer["contact-type"]) {
2849                                 dba::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2850                         }
2851                         // A forum contact can either have set "forum" or "prv" - but not both
2852                         if (($accounttype == ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2853                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2854                                 dba::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2855                         }
2856                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2857                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2858                         dba::update('contact', ['forum' => $forum], $condition);
2859                 }
2860
2861
2862                 // We are processing relocations even if we are ignoring a contact
2863                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2864                 foreach ($relocations as $relocation) {
2865                         self::processRelocation($xpath, $relocation, $importer);
2866                 }
2867
2868                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2869                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2870                         foreach ($mails as $mail) {
2871                                 self::processMail($xpath, $mail, $importer);
2872                         }
2873
2874                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2875                         foreach ($suggestions as $suggestion) {
2876                                 self::processSuggestion($xpath, $suggestion, $importer);
2877                         }
2878                 }
2879
2880                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2881                 foreach ($deletions as $deletion) {
2882                         self::processDeletion($xpath, $deletion, $importer);
2883                 }
2884
2885                 if (!$sort_by_date) {
2886                         $entries = $xpath->query("/atom:feed/atom:entry");
2887                         foreach ($entries as $entry) {
2888                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2889                         }
2890                 } else {
2891                         $newentries = [];
2892                         $entries = $xpath->query("/atom:feed/atom:entry");
2893                         foreach ($entries as $entry) {
2894                                 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2895                                 $newentries[strtotime($created)] = $entry;
2896                         }
2897
2898                         // Now sort after the publishing date
2899                         ksort($newentries);
2900
2901                         foreach ($newentries as $entry) {
2902                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2903                         }
2904                 }
2905                 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2906                 return 200;
2907         }
2908
2909         /**
2910          * @param App    $a            App
2911          * @param string $contact_nick contact nickname
2912          */
2913         public static function autoRedir(App $a, $contact_nick)
2914         {
2915                 // prevent looping
2916                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2917                         return;
2918                 }
2919
2920                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2921                         return;
2922                 }
2923
2924                 if (local_user()) {
2925                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
2926                         // am a contact of that user. However, that user may have other contacts with the
2927                         // same nickname as me on other hubs or other networks. Exclude these by requiring
2928                         // that the contact have a local URL. I will be the only person with my nickname at
2929                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2930                         //
2931                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2932
2933                         $baseurl = System::baseUrl();
2934                         $domain_st = strpos($baseurl, "://");
2935                         if ($domain_st === false) {
2936                                 return;
2937                         }
2938                         $baseurl = substr($baseurl, $domain_st + 3);
2939                         $nurl = normalise_link($baseurl);
2940
2941                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2942                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2943                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2944                                 dbesc($contact_nick),
2945                                 dbesc($a->user['nickname']),
2946                                 dbesc($baseurl),
2947                                 dbesc($nurl)
2948                         );
2949                         if ((! DBM::is_result($r)) || $r[0]['id'] == remote_user()) {
2950                                 return;
2951                         }
2952
2953                         $r = q("SELECT * FROM contact WHERE nick = '%s'
2954                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
2955                                 dbesc($contact_nick),
2956                                 dbesc(NETWORK_DFRN),
2957                                 intval(local_user()),
2958                                 dbesc($baseurl)
2959                         );
2960                         if (! DBM::is_result($r)) {
2961                                 return;
2962                         }
2963
2964                         $cid = $r[0]['id'];
2965
2966                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2967
2968                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
2969                                 $orig_id = $r[0]['issued-id'];
2970                                 $dfrn_id = '1:' . $orig_id;
2971                         }
2972                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2973                                 $orig_id = $r[0]['dfrn-id'];
2974                                 $dfrn_id = '0:' . $orig_id;
2975                         }
2976
2977                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2978                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
2979
2980                         if (strlen($dfrn_id) < 3) {
2981                                 return;
2982                         }
2983
2984                         $sec = random_string();
2985
2986                         dba::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
2987
2988                         $url = curPageURL();
2989
2990                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
2991                         $dest = (($url) ? '&destination_url=' . $url : '');
2992                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
2993                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
2994                 }
2995
2996                 return;
2997         }
2998
2999         /**
3000          * @brief Returns the activity verb
3001          *
3002          * @param array $item Item array
3003          *
3004          * @return string activity verb
3005          */
3006         private static function constructVerb(array $item)
3007         {
3008                 if ($item['verb']) {
3009                         return $item['verb'];
3010                 }
3011                 return ACTIVITY_POST;
3012         }
3013
3014         private static function tgroupCheck($uid, $item)
3015         {
3016                 $mention = false;
3017
3018                 // check that the message originated elsewhere and is a top-level post
3019
3020                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3021                         return false;
3022                 }
3023
3024                 $u = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
3025                         intval($uid)
3026                 );
3027                 if (!DBM::is_result($u)) {
3028                         return false;
3029                 }
3030
3031                 $community_page = ($u[0]['page-flags'] == PAGE_COMMUNITY);
3032                 $prvgroup = ($u[0]['page-flags'] == PAGE_PRVGROUP);
3033
3034                 $link = normalise_link(System::baseUrl() . '/profile/' . $u[0]['nickname']);
3035
3036                 /*
3037                  * Diaspora uses their own hardwired link URL in @-tags
3038                  * instead of the one we supply with webfinger
3039                  */
3040                 $dlink = normalise_link(System::baseUrl() . '/u/' . $u[0]['nickname']);
3041
3042                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3043                 if ($cnt) {
3044                         foreach ($matches as $mtch) {
3045                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3046                                         $mention = true;
3047                                         logger('mention found: ' . $mtch[2]);
3048                                 }
3049                         }
3050                 }
3051
3052                 if (!$mention) {
3053                         return false;
3054                 }
3055
3056                 return $community_page || $prvgroup;
3057         }
3058
3059         /**
3060          * This function returns true if $update has an edited timestamp newer
3061          * than $existing, i.e. $update contains new data which should override
3062          * what's already there.  If there is no timestamp yet, the update is
3063          * assumed to be newer.  If the update has no timestamp, the existing
3064          * item is assumed to be up-to-date.  If the timestamps are equal it
3065          * assumes the update has been seen before and should be ignored.
3066          *
3067          */
3068         private static function isEditedTimestampNewer($existing, $update)
3069         {
3070                 if (!x($existing, 'edited') || !$existing['edited']) {
3071                         return true;
3072                 }
3073                 if (!x($update, 'edited') || !$update['edited']) {
3074                         return false;
3075                 }
3076
3077                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3078                 $update_edited = DateTimeFormat::utc($update['edited']);
3079
3080                 return (strcmp($existing_edited, $update_edited) < 0);
3081         }
3082 }