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