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