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