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