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