Use "received" instead of "created" when displaying posts in creation order
[friendica.git/.git] / src / Protocol / OStatus.php
1 <?php
2 /**
3  * @file src/Protocol/OStatus.php
4  */
5 namespace Friendica\Protocol;
6
7 use DOMDocument;
8 use DOMXPath;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\HTML;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\L10n;
14 use Friendica\Core\Logger;
15 use Friendica\Core\Lock;
16 use Friendica\Core\Protocol;
17 use Friendica\Core\System;
18 use Friendica\Database\DBA;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Conversation;
21 use Friendica\Model\GContact;
22 use Friendica\Model\Item;
23 use Friendica\Model\User;
24 use Friendica\Network\Probe;
25 use Friendica\Object\Image;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\Network;
28 use Friendica\Util\Proxy as ProxyUtils;
29 use Friendica\Util\Strings;
30 use Friendica\Util\XML;
31
32 require_once 'mod/share.php';
33 require_once 'include/api.php';
34
35 /**
36  * @brief This class contain functions for the OStatus protocol
37  */
38 class OStatus
39 {
40         private static $itemlist;
41         private static $conv_list = [];
42
43         /**
44          * @brief Fetches author data
45          *
46          * @param DOMXPath $xpath     The xpath object
47          * @param object   $context   The xml context of the author details
48          * @param array    $importer  user record of the importing user
49          * @param array    $contact   Called by reference, will contain the fetched contact
50          * @param bool     $onlyfetch Only fetch the header without updating the contact entries
51          *
52          * @return array Array of author related entries for the item
53          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
54          * @throws \ImagickException
55          */
56         private static function fetchAuthor(DOMXPath $xpath, $context, array $importer, array &$contact = null, $onlyfetch)
57         {
58                 $author = [];
59                 $author["author-link"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
60                 $author["author-name"] = XML::getFirstNodeValue($xpath, 'atom:author/atom:name/text()', $context);
61                 $addr = XML::getFirstNodeValue($xpath, 'atom:author/atom:email/text()', $context);
62
63                 $aliaslink = $author["author-link"];
64
65                 $alternate_item = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0);
66                 if (is_object($alternate_item)) {
67                         foreach ($alternate_item->attributes as $attributes) {
68                                 if (($attributes->name == "href") && ($attributes->textContent != "")) {
69                                         $author["author-link"] = $attributes->textContent;
70                                 }
71                         }
72                 }
73                 $author["author-id"] = Contact::getIdForURL($author["author-link"]);
74
75                 $author['contact-id'] = defaults($contact, 'id', $author['author-id']);
76
77                 $contact = [];
78
79 /*
80                 This here would be better, but we would get problems with contacts from the statusnet addon
81                 This is kept here as a reminder for the future
82
83                 $cid = Contact::getIdForURL($author["author-link"], $importer["uid"]);
84                 if ($cid) {
85                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
86                 }
87 */
88                 if ($aliaslink != '') {
89                         $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
90                                         $importer["uid"], $aliaslink, Protocol::STATUSNET,
91                                         Contact::SHARING, Contact::FRIEND];
92                         $contact = DBA::selectFirst('contact', [], $condition);
93                 }
94
95                 if (!DBA::isResult($contact) && $author["author-link"] != '') {
96                         if ($aliaslink == "") {
97                                 $aliaslink = $author["author-link"];
98                         }
99
100                         $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
101                                         $importer["uid"], Strings::normaliseLink($author["author-link"]), Strings::normaliseLink($aliaslink),
102                                         Protocol::STATUSNET, Contact::SHARING, Contact::FRIEND];
103                         $contact = DBA::selectFirst('contact', [], $condition);
104                 }
105
106                 if (!DBA::isResult($contact) && ($addr != '')) {
107                         $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
108                                         $importer["uid"], $addr, Protocol::STATUSNET,
109                                         Contact::SHARING, Contact::FRIEND];
110                         $contact = DBA::selectFirst('contact', [], $condition);
111                 }
112
113                 if (DBA::isResult($contact)) {
114                         if ($contact['blocked']) {
115                                 $contact['id'] = -1;
116                         }
117                         $author["contact-id"] = $contact["id"];
118                 }
119
120                 $avatarlist = [];
121                 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
122                 foreach ($avatars as $avatar) {
123                         $href = "";
124                         $width = 0;
125                         foreach ($avatar->attributes as $attributes) {
126                                 if ($attributes->name == "href") {
127                                         $href = $attributes->textContent;
128                                 }
129                                 if ($attributes->name == "width") {
130                                         $width = $attributes->textContent;
131                                 }
132                         }
133                         if ($href != "") {
134                                 $avatarlist[$width] = $href;
135                         }
136                 }
137                 if (count($avatarlist) > 0) {
138                         krsort($avatarlist);
139                         $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
140                 }
141
142                 $displayname = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
143                 if ($displayname != "") {
144                         $author["author-name"] = $displayname;
145                 }
146
147                 $author["owner-id"] = $author["author-id"];
148
149                 // Only update the contacts if it is an OStatus contact
150                 if (DBA::isResult($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == Protocol::OSTATUS)) {
151
152                         // Update contact data
153                         $current = $contact;
154                         unset($current['name-date']);
155
156                         // This query doesn't seem to work
157                         // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
158                         // if ($value != "")
159                         //      $contact["notify"] = $value;
160
161                         // This query doesn't seem to work as well - I hate these queries
162                         // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
163                         // if ($value != "")
164                         //      $contact["poll"] = $value;
165
166                         $contact['url'] = $author["author-link"];
167                         $contact['nurl'] = Strings::normaliseLink($contact['url']);
168
169                         $value = XML::getFirstNodeValue($xpath, 'atom:author/atom:uri/text()', $context);
170                         if ($value != "") {
171                                 $contact["alias"] = $value;
172                         }
173
174                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:displayName/text()', $context);
175                         if ($value != "") {
176                                 $contact["name"] = $value;
177                         }
178
179                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:preferredUsername/text()', $context);
180                         if ($value != "") {
181                                 $contact["nick"] = $value;
182                         }
183
184                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:note/text()', $context);
185                         if ($value != "") {
186                                 $contact["about"] = HTML::toBBCode($value);
187                         }
188
189                         $value = XML::getFirstNodeValue($xpath, 'atom:author/poco:address/poco:formatted/text()', $context);
190                         if ($value != "") {
191                                 $contact["location"] = $value;
192                         }
193
194                         $contact['name-date'] = DateTimeFormat::utcNow();
195
196                         DBA::update('contact', $contact, ['id' => $contact["id"]], $current);
197
198                         if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
199                                 Logger::log("Update profile picture for contact ".$contact["id"], Logger::DEBUG);
200                                 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
201                         }
202
203                         // Ensure that we are having this contact (with uid=0)
204                         $cid = Contact::getIdForURL($aliaslink, 0, true);
205
206                         if ($cid) {
207                                 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
208                                 $old_contact = DBA::selectFirst('contact', $fields, ['id' => $cid]);
209
210                                 // Update it with the current values
211                                 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
212                                                 'nurl' => Strings::normaliseLink($author["author-link"]),
213                                                 'nick' => $contact["nick"], 'alias' => $contact["alias"],
214                                                 'about' => $contact["about"], 'location' => $contact["location"],
215                                                 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
216
217                                 DBA::update('contact', $fields, ['id' => $cid], $old_contact);
218
219                                 // Update the avatar
220                                 if (!empty($author["author-avatar"])) {
221                                         Contact::updateAvatar($author["author-avatar"], 0, $cid);
222                                 }
223                         }
224
225                         $contact["generation"] = 2;
226                         $contact["hide"] = false; // OStatus contacts are never hidden
227                         if (!empty($author["author-avatar"])) {
228                                 $contact["photo"] = $author["author-avatar"];
229                         }
230                         $gcid = GContact::update($contact);
231
232                         GContact::link($gcid, $contact["uid"], $contact["id"]);
233                 } elseif ($contact["network"] != Protocol::DFRN) {
234                         $contact = [];
235                 }
236
237                 return $author;
238         }
239
240         /**
241          * @brief Fetches author data from a given XML string
242          *
243          * @param string $xml      The XML
244          * @param array  $importer user record of the importing user
245          *
246          * @return array Array of author related entries for the item
247          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
248          * @throws \ImagickException
249          */
250         public static function salmonAuthor($xml, array $importer)
251         {
252                 if ($xml == "") {
253                         return;
254                 }
255
256                 $doc = new DOMDocument();
257                 @$doc->loadXML($xml);
258
259                 $xpath = new DOMXPath($doc);
260                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
261                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
262                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
263                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
264                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
265                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
266                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
267                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
268
269                 $contact = ["id" => 0];
270
271                 // Fetch the first author
272                 $authordata = $xpath->query('//author')->item(0);
273                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
274                 return $author;
275         }
276
277         /**
278          * @brief Read attributes from element
279          *
280          * @param object $element Element object
281          *
282          * @return array attributes
283          */
284         private static function readAttributes($element)
285         {
286                 $attribute = [];
287
288                 foreach ($element->attributes as $attributes) {
289                         $attribute[$attributes->name] = $attributes->textContent;
290                 }
291
292                 return $attribute;
293         }
294
295         /**
296          * @brief Imports an XML string containing OStatus elements
297          *
298          * @param string $xml      The XML
299          * @param array  $importer user record of the importing user
300          * @param array  $contact  contact
301          * @param string $hub      Called by reference, returns the fetched hub data
302          * @return void
303          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
304          * @throws \ImagickException
305          */
306         public static function import($xml, array $importer, array &$contact, &$hub)
307         {
308                 self::process($xml, $importer, $contact, $hub);
309         }
310
311         /**
312          * @brief Internal feed processing
313          *
314          * @param string  $xml        The XML
315          * @param array   $importer   user record of the importing user
316          * @param array   $contact    contact
317          * @param string  $hub        Called by reference, returns the fetched hub data
318          * @param boolean $stored     Is the post fresh imported or from the database?
319          * @param boolean $initialize Is it the leading post so that data has to be initialized?
320          *
321          * @return boolean Could the XML be processed?
322          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
323          * @throws \ImagickException
324          */
325         private static function process($xml, array $importer, array &$contact = null, &$hub, $stored = false, $initialize = true)
326         {
327                 if ($initialize) {
328                         self::$itemlist = [];
329                         self::$conv_list = [];
330                 }
331
332                 Logger::log('Import OStatus message for user ' . $importer['uid'], Logger::DEBUG);
333
334                 if ($xml == "") {
335                         return false;
336                 }
337                 $doc = new DOMDocument();
338                 @$doc->loadXML($xml);
339
340                 $xpath = new DOMXPath($doc);
341                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
342                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
343                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
344                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
345                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
346                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
347                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
348                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
349
350                 $hub = "";
351                 $hub_items = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0);
352                 if (is_object($hub_items)) {
353                         $hub_attributes = $hub_items->attributes;
354                         if (is_object($hub_attributes)) {
355                                 foreach ($hub_attributes as $hub_attribute) {
356                                         if ($hub_attribute->name == "href") {
357                                                 $hub = $hub_attribute->textContent;
358                                                 Logger::log("Found hub ".$hub, Logger::DEBUG);
359                                         }
360                                 }
361                         }
362                 }
363
364                 $header = [];
365                 $header["uid"] = $importer["uid"];
366                 $header["network"] = Protocol::OSTATUS;
367                 $header["wall"] = 0;
368                 $header["origin"] = 0;
369                 $header["gravity"] = GRAVITY_COMMENT;
370
371                 if (!is_object($doc->firstChild) || empty($doc->firstChild->tagName)) {
372                         return false;
373                 }
374
375                 $first_child = $doc->firstChild->tagName;
376
377                 if ($first_child == "feed") {
378                         $entries = $xpath->query('/atom:feed/atom:entry');
379                 } else {
380                         $entries = $xpath->query('/atom:entry');
381                 }
382
383                 if ($entries->length == 1) {
384                         // We reformat the XML to make it better readable
385                         $doc2 = new DOMDocument();
386                         $doc2->loadXML($xml);
387                         $doc2->preserveWhiteSpace = false;
388                         $doc2->formatOutput = true;
389                         $xml2 = $doc2->saveXML();
390
391                         $header["protocol"] = Conversation::PARCEL_SALMON;
392                         $header["source"] = $xml2;
393                 } elseif (!$initialize) {
394                         return false;
395                 }
396
397                 // Fetch the first author
398                 $authordata = $xpath->query('//author')->item(0);
399                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
400
401                 // Reverse the order of the entries
402                 $entrylist = [];
403
404                 foreach ($entries as $entry) {
405                         $entrylist[] = $entry;
406                 }
407
408                 foreach (array_reverse($entrylist) as $entry) {
409                         // fetch the author
410                         $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
411
412                         if ($authorelement->length == 0) {
413                                 $authorelement = $xpath->query('atom:author', $entry);
414                         }
415
416                         if ($authorelement->length > 0) {
417                                 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
418                         }
419
420                         $item = array_merge($header, $author);
421
422                         $item["uri"] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
423
424                         $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $entry);
425
426                         // Delete a message
427                         if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
428                                 self::deleteNotice($item);
429                                 continue;
430                         }
431
432                         if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
433                                 // Ignore "Unfavorite" message
434                                 Logger::log("Ignore unfavorite message ".print_r($item, true), Logger::DEBUG);
435                                 continue;
436                         }
437
438                         // Deletions come with the same uri, so we check for duplicates after processing deletions
439                         if (Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
440                                 Logger::log('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
441                                 continue;
442                         } else {
443                                 Logger::log('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
444                         }
445
446                         if ($item["verb"] == ACTIVITY_JOIN) {
447                                 // ignore "Join" messages
448                                 Logger::log("Ignore join message ".print_r($item, true), Logger::DEBUG);
449                                 continue;
450                         }
451
452                         if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
453                                 // ignore mastodon "block" messages
454                                 Logger::log("Ignore block message ".print_r($item, true), Logger::DEBUG);
455                                 continue;
456                         }
457
458                         if ($item["verb"] == ACTIVITY_FOLLOW) {
459                                 Contact::addRelationship($importer, $contact, $item);
460                                 continue;
461                         }
462
463                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
464                                 $dummy = null;
465                                 Contact::removeFollower($importer, $contact, $item, $dummy);
466                                 continue;
467                         }
468
469                         if ($item["verb"] == ACTIVITY_FAVORITE) {
470                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
471                                 Logger::log("Favorite ".$orig_uri." ".print_r($item, true));
472
473                                 $item["verb"] = ACTIVITY_LIKE;
474                                 $item["parent-uri"] = $orig_uri;
475                                 $item["gravity"] = GRAVITY_ACTIVITY;
476                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
477                         }
478
479                         // http://activitystrea.ms/schema/1.0/rsvp-yes
480                         if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
481                                 Logger::log("Unhandled verb ".$item["verb"]." ".print_r($item, true), Logger::DEBUG);
482                         }
483
484                         self::processPost($xpath, $entry, $item, $importer);
485
486                         if ($initialize && (count(self::$itemlist) > 0)) {
487                                 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
488                                         // We will import it everytime, when it is started by our contacts
489                                         $valid = !empty(self::$itemlist[0]['contact-id']);
490                                         if (!$valid) {
491                                                 // If not, then it depends on this setting
492                                                 $valid = !Config::get('system', 'ostatus_full_threads');
493                                                 if ($valid) {
494                                                         Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", Logger::DEBUG);
495                                                 }
496                                         } else {
497                                                 Logger::log("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", Logger::DEBUG);
498                                         }
499                                         if ($valid) {
500                                                 // Never post a thread when the only interaction by our contact was a like
501                                                 $valid = false;
502                                                 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
503                                                 foreach (self::$itemlist as $item) {
504                                                         if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
505                                                                 $valid = true;
506                                                         }
507                                                 }
508                                                 if ($valid) {
509                                                         Logger::log("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", Logger::DEBUG);
510                                                 }
511                                         }
512                                 } else {
513                                         // But we will only import complete threads
514                                         $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
515                                         if ($valid) {
516                                                 Logger::log("Item with uri ".self::$itemlist[0]["uri"]." belongs to parent ".self::$itemlist[0]['parent-uri']." of user ".$importer["uid"].". It will be imported.", Logger::DEBUG);
517                                         }
518                                 }
519
520                                 if ($valid) {
521                                         $default_contact = 0;
522                                         for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
523                                                 if (empty(self::$itemlist[$key]['contact-id'])) {
524                                                         self::$itemlist[$key]['contact-id'] = $default_contact;
525                                                 } else {
526                                                         $default_contact = $item['contact-id'];
527                                                 }
528                                         }
529                                         foreach (self::$itemlist as $item) {
530                                                 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
531                                                 if ($found) {
532                                                         Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", Logger::DEBUG);
533                                                 } elseif ($item['contact-id'] < 0) {
534                                                         Logger::log("Item with uri ".$item["uri"]." is from a blocked contact.", Logger::DEBUG);
535                                                 } else {
536                                                         // We are having duplicated entries. Hopefully this solves it.
537                                                         if (Lock::acquire('ostatus_process_item_insert')) {
538                                                                 $ret = Item::insert($item);
539                                                                 Lock::release('ostatus_process_item_insert');
540                                                                 Logger::log("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
541                                                         } else {
542                                                                 $ret = Item::insert($item);
543                                                                 Logger::log("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
544                                                         }
545                                                 }
546                                         }
547                                 }
548                                 self::$itemlist = [];
549                         }
550                         Logger::log('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', Logger::DEBUG);
551                 }
552                 return true;
553         }
554
555         /**
556          * Removes notice item from database
557          *
558          * @param array $item item
559          * @return void
560          * @throws \Exception
561          */
562         private static function deleteNotice(array $item)
563         {
564                 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
565                 if (!Item::exists($condition)) {
566                         Logger::log('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
567                         return;
568                 }
569
570                 Item::delete($condition);
571
572                 Logger::log('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
573         }
574
575         /**
576          * @brief Processes the XML for a post
577          *
578          * @param DOMXPath $xpath    The xpath object
579          * @param object   $entry    The xml entry that is processed
580          * @param array    $item     The item array
581          * @param array    $importer user record of the importing user
582          * @return void
583          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
584          * @throws \ImagickException
585          */
586         private static function processPost(DOMXPath $xpath, $entry, array &$item, array $importer)
587         {
588                 $item["body"] = HTML::toBBCode(XML::getFirstNodeValue($xpath, 'atom:content/text()', $entry));
589                 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $entry);
590                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
591                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
592                         $item["body"] = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
593                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
594                         $item["title"] = XML::getFirstNodeValue($xpath, 'atom:title/text()', $entry);
595                 }
596
597                 $item["created"] = XML::getFirstNodeValue($xpath, 'atom:published/text()', $entry);
598                 $item["edited"] = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $entry);
599                 $item['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
600
601                 $conv = $xpath->query('ostatus:conversation', $entry);
602                 if (is_object($conv->item(0))) {
603                         foreach ($conv->item(0)->attributes as $attributes) {
604                                 if ($attributes->name == "ref") {
605                                         $item['conversation-uri'] = $attributes->textContent;
606                                 }
607                                 if ($attributes->name == "href") {
608                                         $item['conversation-href'] = $attributes->textContent;
609                                 }
610                         }
611                 }
612
613                 $related = "";
614
615                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
616                 if (is_object($inreplyto->item(0))) {
617                         foreach ($inreplyto->item(0)->attributes as $attributes) {
618                                 if ($attributes->name == "ref") {
619                                         $item["parent-uri"] = $attributes->textContent;
620                                 }
621                                 if ($attributes->name == "href") {
622                                         $related = $attributes->textContent;
623                                 }
624                         }
625                 }
626
627                 $georsspoint = $xpath->query('georss:point', $entry);
628                 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
629                         $item["coord"] = $georsspoint->item(0)->nodeValue;
630                 }
631
632                 $categories = $xpath->query('atom:category', $entry);
633                 if ($categories) {
634                         foreach ($categories as $category) {
635                                 foreach ($category->attributes as $attributes) {
636                                         if ($attributes->name == 'term') {
637                                                 $term = $attributes->textContent;
638                                                 if (!empty($item['tag'])) {
639                                                         $item['tag'] .= ',';
640                                                 } else {
641                                                         $item['tag'] = '';
642                                                 }
643
644                                                 $item['tag'] .= '#[url=' . System::baseUrl() . '/search?tag=' . $term . ']' . $term . '[/url]';
645                                         }
646                                 }
647                         }
648                 }
649
650                 $self = '';
651                 $add_body = '';
652
653                 $links = $xpath->query('atom:link', $entry);
654                 if ($links) {
655                         $link_data = self::processLinks($links, $item);
656                         $self = $link_data['self'];
657                         $add_body = $link_data['add_body'];
658                 }
659
660                 $repeat_of = "";
661
662                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
663                 if ($notice_info && ($notice_info->length > 0)) {
664                         foreach ($notice_info->item(0)->attributes as $attributes) {
665                                 if ($attributes->name == "source") {
666                                         $item["app"] = strip_tags($attributes->textContent);
667                                 }
668                                 if ($attributes->name == "repeat_of") {
669                                         $repeat_of = $attributes->textContent;
670                                 }
671                         }
672                 }
673                 // Is it a repeated post?
674                 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
675                         $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
676                         if (!empty($link_data['add_body'])) {
677                                 $add_body .= $link_data['add_body'];
678                         }
679                 }
680
681                 $item["body"] .= $add_body;
682
683                 // Only add additional data when there is no picture in the post
684                 if (!strstr($item["body"], '[/img]')) {
685                         $item["body"] = add_page_info_to_body($item["body"]);
686                 }
687
688                 // Mastodon Content Warning
689                 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
690                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $entry);
691                         if (!empty($clear_text)) {
692                                 $item['content-warning'] = HTML::toBBCode($clear_text);
693                         }
694                 }
695
696                 if (($self != '') && empty($item['protocol'])) {
697                         self::fetchSelf($self, $item);
698                 }
699
700                 if (!empty($item["conversation-href"])) {
701                         self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
702                 }
703
704                 if (isset($item["parent-uri"])) {
705                         if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
706                                 if ($related != '') {
707                                         self::fetchRelated($related, $item["parent-uri"], $importer);
708                                 }
709                         } else {
710                                 Logger::log('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', Logger::DEBUG);
711                         }
712                 } else {
713                         $item["parent-uri"] = $item["uri"];
714                         $item["gravity"] = GRAVITY_PARENT;
715                 }
716
717                 if (($item['author-link'] != '') && !empty($item['protocol'])) {
718                         $item = Conversation::insert($item);
719                 }
720
721                 self::$itemlist[] = $item;
722         }
723
724         /**
725          * @brief Fetch the conversation for posts
726          *
727          * @param string $conversation     The link to the conversation
728          * @param string $conversation_uri The conversation in "uri" format
729          * @return void
730          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
731          */
732         private static function fetchConversation($conversation, $conversation_uri)
733         {
734                 // Ensure that we only store a conversation once in a process
735                 if (isset(self::$conv_list[$conversation])) {
736                         return;
737                 }
738
739                 self::$conv_list[$conversation] = true;
740
741                 $curlResult = Network::curl($conversation, false, ['accept_content' => 'application/atom+xml, text/html']);
742
743                 if (!$curlResult->isSuccess()) {
744                         return;
745                 }
746
747                 $xml = '';
748
749                 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
750                         $xml = $curlResult->getBody();
751                 }
752
753                 if ($xml == '') {
754                         $doc = new DOMDocument();
755                         if (!@$doc->loadHTML($curlResult->getBody())) {
756                                 return;
757                         }
758                         $xpath = new DOMXPath($doc);
759
760                         $links = $xpath->query('//link');
761                         if ($links) {
762                                 $file = '';
763                                 foreach ($links as $link) {
764                                         $attribute = self::readAttributes($link);
765                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
766                                                 $file = $attribute['href'];
767                                         }
768                                 }
769                                 if ($file != '') {
770                                         $conversation_atom = Network::curl($attribute['href']);
771
772                                         if ($conversation_atom->isSuccess()) {
773                                                 $xml = $conversation_atom->getBody();
774                                         }
775                                 }
776                         }
777                 }
778
779                 if ($xml == '') {
780                         return;
781                 }
782
783                 self::storeConversation($xml, $conversation, $conversation_uri);
784         }
785
786         /**
787          * @brief Store a feed in several conversation entries
788          *
789          * @param string $xml              The feed
790          * @param string $conversation     conversation
791          * @param string $conversation_uri conversation uri
792          * @return void
793          * @throws \Exception
794          */
795         private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
796         {
797                 $doc = new DOMDocument();
798                 @$doc->loadXML($xml);
799
800                 $xpath = new DOMXPath($doc);
801                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
802                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
803                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
804
805                 $entries = $xpath->query('/atom:feed/atom:entry');
806
807                 // Now store the entries
808                 foreach ($entries as $entry) {
809                         $doc2 = new DOMDocument();
810                         $doc2->preserveWhiteSpace = false;
811                         $doc2->formatOutput = true;
812
813                         $conv_data = [];
814
815                         $conv_data['protocol'] = Conversation::PARCEL_SPLIT_CONVERSATION;
816                         $conv_data['network'] = Protocol::OSTATUS;
817                         $conv_data['uri'] = XML::getFirstNodeValue($xpath, 'atom:id/text()', $entry);
818
819                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
820                         if (is_object($inreplyto->item(0))) {
821                                 foreach ($inreplyto->item(0)->attributes as $attributes) {
822                                         if ($attributes->name == "ref") {
823                                                 $conv_data['reply-to-uri'] = $attributes->textContent;
824                                         }
825                                 }
826                         }
827
828                         $conv_data['conversation-uri'] = XML::getFirstNodeValue($xpath, 'ostatus:conversation/text()', $entry);
829
830                         $conv = $xpath->query('ostatus:conversation', $entry);
831                         if (is_object($conv->item(0))) {
832                                 foreach ($conv->item(0)->attributes as $attributes) {
833                                         if ($attributes->name == "ref") {
834                                                 $conv_data['conversation-uri'] = $attributes->textContent;
835                                         }
836                                         if ($attributes->name == "href") {
837                                                 $conv_data['conversation-href'] = $attributes->textContent;
838                                         }
839                                 }
840                         }
841
842                         if ($conversation != '') {
843                                 $conv_data['conversation-uri'] = $conversation;
844                         }
845
846                         if ($conversation_uri != '') {
847                                 $conv_data['conversation-uri'] = $conversation_uri;
848                         }
849
850                         $entry = $doc2->importNode($entry, true);
851
852                         $doc2->appendChild($entry);
853
854                         $conv_data['source'] = $doc2->saveXML();
855
856                         $condition = ['item-uri' => $conv_data['uri'],'protocol' => Conversation::PARCEL_FEED];
857                         if (DBA::exists('conversation', $condition)) {
858                                 Logger::log('Delete deprecated entry for URI '.$conv_data['uri'], Logger::DEBUG);
859                                 DBA::delete('conversation', ['item-uri' => $conv_data['uri']]);
860                         }
861
862                         Logger::log('Store conversation data for uri '.$conv_data['uri'], Logger::DEBUG);
863                         Conversation::insert($conv_data);
864                 }
865         }
866
867         /**
868          * @brief Fetch the own post so that it can be stored later
869          *
870          * We want to store the original data for later processing.
871          * This function is meant for cases where we process a feed with multiple entries.
872          * In that case we need to fetch the single posts here.
873          *
874          * @param string $self The link to the self item
875          * @param array  $item The item array
876          * @return void
877          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
878          */
879         private static function fetchSelf($self, array &$item)
880         {
881                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
882                 if (DBA::exists('conversation', $condition)) {
883                         Logger::log('Conversation '.$item['uri'].' is already stored.', Logger::DEBUG);
884                         return;
885                 }
886
887                 $curlResult = Network::curl($self);
888
889                 if (!$curlResult->isSuccess()) {
890                         return;
891                 }
892
893                 // We reformat the XML to make it better readable
894                 $doc = new DOMDocument();
895                 $doc->loadXML($curlResult->getBody());
896                 $doc->preserveWhiteSpace = false;
897                 $doc->formatOutput = true;
898                 $xml = $doc->saveXML();
899
900                 $item["protocol"] = Conversation::PARCEL_SALMON;
901                 $item["source"] = $xml;
902
903                 Logger::log('Conversation '.$item['uri'].' is now fetched.', Logger::DEBUG);
904         }
905
906         /**
907          * @brief Fetch related posts and processes them
908          *
909          * @param string $related     The link to the related item
910          * @param string $related_uri The related item in "uri" format
911          * @param array  $importer    user record of the importing user
912          * @return void
913          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
914          * @throws \ImagickException
915          */
916         private static function fetchRelated($related, $related_uri, $importer)
917         {
918                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, Conversation::PARCEL_DFRN, Conversation::PARCEL_SALMON];
919                 $conversation = DBA::selectFirst('conversation', ['source', 'protocol'], $condition);
920                 if (DBA::isResult($conversation)) {
921                         $stored = true;
922                         $xml = $conversation['source'];
923                         if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
924                                 Logger::log('Got valid cached XML for URI '.$related_uri, Logger::DEBUG);
925                                 return;
926                         }
927                         if ($conversation['protocol'] == Conversation::PARCEL_SALMON) {
928                                 Logger::log('Delete invalid cached XML for URI '.$related_uri, Logger::DEBUG);
929                                 DBA::delete('conversation', ['item-uri' => $related_uri]);
930                         }
931                 }
932
933                 $stored = false;
934                 $curlResult = Network::curl($related, false, ['accept_content' => 'application/atom+xml, text/html']);
935
936                 if (!$curlResult->isSuccess()) {
937                         return;
938                 }
939
940                 $xml = '';
941
942                 if (stristr($curlResult->getHeader(), 'Content-Type: application/atom+xml')) {
943                         Logger::log('Directly fetched XML for URI ' . $related_uri, Logger::DEBUG);
944                         $xml = $curlResult->getBody();
945                 }
946
947                 if ($xml == '') {
948                         $doc = new DOMDocument();
949                         if (!@$doc->loadHTML($curlResult->getBody())) {
950                                 return;
951                         }
952                         $xpath = new DOMXPath($doc);
953
954                         $atom_file = '';
955
956                         $links = $xpath->query('//link');
957                         if ($links) {
958                                 foreach ($links as $link) {
959                                         $attribute = self::readAttributes($link);
960                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
961                                                 $atom_file = $attribute['href'];
962                                         }
963                                 }
964                                 if ($atom_file != '') {
965                                         $curlResult = Network::curl($atom_file);
966
967                                         if ($curlResult->isSuccess()) {
968                                                 Logger::log('Fetched XML for URI ' . $related_uri, Logger::DEBUG);
969                                                 $xml = $curlResult->getBody();
970                                         }
971                                 }
972                         }
973                 }
974
975                 // Workaround for older GNU Social servers
976                 if (($xml == '') && strstr($related, '/notice/')) {
977                         $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
978
979                         if ($curlResult->isSuccess()) {
980                                 Logger::log('GNU Social workaround to fetch XML for URI ' . $related_uri, Logger::DEBUG);
981                                 $xml = $curlResult->getBody();
982                         }
983                 }
984
985                 // Even more worse workaround for GNU Social ;-)
986                 if ($xml == '') {
987                         $related_guess = OStatus::convertHref($related_uri);
988                         $curlResult = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
989
990                         if ($curlResult->isSuccess()) {
991                                 Logger::log('GNU Social workaround 2 to fetch XML for URI ' . $related_uri, Logger::DEBUG);
992                                 $xml = $curlResult->getBody();
993                         }
994                 }
995
996                 // Finally we take the data that we fetched from "ostatus:conversation"
997                 if ($xml == '') {
998                         $condition = ['item-uri' => $related_uri, 'protocol' => Conversation::PARCEL_SPLIT_CONVERSATION];
999                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1000                         if (DBA::isResult($conversation)) {
1001                                 $stored = true;
1002                                 Logger::log('Got cached XML from conversation for URI '.$related_uri, Logger::DEBUG);
1003                                 $xml = $conversation['source'];
1004                         }
1005                 }
1006
1007                 if ($xml != '') {
1008                         self::process($xml, $importer, $contact, $hub, $stored, false);
1009                 } else {
1010                         Logger::log("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, Logger::DEBUG);
1011                 }
1012                 return;
1013         }
1014
1015         /**
1016          * @brief Processes the XML for a repeated post
1017          *
1018          * @param DOMXPath $xpath    The xpath object
1019          * @param object   $entry    The xml entry that is processed
1020          * @param array    $item     The item array
1021          * @param array    $importer user record of the importing user
1022          *
1023          * @return array with data from links
1024          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1025          * @throws \ImagickException
1026          */
1027         private static function processRepeatedItem(DOMXPath $xpath, $entry, array &$item, array $importer)
1028         {
1029                 $activityobject = $xpath->query('activity:object', $entry)->item(0);
1030
1031                 if (!is_object($activityobject)) {
1032                         return [];
1033                 }
1034
1035                 $link_data = [];
1036
1037                 $orig_uri = XML::getFirstNodeValue($xpath, 'atom:id/text()', $activityobject);
1038
1039                 $links = $xpath->query("atom:link", $activityobject);
1040                 if ($links) {
1041                         $link_data = self::processLinks($links, $item);
1042                 }
1043
1044                 $orig_body = XML::getFirstNodeValue($xpath, 'atom:content/text()', $activityobject);
1045                 $orig_created = XML::getFirstNodeValue($xpath, 'atom:published/text()', $activityobject);
1046                 $orig_edited = XML::getFirstNodeValue($xpath, 'atom:updated/text()', $activityobject);
1047
1048                 $orig_author = self::fetchAuthor($xpath, $activityobject, $importer, $dummy, false);
1049
1050                 $item["author-name"] = $orig_author["author-name"];
1051                 $item["author-link"] = $orig_author["author-link"];
1052                 $item["author-id"] = $orig_author["author-id"];
1053
1054                 $item["body"] = HTML::toBBCode($orig_body);
1055                 $item["created"] = $orig_created;
1056                 $item["edited"] = $orig_edited;
1057
1058                 $item["uri"] = $orig_uri;
1059
1060                 $item["verb"] = XML::getFirstNodeValue($xpath, 'activity:verb/text()', $activityobject);
1061
1062                 $item["object-type"] = XML::getFirstNodeValue($xpath, 'activity:object-type/text()', $activityobject);
1063
1064                 // Mastodon Content Warning
1065                 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $activityobject)) {
1066                         $clear_text = XML::getFirstNodeValue($xpath, 'atom:summary/text()', $activityobject);
1067                         if (!empty($clear_text)) {
1068                                 $item['content-warning'] = HTML::toBBCode($clear_text);
1069                         }
1070                 }
1071
1072                 $inreplyto = $xpath->query('thr:in-reply-to', $activityobject);
1073                 if (is_object($inreplyto->item(0))) {
1074                         foreach ($inreplyto->item(0)->attributes as $attributes) {
1075                                 if ($attributes->name == "ref") {
1076                                         $item["parent-uri"] = $attributes->textContent;
1077                                 }
1078                         }
1079                 }
1080
1081                 return $link_data;
1082         }
1083
1084         /**
1085          * @brief Processes links in the XML
1086          *
1087          * @param object $links The xml data that contain links
1088          * @param array  $item  The item array
1089          *
1090          * @return array with data from the links
1091          */
1092         private static function processLinks($links, array &$item)
1093         {
1094                 $link_data = ['add_body' => '', 'self' => ''];
1095
1096                 foreach ($links as $link) {
1097                         $attribute = self::readAttributes($link);
1098
1099                         if (!empty($attribute['rel']) && !empty($attribute['href'])) {
1100                                 switch ($attribute['rel']) {
1101                                         case "alternate":
1102                                                 $item["plink"] = $attribute['href'];
1103                                                 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1104                                                         || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1105                                                 ) {
1106                                                         $item["body"] .= add_page_info($attribute['href']);
1107                                                 }
1108                                                 break;
1109                                         case "ostatus:conversation":
1110                                                 $link_data['conversation'] = $attribute['href'];
1111                                                 $item['conversation-href'] = $link_data['conversation'];
1112                                                 if (!isset($item['conversation-uri'])) {
1113                                                         $item['conversation-uri'] = $item['conversation-href'];
1114                                                 }
1115                                                 break;
1116                                         case "enclosure":
1117                                                 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1118                                                 if ($filetype == 'image') {
1119                                                         $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1120                                                 } else {
1121                                                         if (!empty($item["attach"])) {
1122                                                                 $item["attach"] .= ',';
1123                                                         } else {
1124                                                                 $item["attach"] = '';
1125                                                         }
1126                                                         if (!isset($attribute['length'])) {
1127                                                                 $attribute['length'] = "0";
1128                                                         }
1129                                                         $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.defaults($attribute, 'title', '').'"[/attach]';
1130                                                 }
1131                                                 break;
1132                                         case "related":
1133                                                 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1134                                                         if (!isset($item["parent-uri"])) {
1135                                                                 $item["parent-uri"] = $attribute['href'];
1136                                                         }
1137                                                         $link_data['related'] = $attribute['href'];
1138                                                 } else {
1139                                                         $item["body"] .= add_page_info($attribute['href']);
1140                                                 }
1141                                                 break;
1142                                         case "self":
1143                                                 if (empty($item["plink"])) {
1144                                                         $item["plink"] = $attribute['href'];
1145                                                 }
1146                                                 $link_data['self'] = $attribute['href'];
1147                                                 break;
1148                                 }
1149                         }
1150                 }
1151                 return $link_data;
1152         }
1153
1154         /**
1155          * @brief Create an url out of an uri
1156          *
1157          * @param string $href URI in the format "parameter1:parameter1:..."
1158          *
1159          * @return string URL in the format http(s)://....
1160          */
1161         public static function convertHref($href)
1162         {
1163                 $elements = explode(":", $href);
1164
1165                 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1166                         return $href;
1167                 }
1168
1169                 $server = explode(",", $elements[1]);
1170                 $conversation = explode("=", $elements[2]);
1171
1172                 if ((count($elements) == 4) && ($elements[2] == "post")) {
1173                         return "http://".$server[0]."/notice/".$elements[3];
1174                 }
1175
1176                 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1177                         return $href;
1178                 }
1179                 if ($elements[3] == "objectType=thread") {
1180                         return "http://".$server[0]."/conversation/".$conversation[1];
1181                 } else {
1182                         return "http://".$server[0]."/notice/".$conversation[1];
1183                 }
1184         }
1185
1186         /**
1187          * @brief Checks if the current post is a reshare
1188          *
1189          * @param array $item The item array of thw post
1190          *
1191          * @return string The guid if the post is a reshare
1192          */
1193         private static function getResharedGuid(array $item)
1194         {
1195                 $body = trim($item["body"]);
1196
1197                 // Skip if it isn't a pure repeated messages
1198                 // Does it start with a share?
1199                 if (strpos($body, "[share") > 0) {
1200                         return "";
1201                 }
1202
1203                 // Does it end with a share?
1204                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1205                         return "";
1206                 }
1207
1208                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1209                 // Skip if there is no shared message in there
1210                 if ($body == $attributes) {
1211                         return false;
1212                 }
1213
1214                 $guid = "";
1215                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1216                 if (!empty($matches[1])) {
1217                         $guid = $matches[1];
1218                 }
1219
1220                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1221                 if (!empty($matches[1])) {
1222                         $guid = $matches[1];
1223                 }
1224
1225                 return $guid;
1226         }
1227
1228         /**
1229          * @brief Cleans the body of a post if it contains picture links
1230          *
1231          * @param string $body The body
1232          *
1233          * @return string The cleaned body
1234          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1235          */
1236         private static function formatPicturePost($body)
1237         {
1238                 $siteinfo = BBCode::getAttachedData($body);
1239
1240                 if (($siteinfo["type"] == "photo") && (!empty($siteinfo["preview"]) || !empty($siteinfo["image"]))) {
1241                         if (isset($siteinfo["preview"])) {
1242                                 $preview = $siteinfo["preview"];
1243                         } else {
1244                                 $preview = $siteinfo["image"];
1245                         }
1246
1247                         // Is it a remote picture? Then make a smaller preview here
1248                         $preview = ProxyUtils::proxifyUrl($preview, false, ProxyUtils::SIZE_SMALL);
1249
1250                         // Is it a local picture? Then make it smaller here
1251                         $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1252                         $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1253
1254                         if (isset($siteinfo["url"])) {
1255                                 $url = $siteinfo["url"];
1256                         } else {
1257                                 $url = $siteinfo["image"];
1258                         }
1259
1260                         $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1261                 }
1262
1263                 return $body;
1264         }
1265
1266         /**
1267          * @brief Adds the header elements to the XML document
1268          *
1269          * @param DOMDocument $doc       XML document
1270          * @param array       $owner     Contact data of the poster
1271          * @param string      $filter    The related feed filter (activity, posts or comments)
1272          * @param bool        $feed_mode Behave like a regular feed for users if true
1273          *
1274          * @return object header root element
1275          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1276          */
1277         private static function addHeader(DOMDocument $doc, array $owner, $filter, $feed_mode = false)
1278         {
1279                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1280                 $doc->appendChild($root);
1281
1282                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1283                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1284                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1285                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1286                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1287                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1288                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1289                 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1290
1291                 $title = '';
1292                 $selfUri = '/feed/' . $owner["nick"] . '/';
1293                 switch ($filter) {
1294                         case 'activity':
1295                                 $title = L10n::t('%s\'s timeline', $owner['name']);
1296                                 $selfUri .= $filter;
1297                                 break;
1298                         case 'posts':
1299                                 $title = L10n::t('%s\'s posts', $owner['name']);
1300                                 break;
1301                         case 'comments':
1302                                 $title = L10n::t('%s\'s comments', $owner['name']);
1303                                 $selfUri .= $filter;
1304                                 break;
1305                 }
1306
1307                 if (!$feed_mode) {
1308                         $selfUri = "/dfrn_poll/" . $owner["nick"];
1309                 }
1310
1311                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1312                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1313                 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1314                 XML::addElement($doc, $root, "title", $title);
1315                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], Config::get('config', 'sitename')));
1316                 XML::addElement($doc, $root, "logo", $owner["photo"]);
1317                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1318
1319                 $author = self::addAuthor($doc, $owner);
1320                 $root->appendChild($author);
1321
1322                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1323                 XML::addElement($doc, $root, "link", "", $attributes);
1324
1325                 /// @TODO We have to find out what this is
1326                 /// $attributes = array("href" => System::baseUrl()."/sup",
1327                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1328                 ///             "type" => "application/json");
1329                 /// XML::addElement($doc, $root, "link", "", $attributes);
1330
1331                 self::hublinks($doc, $root, $owner["nick"]);
1332
1333                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1334                 XML::addElement($doc, $root, "link", "", $attributes);
1335
1336                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1337                 XML::addElement($doc, $root, "link", "", $attributes);
1338
1339                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1340                 XML::addElement($doc, $root, "link", "", $attributes);
1341
1342                 $attributes = ["href" => System::baseUrl() . $selfUri, "rel" => "self", "type" => "application/atom+xml"];
1343                 XML::addElement($doc, $root, "link", "", $attributes);
1344
1345                 if ($owner['account-type'] == Contact::TYPE_COMMUNITY) {
1346                         $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1347                                         'archive' => false, 'hidden' => false, 'blocked' => false];
1348                         $members = DBA::count('contact', $condition);
1349                         XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1350                 }
1351
1352                 return $root;
1353         }
1354
1355         /**
1356          * @brief Add the link to the push hubs to the XML document
1357          *
1358          * @param DOMDocument $doc  XML document
1359          * @param object      $root XML root element where the hub links are added
1360          * @param object      $nick nick
1361          * @return void
1362          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363          */
1364         public static function hublinks(DOMDocument $doc, $root, $nick)
1365         {
1366                 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1367                 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1368         }
1369
1370         /**
1371          * @brief Adds attachment data to the XML document
1372          *
1373          * @param DOMDocument $doc  XML document
1374          * @param object      $root XML root element where the hub links are added
1375          * @param array       $item Data of the item that is to be posted
1376          * @return void
1377          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1378          */
1379         private static function getAttachment(DOMDocument $doc, $root, $item)
1380         {
1381                 $siteinfo = BBCode::getAttachedData($item["body"]);
1382
1383                 switch ($siteinfo["type"]) {
1384                         case 'photo':
1385                                 if (!empty($siteinfo["image"])) {
1386                                         $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1387                                         if ($imgdata) {
1388                                                 $attributes = ["rel" => "enclosure",
1389                                                                 "href" => $siteinfo["image"],
1390                                                                 "type" => $imgdata["mime"],
1391                                                                 "length" => intval($imgdata["size"])];
1392                                                 XML::addElement($doc, $root, "link", "", $attributes);
1393                                         }
1394                                 }
1395                                 break;
1396                         case 'video':
1397                                 $attributes = ["rel" => "enclosure",
1398                                                 "href" => $siteinfo["url"],
1399                                                 "type" => "text/html; charset=UTF-8",
1400                                                 "length" => "",
1401                                                 "title" => defaults($siteinfo, "title", $siteinfo["url"])];
1402                                 XML::addElement($doc, $root, "link", "", $attributes);
1403                                 break;
1404                         default:
1405                                 break;
1406                 }
1407
1408                 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1409                         $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1410                         if ($imgdata) {
1411                                 $attributes = ["rel" => "enclosure",
1412                                                 "href" => $siteinfo["image"],
1413                                                 "type" => $imgdata["mime"],
1414                                                 "length" => intval($imgdata["size"])];
1415
1416                                 XML::addElement($doc, $root, "link", "", $attributes);
1417                         }
1418                 }
1419
1420                 $arr = explode('[/attach],', $item['attach']);
1421                 if (count($arr)) {
1422                         foreach ($arr as $r) {
1423                                 $matches = false;
1424                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1425                                 if ($cnt) {
1426                                         $attributes = ["rel" => "enclosure",
1427                                                         "href" => $matches[1],
1428                                                         "type" => $matches[3]];
1429
1430                                         if (intval($matches[2])) {
1431                                                 $attributes["length"] = intval($matches[2]);
1432                                         }
1433                                         if (trim($matches[4]) != "") {
1434                                                 $attributes["title"] = trim($matches[4]);
1435                                         }
1436                                         XML::addElement($doc, $root, "link", "", $attributes);
1437                                 }
1438                         }
1439                 }
1440         }
1441
1442         /**
1443          * @brief Adds the author element to the XML document
1444          *
1445          * @param DOMDocument $doc          XML document
1446          * @param array       $owner        Contact data of the poster
1447          * @param bool        $show_profile Whether to show profile
1448          *
1449          * @return \DOMElement author element
1450          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1451          */
1452         private static function addAuthor(DOMDocument $doc, array $owner, $show_profile = true)
1453         {
1454                 $profile = DBA::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1455                 $author = $doc->createElement("author");
1456                 XML::addElement($doc, $author, "id", $owner["url"]);
1457                 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1458                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1459                 } else {
1460                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1461                 }
1462                 XML::addElement($doc, $author, "uri", $owner["url"]);
1463                 XML::addElement($doc, $author, "name", $owner["nick"]);
1464                 XML::addElement($doc, $author, "email", $owner["addr"]);
1465                 if ($show_profile) {
1466                         XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1467                 }
1468
1469                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1470                 XML::addElement($doc, $author, "link", "", $attributes);
1471
1472                 $attributes = [
1473                                 "rel" => "avatar",
1474                                 "type" => "image/jpeg", // To-Do?
1475                                 "media:width" => 300,
1476                                 "media:height" => 300,
1477                                 "href" => $owner["photo"]];
1478                 XML::addElement($doc, $author, "link", "", $attributes);
1479
1480                 if (isset($owner["thumb"])) {
1481                         $attributes = [
1482                                         "rel" => "avatar",
1483                                         "type" => "image/jpeg", // To-Do?
1484                                         "media:width" => 80,
1485                                         "media:height" => 80,
1486                                         "href" => $owner["thumb"]];
1487                         XML::addElement($doc, $author, "link", "", $attributes);
1488                 }
1489
1490                 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1491                 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1492                 if ($show_profile) {
1493                         XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1494
1495                         if (trim($owner["location"]) != "") {
1496                                 $element = $doc->createElement("poco:address");
1497                                 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1498                                 $author->appendChild($element);
1499                         }
1500                 }
1501
1502                 if (DBA::isResult($profile) && !$show_profile) {
1503                         if (trim($profile["homepage"]) != "") {
1504                                 $urls = $doc->createElement("poco:urls");
1505                                 XML::addElement($doc, $urls, "poco:type", "homepage");
1506                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1507                                 XML::addElement($doc, $urls, "poco:primary", "true");
1508                                 $author->appendChild($urls);
1509                         }
1510
1511                         XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl() . "/profile/" . $owner["nick"] . "/contacts/followers"]);
1512                         XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1513
1514                         if ($profile["publish"]) {
1515                                 XML::addElement($doc, $author, "mastodon:scope", "public");
1516                         }
1517                 }
1518
1519                 return $author;
1520         }
1521
1522         /**
1523          * @TODO Picture attachments should look like this:
1524          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1525          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1526          */
1527
1528         /**
1529          * @brief Returns the given activity if present - otherwise returns the "post" activity
1530          *
1531          * @param array $item Data of the item that is to be posted
1532          *
1533          * @return string activity
1534          */
1535         private static function constructVerb(array $item)
1536         {
1537                 if (!empty($item['verb'])) {
1538                         return $item['verb'];
1539                 }
1540
1541                 return ACTIVITY_POST;
1542         }
1543
1544         /**
1545          * @brief Returns the given object type if present - otherwise returns the "note" object type
1546          *
1547          * @param array $item Data of the item that is to be posted
1548          *
1549          * @return string Object type
1550          */
1551         private static function constructObjecttype(array $item)
1552         {
1553                 if (!empty($item['object-type']) && in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT])) {
1554                         return $item['object-type'];
1555                 }
1556
1557                 return ACTIVITY_OBJ_NOTE;
1558         }
1559
1560         /**
1561          * @brief Adds an entry element to the XML document
1562          *
1563          * @param DOMDocument $doc       XML document
1564          * @param array       $item      Data of the item that is to be posted
1565          * @param array       $owner     Contact data of the poster
1566          * @param bool        $toplevel  optional default false
1567          * @param bool        $feed_mode Behave like a regular feed for users if true
1568          *
1569          * @return \DOMElement Entry element
1570          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1571          * @throws \ImagickException
1572          */
1573         private static function entry(DOMDocument $doc, array $item, array $owner, $toplevel = false, $feed_mode = false)
1574         {
1575                 $xml = null;
1576
1577                 $repeated_guid = self::getResharedGuid($item);
1578                 if ($repeated_guid != "") {
1579                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1580                 }
1581
1582                 if ($xml) {
1583                         return $xml;
1584                 }
1585
1586                 if ($item["verb"] == ACTIVITY_LIKE) {
1587                         return self::likeEntry($doc, $item, $owner, $toplevel);
1588                 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1589                         return self::followEntry($doc, $item, $owner, $toplevel);
1590                 } else {
1591                         return self::noteEntry($doc, $item, $owner, $toplevel, $feed_mode);
1592                 }
1593         }
1594
1595         /**
1596          * @brief Adds a source entry to the XML document
1597          *
1598          * @param DOMDocument $doc     XML document
1599          * @param array       $contact Array of the contact that is added
1600          *
1601          * @return \DOMElement Source element
1602          * @throws \Exception
1603          */
1604         private static function sourceEntry(DOMDocument $doc, array $contact)
1605         {
1606                 $source = $doc->createElement("source");
1607                 XML::addElement($doc, $source, "id", $contact["poll"]);
1608                 XML::addElement($doc, $source, "title", $contact["name"]);
1609                 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1610                 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1611                 XML::addElement($doc, $source, "icon", $contact["photo"]);
1612                 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1613
1614                 return $source;
1615         }
1616
1617         /**
1618          * @brief Fetches contact data from the contact or the gcontact table
1619          *
1620          * @param string $url   URL of the contact
1621          * @param array  $owner Contact data of the poster
1622          *
1623          * @return array Contact array
1624          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1625          * @throws \ImagickException
1626          */
1627         private static function contactEntry($url, array $owner)
1628         {
1629                 $r = q(
1630                         "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1631                         DBA::escape(Strings::normaliseLink($url)),
1632                         intval($owner["uid"])
1633                 );
1634                 if (DBA::isResult($r)) {
1635                         $contact = $r[0];
1636                         $contact["uid"] = -1;
1637                 }
1638
1639                 if (!DBA::isResult($r)) {
1640                         $gcontact = DBA::selectFirst('gcontact', [], ['nurl' => Strings::normaliseLink($url)]);
1641                         if (DBA::isResult($r)) {
1642                                 $contact = $gcontact;
1643                                 $contact["uid"] = -1;
1644                                 $contact["success_update"] = $contact["updated"];
1645                         }
1646                 }
1647
1648                 if (!DBA::isResult($r)) {
1649                         $contact = $owner;
1650                 }
1651
1652                 if (!isset($contact["poll"])) {
1653                         $data = Probe::uri($url);
1654                         $contact["poll"] = $data["poll"];
1655
1656                         if (!$contact["alias"]) {
1657                                 $contact["alias"] = $data["alias"];
1658                         }
1659                 }
1660
1661                 if (!isset($contact["alias"])) {
1662                         $contact["alias"] = $contact["url"];
1663                 }
1664
1665                 $contact['account-type'] = $owner['account-type'];
1666
1667                 return $contact;
1668         }
1669
1670         /**
1671          * @brief Adds an entry element with reshared content
1672          *
1673          * @param DOMDocument $doc           XML document
1674          * @param array       $item          Data of the item that is to be posted
1675          * @param array       $owner         Contact data of the poster
1676          * @param string      $repeated_guid guid
1677          * @param bool        $toplevel      Is it for en entry element (false) or a feed entry (true)?
1678          *
1679          * @return bool Entry element
1680          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1681          * @throws \ImagickException
1682          */
1683         private static function reshareEntry(DOMDocument $doc, array $item, array $owner, $repeated_guid, $toplevel)
1684         {
1685                 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1686                         Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1687                 }
1688
1689                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1690
1691                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1692                         'network' => [Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS]];
1693                 $repeated_item = Item::selectFirst([], $condition);
1694                 if (!DBA::isResult($repeated_item)) {
1695                         return false;
1696                 }
1697
1698                 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1699
1700                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1701
1702                 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1703
1704                 $as_object = $doc->createElement("activity:object");
1705
1706                 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1707
1708                 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1709
1710                 $author = self::addAuthor($doc, $contact, false);
1711                 $as_object->appendChild($author);
1712
1713                 $as_object2 = $doc->createElement("activity:object");
1714
1715                 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1716
1717                 $title = sprintf("New comment by %s", $contact["nick"]);
1718
1719                 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1720
1721                 $as_object->appendChild($as_object2);
1722
1723                 self::entryFooter($doc, $as_object, $item, $owner, false);
1724
1725                 $source = self::sourceEntry($doc, $contact);
1726
1727                 $as_object->appendChild($source);
1728
1729                 $entry->appendChild($as_object);
1730
1731                 self::entryFooter($doc, $entry, $item, $owner);
1732
1733                 return $entry;
1734         }
1735
1736         /**
1737          * @brief Adds an entry element with a "like"
1738          *
1739          * @param DOMDocument $doc      XML document
1740          * @param array       $item     Data of the item that is to be posted
1741          * @param array       $owner    Contact data of the poster
1742          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1743          *
1744          * @return \DOMElement Entry element with "like"
1745          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1746          * @throws \ImagickException
1747          */
1748         private static function likeEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1749         {
1750                 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1751                         Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1752                 }
1753
1754                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1755
1756                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1757                 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1758
1759                 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1760                 if (DBA::isResult($parent)) {
1761                         $as_object = $doc->createElement("activity:object");
1762
1763                         XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1764
1765                         self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1766
1767                         $entry->appendChild($as_object);
1768                 }
1769
1770                 self::entryFooter($doc, $entry, $item, $owner);
1771
1772                 return $entry;
1773         }
1774
1775         /**
1776          * @brief Adds the person object element to the XML document
1777          *
1778          * @param DOMDocument $doc     XML document
1779          * @param array       $owner   Contact data of the poster
1780          * @param array       $contact Contact data of the target
1781          *
1782          * @return object author element
1783          */
1784         private static function addPersonObject(DOMDocument $doc, array $owner, array $contact)
1785         {
1786                 $object = $doc->createElement("activity:object");
1787                 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1788
1789                 if ($contact['network'] == Protocol::PHANTOM) {
1790                         XML::addElement($doc, $object, "id", $contact['url']);
1791                         return $object;
1792                 }
1793
1794                 XML::addElement($doc, $object, "id", $contact["alias"]);
1795                 XML::addElement($doc, $object, "title", $contact["nick"]);
1796
1797                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1798                 XML::addElement($doc, $object, "link", "", $attributes);
1799
1800                 $attributes = [
1801                                 "rel" => "avatar",
1802                                 "type" => "image/jpeg", // To-Do?
1803                                 "media:width" => 300,
1804                                 "media:height" => 300,
1805                                 "href" => $contact["photo"]];
1806                 XML::addElement($doc, $object, "link", "", $attributes);
1807
1808                 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1809                 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1810
1811                 if (trim($contact["location"]) != "") {
1812                         $element = $doc->createElement("poco:address");
1813                         XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1814                         $object->appendChild($element);
1815                 }
1816
1817                 return $object;
1818         }
1819
1820         /**
1821          * @brief Adds a follow/unfollow entry element
1822          *
1823          * @param DOMDocument $doc      XML document
1824          * @param array       $item     Data of the follow/unfollow message
1825          * @param array       $owner    Contact data of the poster
1826          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1827          *
1828          * @return \DOMElement Entry element
1829          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1830          * @throws \ImagickException
1831          */
1832         private static function followEntry(DOMDocument $doc, array $item, array $owner, $toplevel)
1833         {
1834                 $item["id"] = $item["parent"] = 0;
1835                 $item["created"] = $item["edited"] = date("c");
1836                 $item["private"] = true;
1837
1838                 $contact = Probe::uri($item['follow']);
1839
1840                 if ($contact['alias'] == '') {
1841                         $contact['alias'] = $contact["url"];
1842                 } else {
1843                         $item['follow'] = $contact['alias'];
1844                 }
1845
1846                 $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($contact["url"])];
1847                 $user_contact = DBA::selectFirst('contact', ['id'], $condition);
1848
1849                 if (DBA::isResult($user_contact)) {
1850                         $connect_id = $user_contact['id'];
1851                 } else {
1852                         $connect_id = 0;
1853                 }
1854
1855                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1856                         $message = L10n::t('%s is now following %s.');
1857                         $title = L10n::t('following');
1858                         $action = "subscription";
1859                 } else {
1860                         $message = L10n::t('%s stopped following %s.');
1861                         $title = L10n::t('stopped following');
1862                         $action = "unfollow";
1863                 }
1864
1865                 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1866                                 = 'tag:'.get_app()->getHostName().
1867                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1868                                 ':person:'.$connect_id.':'.$item['created'];
1869
1870                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1871
1872                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1873
1874                 self::entryContent($doc, $entry, $item, $owner, $title);
1875
1876                 $object = self::addPersonObject($doc, $owner, $contact);
1877                 $entry->appendChild($object);
1878
1879                 self::entryFooter($doc, $entry, $item, $owner);
1880
1881                 return $entry;
1882         }
1883
1884         /**
1885          * @brief Adds a regular entry element
1886          *
1887          * @param DOMDocument $doc       XML document
1888          * @param array       $item      Data of the item that is to be posted
1889          * @param array       $owner     Contact data of the poster
1890          * @param bool        $toplevel  Is it for en entry element (false) or a feed entry (true)?
1891          * @param bool        $feed_mode Behave like a regular feed for users if true
1892          *
1893          * @return \DOMElement Entry element
1894          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1895          * @throws \ImagickException
1896          */
1897         private static function noteEntry(DOMDocument $doc, array $item, array $owner, $toplevel, $feed_mode)
1898         {
1899                 if (($item["id"] != $item["parent"]) && (Strings::normaliseLink($item["author-link"]) != Strings::normaliseLink($owner["url"]))) {
1900                         Logger::log("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", Logger::DEBUG);
1901                 }
1902
1903                 if (!$toplevel) {
1904                         if (!empty($item['title'])) {
1905                                 $title = BBCode::convert($item['title'], false, 7);
1906                         } else {
1907                                 $title = sprintf("New note by %s", $owner["nick"]);
1908                         }
1909                 } else {
1910                         $title = sprintf("New comment by %s", $owner["nick"]);
1911                 }
1912
1913                 $entry = self::entryHeader($doc, $owner, $item, $toplevel);
1914
1915                 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1916
1917                 self::entryContent($doc, $entry, $item, $owner, $title, '', true, $feed_mode);
1918
1919                 self::entryFooter($doc, $entry, $item, $owner, !$feed_mode, $feed_mode);
1920
1921                 return $entry;
1922         }
1923
1924         /**
1925          * @brief Adds a header element to the XML document
1926          *
1927          * @param DOMDocument $doc      XML document
1928          * @param array       $owner    Contact data of the poster
1929          * @param array       $item
1930          * @param bool        $toplevel Is it for en entry element (false) or a feed entry (true)?
1931          *
1932          * @return \DOMElement The entry element where the elements are added
1933          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1934          * @throws \ImagickException
1935          */
1936         private static function entryHeader(DOMDocument $doc, array $owner, array $item, $toplevel)
1937         {
1938                 if (!$toplevel) {
1939                         $entry = $doc->createElement("entry");
1940
1941                         if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
1942                                 $contact = self::contactEntry($item['author-link'], $owner);
1943                                 $author = self::addAuthor($doc, $contact, false);
1944                                 $entry->appendChild($author);
1945                         }
1946                 } else {
1947                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1948
1949                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1950                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1951                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1952                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1953                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1954                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1955                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1956                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1957
1958                         $author = self::addAuthor($doc, $owner);
1959                         $entry->appendChild($author);
1960                 }
1961
1962                 return $entry;
1963         }
1964
1965         /**
1966          * @brief Adds elements to the XML document
1967          *
1968          * @param DOMDocument $doc       XML document
1969          * @param \DOMElement $entry     Entry element where the content is added
1970          * @param array       $item      Data of the item that is to be posted
1971          * @param array       $owner     Contact data of the poster
1972          * @param string      $title     Title for the post
1973          * @param string      $verb      The activity verb
1974          * @param bool        $complete  Add the "status_net" element?
1975          * @param bool        $feed_mode Behave like a regular feed for users if true
1976          * @return void
1977          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1978          */
1979         private static function entryContent(DOMDocument $doc, \DOMElement $entry, array $item, array $owner, $title, $verb = "", $complete = true, $feed_mode = false)
1980         {
1981                 if ($verb == "") {
1982                         $verb = self::constructVerb($item);
1983                 }
1984
1985                 XML::addElement($doc, $entry, "id", $item["uri"]);
1986                 XML::addElement($doc, $entry, "title", html_entity_decode($title, ENT_QUOTES, 'UTF-8'));
1987
1988                 $body = self::formatPicturePost($item['body']);
1989
1990                 if (!empty($item['title']) && !$feed_mode) {
1991                         $body = "[b]".$item['title']."[/b]\n\n".$body;
1992                 }
1993
1994                 $body = BBCode::convert($body, false, 7);
1995
1996                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1997
1998                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1999                                                                 "href" => System::baseUrl()."/display/".$item["guid"]]
2000                 );
2001
2002                 if (!$feed_mode && $complete && ($item["id"] > 0)) {
2003                         XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
2004                 }
2005
2006                 if (!$feed_mode) {
2007                         XML::addElement($doc, $entry, "activity:verb", $verb);
2008                 }
2009
2010                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
2011                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
2012         }
2013
2014         /**
2015          * @brief Adds the elements at the foot of an entry to the XML document
2016          *
2017          * @param DOMDocument $doc       XML document
2018          * @param object      $entry     The entry element where the elements are added
2019          * @param array       $item      Data of the item that is to be posted
2020          * @param array       $owner     Contact data of the poster
2021          * @param bool        $complete  default true
2022          * @param bool        $feed_mode Behave like a regular feed for users if true
2023          * @return void
2024          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2025          */
2026         private static function entryFooter(DOMDocument $doc, $entry, array $item, array $owner, $complete = true, $feed_mode = false)
2027         {
2028                 $mentioned = [];
2029
2030                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
2031                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
2032                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2033
2034                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
2035
2036                         if (DBA::isResult($thrparent)) {
2037                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
2038                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
2039                                 $parent_plink = $thrparent["plink"];
2040                         } else {
2041                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
2042                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
2043                                 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
2044                         }
2045
2046                         $attributes = [
2047                                         "ref" => $parent_item,
2048                                         "href" => $parent_plink];
2049                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
2050
2051                         $attributes = [
2052                                         "rel" => "related",
2053                                         "href" => $parent_plink];
2054                         XML::addElement($doc, $entry, "link", "", $attributes);
2055                 }
2056
2057                 if (!$feed_mode && (intval($item["parent"]) > 0)) {
2058                         $conversation_href = $conversation_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
2059
2060                         if (isset($parent_item)) {
2061                                 $conversation = DBA::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
2062                                 if (DBA::isResult($conversation)) {
2063                                         if ($conversation['conversation-uri'] != '') {
2064                                                 $conversation_uri = $conversation['conversation-uri'];
2065                                         }
2066                                         if ($conversation['conversation-href'] != '') {
2067                                                 $conversation_href = $conversation['conversation-href'];
2068                                         }
2069                                 }
2070                         }
2071
2072                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
2073
2074                         $attributes = [
2075                                         "href" => $conversation_href,
2076                                         "local_id" => $item["parent"],
2077                                         "ref" => $conversation_uri];
2078
2079                         XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2080                 }
2081
2082                 $tags = item::getFeedTags($item);
2083
2084                 if (count($tags)) {
2085                         foreach ($tags as $t) {
2086                                 if ($t[0] == "@") {
2087                                         $mentioned[$t[1]] = $t[1];
2088                                 }
2089                         }
2090                 }
2091
2092                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2093                 $newmentions = [];
2094                 foreach ($mentioned as $mention) {
2095                         $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2096                         $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2097                 }
2098                 $mentioned = $newmentions;
2099
2100                 foreach ($mentioned as $mention) {
2101                         $condition = ['uid' => $owner['uid'], 'nurl' => Strings::normaliseLink($mention)];
2102                         $contact = DBA::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2103                         if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == Contact::TYPE_COMMUNITY) ||
2104                                 ($contact['self'] && ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY))) {
2105                                 XML::addElement($doc, $entry, "link", "",
2106                                         [
2107                                                 "rel" => "mentioned",
2108                                                 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2109                                                 "href" => $mention]
2110                                 );
2111                         } else {
2112                                 XML::addElement($doc, $entry, "link", "",
2113                                         [
2114                                                 "rel" => "mentioned",
2115                                                 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2116                                                 "href" => $mention]
2117                                 );
2118                         }
2119                 }
2120
2121                 if ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) {
2122                         XML::addElement($doc, $entry, "link", "", [
2123                                 "rel" => "mentioned",
2124                                 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2125                                 "href" => $owner['url']
2126                         ]);
2127                 }
2128
2129                 if (!$item["private"] && !$feed_mode) {
2130                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2131                                                                         "href" => "http://activityschema.org/collection/public"]);
2132                         XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2133                                                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2134                                                                         "href" => "http://activityschema.org/collection/public"]);
2135                         XML::addElement($doc, $entry, "mastodon:scope", "public");
2136                 }
2137
2138                 if (count($tags)) {
2139                         foreach ($tags as $t) {
2140                                 if ($t[0] != "@") {
2141                                         XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2142                                 }
2143                         }
2144                 }
2145
2146                 self::getAttachment($doc, $entry, $item);
2147
2148                 if ($complete && ($item["id"] > 0)) {
2149                         $app = $item["app"];
2150                         if ($app == "") {
2151                                 $app = "web";
2152                         }
2153
2154                         $attributes = ["local_id" => $item["id"], "source" => $app];
2155
2156                         if (isset($parent["id"])) {
2157                                 $attributes["repeat_of"] = $parent["id"];
2158                         }
2159
2160                         if ($item["coord"] != "") {
2161                                 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2162                         }
2163
2164                         XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2165                 }
2166         }
2167
2168         /**
2169          * Creates the XML feed for a given nickname
2170          *
2171          * Supported filters:
2172          * - activity (default): all the public posts
2173          * - posts: all the public top-level posts
2174          * - comments: all the public replies
2175          *
2176          * Updates the provided last_update parameter if the result comes from the
2177          * cache or it is empty
2178          *
2179          * @brief Creates the XML feed for a given nickname
2180          *
2181          * @param string  $owner_nick  Nickname of the feed owner
2182          * @param string  $last_update Date of the last update
2183          * @param integer $max_items   Number of maximum items to fetch
2184          * @param string  $filter      Feed items filter (activity, posts or comments)
2185          * @param boolean $nocache     Wether to bypass caching
2186          * @param boolean $feed_mode   Behave like a regular feed for users if true
2187          *
2188          * @return string XML feed
2189          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2190          * @throws \ImagickException
2191          */
2192         public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false, $feed_mode = false)
2193         {
2194                 $stamp = microtime(true);
2195
2196                 $owner = User::getOwnerDataByNick($owner_nick);
2197                 if (!$owner) {
2198                         return;
2199                 }
2200
2201                 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2202
2203                 $previous_created = $last_update;
2204
2205                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2206                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2207                         $result = Cache::get($cachekey);
2208                         if (!$nocache && !is_null($result)) {
2209                                 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', Logger::DEBUG);
2210                                 $last_update = $result['last_update'];
2211                                 return $result['feed'];
2212                         }
2213                 }
2214
2215                 if (!strlen($last_update)) {
2216                         $last_update = 'now -30 days';
2217                 }
2218
2219                 $check_date = DateTimeFormat::utc($last_update);
2220                 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2221
2222                 $condition = ["`uid` = ? AND `received` > ? AND NOT `deleted`
2223                         AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2224                         $owner["uid"], $check_date, Protocol::OSTATUS, Protocol::DFRN];
2225
2226                 if ($filter === 'comments') {
2227                         $condition[0] .= " AND `object-type` = ? ";
2228                         $condition[] = ACTIVITY_OBJ_COMMENT;
2229                 }
2230
2231                 if ($owner['account-type'] != User::ACCOUNT_TYPE_COMMUNITY) {
2232                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2233                         $condition[] = $owner["id"];
2234                         $condition[] = $authorid;
2235                 }
2236
2237                 $params = ['order' => ['received' => true], 'limit' => $max_items];
2238
2239                 if ($filter === 'posts') {
2240                         $ret = Item::selectThread([], $condition, $params);
2241                 } else {
2242                         $ret = Item::select([], $condition, $params);
2243                 }
2244
2245                 $items = Item::inArray($ret);
2246
2247                 $doc = new DOMDocument('1.0', 'utf-8');
2248                 $doc->formatOutput = true;
2249
2250                 $root = self::addHeader($doc, $owner, $filter, $feed_mode);
2251
2252                 foreach ($items as $item) {
2253                         if (Config::get('system', 'ostatus_debug')) {
2254                                 $item['body'] .= '🍼';
2255                         }
2256
2257                         $entry = self::entry($doc, $item, $owner, false, $feed_mode);
2258                         $root->appendChild($entry);
2259
2260                         if ($last_update < $item['created']) {
2261                                 $last_update = $item['created'];
2262                         }
2263                 }
2264
2265                 $feeddata = trim($doc->saveXML());
2266
2267                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2268                 Cache::set($cachekey, $msg, Cache::QUARTER_HOUR);
2269
2270                 Logger::log('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, Logger::DEBUG);
2271
2272                 return $feeddata;
2273         }
2274
2275         /**
2276          * @brief Creates the XML for a salmon message
2277          *
2278          * @param array $item  Data of the item that is to be posted
2279          * @param array $owner Contact data of the poster
2280          *
2281          * @return string XML for the salmon
2282          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2283          * @throws \ImagickException
2284          */
2285         public static function salmon(array $item, array $owner)
2286         {
2287                 $doc = new DOMDocument('1.0', 'utf-8');
2288                 $doc->formatOutput = true;
2289
2290                 if (Config::get('system', 'ostatus_debug')) {
2291                         $item['body'] .= '🐟';
2292                 }
2293
2294                 $entry = self::entry($doc, $item, $owner, true);
2295
2296                 $doc->appendChild($entry);
2297
2298                 return trim($doc->saveXML());
2299         }
2300 }