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