]> git.mxchange.org Git - friendica.git/blob - src/Protocol/DFRN.php
Cleanups: isResult() more used, readability improved (#5608)
[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                 } else {
86                         $user = ['importer_uid' => 0, 'uprvkey' => '', 'timezone' => 'UTC',
87                                 'nickname' => '', 'sprvkey' => '', 'spubkey' => '',
88                                 'page-flags' => 0, 'account-type' => 0, 'prvnets' => 0];
89                 }
90
91                 return array_merge($contact, $user);
92         }
93
94         /**
95          * @brief Generates the atom entries for delivery.php
96          *
97          * This function is used whenever content is transmitted via DFRN.
98          *
99          * @param array $items Item elements
100          * @param array $owner Owner record
101          *
102          * @return string DFRN entries
103          * @todo Find proper type-hints
104          */
105         public static function entries($items, $owner)
106         {
107                 $doc = new DOMDocument('1.0', 'utf-8');
108                 $doc->formatOutput = true;
109
110                 $root = self::addHeader($doc, $owner, "dfrn:owner", "", false);
111
112                 if (! count($items)) {
113                         return trim($doc->saveXML());
114                 }
115
116                 foreach ($items as $item) {
117                         // These values aren't sent when sending from the queue.
118                         /// @todo Check if we can set these values from the queue or if they are needed at all.
119                         $item["entry:comment-allow"] = defaults($item, "entry:comment-allow", true);
120                         $item["entry:cid"] = defaults($item, "entry:cid", 0);
121
122                         $entry = self::entry($doc, "text", $item, $owner, $item["entry:comment-allow"], $item["entry:cid"]);
123                         $root->appendChild($entry);
124                 }
125
126                 return trim($doc->saveXML());
127         }
128
129         /**
130          * @brief Generate an atom feed for the given user
131          *
132          * This function is called when another server is pulling data from the user feed.
133          *
134          * @param string  $dfrn_id     DFRN ID from the requesting party
135          * @param string  $owner_nick  Owner nick name
136          * @param string  $last_update Date of the last update
137          * @param int     $direction   Can be -1, 0 or 1.
138          * @param boolean $onlyheader  Output only the header without content? (Default is "no")
139          *
140          * @return string DFRN feed entries
141          */
142         public static function feed($dfrn_id, $owner_nick, $last_update, $direction = 0, $onlyheader = false)
143         {
144                 $a = get_app();
145
146                 $sitefeed    = ((strlen($owner_nick)) ? false : true); // not yet implemented, need to rewrite huge chunks of following logic
147                 $public_feed = (($dfrn_id) ? false : true);
148                 $starred     = false;   // not yet implemented, possible security issues
149                 $converse    = false;
150
151                 if ($public_feed && $a->argc > 2) {
152                         for ($x = 2; $x < $a->argc; $x++) {
153                                 if ($a->argv[$x] == 'converse') {
154                                         $converse = true;
155                                 }
156                                 if ($a->argv[$x] == 'starred') {
157                                         $starred = true;
158                                 }
159                                 if ($a->argv[$x] == 'category' && $a->argc > ($x + 1) && strlen($a->argv[$x+1])) {
160                                         $category = $a->argv[$x+1];
161                                 }
162                         }
163                 }
164
165                 // default permissions - anonymous user
166
167                 $sql_extra = " AND NOT `item`.`private` ";
168
169                 $r = q(
170                         "SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`, `user`.`account-type`
171                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
172                         WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
173                         DBA::escape($owner_nick)
174                 );
175
176                 if (! DBA::isResult($r)) {
177                         logger(sprintf('No contact found for nickname=%d', $owner_nick), LOGGER_WARNING);
178                         killme();
179                 }
180
181                 $owner = $r[0];
182                 $owner_id = $owner['uid'];
183                 $owner_nick = $owner['nickname'];
184
185                 $sql_post_table = "";
186
187                 if (! $public_feed) {
188                         $sql_extra = '';
189                         switch ($direction) {
190                                 case (-1):
191                                         $sql_extra = sprintf(" AND `issued-id` = '%s' ", DBA::escape($dfrn_id));
192                                         $my_id = $dfrn_id;
193                                         break;
194                                 case 0:
195                                         $sql_extra = sprintf(" AND `issued-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
196                                         $my_id = '1:' . $dfrn_id;
197                                         break;
198                                 case 1:
199                                         $sql_extra = sprintf(" AND `dfrn-id` = '%s' AND `duplex` = 1 ", DBA::escape($dfrn_id));
200                                         $my_id = '0:' . $dfrn_id;
201                                         break;
202                                 default:
203                                         return false;
204                                         break; // NOTREACHED
205                         }
206
207                         $r = q(
208                                 "SELECT * FROM `contact` WHERE NOT `blocked` AND `contact`.`uid` = %d $sql_extra LIMIT 1",
209                                 intval($owner_id)
210                         );
211
212                         if (! DBA::isResult($r)) {
213                                 logger(sprintf('No contact found for uid=%d', $owner_id), LOGGER_WARNING);
214                                 killme();
215                         }
216
217                         $contact = $r[0];
218                         include_once 'include/security.php';
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)
1167         {
1168                 $a = get_app();
1169
1170                 // At first try the Diaspora transport layer
1171                 $ret = self::transmit($owner, $contact, $atom);
1172                 if ($ret >= 200) {
1173                         logger('Delivery via Diaspora transport layer was successful with status ' . $ret);
1174                         return $ret;
1175                 }
1176
1177                 $idtosend = $orig_id = (($contact['dfrn-id']) ? $contact['dfrn-id'] : $contact['issued-id']);
1178
1179                 if ($contact['duplex'] && $contact['dfrn-id']) {
1180                         $idtosend = '0:' . $orig_id;
1181                 }
1182                 if ($contact['duplex'] && $contact['issued-id']) {
1183                         $idtosend = '1:' . $orig_id;
1184                 }
1185
1186                 $rino = Config::get('system', 'rino_encrypt');
1187                 $rino = intval($rino);
1188
1189                 logger("Local rino version: ". $rino, LOGGER_DEBUG);
1190
1191                 $ssl_val = intval(Config::get('system', 'ssl_policy'));
1192                 $ssl_policy = '';
1193
1194                 switch ($ssl_val) {
1195                         case SSL_POLICY_FULL:
1196                                 $ssl_policy = 'full';
1197                                 break;
1198                         case SSL_POLICY_SELFSIGN:
1199                                 $ssl_policy = 'self';
1200                                 break;
1201                         case SSL_POLICY_NONE:
1202                         default:
1203                                 $ssl_policy = 'none';
1204                                 break;
1205                 }
1206
1207                 $url = $contact['notify'] . '&dfrn_id=' . $idtosend . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . (($rino) ? '&rino='.$rino : '');
1208
1209                 logger('dfrn_deliver: ' . $url);
1210
1211                 $ret = Network::curl($url);
1212
1213                 if (!empty($ret["errno"]) && ($ret['errno'] == CURLE_OPERATION_TIMEDOUT)) {
1214                         Contact::markForArchival($contact);
1215                         return -2; // timed out
1216                 }
1217
1218                 $xml = $ret['body'];
1219
1220                 $curl_stat = $a->get_curl_code();
1221                 if (empty($curl_stat)) {
1222                         Contact::markForArchival($contact);
1223                         return -3; // timed out
1224                 }
1225
1226                 logger('dfrn_deliver: ' . $xml, LOGGER_DATA);
1227
1228                 if (empty($xml)) {
1229                         Contact::markForArchival($contact);
1230                         return 3;
1231                 }
1232
1233                 if (strpos($xml, '<?xml') === false) {
1234                         logger('dfrn_deliver: no valid XML returned');
1235                         logger('dfrn_deliver: returned XML: ' . $xml, LOGGER_DATA);
1236                         Contact::markForArchival($contact);
1237                         return 3;
1238                 }
1239
1240                 $res = XML::parseString($xml);
1241
1242                 if (!is_object($res) || (intval($res->status) != 0) || !strlen($res->challenge) || !strlen($res->dfrn_id)) {
1243                         Contact::markForArchival($contact);
1244
1245                         if (empty($res->status)) {
1246                                 $status = 3;
1247                         } else {
1248                                 $status = $res->status;
1249                         }
1250
1251                         return $status;
1252                 }
1253
1254                 $postvars     = [];
1255                 $sent_dfrn_id = hex2bin((string) $res->dfrn_id);
1256                 $challenge    = hex2bin((string) $res->challenge);
1257                 $perm         = (($res->perm) ? $res->perm : null);
1258                 $dfrn_version = (float) (($res->dfrn_version) ? $res->dfrn_version : 2.0);
1259                 $rino_remote_version = intval($res->rino);
1260                 $page         = (($owner['page-flags'] == Contact::PAGE_COMMUNITY) ? 1 : 0);
1261
1262                 logger("Remote rino version: ".$rino_remote_version." for ".$contact["url"], LOGGER_DEBUG);
1263
1264                 if ($owner['page-flags'] == Contact::PAGE_PRVGROUP) {
1265                         $page = 2;
1266                 }
1267
1268                 $final_dfrn_id = '';
1269
1270                 if ($perm) {
1271                         if ((($perm == 'rw') && !intval($contact['writable']))
1272                                 || (($perm == 'r') && intval($contact['writable']))
1273                         ) {
1274                                 DBA::update('contact', ['writable' => ($perm == 'rw')], ['id' => $contact['id']]);
1275
1276                                 $contact['writable'] = (string) 1 - intval($contact['writable']);
1277                         }
1278                 }
1279
1280                 if (($contact['duplex'] && strlen($contact['pubkey']))
1281                         || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1282                         || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1283                 ) {
1284                         openssl_public_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['pubkey']);
1285                         openssl_public_decrypt($challenge, $postvars['challenge'], $contact['pubkey']);
1286                 } else {
1287                         openssl_private_decrypt($sent_dfrn_id, $final_dfrn_id, $contact['prvkey']);
1288                         openssl_private_decrypt($challenge, $postvars['challenge'], $contact['prvkey']);
1289                 }
1290
1291                 $final_dfrn_id = substr($final_dfrn_id, 0, strpos($final_dfrn_id, '.'));
1292
1293                 if (strpos($final_dfrn_id, ':') == 1) {
1294                         $final_dfrn_id = substr($final_dfrn_id, 2);
1295                 }
1296
1297                 if ($final_dfrn_id != $orig_id) {
1298                         logger('dfrn_deliver: wrong dfrn_id.');
1299                         // did not decode properly - cannot trust this site
1300                         Contact::markForArchival($contact);
1301                         return 3;
1302                 }
1303
1304                 $postvars['dfrn_id']      = $idtosend;
1305                 $postvars['dfrn_version'] = DFRN_PROTOCOL_VERSION;
1306                 if ($dissolve) {
1307                         $postvars['dissolve'] = '1';
1308                 }
1309
1310                 if ((($contact['rel']) && ($contact['rel'] != Contact::SHARING) && (! $contact['blocked'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1311                         $postvars['data'] = $atom;
1312                         $postvars['perm'] = 'rw';
1313                 } else {
1314                         $postvars['data'] = str_replace('<dfrn:comment-allow>1', '<dfrn:comment-allow>0', $atom);
1315                         $postvars['perm'] = 'r';
1316                 }
1317
1318                 $postvars['ssl_policy'] = $ssl_policy;
1319
1320                 if ($page) {
1321                         $postvars['page'] = $page;
1322                 }
1323
1324
1325                 if ($rino > 0 && $rino_remote_version > 0 && (! $dissolve)) {
1326                         logger('rino version: '. $rino_remote_version);
1327
1328                         switch ($rino_remote_version) {
1329                                 case 1:
1330                                         $key = openssl_random_pseudo_bytes(16);
1331                                         $data = self::aesEncrypt($postvars['data'], $key);
1332                                         break;
1333
1334                                 default:
1335                                         logger("rino: invalid requested version '$rino_remote_version'");
1336                                         Contact::markForArchival($contact);
1337                                         return -8;
1338                         }
1339
1340                         $postvars['rino'] = $rino_remote_version;
1341                         $postvars['data'] = bin2hex($data);
1342
1343                         if ($dfrn_version >= 2.1) {
1344                                 if (($contact['duplex'] && strlen($contact['pubkey']))
1345                                         || ($owner['page-flags'] == Contact::PAGE_COMMUNITY && strlen($contact['pubkey']))
1346                                         || ($contact['rel'] == Contact::SHARING && strlen($contact['pubkey']))
1347                                 ) {
1348                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1349                                 } else {
1350                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1351                                 }
1352                         } else {
1353                                 if (($contact['duplex'] && strlen($contact['prvkey'])) || ($owner['page-flags'] == Contact::PAGE_COMMUNITY)) {
1354                                         openssl_private_encrypt($key, $postvars['key'], $contact['prvkey']);
1355                                 } else {
1356                                         openssl_public_encrypt($key, $postvars['key'], $contact['pubkey']);
1357                                 }
1358                         }
1359
1360                         logger('md5 rawkey ' . md5($postvars['key']));
1361
1362                         $postvars['key'] = bin2hex($postvars['key']);
1363                 }
1364
1365
1366                 logger('dfrn_deliver: ' . "SENDING: " . print_r($postvars, true), LOGGER_DATA);
1367
1368                 $xml = Network::post($contact['notify'], $postvars);
1369
1370                 logger('dfrn_deliver: ' . "RECEIVED: " . $xml, LOGGER_DATA);
1371
1372                 $curl_stat = $a->get_curl_code();
1373                 if (empty($curl_stat) || empty($xml)) {
1374                         Contact::markForArchival($contact);
1375                         return -9; // timed out
1376                 }
1377
1378                 if (($curl_stat == 503) && stristr($a->get_curl_headers(), 'retry-after')) {
1379                         Contact::markForArchival($contact);
1380                         return -10;
1381                 }
1382
1383                 if (strpos($xml, '<?xml') === false) {
1384                         logger('dfrn_deliver: phase 2: no valid XML returned');
1385                         logger('dfrn_deliver: phase 2: returned XML: ' . $xml, LOGGER_DATA);
1386                         Contact::markForArchival($contact);
1387                         return 3;
1388                 }
1389
1390                 $res = XML::parseString($xml);
1391
1392                 if (!isset($res->status)) {
1393                         Contact::markForArchival($contact);
1394                         return -11;
1395                 }
1396
1397                 // Possibly old servers had returned an empty value when everything was okay
1398                 if (empty($res->status)) {
1399                         $res->status = 200;
1400                 }
1401
1402                 if (!empty($res->message)) {
1403                         logger('Delivery returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1404                 }
1405
1406                 if (($res->status >= 200) && ($res->status <= 299)) {
1407                         Contact::unmarkForArchival($contact);
1408                 }
1409
1410                 return intval($res->status);
1411         }
1412
1413         /**
1414          * @brief Transmits atom content to the contacts via the Diaspora transport layer
1415          *
1416          * @param array  $owner    Owner record
1417          * @param array  $contact  Contact record of the receiver
1418          * @param string $atom     Content that will be transmitted
1419          *
1420          * @return int Deliver status. Negative values mean an error.
1421          */
1422         public static function transmit($owner, $contact, $atom, $public_batch = false)
1423         {
1424                 $a = get_app();
1425
1426                 if (!$public_batch) {
1427                         if (empty($contact['addr'])) {
1428                                 logger('Empty contact handle for ' . $contact['id'] . ' - ' . $contact['url'] . ' - trying to update it.');
1429                                 if (Contact::updateFromProbe($contact['id'])) {
1430                                         $new_contact = DBA::selectFirst('contact', ['addr'], ['id' => $contact['id']]);
1431                                         $contact['addr'] = $new_contact['addr'];
1432                                 }
1433
1434                                 if (empty($contact['addr'])) {
1435                                         logger('Unable to find contact handle for ' . $contact['id'] . ' - ' . $contact['url']);
1436                                         Contact::markForArchival($contact);
1437                                         return -21;
1438                                 }
1439                         }
1440
1441                         $fcontact = Diaspora::personByHandle($contact['addr']);
1442                         if (empty($fcontact)) {
1443                                 logger('Unable to find contact details for ' . $contact['id'] . ' - ' . $contact['addr']);
1444                                 Contact::markForArchival($contact);
1445                                 return -22;
1446                         }
1447                         $pubkey = $fcontact['pubkey'];
1448                 } else {
1449                         $pubkey = '';
1450                 }
1451
1452                 $envelope = Diaspora::buildMessage($atom, $owner, $contact, $owner['uprvkey'], $pubkey, $public_batch);
1453
1454                 // Create the endpoint for public posts. This is some WIP and should later be added to the probing
1455                 if ($public_batch && empty($contact["batch"])) {
1456                         $parts = parse_url($contact["notify"]);
1457                         $path_parts = explode('/', $parts['path']);
1458                         array_pop($path_parts);
1459                         $parts['path'] =  implode('/', $path_parts);
1460                         $contact["batch"] = Network::unparseURL($parts);
1461                 }
1462
1463                 $dest_url = ($public_batch ? $contact["batch"] : $contact["notify"]);
1464
1465                 $content_type = ($public_batch ? "application/magic-envelope+xml" : "application/json");
1466
1467                 $xml = Network::post($dest_url, $envelope, ["Content-Type: ".$content_type]);
1468
1469                 $curl_stat = $a->get_curl_code();
1470                 if (empty($curl_stat) || empty($xml)) {
1471                         logger('Empty answer from ' . $contact['id'] . ' - ' . $dest_url);
1472                         Contact::markForArchival($contact);
1473                         return -9; // timed out
1474                 }
1475
1476                 if (($curl_stat == 503) && (stristr($a->get_curl_headers(), 'retry-after'))) {
1477                         Contact::markForArchival($contact);
1478                         return -10;
1479                 }
1480
1481                 if (strpos($xml, '<?xml') === false) {
1482                         logger('No valid XML returned from ' . $contact['id'] . ' - ' . $dest_url);
1483                         logger('Returned XML: ' . $xml, LOGGER_DATA);
1484                         Contact::markForArchival($contact);
1485                         return 3;
1486                 }
1487
1488                 $res = XML::parseString($xml);
1489
1490                 if (empty($res->status)) {
1491                         Contact::markForArchival($contact);
1492                         return -23;
1493                 }
1494
1495                 if (!empty($res->message)) {
1496                         logger('Transmit to ' . $dest_url . ' returned status '.$res->status.' - '.$res->message, LOGGER_DEBUG);
1497                 }
1498
1499                 if (($res->status >= 200) && ($res->status <= 299)) {
1500                         Contact::unmarkForArchival($contact);
1501                 }
1502
1503                 return intval($res->status);
1504         }
1505
1506         /**
1507          * @brief Add new birthday event for this person
1508          *
1509          * @param array  $contact  Contact record
1510          * @param string $birthday Birthday of the contact
1511          * @return void
1512          * @todo Add array type-hint for $contact
1513          */
1514         private static function birthdayEvent($contact, $birthday)
1515         {
1516                 // Check for duplicates
1517                 $condition = ['uid' => $contact['uid'], 'cid' => $contact['id'],
1518                         'start' => DateTimeFormat::utc($birthday), 'type' => 'birthday'];
1519                 if (DBA::exists('event', $condition)) {
1520                         return;
1521                 }
1522
1523                 logger('updating birthday: ' . $birthday . ' for contact ' . $contact['id']);
1524
1525                 $bdtext = L10n::t('%s\'s birthday', $contact['name']);
1526                 $bdtext2 = L10n::t('Happy Birthday %s', ' [url=' . $contact['url'] . ']' . $contact['name'] . '[/url]');
1527
1528                 $r = q(
1529                         "INSERT INTO `event` (`uid`,`cid`,`created`,`edited`,`start`,`finish`,`summary`,`desc`,`type`)
1530                         VALUES ( %d, %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s') ",
1531                         intval($contact['uid']),
1532                         intval($contact['id']),
1533                         DBA::escape(DateTimeFormat::utcNow()),
1534                         DBA::escape(DateTimeFormat::utcNow()),
1535                         DBA::escape(DateTimeFormat::utc($birthday)),
1536                         DBA::escape(DateTimeFormat::utc($birthday . ' + 1 day ')),
1537                         DBA::escape($bdtext),
1538                         DBA::escape($bdtext2),
1539                         DBA::escape('birthday')
1540                 );
1541         }
1542
1543         /**
1544          * @brief Fetch the author data from head or entry items
1545          *
1546          * @param object $xpath     XPath object
1547          * @param object $context   In which context should the data be searched
1548          * @param array  $importer  Record of the importer user mixed with contact of the content
1549          * @param string $element   Element name from which the data is fetched
1550          * @param bool   $onlyfetch Should the data only be fetched or should it update the contact record as well
1551          * @param string $xml       optional, default empty
1552          *
1553          * @return array Relevant data of the author
1554          * @todo Find good type-hints for all parameter
1555          */
1556         private static function fetchauthor($xpath, $context, $importer, $element, $onlyfetch, $xml = "")
1557         {
1558                 $author = [];
1559                 $author["name"] = XML::getFirstNodeValue($xpath, $element."/atom:name/text()", $context);
1560                 $author["link"] = XML::getFirstNodeValue($xpath, $element."/atom:uri/text()", $context);
1561
1562                 $fields = ['id', 'uid', 'url', 'network', 'avatar-date', 'avatar', 'name-date', 'uri-date', 'addr',
1563                         'name', 'nick', 'about', 'location', 'keywords', 'xmpp', 'bdyear', 'bd', 'hidden', 'contact-type'];
1564                 $condition = ["`uid` = ? AND `nurl` = ? AND `network` != ?",
1565                         $importer["importer_uid"], normalise_link($author["link"]), Protocol::STATUSNET];
1566                 $contact_old = DBA::selectFirst('contact', $fields, $condition);
1567
1568                 if (DBA::isResult($contact_old)) {
1569                         $author["contact-id"] = $contact_old["id"];
1570                         $author["network"] = $contact_old["network"];
1571                 } else {
1572                         if (!$onlyfetch) {
1573                                 logger("Contact ".$author["link"]." wasn't found for user ".$importer["importer_uid"]." XML: ".$xml, LOGGER_DEBUG);
1574                         }
1575
1576                         $author["contact-unknown"] = true;
1577                         $author["contact-id"] = $importer["id"];
1578                         $author["network"] = $importer["network"];
1579                         $onlyfetch = true;
1580                 }
1581
1582                 // Until now we aren't serving different sizes - but maybe later
1583                 $avatarlist = [];
1584                 /// @todo check if "avatar" or "photo" would be the best field in the specification
1585                 $avatars = $xpath->query($element . "/atom:link[@rel='avatar']", $context);
1586                 foreach ($avatars as $avatar) {
1587                         $href = "";
1588                         $width = 0;
1589                         foreach ($avatar->attributes as $attributes) {
1590                                 /// @TODO Rewrite these similar if() to one switch
1591                                 if ($attributes->name == "href") {
1592                                         $href = $attributes->textContent;
1593                                 }
1594                                 if ($attributes->name == "width") {
1595                                         $width = $attributes->textContent;
1596                                 }
1597                                 if ($attributes->name == "updated") {
1598                                         $author["avatar-date"] = $attributes->textContent;
1599                                 }
1600                         }
1601                         if (($width > 0) && ($href != "")) {
1602                                 $avatarlist[$width] = $href;
1603                         }
1604                 }
1605
1606                 if (count($avatarlist) > 0) {
1607                         krsort($avatarlist);
1608                         $author["avatar"] = current($avatarlist);
1609                 }
1610
1611                 if (empty($author['avatar']) && !empty($author['link'])) {
1612                         $cid = Contact::getIdForURL($author['link'], 0);
1613                         if (!empty($cid)) {
1614                                 $contact = DBA::selectFirst('contact', ['avatar'], ['id' => $cid]);
1615                                 if (DBA::isResult($contact)) {
1616                                         $author['avatar'] = $contact['avatar'];
1617                                 }
1618                         }
1619                 }
1620
1621                 if (DBA::isResult($contact_old) && !$onlyfetch) {
1622                         logger("Check if contact details for contact " . $contact_old["id"] . " (" . $contact_old["nick"] . ") have to be updated.", LOGGER_DEBUG);
1623
1624                         $poco = ["url" => $contact_old["url"]];
1625
1626                         // When was the last change to name or uri?
1627                         $name_element = $xpath->query($element . "/atom:name", $context)->item(0);
1628                         foreach ($name_element->attributes as $attributes) {
1629                                 if ($attributes->name == "updated") {
1630                                         $poco["name-date"] = $attributes->textContent;
1631                                 }
1632                         }
1633
1634                         $link_element = $xpath->query($element . "/atom:link", $context)->item(0);
1635                         foreach ($link_element->attributes as $attributes) {
1636                                 if ($attributes->name == "updated") {
1637                                         $poco["uri-date"] = $attributes->textContent;
1638                                 }
1639                         }
1640
1641                         // Update contact data
1642                         $value = XML::getFirstNodeValue($xpath, $element . "/dfrn:handle/text()", $context);
1643                         if ($value != "") {
1644                                 $poco["addr"] = $value;
1645                         }
1646
1647                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:displayName/text()", $context);
1648                         if ($value != "") {
1649                                 $poco["name"] = $value;
1650                         }
1651
1652                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:preferredUsername/text()", $context);
1653                         if ($value != "") {
1654                                 $poco["nick"] = $value;
1655                         }
1656
1657                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:note/text()", $context);
1658                         if ($value != "") {
1659                                 $poco["about"] = $value;
1660                         }
1661
1662                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:address/poco:formatted/text()", $context);
1663                         if ($value != "") {
1664                                 $poco["location"] = $value;
1665                         }
1666
1667                         /// @todo Only search for elements with "poco:type" = "xmpp"
1668                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:ims/poco:value/text()", $context);
1669                         if ($value != "") {
1670                                 $poco["xmpp"] = $value;
1671                         }
1672
1673                         /// @todo Add support for the following fields that we don't support by now in the contact table:
1674                         /// - poco:utcOffset
1675                         /// - poco:urls
1676                         /// - poco:locality
1677                         /// - poco:region
1678                         /// - poco:country
1679
1680                         // If the "hide" element is present then the profile isn't searchable.
1681                         $hide = intval(XML::getFirstNodeValue($xpath, $element . "/dfrn:hide/text()", $context) == "true");
1682
1683                         logger("Hidden status for contact " . $contact_old["url"] . ": " . $hide, LOGGER_DEBUG);
1684
1685                         // If the contact isn't searchable then set the contact to "hidden".
1686                         // Problem: This can be manually overridden by the user.
1687                         if ($hide) {
1688                                 $contact_old["hidden"] = true;
1689                         }
1690
1691                         // Save the keywords into the contact table
1692                         $tags = [];
1693                         $tagelements = $xpath->evaluate($element . "/poco:tags/text()", $context);
1694                         foreach ($tagelements as $tag) {
1695                                 $tags[$tag->nodeValue] = $tag->nodeValue;
1696                         }
1697
1698                         if (count($tags)) {
1699                                 $poco["keywords"] = implode(", ", $tags);
1700                         }
1701
1702                         // "dfrn:birthday" contains the birthday converted to UTC
1703                         $birthday = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1704
1705                         if (strtotime($birthday) > time()) {
1706                                 $bd_timestamp = strtotime($birthday);
1707
1708                                 $poco["bdyear"] = date("Y", $bd_timestamp);
1709                         }
1710
1711                         // "poco:birthday" is the birthday in the format "yyyy-mm-dd"
1712                         $value = XML::getFirstNodeValue($xpath, $element . "/poco:birthday/text()", $context);
1713
1714                         if (!in_array($value, ["", "0000-00-00", "0001-01-01"])) {
1715                                 $bdyear = date("Y");
1716                                 $value = str_replace("0000", $bdyear, $value);
1717
1718                                 if (strtotime($value) < time()) {
1719                                         $value = str_replace($bdyear, $bdyear + 1, $value);
1720                                         $bdyear = $bdyear + 1;
1721                                 }
1722
1723                                 $poco["bd"] = $value;
1724                         }
1725
1726                         $contact = array_merge($contact_old, $poco);
1727
1728                         if ($contact_old["bdyear"] != $contact["bdyear"]) {
1729                                 self::birthdayEvent($contact, $birthday);
1730                         }
1731
1732                         // Get all field names
1733                         $fields = [];
1734                         foreach ($contact_old as $field => $data) {
1735                                 $fields[$field] = $data;
1736                         }
1737
1738                         unset($fields["id"]);
1739                         unset($fields["uid"]);
1740                         unset($fields["url"]);
1741                         unset($fields["avatar-date"]);
1742                         unset($fields["avatar"]);
1743                         unset($fields["name-date"]);
1744                         unset($fields["uri-date"]);
1745
1746                         $update = false;
1747                         // Update check for this field has to be done differently
1748                         $datefields = ["name-date", "uri-date"];
1749                         foreach ($datefields as $field) {
1750                                 if (strtotime($contact[$field]) > strtotime($contact_old[$field])) {
1751                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1752                                         $update = true;
1753                                 }
1754                         }
1755
1756                         foreach ($fields as $field => $data) {
1757                                 if ($contact[$field] != $contact_old[$field]) {
1758                                         logger("Difference for contact " . $contact["id"] . " in field '" . $field . "'. New value: '" . $contact[$field] . "', old value '" . $contact_old[$field] . "'", LOGGER_DEBUG);
1759                                         $update = true;
1760                                 }
1761                         }
1762
1763                         if ($update) {
1764                                 logger("Update contact data for contact " . $contact["id"] . " (" . $contact["nick"] . ")", LOGGER_DEBUG);
1765
1766                                 q(
1767                                         "UPDATE `contact` SET `name` = '%s', `nick` = '%s', `about` = '%s', `location` = '%s',
1768                                         `addr` = '%s', `keywords` = '%s', `bdyear` = '%s', `bd` = '%s', `hidden` = %d,
1769                                         `xmpp` = '%s', `name-date`  = '%s', `uri-date` = '%s'
1770                                         WHERE `id` = %d AND `network` = '%s'",
1771                                         DBA::escape($contact["name"]), DBA::escape($contact["nick"]), DBA::escape($contact["about"]),   DBA::escape($contact["location"]),
1772                                         DBA::escape($contact["addr"]), DBA::escape($contact["keywords"]), DBA::escape($contact["bdyear"]),
1773                                         DBA::escape($contact["bd"]), intval($contact["hidden"]), DBA::escape($contact["xmpp"]),
1774                                         DBA::escape(DateTimeFormat::utc($contact["name-date"])), DBA::escape(DateTimeFormat::utc($contact["uri-date"])),
1775                                         intval($contact["id"]), DBA::escape($contact["network"])
1776                                 );
1777                         }
1778
1779                         Contact::updateAvatar(
1780                                 $author['avatar'],
1781                                 $importer['importer_uid'],
1782                                 $contact['id'],
1783                                 (strtotime($contact['avatar-date']) > strtotime($contact_old['avatar-date']) || ($author['avatar'] != $contact_old['avatar']))
1784                         );
1785
1786                         /*
1787                          * The generation is a sign for the reliability of the provided data.
1788                          * It is used in the socgraph.php to prevent that old contact data
1789                          * that was relayed over several servers can overwrite contact
1790                          * data that we received directly.
1791                          */
1792
1793                         $poco["generation"] = 2;
1794                         $poco["photo"] = $author["avatar"];
1795                         $poco["hide"] = $hide;
1796                         $poco["contact-type"] = $contact["contact-type"];
1797                         $gcid = GContact::update($poco);
1798
1799                         GContact::link($gcid, $importer["importer_uid"], $contact["id"]);
1800                 }
1801
1802                 return $author;
1803         }
1804
1805         /**
1806          * @brief Transforms activity objects into an XML string
1807          *
1808          * @param object $xpath    XPath object
1809          * @param object $activity Activity object
1810          * @param string $element  element name
1811          *
1812          * @return string XML string
1813          * @todo Find good type-hints for all parameter
1814          */
1815         private static function transformActivity($xpath, $activity, $element)
1816         {
1817                 if (!is_object($activity)) {
1818                         return "";
1819                 }
1820
1821                 $obj_doc = new DOMDocument("1.0", "utf-8");
1822                 $obj_doc->formatOutput = true;
1823
1824                 $obj_element = $obj_doc->createElementNS(NAMESPACE_ATOM1, $element);
1825
1826                 $activity_type = $xpath->query("activity:object-type/text()", $activity)->item(0)->nodeValue;
1827                 XML::addElement($obj_doc, $obj_element, "type", $activity_type);
1828
1829                 $id = $xpath->query("atom:id", $activity)->item(0);
1830                 if (is_object($id)) {
1831                         $obj_element->appendChild($obj_doc->importNode($id, true));
1832                 }
1833
1834                 $title = $xpath->query("atom:title", $activity)->item(0);
1835                 if (is_object($title)) {
1836                         $obj_element->appendChild($obj_doc->importNode($title, true));
1837                 }
1838
1839                 $links = $xpath->query("atom:link", $activity);
1840                 if (is_object($links)) {
1841                         foreach ($links as $link) {
1842                                 $obj_element->appendChild($obj_doc->importNode($link, true));
1843                         }
1844                 }
1845
1846                 $content = $xpath->query("atom:content", $activity)->item(0);
1847                 if (is_object($content)) {
1848                         $obj_element->appendChild($obj_doc->importNode($content, true));
1849                 }
1850
1851                 $obj_doc->appendChild($obj_element);
1852
1853                 $objxml = $obj_doc->saveXML($obj_element);
1854
1855                 /// @todo This isn't totally clean. We should find a way to transform the namespaces
1856                 $objxml = str_replace("<".$element.' xmlns="http://www.w3.org/2005/Atom">', "<".$element.">", $objxml);
1857                 return($objxml);
1858         }
1859
1860         /**
1861          * @brief Processes the mail elements
1862          *
1863          * @param object $xpath    XPath object
1864          * @param object $mail     mail elements
1865          * @param array  $importer Record of the importer user mixed with contact of the content
1866          * @return void
1867          * @todo Find good type-hints for all parameter
1868          */
1869         private static function processMail($xpath, $mail, $importer)
1870         {
1871                 logger("Processing mails");
1872
1873                 /// @TODO Rewrite this to one statement
1874                 $msg = [];
1875                 $msg["uid"] = $importer["importer_uid"];
1876                 $msg["from-name"] = $xpath->query("dfrn:sender/dfrn:name/text()", $mail)->item(0)->nodeValue;
1877                 $msg["from-url"] = $xpath->query("dfrn:sender/dfrn:uri/text()", $mail)->item(0)->nodeValue;
1878                 $msg["from-photo"] = $xpath->query("dfrn:sender/dfrn:avatar/text()", $mail)->item(0)->nodeValue;
1879                 $msg["contact-id"] = $importer["id"];
1880                 $msg["uri"] = $xpath->query("dfrn:id/text()", $mail)->item(0)->nodeValue;
1881                 $msg["parent-uri"] = $xpath->query("dfrn:in-reply-to/text()", $mail)->item(0)->nodeValue;
1882                 $msg["created"] = DateTimeFormat::utc($xpath->query("dfrn:sentdate/text()", $mail)->item(0)->nodeValue);
1883                 $msg["title"] = $xpath->query("dfrn:subject/text()", $mail)->item(0)->nodeValue;
1884                 $msg["body"] = $xpath->query("dfrn:content/text()", $mail)->item(0)->nodeValue;
1885                 $msg["seen"] = 0;
1886                 $msg["replied"] = 0;
1887
1888                 DBA::insert('mail', $msg);
1889
1890                 $msg["id"] = DBA::lastInsertId();
1891
1892                 // send notifications.
1893                 /// @TODO Arange this mess
1894                 $notif_params = [
1895                         "type" => NOTIFY_MAIL,
1896                         "notify_flags" => $importer["notify-flags"],
1897                         "language" => $importer["language"],
1898                         "to_name" => $importer["username"],
1899                         "to_email" => $importer["email"],
1900                         "uid" => $importer["importer_uid"],
1901                         "item" => $msg,
1902                         "source_name" => $msg["from-name"],
1903                         "source_link" => $importer["url"],
1904                         "source_photo" => $importer["thumb"],
1905                         "verb" => ACTIVITY_POST,
1906                         "otype" => "mail"
1907                 ];
1908
1909                 notification($notif_params);
1910
1911                 logger("Mail is processed, notification was sent.");
1912         }
1913
1914         /**
1915          * @brief Processes the suggestion elements
1916          *
1917          * @param object $xpath      XPath object
1918          * @param object $suggestion suggestion elements
1919          * @param array  $importer   Record of the importer user mixed with contact of the content
1920          * @return boolean
1921          * @todo Find good type-hints for all parameter
1922          */
1923         private static function processSuggestion($xpath, $suggestion, $importer)
1924         {
1925                 $a = get_app();
1926
1927                 logger("Processing suggestions");
1928
1929                 /// @TODO Rewrite this to one statement
1930                 $suggest = [];
1931                 $suggest["uid"] = $importer["importer_uid"];
1932                 $suggest["cid"] = $importer["id"];
1933                 $suggest["url"] = $xpath->query("dfrn:url/text()", $suggestion)->item(0)->nodeValue;
1934                 $suggest["name"] = $xpath->query("dfrn:name/text()", $suggestion)->item(0)->nodeValue;
1935                 $suggest["photo"] = $xpath->query("dfrn:photo/text()", $suggestion)->item(0)->nodeValue;
1936                 $suggest["request"] = $xpath->query("dfrn:request/text()", $suggestion)->item(0)->nodeValue;
1937                 $suggest["body"] = $xpath->query("dfrn:note/text()", $suggestion)->item(0)->nodeValue;
1938
1939                 // Does our member already have a friend matching this description?
1940
1941                 /*
1942                  * The valid result means the friend we're about to send a friend
1943                  * suggestion already has them in their contact, which means no further
1944                  * action is required.
1945                  *
1946                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1947                  */
1948                 $condition = ['name' => $suggest["name"], 'nurl' => normalise_link($suggest["url"]),
1949                         'uid' => $suggest["uid"]];
1950                 if (DBA::exists('contact', $condition)) {
1951                         return false;
1952                 }
1953
1954                 // Do we already have an fcontact record for this person?
1955
1956                 $fid = 0;
1957                 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1958                 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1959                 if (DBA::isResult($fcontact)) {
1960                         $fid = $fcontact["id"];
1961
1962                         // OK, we do. Do we already have an introduction for this person?
1963                         if (DBA::exists('intro', ['uid' => $suggest["uid"], 'fid' => $fid])) {
1964                                 /*
1965                                  * The valid result means the friend we're about to send a friend
1966                                  * suggestion already has them in their contact, which means no further
1967                                  * action is required.
1968                                  *
1969                                  * @see https://github.com/friendica/friendica/pull/3254#discussion_r107315246
1970                                  */
1971                                 return false;
1972                         }
1973                 }
1974                 if (!$fid) {
1975                         $r = q(
1976                                 "INSERT INTO `fcontact` (`name`,`url`,`photo`,`request`) VALUES ('%s', '%s', '%s', '%s')",
1977                                 DBA::escape($suggest["name"]),
1978                                 DBA::escape($suggest["url"]),
1979                                 DBA::escape($suggest["photo"]),
1980                                 DBA::escape($suggest["request"])
1981                         );
1982                 }
1983
1984                 $condition = ['url' => $suggest["url"], 'name' => $suggest["name"], 'request' => $suggest["request"]];
1985                 $fcontact = DBA::selectFirst('fcontact', ['id'], $condition);
1986
1987                 /*
1988                  * If no record in fcontact is found, below INSERT statement will not
1989                  * link an introduction to it.
1990                  */
1991                 if (!DBA::isResult($fcontact)) {
1992                         // Database record did not get created. Quietly give up.
1993                         killme();
1994                 }
1995
1996                 $fid = $r[0]["id"];
1997
1998                 $hash = random_string();
1999
2000                 $r = q(
2001                         "INSERT INTO `intro` (`uid`, `fid`, `contact-id`, `note`, `hash`, `datetime`, `blocked`)
2002                         VALUES(%d, %d, %d, '%s', '%s', '%s', %d)",
2003                         intval($suggest["uid"]),
2004                         intval($fid),
2005                         intval($suggest["cid"]),
2006                         DBA::escape($suggest["body"]),
2007                         DBA::escape($hash),
2008                         DBA::escape(DateTimeFormat::utcNow()),
2009                         intval(0)
2010                 );
2011
2012                 notification(
2013                         [
2014                                 "type"         => NOTIFY_SUGGEST,
2015                                 "notify_flags" => $importer["notify-flags"],
2016                                 "language"     => $importer["language"],
2017                                 "to_name"      => $importer["username"],
2018                                 "to_email"     => $importer["email"],
2019                                 "uid"          => $importer["importer_uid"],
2020                                 "item"         => $suggest,
2021                                 "link"         => System::baseUrl()."/notifications/intros",
2022                                 "source_name"  => $importer["name"],
2023                                 "source_link"  => $importer["url"],
2024                                 "source_photo" => $importer["photo"],
2025                                 "verb"         => ACTIVITY_REQ_FRIEND,
2026                                 "otype"        => "intro"]
2027                 );
2028
2029                 return true;
2030         }
2031
2032         /**
2033          * @brief Processes the relocation elements
2034          *
2035          * @param object $xpath      XPath object
2036          * @param object $relocation relocation elements
2037          * @param array  $importer   Record of the importer user mixed with contact of the content
2038          * @return boolean
2039          * @todo Find good type-hints for all parameter
2040          */
2041         private static function processRelocation($xpath, $relocation, $importer)
2042         {
2043                 logger("Processing relocations");
2044
2045                 /// @TODO Rewrite this to one statement
2046                 $relocate = [];
2047                 $relocate["uid"] = $importer["importer_uid"];
2048                 $relocate["cid"] = $importer["id"];
2049                 $relocate["url"] = $xpath->query("dfrn:url/text()", $relocation)->item(0)->nodeValue;
2050                 $relocate["addr"] = $xpath->query("dfrn:addr/text()", $relocation)->item(0)->nodeValue;
2051                 $relocate["name"] = $xpath->query("dfrn:name/text()", $relocation)->item(0)->nodeValue;
2052                 $relocate["avatar"] = $xpath->query("dfrn:avatar/text()", $relocation)->item(0)->nodeValue;
2053                 $relocate["photo"] = $xpath->query("dfrn:photo/text()", $relocation)->item(0)->nodeValue;
2054                 $relocate["thumb"] = $xpath->query("dfrn:thumb/text()", $relocation)->item(0)->nodeValue;
2055                 $relocate["micro"] = $xpath->query("dfrn:micro/text()", $relocation)->item(0)->nodeValue;
2056                 $relocate["request"] = $xpath->query("dfrn:request/text()", $relocation)->item(0)->nodeValue;
2057                 $relocate["confirm"] = $xpath->query("dfrn:confirm/text()", $relocation)->item(0)->nodeValue;
2058                 $relocate["notify"] = $xpath->query("dfrn:notify/text()", $relocation)->item(0)->nodeValue;
2059                 $relocate["poll"] = $xpath->query("dfrn:poll/text()", $relocation)->item(0)->nodeValue;
2060                 $relocate["sitepubkey"] = $xpath->query("dfrn:sitepubkey/text()", $relocation)->item(0)->nodeValue;
2061
2062                 if (($relocate["avatar"] == "") && ($relocate["photo"] != "")) {
2063                         $relocate["avatar"] = $relocate["photo"];
2064                 }
2065
2066                 if ($relocate["addr"] == "") {
2067                         $relocate["addr"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$3@$2", $relocate["url"]);
2068                 }
2069
2070                 // update contact
2071                 $r = q(
2072                         "SELECT `photo`, `url` FROM `contact` WHERE `id` = %d AND `uid` = %d",
2073                         intval($importer["id"]),
2074                         intval($importer["importer_uid"])
2075                 );
2076
2077                 if (!DBA::isResult($r)) {
2078                         logger("Query failed to execute, no result returned in " . __FUNCTION__);
2079                         return false;
2080                 }
2081
2082                 $old = $r[0];
2083
2084                 // Update the gcontact entry
2085                 $relocate["server_url"] = preg_replace("=(https?://)(.*)/profile/(.*)=ism", "$1$2", $relocate["url"]);
2086
2087                 $fields = ['name' => $relocate["name"], 'photo' => $relocate["avatar"],
2088                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2089                         'addr' => $relocate["addr"], 'connect' => $relocate["addr"],
2090                         'notify' => $relocate["notify"], 'server_url' => $relocate["server_url"]];
2091                 DBA::update('gcontact', $fields, ['nurl' => normalise_link($old["url"])]);
2092
2093                 // Update the contact table. We try to find every entry.
2094                 $fields = ['name' => $relocate["name"], 'avatar' => $relocate["avatar"],
2095                         'url' => $relocate["url"], 'nurl' => normalise_link($relocate["url"]),
2096                         'addr' => $relocate["addr"], 'request' => $relocate["request"],
2097                         'confirm' => $relocate["confirm"], 'notify' => $relocate["notify"],
2098                         'poll' => $relocate["poll"], 'site-pubkey' => $relocate["sitepubkey"]];
2099                 $condition = ["(`id` = ?) OR (`nurl` = ?)", $importer["id"], normalise_link($old["url"])];
2100
2101                 DBA::update('contact', $fields, $condition);
2102
2103                 Contact::updateAvatar($relocate["avatar"], $importer["importer_uid"], $importer["id"], true);
2104
2105                 logger('Contacts are updated.');
2106
2107                 /// @TODO
2108                 /// merge with current record, current contents have priority
2109                 /// update record, set url-updated
2110                 /// update profile photos
2111                 /// schedule a scan?
2112                 return true;
2113         }
2114
2115         /**
2116          * @brief Updates an item
2117          *
2118          * @param array $current   the current item record
2119          * @param array $item      the new item record
2120          * @param array $importer  Record of the importer user mixed with contact of the content
2121          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2122          * @return mixed
2123          * @todo set proper type-hints (array?)
2124          */
2125         private static function updateContent($current, $item, $importer, $entrytype)
2126         {
2127                 $changed = false;
2128
2129                 if (self::isEditedTimestampNewer($current, $item)) {
2130                         // do not accept (ignore) an earlier edit than one we currently have.
2131                         if (DateTimeFormat::utc($item["edited"]) < $current["edited"]) {
2132                                 return false;
2133                         }
2134
2135                         $fields = ['title' => defaults($item, 'title', ''), 'body' => defaults($item, 'body', ''),
2136                                         'tag' => defaults($item, 'tag', ''), 'changed' => DateTimeFormat::utcNow(),
2137                                         'edited' => DateTimeFormat::utc($item["edited"])];
2138
2139                         $condition = ["`uri` = ? AND `uid` IN (0, ?)", $item["uri"], $importer["importer_uid"]];
2140                         Item::update($fields, $condition);
2141
2142                         $changed = true;
2143                 }
2144                 return $changed;
2145         }
2146
2147         /**
2148          * @brief Detects the entry type of the item
2149          *
2150          * @param array $importer Record of the importer user mixed with contact of the content
2151          * @param array $item     the new item record
2152          *
2153          * @return int Is it a toplevel entry, a comment or a relayed comment?
2154          * @todo set proper type-hints (array?)
2155          */
2156         private static function getEntryType($importer, $item)
2157         {
2158                 if ($item["parent-uri"] != $item["uri"]) {
2159                         $community = false;
2160
2161                         if ($importer["page-flags"] == Contact::PAGE_COMMUNITY || $importer["page-flags"] == Contact::PAGE_PRVGROUP) {
2162                                 $sql_extra = "";
2163                                 $community = true;
2164                                 logger("possible community action");
2165                         } else {
2166                                 $sql_extra = " AND `contact`.`self` AND `item`.`wall` ";
2167                         }
2168
2169                         // was the top-level post for this action written by somebody on this site?
2170                         // Specifically, the recipient?
2171
2172                         $is_a_remote_action = false;
2173
2174                         $parent = Item::selectFirst(['parent-uri'], ['uri' => $item["parent-uri"]]);
2175                         if (DBA::isResult($parent)) {
2176                                 $r = q(
2177                                         "SELECT `item`.`forum_mode`, `item`.`wall` FROM `item`
2178                                         INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
2179                                         WHERE `item`.`uri` = '%s' AND (`item`.`parent-uri` = '%s' OR `item`.`thr-parent` = '%s')
2180                                         AND `item`.`uid` = %d
2181                                         $sql_extra
2182                                         LIMIT 1",
2183                                         DBA::escape($parent["parent-uri"]),
2184                                         DBA::escape($parent["parent-uri"]),
2185                                         DBA::escape($parent["parent-uri"]),
2186                                         intval($importer["importer_uid"])
2187                                 );
2188                                 if (DBA::isResult($r)) {
2189                                         $is_a_remote_action = true;
2190                                 }
2191                         }
2192
2193                         /*
2194                          * Does this have the characteristics of a community or private group action?
2195                          * If it's an action to a wall post on a community/prvgroup page it's a
2196                          * valid community action. Also forum_mode makes it valid for sure.
2197                          * If neither, it's not.
2198                          */
2199                         if ($is_a_remote_action && $community && (!$r[0]["forum_mode"]) && (!$r[0]["wall"])) {
2200                                 $is_a_remote_action = false;
2201                                 logger("not a community action");
2202                         }
2203
2204                         if ($is_a_remote_action) {
2205                                 return DFRN::REPLY_RC;
2206                         } else {
2207                                 return DFRN::REPLY;
2208                         }
2209                 } else {
2210                         return DFRN::TOP_LEVEL;
2211                 }
2212         }
2213
2214         /**
2215          * @brief Send a "poke"
2216          *
2217          * @param array $item      the new item record
2218          * @param array $importer  Record of the importer user mixed with contact of the content
2219          * @param int   $posted_id The record number of item record that was just posted
2220          * @return void
2221          * @todo set proper type-hints (array?)
2222          */
2223         private static function doPoke($item, $importer, $posted_id)
2224         {
2225                 $verb = urldecode(substr($item["verb"], strpos($item["verb"], "#")+1));
2226                 if (!$verb) {
2227                         return;
2228                 }
2229                 $xo = XML::parseString($item["object"], false);
2230
2231                 if (($xo->type == ACTIVITY_OBJ_PERSON) && ($xo->id)) {
2232                         // somebody was poked/prodded. Was it me?
2233                         foreach ($xo->link as $l) {
2234                                 $atts = $l->attributes();
2235                                 switch ($atts["rel"]) {
2236                                         case "alternate":
2237                                                 $Blink = $atts["href"];
2238                                                 break;
2239                                         default:
2240                                                 break;
2241                                 }
2242                         }
2243
2244                         if ($Blink && link_compare($Blink, System::baseUrl() . "/profile/" . $importer["nickname"])) {
2245                                 $author = DBA::selectFirst('contact', ['name', 'thumb', 'url'], ['id' => $item['author-id']]);
2246
2247                                 // send a notification
2248                                 notification(
2249                                         [
2250                                         "type"         => NOTIFY_POKE,
2251                                         "notify_flags" => $importer["notify-flags"],
2252                                         "language"     => $importer["language"],
2253                                         "to_name"      => $importer["username"],
2254                                         "to_email"     => $importer["email"],
2255                                         "uid"          => $importer["importer_uid"],
2256                                         "item"         => $item,
2257                                         "link"         => System::baseUrl()."/display/".urlencode(Item::getGuidById($posted_id)),
2258                                         "source_name"  => $author["name"],
2259                                         "source_link"  => $author["url"],
2260                                         "source_photo" => $author["thumb"],
2261                                         "verb"         => $item["verb"],
2262                                         "otype"        => "person",
2263                                         "activity"     => $verb,
2264                                         "parent"       => $item["parent"]]
2265                                 );
2266                         }
2267                 }
2268         }
2269
2270         /**
2271          * @brief Processes several actions, depending on the verb
2272          *
2273          * @param int   $entrytype Is it a toplevel entry, a comment or a relayed comment?
2274          * @param array $importer  Record of the importer user mixed with contact of the content
2275          * @param array $item      the new item record
2276          * @param bool  $is_like   Is the verb a "like"?
2277          *
2278          * @return bool Should the processing of the entries be continued?
2279          * @todo set proper type-hints (array?)
2280          */
2281         private static function processVerbs($entrytype, $importer, &$item, &$is_like)
2282         {
2283                 logger("Process verb ".$item["verb"]." and object-type ".$item["object-type"]." for entrytype ".$entrytype, LOGGER_DEBUG);
2284
2285                 if (($entrytype == DFRN::TOP_LEVEL)) {
2286                         // The filling of the the "contact" variable is done for legcy reasons
2287                         // The functions below are partly used by ostatus.php as well - where we have this variable
2288                         $r = q("SELECT * FROM `contact` WHERE `id` = %d", intval($importer["id"]));
2289                         $contact = $r[0];
2290                         $nickname = $contact["nick"];
2291
2292                         // Big question: Do we need these functions? They were part of the "consume_feed" function.
2293                         // This function once was responsible for DFRN and OStatus.
2294                         if (activity_match($item["verb"], ACTIVITY_FOLLOW)) {
2295                                 logger("New follower");
2296                                 Contact::addRelationship($importer, $contact, $item, $nickname);
2297                                 return false;
2298                         }
2299                         if (activity_match($item["verb"], ACTIVITY_UNFOLLOW)) {
2300                                 logger("Lost follower");
2301                                 Contact::removeFollower($importer, $contact, $item);
2302                                 return false;
2303                         }
2304                         if (activity_match($item["verb"], ACTIVITY_REQ_FRIEND)) {
2305                                 logger("New friend request");
2306                                 Contact::addRelationship($importer, $contact, $item, $nickname, true);
2307                                 return false;
2308                         }
2309                         if (activity_match($item["verb"], ACTIVITY_UNFRIEND)) {
2310                                 logger("Lost sharer");
2311                                 Contact::removeSharer($importer, $contact, $item);
2312                                 return false;
2313                         }
2314                 } else {
2315                         if (($item["verb"] == ACTIVITY_LIKE)
2316                                 || ($item["verb"] == ACTIVITY_DISLIKE)
2317                                 || ($item["verb"] == ACTIVITY_ATTEND)
2318                                 || ($item["verb"] == ACTIVITY_ATTENDNO)
2319                                 || ($item["verb"] == ACTIVITY_ATTENDMAYBE)
2320                         ) {
2321                                 $is_like = true;
2322                                 $item["gravity"] = GRAVITY_ACTIVITY;
2323                                 // only one like or dislike per person
2324                                 // splitted into two queries for performance issues
2325                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2326                                         'verb' => $item["verb"], 'parent-uri' => $item["parent-uri"]];
2327                                 if (Item::exists($condition)) {
2328                                         return false;
2329                                 }
2330
2331                                 $condition = ['uid' => $item["uid"], 'author-id' => $item["author-id"], 'gravity' => GRAVITY_ACTIVITY,
2332                                         'verb' => $item["verb"], 'thr-parent' => $item["parent-uri"]];
2333                                 if (Item::exists($condition)) {
2334                                         return false;
2335                                 }
2336                         } else {
2337                                 $is_like = false;
2338                         }
2339
2340                         if (($item["verb"] == ACTIVITY_TAG) && ($item["object-type"] == ACTIVITY_OBJ_TAGTERM)) {
2341                                 $xo = XML::parseString($item["object"], false);
2342                                 $xt = XML::parseString($item["target"], false);
2343
2344                                 if ($xt->type == ACTIVITY_OBJ_NOTE) {
2345                                         $item_tag = Item::selectFirst(['id', 'tag'], ['uri' => $xt->id, 'uid' => $importer["importer_uid"]]);
2346
2347                                         if (!DBA::isResult($item_tag)) {
2348                                                 logger("Query failed to execute, no result returned in " . __FUNCTION__);
2349                                                 return false;
2350                                         }
2351
2352                                         // extract tag, if not duplicate, add to parent item
2353                                         if ($xo->content) {
2354                                                 if (!stristr($item_tag["tag"], trim($xo->content))) {
2355                                                         $tag = $item_tag["tag"] . (strlen($item_tag["tag"]) ? ',' : '') . '#[url=' . $xo->id . ']'. $xo->content . '[/url]';
2356                                                         Item::update(['tag' => $tag], ['id' => $item_tag["id"]]);
2357                                                 }
2358                                         }
2359                                 }
2360                         }
2361                 }
2362                 return true;
2363         }
2364
2365         /**
2366          * @brief Processes the link elements
2367          *
2368          * @param object $links link elements
2369          * @param array  $item  the item record
2370          * @return void
2371          * @todo set proper type-hints
2372          */
2373         private static function parseLinks($links, &$item)
2374         {
2375                 $rel = "";
2376                 $href = "";
2377                 $type = "";
2378                 $length = "0";
2379                 $title = "";
2380                 foreach ($links as $link) {
2381                         foreach ($link->attributes as $attributes) {
2382                                 switch ($attributes->name) {
2383                                         case "href"  : $href   = $attributes->textContent; break;
2384                                         case "rel"   : $rel    = $attributes->textContent; break;
2385                                         case "type"  : $type   = $attributes->textContent; break;
2386                                         case "length": $length = $attributes->textContent; break;
2387                                         case "title" : $title  = $attributes->textContent; break;
2388                                 }
2389                         }
2390                         if (($rel != "") && ($href != "")) {
2391                                 switch ($rel) {
2392                                         case "alternate":
2393                                                 $item["plink"] = $href;
2394                                                 break;
2395                                         case "enclosure":
2396                                                 $enclosure = $href;
2397                                                 if (strlen($item["attach"])) {
2398                                                         $item["attach"] .= ",";
2399                                                 }
2400
2401                                                 $item["attach"] .= '[attach]href="' . $href . '" length="' . $length . '" type="' . $type . '" title="' . $title . '"[/attach]';
2402                                                 break;
2403                                 }
2404                         }
2405                 }
2406         }
2407
2408         /**
2409          * @brief Processes the entry elements which contain the items and comments
2410          *
2411          * @param array  $header   Array of the header elements that always stay the same
2412          * @param object $xpath    XPath object
2413          * @param object $entry    entry elements
2414          * @param array  $importer Record of the importer user mixed with contact of the content
2415          * @param object $xml      xml
2416          * @return void
2417          * @todo Add type-hints
2418          */
2419         private static function processEntry($header, $xpath, $entry, $importer, $xml)
2420         {
2421                 logger("Processing entries");
2422
2423                 $item = $header;
2424
2425                 $item["protocol"] = Conversation::PARCEL_DFRN;
2426
2427                 $item["source"] = $xml;
2428
2429                 // Get the uri
2430                 $item["uri"] = XML::getFirstNodeValue($xpath, "atom:id/text()", $entry);
2431
2432                 $item["edited"] = XML::getFirstNodeValue($xpath, "atom:updated/text()", $entry);
2433
2434                 $current = Item::selectFirst(['id', 'uid', 'edited', 'body'],
2435                         ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]]
2436                 );
2437                 // Is there an existing item?
2438                 if (DBA::isResult($current) && !self::isEditedTimestampNewer($current, $item)) {
2439                         logger("Item ".$item["uri"]." (".$item['edited'].") already existed.", LOGGER_DEBUG);
2440                         return;
2441                 }
2442
2443                 // Fetch the owner
2444                 $owner = self::fetchauthor($xpath, $entry, $importer, "dfrn:owner", true);
2445
2446                 $owner_unknown = (isset($owner["contact-unknown"]) && $owner["contact-unknown"]);
2447
2448                 $item["owner-name"] = $owner["name"];
2449                 $item["owner-link"] = $owner["link"];
2450                 $item["owner-avatar"] = $owner["avatar"];
2451                 $item["owner-id"] = Contact::getIdForURL($owner["link"], 0);
2452
2453                 // fetch the author
2454                 $author = self::fetchauthor($xpath, $entry, $importer, "atom:author", true);
2455
2456                 $item["author-name"] = $author["name"];
2457                 $item["author-link"] = $author["link"];
2458                 $item["author-avatar"] = $author["avatar"];
2459                 $item["author-id"] = Contact::getIdForURL($author["link"], 0);
2460
2461                 $item["title"] = XML::getFirstNodeValue($xpath, "atom:title/text()", $entry);
2462
2463                 $item["created"] = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2464
2465                 $item["body"] = XML::getFirstNodeValue($xpath, "dfrn:env/text()", $entry);
2466                 $item["body"] = str_replace([' ',"\t","\r","\n"], ['','','',''], $item["body"]);
2467                 // make sure nobody is trying to sneak some html tags by us
2468                 $item["body"] = notags(base64url_decode($item["body"]));
2469
2470                 $item["body"] = BBCode::limitBodySize($item["body"]);
2471
2472                 /// @todo Do we really need this check for HTML elements? (It was copied from the old function)
2473                 if ((strpos($item['body'], '<') !== false) && (strpos($item['body'], '>') !== false)) {
2474                         $base_url = get_app()->get_baseurl();
2475                         $item['body'] = reltoabs($item['body'], $base_url);
2476
2477                         $item['body'] = html2bb_video($item['body']);
2478
2479                         $item['body'] = OEmbed::HTML2BBCode($item['body']);
2480
2481                         $config = HTMLPurifier_Config::createDefault();
2482                         $config->set('Cache.DefinitionImpl', null);
2483
2484                         // we shouldn't need a whitelist, because the bbcode converter
2485                         // will strip out any unsupported tags.
2486
2487                         $purifier = new HTMLPurifier($config);
2488                         $item['body'] = $purifier->purify($item['body']);
2489
2490                         $item['body'] = @HTML::toBBCode($item['body']);
2491                 }
2492
2493                 /// @todo We should check for a repeated post and if we know the repeated author.
2494
2495                 // We don't need the content element since "dfrn:env" is always present
2496                 //$item["body"] = $xpath->query("atom:content/text()", $entry)->item(0)->nodeValue;
2497
2498                 $item["location"] = XML::getFirstNodeValue($xpath, "dfrn:location/text()", $entry);
2499
2500                 $item["coord"] = XML::getFirstNodeValue($xpath, "georss:point", $entry);
2501
2502                 $item["private"] = XML::getFirstNodeValue($xpath, "dfrn:private/text()", $entry);
2503
2504                 $item["extid"] = XML::getFirstNodeValue($xpath, "dfrn:extid/text()", $entry);
2505
2506                 if (XML::getFirstNodeValue($xpath, "dfrn:bookmark/text()", $entry) == "true") {
2507                         $item["post-type"] = Item::PT_PAGE;
2508                 }
2509
2510                 $notice_info = $xpath->query("statusnet:notice_info", $entry);
2511                 if ($notice_info && ($notice_info->length > 0)) {
2512                         foreach ($notice_info->item(0)->attributes as $attributes) {
2513                                 if ($attributes->name == "source") {
2514                                         $item["app"] = strip_tags($attributes->textContent);
2515                                 }
2516                         }
2517                 }
2518
2519                 $item["guid"] = XML::getFirstNodeValue($xpath, "dfrn:diaspora_guid/text()", $entry);
2520
2521                 // We store the data from "dfrn:diaspora_signature" in a different table, this is done in "Item::insert"
2522                 $dsprsig = unxmlify(XML::getFirstNodeValue($xpath, "dfrn:diaspora_signature/text()", $entry));
2523                 if ($dsprsig != "") {
2524                         $item["dsprsig"] = $dsprsig;
2525                 }
2526
2527                 $item["verb"] = XML::getFirstNodeValue($xpath, "activity:verb/text()", $entry);
2528
2529                 if (XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry) != "") {
2530                         $item["object-type"] = XML::getFirstNodeValue($xpath, "activity:object-type/text()", $entry);
2531                 }
2532
2533                 $object = $xpath->query("activity:object", $entry)->item(0);
2534                 $item["object"] = self::transformActivity($xpath, $object, "object");
2535
2536                 if (trim($item["object"]) != "") {
2537                         $r = XML::parseString($item["object"], false);
2538                         if (isset($r->type)) {
2539                                 $item["object-type"] = $r->type;
2540                         }
2541                 }
2542
2543                 $target = $xpath->query("activity:target", $entry)->item(0);
2544                 $item["target"] = self::transformActivity($xpath, $target, "target");
2545
2546                 $categories = $xpath->query("atom:category", $entry);
2547                 if ($categories) {
2548                         foreach ($categories as $category) {
2549                                 $term = "";
2550                                 $scheme = "";
2551                                 foreach ($category->attributes as $attributes) {
2552                                         if ($attributes->name == "term") {
2553                                                 $term = $attributes->textContent;
2554                                         }
2555
2556                                         if ($attributes->name == "scheme") {
2557                                                 $scheme = $attributes->textContent;
2558                                         }
2559                                 }
2560
2561                                 if (($term != "") && ($scheme != "")) {
2562                                         $parts = explode(":", $scheme);
2563                                         if ((count($parts) >= 4) && (array_shift($parts) == "X-DFRN")) {
2564                                                 $termhash = array_shift($parts);
2565                                                 $termurl = implode(":", $parts);
2566
2567                                                 if (!empty($item["tag"])) {
2568                                                         $item["tag"] .= ",";
2569                                                 } else {
2570                                                         $item["tag"] = "";
2571                                                 }
2572
2573                                                 $item["tag"] .= $termhash . "[url=" . $termurl . "]" . $term . "[/url]";
2574                                         }
2575                                 }
2576                         }
2577                 }
2578
2579                 $enclosure = "";
2580
2581                 $links = $xpath->query("atom:link", $entry);
2582                 if ($links) {
2583                         self::parseLinks($links, $item);
2584                 }
2585
2586                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
2587
2588                 $conv = $xpath->query('ostatus:conversation', $entry);
2589                 if (is_object($conv->item(0))) {
2590                         foreach ($conv->item(0)->attributes as $attributes) {
2591                                 if ($attributes->name == "ref") {
2592                                         $item['conversation-uri'] = $attributes->textContent;
2593                                 }
2594                                 if ($attributes->name == "href") {
2595                                         $item['conversation-href'] = $attributes->textContent;
2596                                 }
2597                         }
2598                 }
2599
2600                 // Is it a reply or a top level posting?
2601                 $item["parent-uri"] = $item["uri"];
2602
2603                 $inreplyto = $xpath->query("thr:in-reply-to", $entry);
2604                 if (is_object($inreplyto->item(0))) {
2605                         foreach ($inreplyto->item(0)->attributes as $attributes) {
2606                                 if ($attributes->name == "ref") {
2607                                         $item["parent-uri"] = $attributes->textContent;
2608                                 }
2609                         }
2610                 }
2611
2612                 // Get the type of the item (Top level post, reply or remote reply)
2613                 $entrytype = self::getEntryType($importer, $item);
2614
2615                 // Now assign the rest of the values that depend on the type of the message
2616                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2617                         if (!isset($item["object-type"])) {
2618                                 $item["object-type"] = ACTIVITY_OBJ_COMMENT;
2619                         }
2620
2621                         if ($item["contact-id"] != $owner["contact-id"]) {
2622                                 $item["contact-id"] = $owner["contact-id"];
2623                         }
2624
2625                         if (($item["network"] != $owner["network"]) && ($owner["network"] != "")) {
2626                                 $item["network"] = $owner["network"];
2627                         }
2628
2629                         if ($item["contact-id"] != $author["contact-id"]) {
2630                                 $item["contact-id"] = $author["contact-id"];
2631                         }
2632
2633                         if (($item["network"] != $author["network"]) && ($author["network"] != "")) {
2634                                 $item["network"] = $author["network"];
2635                         }
2636                 }
2637
2638                 if ($entrytype == DFRN::REPLY_RC) {
2639                         $item["wall"] = 1;
2640                 } elseif ($entrytype == DFRN::TOP_LEVEL) {
2641                         if (!isset($item["object-type"])) {
2642                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
2643                         }
2644
2645                         // Is it an event?
2646                         if (($item["object-type"] == ACTIVITY_OBJ_EVENT) && !$owner_unknown) {
2647                                 logger("Item ".$item["uri"]." seems to contain an event.", LOGGER_DEBUG);
2648                                 $ev = Event::fromBBCode($item["body"]);
2649                                 if ((x($ev, "desc") || x($ev, "summary")) && x($ev, "start")) {
2650                                         logger("Event in item ".$item["uri"]." was found.", LOGGER_DEBUG);
2651                                         $ev["cid"]     = $importer["id"];
2652                                         $ev["uid"]     = $importer["importer_uid"];
2653                                         $ev["uri"]     = $item["uri"];
2654                                         $ev["edited"]  = $item["edited"];
2655                                         $ev["private"] = $item["private"];
2656                                         $ev["guid"]    = $item["guid"];
2657                                         $ev["plink"]   = $item["plink"];
2658
2659                                         $condition = ['uri' => $item["uri"], 'uid' => $importer["importer_uid"]];
2660                                         $event = DBA::selectFirst('event', ['id'], $condition);
2661                                         if (DBA::isResult($event)) {
2662                                                 $ev["id"] = $event["id"];
2663                                         }
2664
2665                                         $event_id = Event::store($ev);
2666                                         logger("Event ".$event_id." was stored", LOGGER_DEBUG);
2667                                         return;
2668                                 }
2669                         }
2670                 }
2671
2672                 if (!self::processVerbs($entrytype, $importer, $item, $is_like)) {
2673                         logger("Exiting because 'processVerbs' told us so", LOGGER_DEBUG);
2674                         return;
2675                 }
2676
2677                 // This check is done here to be able to receive connection requests in "processVerbs"
2678                 if (($entrytype == DFRN::TOP_LEVEL) && $owner_unknown) {
2679                         logger("Item won't be stored because user " . $importer["importer_uid"] . " doesn't follow " . $item["owner-link"] . ".", LOGGER_DEBUG);
2680                         return;
2681                 }
2682
2683
2684                 // Update content if 'updated' changes
2685                 if (DBA::isResult($current)) {
2686                         if (self::updateContent($current, $item, $importer, $entrytype)) {
2687                                 logger("Item ".$item["uri"]." was updated.", LOGGER_DEBUG);
2688                         } else {
2689                                 logger("Item " . $item["uri"] . " already existed.", LOGGER_DEBUG);
2690                         }
2691                         return;
2692                 }
2693
2694                 if (in_array($entrytype, [DFRN::REPLY, DFRN::REPLY_RC])) {
2695                         $posted_id = Item::insert($item);
2696                         $parent = 0;
2697
2698                         if ($posted_id) {
2699                                 logger("Reply from contact ".$item["contact-id"]." was stored with id ".$posted_id, LOGGER_DEBUG);
2700
2701                                 if ($item['uid'] == 0) {
2702                                         Item::distribute($posted_id);
2703                                 }
2704
2705                                 return true;
2706                         }
2707                 } else { // $entrytype == DFRN::TOP_LEVEL
2708                         if (($importer["uid"] == 0) && ($importer["importer_uid"] != 0)) {
2709                                 logger("Contact ".$importer["id"]." isn't known to user ".$importer["importer_uid"].". The post will be ignored.", LOGGER_DEBUG);
2710                                 return;
2711                         }
2712                         if (!link_compare($item["owner-link"], $importer["url"])) {
2713                                 /*
2714                                  * The item owner info is not our contact. It's OK and is to be expected if this is a tgroup delivery,
2715                                  * but otherwise there's a possible data mixup on the sender's system.
2716                                  * the tgroup delivery code called from Item::insert will correct it if it's a forum,
2717                                  * but we're going to unconditionally correct it here so that the post will always be owned by our contact.
2718                                  */
2719                                 logger('Correcting item owner.', LOGGER_DEBUG);
2720                                 $item["owner-link"] = $importer["url"];
2721                                 $item["owner-id"] = Contact::getIdForURL($importer["url"], 0);
2722                         }
2723
2724                         if (($importer["rel"] == Contact::FOLLOWER) && (!self::tgroupCheck($importer["importer_uid"], $item))) {
2725                                 logger("Contact ".$importer["id"]." is only follower and tgroup check was negative.", LOGGER_DEBUG);
2726                                 return;
2727                         }
2728
2729                         // This is my contact on another system, but it's really me.
2730                         // Turn this into a wall post.
2731                         $notify = Item::isRemoteSelf($importer, $item);
2732
2733                         $posted_id = Item::insert($item, false, $notify);
2734
2735                         if ($notify) {
2736                                 $posted_id = $notify;
2737                         }
2738
2739                         logger("Item was stored with id ".$posted_id, LOGGER_DEBUG);
2740
2741                         if ($item['uid'] == 0) {
2742                                 Item::distribute($posted_id);
2743                         }
2744
2745                         if (stristr($item["verb"], ACTIVITY_POKE)) {
2746                                 self::doPoke($item, $importer, $posted_id);
2747                         }
2748                 }
2749         }
2750
2751         /**
2752          * @brief Deletes items
2753          *
2754          * @param object $xpath    XPath object
2755          * @param object $deletion deletion elements
2756          * @param array  $importer Record of the importer user mixed with contact of the content
2757          * @return void
2758          * @todo set proper type-hints
2759          */
2760         private static function processDeletion($xpath, $deletion, $importer)
2761         {
2762                 logger("Processing deletions");
2763                 $uri = null;
2764
2765                 foreach ($deletion->attributes as $attributes) {
2766                         if ($attributes->name == "ref") {
2767                                 $uri = $attributes->textContent;
2768                         }
2769                 }
2770
2771                 if (!$uri || !$importer["id"]) {
2772                         return false;
2773                 }
2774
2775                 $condition = ['uri' => $uri, 'uid' => $importer["importer_uid"]];
2776                 $item = Item::selectFirst(['id', 'parent', 'contact-id', 'file', 'deleted'], $condition);
2777                 if (!DBA::isResult($item)) {
2778                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " wasn't found.", LOGGER_DEBUG);
2779                         return;
2780                 }
2781
2782                 if (strstr($item['file'], '[')) {
2783                         logger("Item with uri " . $uri . " for user " . $importer["importer_uid"] . " is filed. So it won't be deleted.", LOGGER_DEBUG);
2784                         return;
2785                 }
2786
2787                 // When it is a starting post it has to belong to the person that wants to delete it
2788                 if (($item['id'] == $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2789                         logger("Item with uri " . $uri . " don't belong to contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2790                         return;
2791                 }
2792
2793                 // Comments can be deleted by the thread owner or comment owner
2794                 if (($item['id'] != $item['parent']) && ($item['contact-id'] != $importer["id"])) {
2795                         $condition = ['id' => $item['parent'], 'contact-id' => $importer["id"]];
2796                         if (!Item::exists($condition)) {
2797                                 logger("Item with uri " . $uri . " wasn't found or mustn't be deleted by contact " . $importer["id"] . " - ignoring deletion.", LOGGER_DEBUG);
2798                                 return;
2799                         }
2800                 }
2801
2802                 if ($item["deleted"]) {
2803                         return;
2804                 }
2805
2806                 logger('deleting item '.$item['id'].' uri='.$uri, LOGGER_DEBUG);
2807
2808                 Item::delete(['id' => $item['id']]);
2809         }
2810
2811         /**
2812          * @brief Imports a DFRN message
2813          *
2814          * @param string $xml          The DFRN message
2815          * @param array  $importer     Record of the importer user mixed with contact of the content
2816          * @param bool   $sort_by_date Is used when feeds are polled
2817          * @return integer Import status
2818          * @todo set proper type-hints
2819          */
2820         public static function import($xml, $importer, $sort_by_date = false)
2821         {
2822                 if ($xml == "") {
2823                         return 400;
2824                 }
2825
2826                 $doc = new DOMDocument();
2827                 @$doc->loadXML($xml);
2828
2829                 $xpath = new DOMXPath($doc);
2830                 $xpath->registerNamespace("atom", NAMESPACE_ATOM1);
2831                 $xpath->registerNamespace("thr", NAMESPACE_THREAD);
2832                 $xpath->registerNamespace("at", NAMESPACE_TOMB);
2833                 $xpath->registerNamespace("media", NAMESPACE_MEDIA);
2834                 $xpath->registerNamespace("dfrn", NAMESPACE_DFRN);
2835                 $xpath->registerNamespace("activity", NAMESPACE_ACTIVITY);
2836                 $xpath->registerNamespace("georss", NAMESPACE_GEORSS);
2837                 $xpath->registerNamespace("poco", NAMESPACE_POCO);
2838                 $xpath->registerNamespace("ostatus", NAMESPACE_OSTATUS);
2839                 $xpath->registerNamespace("statusnet", NAMESPACE_STATUSNET);
2840
2841                 $header = [];
2842                 $header["uid"] = $importer["importer_uid"];
2843                 $header["network"] = Protocol::DFRN;
2844                 $header["wall"] = 0;
2845                 $header["origin"] = 0;
2846                 $header["contact-id"] = $importer["id"];
2847
2848                 // Update the contact table if the data has changed
2849
2850                 // The "atom:author" is only present in feeds
2851                 if ($xpath->query("/atom:feed/atom:author")->length > 0) {
2852                         self::fetchauthor($xpath, $doc->firstChild, $importer, "atom:author", false, $xml);
2853                 }
2854
2855                 // Only the "dfrn:owner" in the head section contains all data
2856                 if ($xpath->query("/atom:feed/dfrn:owner")->length > 0) {
2857                         self::fetchauthor($xpath, $doc->firstChild, $importer, "dfrn:owner", false, $xml);
2858                 }
2859
2860                 logger("Import DFRN message for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2861
2862                 // is it a public forum? Private forums aren't exposed with this method
2863                 $forum = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:community/text()"));
2864
2865                 // The account type is new since 3.5.1
2866                 if ($xpath->query("/atom:feed/dfrn:account_type")->length > 0) {
2867                         $accounttype = intval(XML::getFirstNodeValue($xpath, "/atom:feed/dfrn:account_type/text()"));
2868
2869                         if ($accounttype != $importer["contact-type"]) {
2870                                 DBA::update('contact', ['contact-type' => $accounttype], ['id' => $importer["id"]]);
2871                         }
2872                         // A forum contact can either have set "forum" or "prv" - but not both
2873                         if (($accounttype == Contact::ACCOUNT_TYPE_COMMUNITY) && (($forum != $importer["forum"]) || ($forum == $importer["prv"]))) {
2874                                 $condition = ['(`forum` != ? OR `prv` != ?) AND `id` = ?', $forum, !$forum, $importer["id"]];
2875                                 DBA::update('contact', ['forum' => $forum, 'prv' => !$forum], $condition);
2876                         }
2877                 } elseif ($forum != $importer["forum"]) { // Deprecated since 3.5.1
2878                         $condition = ['`forum` != ? AND `id` = ?', $forum, $importer["id"]];
2879                         DBA::update('contact', ['forum' => $forum], $condition);
2880                 }
2881
2882
2883                 // We are processing relocations even if we are ignoring a contact
2884                 $relocations = $xpath->query("/atom:feed/dfrn:relocate");
2885                 foreach ($relocations as $relocation) {
2886                         self::processRelocation($xpath, $relocation, $importer);
2887                 }
2888
2889                 if (($importer["uid"] != 0) && !$importer["readonly"]) {
2890                         $mails = $xpath->query("/atom:feed/dfrn:mail");
2891                         foreach ($mails as $mail) {
2892                                 self::processMail($xpath, $mail, $importer);
2893                         }
2894
2895                         $suggestions = $xpath->query("/atom:feed/dfrn:suggest");
2896                         foreach ($suggestions as $suggestion) {
2897                                 self::processSuggestion($xpath, $suggestion, $importer);
2898                         }
2899                 }
2900
2901                 $deletions = $xpath->query("/atom:feed/at:deleted-entry");
2902                 foreach ($deletions as $deletion) {
2903                         self::processDeletion($xpath, $deletion, $importer);
2904                 }
2905
2906                 if (!$sort_by_date) {
2907                         $entries = $xpath->query("/atom:feed/atom:entry");
2908                         foreach ($entries as $entry) {
2909                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2910                         }
2911                 } else {
2912                         $newentries = [];
2913                         $entries = $xpath->query("/atom:feed/atom:entry");
2914                         foreach ($entries as $entry) {
2915                                 $created = XML::getFirstNodeValue($xpath, "atom:published/text()", $entry);
2916                                 $newentries[strtotime($created)] = $entry;
2917                         }
2918
2919                         // Now sort after the publishing date
2920                         ksort($newentries);
2921
2922                         foreach ($newentries as $entry) {
2923                                 self::processEntry($header, $xpath, $entry, $importer, $xml);
2924                         }
2925                 }
2926                 logger("Import done for user " . $importer["importer_uid"] . " from contact " . $importer["id"], LOGGER_DEBUG);
2927                 return 200;
2928         }
2929
2930         /**
2931          * @param App    $a            App
2932          * @param string $contact_nick contact nickname
2933          */
2934         public static function autoRedir(App $a, $contact_nick)
2935         {
2936                 // prevent looping
2937                 if (x($_REQUEST, 'redir') && intval($_REQUEST['redir'])) {
2938                         return;
2939                 }
2940
2941                 if ((! $contact_nick) || ($contact_nick === $a->user['nickname'])) {
2942                         return;
2943                 }
2944
2945                 if (local_user()) {
2946                         // We need to find out if $contact_nick is a user on this hub, and if so, if I
2947                         // am a contact of that user. However, that user may have other contacts with the
2948                         // same nickname as me on other hubs or other networks. Exclude these by requiring
2949                         // that the contact have a local URL. I will be the only person with my nickname at
2950                         // this URL, so if a result is found, then I am a contact of the $contact_nick user.
2951                         //
2952                         // We also have to make sure that I'm a legitimate contact--I'm not blocked or pending.
2953
2954                         $baseurl = System::baseUrl();
2955                         $domain_st = strpos($baseurl, "://");
2956                         if ($domain_st === false) {
2957                                 return;
2958                         }
2959                         $baseurl = substr($baseurl, $domain_st + 3);
2960                         $nurl = normalise_link($baseurl);
2961
2962                         /// @todo Why is there a query for "url" *and* "nurl"? Especially this normalising is strange.
2963                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = (SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1)
2964                                         AND `nick` = '%s' AND NOT `self` AND (`url` LIKE '%%%s%%' OR `nurl` LIKE '%%%s%%') AND NOT `blocked` AND NOT `pending` LIMIT 1",
2965                                 DBA::escape($contact_nick),
2966                                 DBA::escape($a->user['nickname']),
2967                                 DBA::escape($baseurl),
2968                                 DBA::escape($nurl)
2969                         );
2970                         if ((! DBA::isResult($r)) || $r[0]['id'] == remote_user()) {
2971                                 return;
2972                         }
2973
2974                         $r = q("SELECT * FROM contact WHERE nick = '%s'
2975                                         AND network = '%s' AND uid = %d  AND url LIKE '%%%s%%' LIMIT 1",
2976                                 DBA::escape($contact_nick),
2977                                 DBA::escape(Protocol::DFRN),
2978                                 intval(local_user()),
2979                                 DBA::escape($baseurl)
2980                         );
2981                         if (! DBA::isResult($r)) {
2982                                 return;
2983                         }
2984
2985                         $cid = $r[0]['id'];
2986
2987                         $dfrn_id = (($r[0]['issued-id']) ? $r[0]['issued-id'] : $r[0]['dfrn-id']);
2988
2989                         if ($r[0]['duplex'] && $r[0]['issued-id']) {
2990                                 $orig_id = $r[0]['issued-id'];
2991                                 $dfrn_id = '1:' . $orig_id;
2992                         }
2993                         if ($r[0]['duplex'] && $r[0]['dfrn-id']) {
2994                                 $orig_id = $r[0]['dfrn-id'];
2995                                 $dfrn_id = '0:' . $orig_id;
2996                         }
2997
2998                         // ensure that we've got a valid ID. There may be some edge cases with forums and non-duplex mode
2999                         // that may have triggered some of the "went to {profile/intro} and got an RSS feed" issues
3000
3001                         if (strlen($dfrn_id) < 3) {
3002                                 return;
3003                         }
3004
3005                         $sec = random_string();
3006
3007                         DBA::insert('profile_check', ['uid' => local_user(), 'cid' => $cid, 'dfrn_id' => $dfrn_id, 'sec' => $sec, 'expire' => time() + 45]);
3008
3009                         $url = curPageURL();
3010
3011                         logger('auto_redir: ' . $r[0]['name'] . ' ' . $sec, LOGGER_DEBUG);
3012                         $dest = (($url) ? '&destination_url=' . $url : '');
3013                         goaway($r[0]['poll'] . '?dfrn_id=' . $dfrn_id
3014                                 . '&dfrn_version=' . DFRN_PROTOCOL_VERSION . '&type=profile&sec=' . $sec . $dest);
3015                 }
3016
3017                 return;
3018         }
3019
3020         /**
3021          * @brief Returns the activity verb
3022          *
3023          * @param array $item Item array
3024          *
3025          * @return string activity verb
3026          */
3027         private static function constructVerb(array $item)
3028         {
3029                 if ($item['verb']) {
3030                         return $item['verb'];
3031                 }
3032                 return ACTIVITY_POST;
3033         }
3034
3035         private static function tgroupCheck($uid, $item)
3036         {
3037                 $mention = false;
3038
3039                 // check that the message originated elsewhere and is a top-level post
3040
3041                 if ($item['wall'] || $item['origin'] || ($item['uri'] != $item['parent-uri'])) {
3042                         return false;
3043                 }
3044
3045                 $user = DBA::selectFirst('user', ['page-flags', 'nickname'], ['uid' => $uid]);
3046                 if (!DBA::isResult($user)) {
3047                         return false;
3048                 }
3049
3050                 $community_page = ($user['page-flags'] == Contact::PAGE_COMMUNITY);
3051                 $prvgroup = ($user['page-flags'] == Contact::PAGE_PRVGROUP);
3052
3053                 $link = normalise_link(System::baseUrl() . '/profile/' . $user['nickname']);
3054
3055                 /*
3056                  * Diaspora uses their own hardwired link URL in @-tags
3057                  * instead of the one we supply with webfinger
3058                  */
3059                 $dlink = normalise_link(System::baseUrl() . '/u/' . $user['nickname']);
3060
3061                 $cnt = preg_match_all('/[\@\!]\[url\=(.*?)\](.*?)\[\/url\]/ism', $item['body'], $matches, PREG_SET_ORDER);
3062                 if ($cnt) {
3063                         foreach ($matches as $mtch) {
3064                                 if (link_compare($link, $mtch[1]) || link_compare($dlink, $mtch[1])) {
3065                                         $mention = true;
3066                                         logger('mention found: ' . $mtch[2]);
3067                                 }
3068                         }
3069                 }
3070
3071                 if (!$mention) {
3072                         return false;
3073                 }
3074
3075                 return $community_page || $prvgroup;
3076         }
3077
3078         /**
3079          * This function returns true if $update has an edited timestamp newer
3080          * than $existing, i.e. $update contains new data which should override
3081          * what's already there.  If there is no timestamp yet, the update is
3082          * assumed to be newer.  If the update has no timestamp, the existing
3083          * item is assumed to be up-to-date.  If the timestamps are equal it
3084          * assumes the update has been seen before and should be ignored.
3085          *
3086          */
3087         private static function isEditedTimestampNewer($existing, $update)
3088         {
3089                 if (!x($existing, 'edited') || !$existing['edited']) {
3090                         return true;
3091                 }
3092                 if (!x($update, 'edited') || !$update['edited']) {
3093                         return false;
3094                 }
3095
3096                 $existing_edited = DateTimeFormat::utc($existing['edited']);
3097                 $update_edited = DateTimeFormat::utc($update['edited']);
3098
3099                 return (strcmp($existing_edited, $update_edited) < 0);
3100         }
3101 }