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