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