]> git.mxchange.org Git - friendica.git/blob - src/Protocol/OStatus.php
Typo
[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\Content\Text\HTML;
9 use Friendica\Core\Cache;
10 use Friendica\Core\Config;
11 use Friendica\Core\L10n;
12 use Friendica\Core\System;
13 use Friendica\Database\DBM;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Conversation;
16 use Friendica\Model\GContact;
17 use Friendica\Model\Item;
18 use Friendica\Model\User;
19 use Friendica\Network\Probe;
20 use Friendica\Object\Image;
21 use Friendica\Util\DateTimeFormat;
22 use Friendica\Util\Lock;
23 use Friendica\Util\Network;
24 use Friendica\Util\XML;
25 use dba;
26 use DOMDocument;
27 use DOMXPath;
28
29 require_once 'include/dba.php';
30 require_once 'include/items.php';
31 require_once 'mod/share.php';
32 require_once 'include/enotify.php';
33 require_once 'include/api.php';
34 require_once 'mod/proxy.php';
35
36 /**
37  * @brief This class contain functions for the OStatus protocol
38  */
39 class OStatus
40 {
41         private static $itemlist;
42         private static $conv_list = [];
43
44         /**
45          * @brief Fetches author data
46          *
47          * @param object $xpath     The xpath object
48          * @param object $context   The xml context of the author details
49          * @param array  $importer  user record of the importing user
50          * @param array  $contact   Called by reference, will contain the fetched contact
51          * @param bool   $onlyfetch Only fetch the header without updating the contact entries
52          *
53          * @return array Array of author related entries for the item
54          */
55         private static function fetchAuthor($xpath, $context, $importer, &$contact, $onlyfetch)
56         {
57                 $author = [];
58                 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
59                 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
60                 $addr = $xpath->evaluate('atom:author/atom:email/text()', $context)->item(0)->nodeValue;
61
62                 $aliaslink = $author["author-link"];
63
64                 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
65                 if (is_object($alternate)) {
66                         foreach ($alternate as $attributes) {
67                                 if (($attributes->name == "href") && ($attributes->textContent != "")) {
68                                         $author["author-link"] = $attributes->textContent;
69                                 }
70                         }
71                 }
72                 $author["contact-id"] = $contact["id"];
73
74                 $contact = null;
75                 if ($aliaslink != '') {
76                         $condition = ["`uid` = ? AND `alias` = ? AND `network` != ? AND `rel` IN (?, ?)",
77                                         $importer["uid"], $aliaslink, NETWORK_STATUSNET,
78                                         CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
79                         $contact = dba::selectFirst('contact', [], $condition);
80                 }
81
82                 if (!DBM::is_result($contact) && $author["author-link"] != '') {
83                         if ($aliaslink == "") {
84                                 $aliaslink = $author["author-link"];
85                         }
86
87                         $condition = ["`uid` = ? AND `nurl` IN (?, ?) AND `network` != ? AND `rel` IN (?, ?)",
88                                         $importer["uid"], normalise_link($author["author-link"]), normalise_link($aliaslink),
89                                         NETWORK_STATUSNET, CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
90                         $contact = dba::selectFirst('contact', [], $condition);
91                 }
92
93                 if (!DBM::is_result($contact) && ($addr != '')) {
94                         $condition = ["`uid` = ? AND `addr` = ? AND `network` != ? AND `rel` IN (?, ?)",
95                                         $importer["uid"], $addr, NETWORK_STATUSNET,
96                                         CONTACT_IS_SHARING, CONTACT_IS_FRIEND];
97                         $contact = dba::selectFirst('contact', [], $condition);
98                 }
99
100                 if (DBM::is_result($contact)) {
101                         if ($contact['blocked']) {
102                                 $contact['id'] = -1;
103                         }
104                         $author["contact-id"] = $contact["id"];
105                 }
106
107                 $avatarlist = [];
108                 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
109                 foreach ($avatars as $avatar) {
110                         $href = "";
111                         $width = 0;
112                         foreach ($avatar->attributes as $attributes) {
113                                 if ($attributes->name == "href") {
114                                         $href = $attributes->textContent;
115                                 }
116                                 if ($attributes->name == "width") {
117                                         $width = $attributes->textContent;
118                                 }
119                         }
120                         if ($href != "") {
121                                 $avatarlist[$width] = $href;
122                         }
123                 }
124                 if (count($avatarlist) > 0) {
125                         krsort($avatarlist);
126                         $author["author-avatar"] = Probe::fixAvatar(current($avatarlist), $author["author-link"]);
127                 }
128
129                 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
130                 if ($displayname != "") {
131                         $author["author-name"] = $displayname;
132                 }
133
134                 $author["owner-name"] = $author["author-name"];
135                 $author["owner-link"] = $author["author-link"];
136                 $author["owner-avatar"] = $author["author-avatar"];
137
138                 // Only update the contacts if it is an OStatus contact
139                 if (DBM::is_result($contact) && ($contact['id'] > 0) && !$onlyfetch && ($contact["network"] == NETWORK_OSTATUS)) {
140
141                         // Update contact data
142                         $current = $contact;
143                         unset($current['name-date']);
144
145                         // This query doesn't seem to work
146                         // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
147                         // if ($value != "")
148                         //      $contact["notify"] = $value;
149
150                         // This query doesn't seem to work as well - I hate these queries
151                         // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
152                         // if ($value != "")
153                         //      $contact["poll"] = $value;
154
155                         $contact['url'] = $author["author-link"];
156                         $contact['nurl'] = normalise_link($contact['url']);
157
158                         $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
159                         if ($value != "") {
160                                 $contact["alias"] = $value;
161                         }
162
163                         $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
164                         if ($value != "") {
165                                 $contact["name"] = $value;
166                         }
167
168                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
169                         if ($value != "") {
170                                 $contact["nick"] = $value;
171                         }
172
173                         $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
174                         if ($value != "") {
175                                 $contact["about"] = HTML::toBBCode($value);
176                         }
177
178                         $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
179                         if ($value != "") {
180                                 $contact["location"] = $value;
181                         }
182
183                         $contact['name-date'] = DateTimeFormat::utcNow();
184
185                         dba::update('contact', $contact, ['id' => $contact["id"]], $current);
186
187                         if (!empty($author["author-avatar"]) && ($author["author-avatar"] != $current['avatar'])) {
188                                 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
189                                 Contact::updateAvatar($author["author-avatar"], $importer["uid"], $contact["id"]);
190                         }
191
192                         // Ensure that we are having this contact (with uid=0)
193                         $cid = Contact::getIdForURL($aliaslink, 0, true);
194
195                         if ($cid) {
196                                 $fields = ['url', 'nurl', 'name', 'nick', 'alias', 'about', 'location'];
197                                 $old_contact = dba::selectFirst('contact', $fields, ['id' => $cid]);
198
199                                 // Update it with the current values
200                                 $fields = ['url' => $author["author-link"], 'name' => $contact["name"],
201                                                 'nurl' => normalise_link($author["author-link"]),
202                                                 'nick' => $contact["nick"], 'alias' => $contact["alias"],
203                                                 'about' => $contact["about"], 'location' => $contact["location"],
204                                                 'success_update' => DateTimeFormat::utcNow(), 'last-update' => DateTimeFormat::utcNow()];
205
206                                 dba::update('contact', $fields, ['id' => $cid], $old_contact);
207
208                                 // Update the avatar
209                                 Contact::updateAvatar($author["author-avatar"], 0, $cid);
210                         }
211
212                         $contact["generation"] = 2;
213                         $contact["hide"] = false; // OStatus contacts are never hidden
214                         $contact["photo"] = $author["author-avatar"];
215                         $gcid = GContact::update($contact);
216
217                         GContact::link($gcid, $contact["uid"], $contact["id"]);
218                 }
219
220                 return $author;
221         }
222
223         /**
224          * @brief Fetches author data from a given XML string
225          *
226          * @param string $xml      The XML
227          * @param array  $importer user record of the importing user
228          *
229          * @return array Array of author related entries for the item
230          */
231         public static function salmonAuthor($xml, $importer)
232         {
233                 if ($xml == "") {
234                         return;
235                 }
236
237                 $doc = new DOMDocument();
238                 @$doc->loadXML($xml);
239
240                 $xpath = new DOMXPath($doc);
241                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
242                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
243                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
244                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
245                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
246                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
247                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
248                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
249
250                 $contact = ["id" => 0];
251
252                 // Fetch the first author
253                 $authordata = $xpath->query('//author')->item(0);
254                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, true);
255                 return $author;
256         }
257
258         /**
259          * @brief Read attributes from element
260          *
261          * @param object $element Element object
262          *
263          * @return array attributes
264          */
265         private static function readAttributes($element)
266         {
267                 $attribute = [];
268
269                 foreach ($element->attributes as $attributes) {
270                         $attribute[$attributes->name] = $attributes->textContent;
271                 }
272
273                 return $attribute;
274         }
275
276         /**
277          * @brief Imports an XML string containing OStatus elements
278          *
279          * @param string $xml      The XML
280          * @param array  $importer user record of the importing user
281          * @param array  $contact  contact
282          * @param string $hub      Called by reference, returns the fetched hub data
283          * @return void
284          */
285         public static function import($xml, $importer, &$contact, &$hub)
286         {
287                 self::process($xml, $importer, $contact, $hub);
288         }
289
290         /**
291          * @brief Internal feed processing
292          *
293          * @param string  $xml        The XML
294          * @param array   $importer   user record of the importing user
295          * @param array   $contact    contact
296          * @param string  $hub        Called by reference, returns the fetched hub data
297          * @param boolean $stored     Is the post fresh imported or from the database?
298          * @param boolean $initialize Is it the leading post so that data has to be initialized?
299          *
300          * @return boolean Could the XML be processed?
301          */
302         private static function process($xml, $importer, &$contact, &$hub, $stored = false, $initialize = true)
303         {
304                 if ($initialize) {
305                         self::$itemlist = [];
306                         self::$conv_list = [];
307                 }
308
309                 logger("Import OStatus message", LOGGER_DEBUG);
310
311                 if ($xml == "") {
312                         return false;
313                 }
314                 $doc = new DOMDocument();
315                 @$doc->loadXML($xml);
316
317                 $xpath = new DOMXPath($doc);
318                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
319                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
320                 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
321                 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
322                 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
323                 $xpath->registerNamespace('poco', NAMESPACE_POCO);
324                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
325                 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
326
327                 $hub = "";
328                 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
329                 if (is_object($hub_attributes)) {
330                         foreach ($hub_attributes as $hub_attribute) {
331                                 if ($hub_attribute->name == "href") {
332                                         $hub = $hub_attribute->textContent;
333                                         logger("Found hub ".$hub, LOGGER_DEBUG);
334                                 }
335                         }
336                 }
337
338                 $header = [];
339                 $header["uid"] = $importer["uid"];
340                 $header["network"] = NETWORK_OSTATUS;
341                 $header["type"] = "remote";
342                 $header["wall"] = 0;
343                 $header["origin"] = 0;
344                 $header["gravity"] = GRAVITY_PARENT;
345
346                 $first_child = $doc->firstChild->tagName;
347
348                 if ($first_child == "feed") {
349                         $entries = $xpath->query('/atom:feed/atom:entry');
350                 } else {
351                         $entries = $xpath->query('/atom:entry');
352                 }
353
354                 if ($entries->length == 1) {
355                         // We reformat the XML to make it better readable
356                         $doc2 = new DOMDocument();
357                         $doc2->loadXML($xml);
358                         $doc2->preserveWhiteSpace = false;
359                         $doc2->formatOutput = true;
360                         $xml2 = $doc2->saveXML();
361
362                         $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
363                         $header["source"] = $xml2;
364                 } elseif (!$initialize) {
365                         return false;
366                 }
367
368                 // Fetch the first author
369                 $authordata = $xpath->query('//author')->item(0);
370                 $author = self::fetchAuthor($xpath, $authordata, $importer, $contact, $stored);
371
372                 $entry = $xpath->query('/atom:entry');
373
374                 // Reverse the order of the entries
375                 $entrylist = [];
376
377                 foreach ($entries as $entry) {
378                         $entrylist[] = $entry;
379                 }
380
381                 foreach (array_reverse($entrylist) as $entry) {
382                         // fetch the author
383                         $authorelement = $xpath->query('/atom:entry/atom:author', $entry);
384
385                         if ($authorelement->length == 0) {
386                                 $authorelement = $xpath->query('atom:author', $entry);
387                         }
388
389                         if ($authorelement->length > 0) {
390                                 $author = self::fetchAuthor($xpath, $entry, $importer, $contact, $stored);
391                         }
392
393                         $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $entry)->item(0)->nodeValue;
394                         if ($value != "") {
395                                 $nickname = $value;
396                         } else {
397                                 $nickname = $author["author-name"];
398                         }
399
400                         $item = array_merge($header, $author);
401
402                         $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
403
404                         $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
405
406                         // Delete a message
407                         if (in_array($item["verb"], ['qvitter-delete-notice', ACTIVITY_DELETE, 'delete'])) {
408                                 self::deleteNotice($item);
409                                 continue;
410                         }
411
412                         if (in_array($item["verb"], [NAMESPACE_OSTATUS."/unfavorite", ACTIVITY_UNFAVORITE])) {
413                                 // Ignore "Unfavorite" message
414                                 logger("Ignore unfavorite message ".print_r($item, true), LOGGER_DEBUG);
415                                 continue;
416                         }
417
418                         // Deletions come with the same uri, so we check for duplicates after processing deletions
419                         if (dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]])) {
420                                 logger('Post with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
421                                 continue;
422                         } else {
423                                 logger('Processing post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
424                         }
425
426                         if ($item["verb"] == ACTIVITY_JOIN) {
427                                 // ignore "Join" messages
428                                 logger("Ignore join message ".print_r($item, true), LOGGER_DEBUG);
429                                 continue;
430                         }
431
432                         if ($item["verb"] == "http://mastodon.social/schema/1.0/block") {
433                                 // ignore mastodon "block" messages
434                                 logger("Ignore block message ".print_r($item, true), LOGGER_DEBUG);
435                                 continue;
436                         }
437
438                         if ($item["verb"] == ACTIVITY_FOLLOW) {
439                                 Contact::addRelationship($importer, $contact, $item, $nickname);
440                                 continue;
441                         }
442
443                         if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
444                                 Contact::removeFollower($importer, $contact, $item, $dummy);
445                                 continue;
446                         }
447
448                         if ($item["verb"] == ACTIVITY_FAVORITE) {
449                                 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
450                                 logger("Favorite ".$orig_uri." ".print_r($item, true));
451
452                                 $item["verb"] = ACTIVITY_LIKE;
453                                 $item["parent-uri"] = $orig_uri;
454                                 $item["gravity"] = GRAVITY_LIKE;
455                         }
456
457                         // http://activitystrea.ms/schema/1.0/rsvp-yes
458                         if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
459                                 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
460                         }
461
462                         self::processPost($xpath, $entry, $item, $importer);
463
464                         if ($initialize && (count(self::$itemlist) > 0)) {
465                                 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
466                                         // We will import it everytime, when it is started by our contacts
467                                         $valid = !empty(self::$itemlist[0]['contact-id']);
468                                         if (!$valid) {
469                                                 // If not, then it depends on this setting
470                                                 $valid = !Config::get('system', 'ostatus_full_threads');
471                                                 if ($valid) {
472                                                         logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
473                                                 }
474                                         } else {
475                                                 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
476                                         }
477                                         if ($valid) {
478                                                 // Never post a thread when the only interaction by our contact was a like
479                                                 $valid = false;
480                                                 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
481                                                 foreach (self::$itemlist as $item) {
482                                                         if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
483                                                                 $valid = true;
484                                                         }
485                                                 }
486                                                 if ($valid) {
487                                                         logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
488                                                 }
489                                         }
490                                 } else {
491                                         // But we will only import complete threads
492                                         $valid = dba::exists('item', ['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
493                                         if ($valid) {
494                                                 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);
495                                         }
496                                 }
497
498                                 if ($valid) {
499                                         $default_contact = 0;
500                                         $key = count(self::$itemlist);
501                                         for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
502                                                 if (empty(self::$itemlist[$key]['contact-id'])) {
503                                                         self::$itemlist[$key]['contact-id'] = $default_contact;
504                                                 } else {
505                                                         $default_contact = $item['contact-id'];
506                                                 }
507                                         }
508                                         foreach (self::$itemlist as $item) {
509                                                 $found = dba::exists('item', ['uid' => $importer["uid"], 'uri' => $item["uri"]]);
510                                                 if ($found) {
511                                                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
512                                                 } elseif ($item['contact-id'] < 0) {
513                                                         logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
514                                                 } else {
515                                                         // We are having duplicated entries. Hopefully this solves it.
516                                                         if (Lock::set('ostatus_process_item_insert')) {
517                                                                 $ret = Item::insert($item);
518                                                                 Lock::remove('ostatus_process_item_insert');
519                                                                 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
520                                                         } else {
521                                                                 $ret = Item::insert($item);
522                                                                 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
523                                                         }
524                                                 }
525                                         }
526                                 }
527                                 self::$itemlist = [];
528                         }
529                         logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
530                 }
531                 return true;
532         }
533
534         /**
535          * @param object $item item
536          * @return void
537          */
538         private static function deleteNotice($item)
539         {
540                 $condition = ['uid' => $item['uid'], 'author-link' => $item['author-link'], 'uri' => $item['uri']];
541                 if (!dba::exists('item', $condition)) {
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::delete($condition);
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"] = HTML::toBBCode($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'] = HTML::toBBCode($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"] = HTML::toBBCode($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                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1292                         $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1293                                         'archive' => false, 'hidden' => false, 'blocked' => false];
1294                         $members = dba::count('contact', $condition);
1295                         XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1296                 }
1297
1298                 return $root;
1299         }
1300
1301         /**
1302          * @brief Add the link to the push hubs to the XML document
1303          *
1304          * @param object $doc  XML document
1305          * @param object $root XML root element where the hub links are added
1306          * @param object $nick nick
1307          * @return void
1308          */
1309         public static function hublinks($doc, $root, $nick)
1310         {
1311                 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1312                 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1313         }
1314
1315         /**
1316          * @brief Adds attachment data to the XML document
1317          *
1318          * @param object $doc  XML document
1319          * @param object $root XML root element where the hub links are added
1320          * @param array  $item Data of the item that is to be posted
1321          * @return void
1322          */
1323         private static function getAttachment($doc, $root, $item)
1324         {
1325                 $o = "";
1326                 $siteinfo = BBCode::getAttachedData($item["body"]);
1327
1328                 switch ($siteinfo["type"]) {
1329                         case 'photo':
1330                                 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1331                                 if ($imgdata) {
1332                                         $attributes = ["rel" => "enclosure",
1333                                                         "href" => $siteinfo["image"],
1334                                                         "type" => $imgdata["mime"],
1335                                                         "length" => intval($imgdata["size"])];
1336                                         XML::addElement($doc, $root, "link", "", $attributes);
1337                                 }
1338                                 break;
1339                         case 'video':
1340                                 $attributes = ["rel" => "enclosure",
1341                                                 "href" => $siteinfo["url"],
1342                                                 "type" => "text/html; charset=UTF-8",
1343                                                 "length" => "",
1344                                                 "title" => $siteinfo["title"]];
1345                                 XML::addElement($doc, $root, "link", "", $attributes);
1346                                 break;
1347                         default:
1348                                 break;
1349                 }
1350
1351                 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1352                         $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1353                         if ($imgdata) {
1354                                 $attributes = ["rel" => "enclosure",
1355                                                 "href" => $siteinfo["image"],
1356                                                 "type" => $imgdata["mime"],
1357                                                 "length" => intval($imgdata["size"])];
1358
1359                                 XML::addElement($doc, $root, "link", "", $attributes);
1360                         }
1361                 }
1362
1363                 $arr = explode('[/attach],', $item['attach']);
1364                 if (count($arr)) {
1365                         foreach ($arr as $r) {
1366                                 $matches = false;
1367                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1368                                 if ($cnt) {
1369                                         $attributes = ["rel" => "enclosure",
1370                                                         "href" => $matches[1],
1371                                                         "type" => $matches[3]];
1372
1373                                         if (intval($matches[2])) {
1374                                                 $attributes["length"] = intval($matches[2]);
1375                                         }
1376                                         if (trim($matches[4]) != "") {
1377                                                 $attributes["title"] = trim($matches[4]);
1378                                         }
1379                                         XML::addElement($doc, $root, "link", "", $attributes);
1380                                 }
1381                         }
1382                 }
1383         }
1384
1385         /**
1386          * @brief Adds the author element to the XML document
1387          *
1388          * @param object $doc   XML document
1389          * @param array  $owner Contact data of the poster
1390          *
1391          * @return object author element
1392          */
1393         private static function addAuthor($doc, $owner, $show_profile = true)
1394         {
1395                 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1396                 $author = $doc->createElement("author");
1397                 XML::addElement($doc, $author, "id", $owner["url"]);
1398                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1399                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1400                 } else {
1401                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1402                 }
1403                 XML::addElement($doc, $author, "uri", $owner["url"]);
1404                 XML::addElement($doc, $author, "name", $owner["nick"]);
1405                 XML::addElement($doc, $author, "email", $owner["addr"]);
1406                 if ($show_profile) {
1407                         XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1408                 }
1409
1410                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1411                 XML::addElement($doc, $author, "link", "", $attributes);
1412
1413                 $attributes = [
1414                                 "rel" => "avatar",
1415                                 "type" => "image/jpeg", // To-Do?
1416                                 "media:width" => 175,
1417                                 "media:height" => 175,
1418                                 "href" => $owner["photo"]];
1419                 XML::addElement($doc, $author, "link", "", $attributes);
1420
1421                 if (isset($owner["thumb"])) {
1422                         $attributes = [
1423                                         "rel" => "avatar",
1424                                         "type" => "image/jpeg", // To-Do?
1425                                         "media:width" => 80,
1426                                         "media:height" => 80,
1427                                         "href" => $owner["thumb"]];
1428                         XML::addElement($doc, $author, "link", "", $attributes);
1429                 }
1430
1431                 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1432                 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1433                 if ($show_profile) {
1434                         XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1435
1436                         if (trim($owner["location"]) != "") {
1437                                 $element = $doc->createElement("poco:address");
1438                                 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1439                                 $author->appendChild($element);
1440                         }
1441                 }
1442
1443                 if (DBM::is_result($profile) && !$show_profile) {
1444                         if (trim($profile["homepage"]) != "") {
1445                                 $urls = $doc->createElement("poco:urls");
1446                                 XML::addElement($doc, $urls, "poco:type", "homepage");
1447                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1448                                 XML::addElement($doc, $urls, "poco:primary", "true");
1449                                 $author->appendChild($urls);
1450                         }
1451
1452                         XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1453                         XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1454
1455                         if ($profile["publish"]) {
1456                                 XML::addElement($doc, $author, "mastodon:scope", "public");
1457                         }
1458                 }
1459
1460                 return $author;
1461         }
1462
1463         /**
1464          * @TODO Picture attachments should look like this:
1465          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1466          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1467          */
1468
1469         /**
1470          * @brief Returns the given activity if present - otherwise returns the "post" activity
1471          *
1472          * @param array $item Data of the item that is to be posted
1473          *
1474          * @return string activity
1475          */
1476         private static function constructVerb($item)
1477         {
1478                 if ($item['verb']) {
1479                         return $item['verb'];
1480                 }
1481
1482                 return ACTIVITY_POST;
1483         }
1484
1485         /**
1486          * @brief Returns the given object type if present - otherwise returns the "note" object type
1487          *
1488          * @param array $item Data of the item that is to be posted
1489          *
1490          * @return string Object type
1491          */
1492         private static function constructObjecttype($item)
1493         {
1494                 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1495                         return $item['object-type'];
1496                 return ACTIVITY_OBJ_NOTE;
1497         }
1498
1499         /**
1500          * @brief Adds an entry element to the XML document
1501          *
1502          * @param object $doc      XML document
1503          * @param array  $item     Data of the item that is to be posted
1504          * @param array  $owner    Contact data of the poster
1505          * @param bool   $toplevel optional default false
1506          *
1507          * @return object Entry element
1508          */
1509         private static function entry($doc, $item, $owner, $toplevel = false)
1510         {
1511                 $xml = null;
1512
1513                 $repeated_guid = self::getResharedGuid($item);
1514                 if ($repeated_guid != "") {
1515                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1516                 }
1517
1518                 if ($xml) {
1519                         return $xml;
1520                 }
1521
1522                 if ($item["verb"] == ACTIVITY_LIKE) {
1523                         return self::likeEntry($doc, $item, $owner, $toplevel);
1524                 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1525                         return self::followEntry($doc, $item, $owner, $toplevel);
1526                 } else {
1527                         return self::noteEntry($doc, $item, $owner, $toplevel);
1528                 }
1529         }
1530
1531         /**
1532          * @brief Adds a source entry to the XML document
1533          *
1534          * @param object $doc     XML document
1535          * @param array  $contact Array of the contact that is added
1536          *
1537          * @return object Source element
1538          */
1539         private static function sourceEntry($doc, $contact)
1540         {
1541                 $source = $doc->createElement("source");
1542                 XML::addElement($doc, $source, "id", $contact["poll"]);
1543                 XML::addElement($doc, $source, "title", $contact["name"]);
1544                 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1545                 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1546                 XML::addElement($doc, $source, "icon", $contact["photo"]);
1547                 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1548
1549                 return $source;
1550         }
1551
1552         /**
1553          * @brief Fetches contact data from the contact or the gcontact table
1554          *
1555          * @param string $url   URL of the contact
1556          * @param array  $owner Contact data of the poster
1557          *
1558          * @return array Contact array
1559          */
1560         private static function contactEntry($url, $owner)
1561         {
1562                 $r = q(
1563                         "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1564                         dbesc(normalise_link($url)),
1565                         intval($owner["uid"])
1566                 );
1567                 if (DBM::is_result($r)) {
1568                         $contact = $r[0];
1569                         $contact["uid"] = -1;
1570                 }
1571
1572                 if (!DBM::is_result($r)) {
1573                         $r = q(
1574                                 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1575                                 dbesc(normalise_link($url))
1576                         );
1577                         if (DBM::is_result($r)) {
1578                                 $contact = $r[0];
1579                                 $contact["uid"] = -1;
1580                                 $contact["success_update"] = $contact["updated"];
1581                         }
1582                 }
1583
1584                 if (!DBM::is_result($r)) {
1585                         $contact = owner;
1586                 }
1587
1588                 if (!isset($contact["poll"])) {
1589                         $data = Probe::uri($url);
1590                         $contact["poll"] = $data["poll"];
1591
1592                         if (!$contact["alias"]) {
1593                                 $contact["alias"] = $data["alias"];
1594                         }
1595                 }
1596
1597                 if (!isset($contact["alias"])) {
1598                         $contact["alias"] = $contact["url"];
1599                 }
1600
1601                 return $contact;
1602         }
1603
1604         /**
1605          * @brief Adds an entry element with reshared content
1606          *
1607          * @param object $doc           XML document
1608          * @param array  $item          Data of the item that is to be posted
1609          * @param array  $owner         Contact data of the poster
1610          * @param string $repeated_guid guid
1611          * @param bool   $toplevel      Is it for en entry element (false) or a feed entry (true)?
1612          *
1613          * @return object Entry element
1614          */
1615         private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1616         {
1617                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1618                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1619                 }
1620
1621                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1622
1623                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1624                         'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]];
1625                 $repeated_item = Item::selectFirst([], $condition);
1626                 if (!DBM::is_result($repeated_item)) {
1627                         return false;
1628                 }
1629
1630                 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1631
1632                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1633
1634                 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1635
1636                 $as_object = $doc->createElement("activity:object");
1637
1638                 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1639
1640                 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1641
1642                 $author = self::addAuthor($doc, $contact, false);
1643                 $as_object->appendChild($author);
1644
1645                 $as_object2 = $doc->createElement("activity:object");
1646
1647                 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1648
1649                 $title = sprintf("New comment by %s", $contact["nick"]);
1650
1651                 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1652
1653                 $as_object->appendChild($as_object2);
1654
1655                 self::entryFooter($doc, $as_object, $item, $owner, false);
1656
1657                 $source = self::sourceEntry($doc, $contact);
1658
1659                 $as_object->appendChild($source);
1660
1661                 $entry->appendChild($as_object);
1662
1663                 self::entryFooter($doc, $entry, $item, $owner);
1664
1665                 return $entry;
1666         }
1667
1668         /**
1669          * @brief Adds an entry element with a "like"
1670          *
1671          * @param object $doc      XML document
1672          * @param array  $item     Data of the item that is to be posted
1673          * @param array  $owner    Contact data of the poster
1674          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1675          *
1676          * @return object Entry element with "like"
1677          */
1678         private static function likeEntry($doc, $item, $owner, $toplevel)
1679         {
1680                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1681                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1682                 }
1683
1684                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1685
1686                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1687                 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1688
1689                 $as_object = $doc->createElement("activity:object");
1690
1691                 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1692
1693                 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1694
1695                 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1696
1697                 $entry->appendChild($as_object);
1698
1699                 self::entryFooter($doc, $entry, $item, $owner);
1700
1701                 return $entry;
1702         }
1703
1704         /**
1705          * @brief Adds the person object element to the XML document
1706          *
1707          * @param object $doc     XML document
1708          * @param array  $owner   Contact data of the poster
1709          * @param array  $contact Contact data of the target
1710          *
1711          * @return object author element
1712          */
1713         private static function addPersonObject($doc, $owner, $contact)
1714         {
1715                 $object = $doc->createElement("activity:object");
1716                 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1717
1718                 if ($contact['network'] == NETWORK_PHANTOM) {
1719                         XML::addElement($doc, $object, "id", $contact['url']);
1720                         return $object;
1721                 }
1722
1723                 XML::addElement($doc, $object, "id", $contact["alias"]);
1724                 XML::addElement($doc, $object, "title", $contact["nick"]);
1725
1726                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1727                 XML::addElement($doc, $object, "link", "", $attributes);
1728
1729                 $attributes = [
1730                                 "rel" => "avatar",
1731                                 "type" => "image/jpeg", // To-Do?
1732                                 "media:width" => 175,
1733                                 "media:height" => 175,
1734                                 "href" => $contact["photo"]];
1735                 XML::addElement($doc, $object, "link", "", $attributes);
1736
1737                 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1738                 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1739
1740                 if (trim($contact["location"]) != "") {
1741                         $element = $doc->createElement("poco:address");
1742                         XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1743                         $object->appendChild($element);
1744                 }
1745
1746                 return $object;
1747         }
1748
1749         /**
1750          * @brief Adds a follow/unfollow entry element
1751          *
1752          * @param object $doc      XML document
1753          * @param array  $item     Data of the follow/unfollow message
1754          * @param array  $owner    Contact data of the poster
1755          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1756          *
1757          * @return object Entry element
1758          */
1759         private static function followEntry($doc, $item, $owner, $toplevel)
1760         {
1761                 $item["id"] = $item["parent"] = 0;
1762                 $item["created"] = $item["edited"] = date("c");
1763                 $item["private"] = true;
1764
1765                 $contact = Probe::uri($item['follow']);
1766
1767                 if ($contact['alias'] == '') {
1768                         $contact['alias'] = $contact["url"];
1769                 } else {
1770                         $item['follow'] = $contact['alias'];
1771                 }
1772
1773                 $r = q(
1774                         "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1775                         intval($owner['uid']),
1776                         dbesc(normalise_link($contact["url"]))
1777                 );
1778
1779                 if (DBM::is_result($r)) {
1780                         $connect_id = $r[0]['id'];
1781                 } else {
1782                         $connect_id = 0;
1783                 }
1784
1785                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1786                         $message = L10n::t('%s is now following %s.');
1787                         $title = L10n::t('following');
1788                         $action = "subscription";
1789                 } else {
1790                         $message = L10n::t('%s stopped following %s.');
1791                         $title = L10n::t('stopped following');
1792                         $action = "unfollow";
1793                 }
1794
1795                 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1796                                 = 'tag:'.get_app()->get_hostname().
1797                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1798                                 ':person:'.$connect_id.':'.$item['created'];
1799
1800                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1801
1802                 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1803
1804                 self::entryContent($doc, $entry, $item, $owner, $title);
1805
1806                 $object = self::addPersonObject($doc, $owner, $contact);
1807                 $entry->appendChild($object);
1808
1809                 self::entryFooter($doc, $entry, $item, $owner);
1810
1811                 return $entry;
1812         }
1813
1814         /**
1815          * @brief Adds a regular entry element
1816          *
1817          * @param object $doc      XML document
1818          * @param array  $item     Data of the item that is to be posted
1819          * @param array  $owner    Contact data of the poster
1820          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1821          *
1822          * @return object Entry element
1823          */
1824         private static function noteEntry($doc, $item, $owner, $toplevel)
1825         {
1826                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1827                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1828                 }
1829
1830                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1831
1832                 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1833
1834                 self::entryContent($doc, $entry, $item, $owner, $title);
1835
1836                 self::entryFooter($doc, $entry, $item, $owner);
1837
1838                 return $entry;
1839         }
1840
1841         /**
1842          * @brief Adds a header element to the XML document
1843          *
1844          * @param object $doc      XML document
1845          * @param object $entry    The entry element where the elements are added
1846          * @param array  $owner    Contact data of the poster
1847          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1848          *
1849          * @return string The title for the element
1850          */
1851         private static function entryHeader($doc, &$entry, $owner, $item, $toplevel)
1852         {
1853                 /// @todo Check if this title stuff is really needed (I guess not)
1854                 if (!$toplevel) {
1855                         $entry = $doc->createElement("entry");
1856                         $title = sprintf("New note by %s", $owner["nick"]);
1857
1858                         if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1859                                 $contact = self::contactEntry($item['author-link'], $owner);
1860                                 $author = self::addAuthor($doc, $contact, false);
1861                                 $entry->appendChild($author);
1862                         }
1863                 } else {
1864                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1865
1866                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1867                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1868                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1869                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1870                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1871                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1872                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1873                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1874
1875                         $author = self::addAuthor($doc, $owner);
1876                         $entry->appendChild($author);
1877
1878                         $title = sprintf("New comment by %s", $owner["nick"]);
1879                 }
1880                 return $title;
1881         }
1882
1883         /**
1884          * @brief Adds elements to the XML document
1885          *
1886          * @param object $doc      XML document
1887          * @param object $entry    Entry element where the content is added
1888          * @param array  $item     Data of the item that is to be posted
1889          * @param array  $owner    Contact data of the poster
1890          * @param string $title    Title for the post
1891          * @param string $verb     The activity verb
1892          * @param bool   $complete Add the "status_net" element?
1893          * @return void
1894          */
1895         private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1896         {
1897                 if ($verb == "") {
1898                         $verb = self::constructVerb($item);
1899                 }
1900
1901                 XML::addElement($doc, $entry, "id", $item["uri"]);
1902                 XML::addElement($doc, $entry, "title", $title);
1903
1904                 $body = self::formatPicturePost($item['body']);
1905
1906                 if ($item['title'] != "") {
1907                         $body = "[b]".$item['title']."[/b]\n\n".$body;
1908                 }
1909
1910                 $body = BBCode::convert($body, false, 7);
1911
1912                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1913
1914                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1915                                                                 "href" => System::baseUrl()."/display/".$item["guid"]]
1916                 );
1917
1918                 if ($complete && ($item["id"] > 0)) {
1919                         XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1920                 }
1921
1922                 XML::addElement($doc, $entry, "activity:verb", $verb);
1923
1924                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1925                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1926         }
1927
1928         /**
1929          * @brief Adds the elements at the foot of an entry to the XML document
1930          *
1931          * @param object $doc      XML document
1932          * @param object $entry    The entry element where the elements are added
1933          * @param array  $item     Data of the item that is to be posted
1934          * @param array  $owner    Contact data of the poster
1935          * @param bool   $complete default true
1936          * @return void
1937          */
1938         private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
1939         {
1940                 $mentioned = [];
1941
1942                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1943                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1944                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1945
1946                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1947
1948                         if (DBM::is_result($thrparent)) {
1949                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1950                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1951                                 $parent_plink = $thrparent["plink"];
1952                         } else {
1953                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
1954                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1955                                 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1956                         }
1957
1958                         $attributes = [
1959                                         "ref" => $parent_item,
1960                                         "href" => $parent_plink];
1961                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1962
1963                         $attributes = [
1964                                         "rel" => "related",
1965                                         "href" => $parent_plink];
1966                         XML::addElement($doc, $entry, "link", "", $attributes);
1967                 }
1968
1969                 if (intval($item["parent"]) > 0) {
1970                         $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1971                         $conversation_uri = $conversation_href;
1972
1973                         if (isset($parent_item)) {
1974                                 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
1975
1976                                 if (DBM::is_result($r)) {
1977                                         if ($r['conversation-uri'] != '') {
1978                                                 $conversation_uri = $r['conversation-uri'];
1979                                         }
1980                                         if ($r['conversation-href'] != '') {
1981                                                 $conversation_href = $r['conversation-href'];
1982                                         }
1983                                 }
1984                         }
1985
1986                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:conversation", "href" => $conversation_href]);
1987
1988                         $attributes = [
1989                                         "href" => $conversation_href,
1990                                         "local_id" => $item["parent"],
1991                                         "ref" => $conversation_uri];
1992
1993                         XML::addElement($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
1994                 }
1995
1996                 $tags = item::getFeedTags($item);
1997
1998                 if (count($tags)) {
1999                         foreach ($tags as $t) {
2000                                 if ($t[0] == "@") {
2001                                         $mentioned[$t[1]] = $t[1];
2002                                 }
2003                         }
2004                 }
2005
2006                 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2007                 $newmentions = [];
2008                 foreach ($mentioned as $mention) {
2009                         $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2010                         $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2011                 }
2012                 $mentioned = $newmentions;
2013
2014                 foreach ($mentioned as $mention) {
2015                         $condition = ['uid' => $owner['uid'], 'nurl' => normalise_link($mention)];
2016                         $contact = dba::selectFirst('contact', ['forum', 'prv', 'self', 'contact-type'], $condition);
2017                         if ($contact["forum"] || $contact["prv"] || ($owner['contact-type'] == ACCOUNT_TYPE_COMMUNITY) ||
2018                                 ($contact['self'] && ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY))) {
2019                                 XML::addElement($doc, $entry, "link", "",
2020                                         [
2021                                                 "rel" => "mentioned",
2022                                                 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2023                                                 "href" => $mention]
2024                                 );
2025                         } else {
2026                                 XML::addElement($doc, $entry, "link", "",
2027                                         [
2028                                                 "rel" => "mentioned",
2029                                                 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2030                                                 "href" => $mention]
2031                                 );
2032                         }
2033                 }
2034
2035                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
2036                         XML::addElement($doc, $entry, "link", "", [
2037                                 "rel" => "mentioned",
2038                                 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/group",
2039                                 "href" => $owner['url']
2040                         ]);
2041                 }
2042
2043                 if (!$item["private"]) {
2044                         XML::addElement($doc, $entry, "link", "", ["rel" => "ostatus:attention",
2045                                                                         "href" => "http://activityschema.org/collection/public"]);
2046                         XML::addElement($doc, $entry, "link", "", ["rel" => "mentioned",
2047                                                                         "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2048                                                                         "href" => "http://activityschema.org/collection/public"]);
2049                         XML::addElement($doc, $entry, "mastodon:scope", "public");
2050                 }
2051
2052                 if (count($tags)) {
2053                         foreach ($tags as $t) {
2054                                 if ($t[0] != "@") {
2055                                         XML::addElement($doc, $entry, "category", "", ["term" => $t[2]]);
2056                                 }
2057                         }
2058                 }
2059
2060                 self::getAttachment($doc, $entry, $item);
2061
2062                 if ($complete && ($item["id"] > 0)) {
2063                         $app = $item["app"];
2064                         if ($app == "") {
2065                                 $app = "web";
2066                         }
2067
2068                         $attributes = ["local_id" => $item["id"], "source" => $app];
2069
2070                         if (isset($parent["id"])) {
2071                                 $attributes["repeat_of"] = $parent["id"];
2072                         }
2073
2074                         if ($item["coord"] != "") {
2075                                 XML::addElement($doc, $entry, "georss:point", $item["coord"]);
2076                         }
2077
2078                         XML::addElement($doc, $entry, "statusnet:notice_info", "", $attributes);
2079                 }
2080         }
2081
2082         /**
2083          * Creates the XML feed for a given nickname
2084          *
2085          * Supported filters:
2086          * - activity (default): all the public posts
2087          * - posts: all the public top-level posts
2088          * - comments: all the public replies
2089          *
2090          * Updates the provided last_update parameter if the result comes from the
2091          * cache or it is empty
2092          *
2093          * @brief Creates the XML feed for a given nickname
2094          *
2095          * @param string  $owner_nick  Nickname of the feed owner
2096          * @param string  $last_update Date of the last update
2097          * @param integer $max_items   Number of maximum items to fetch
2098          * @param string  $filter      Feed items filter (activity, posts or comments)
2099          * @param boolean $nocache     Wether to bypass caching
2100          *
2101          * @return string XML feed
2102          */
2103         public static function feed($owner_nick, &$last_update, $max_items = 300, $filter = 'activity', $nocache = false)
2104         {
2105                 $stamp = microtime(true);
2106
2107                 $owner = User::getOwnerDataByNick($owner_nick);
2108                 if (!$owner) {
2109                         return;
2110                 }
2111
2112                 $cachekey = "ostatus:feed:" . $owner_nick . ":" . $filter . ":" . $last_update;
2113
2114                 $previous_created = $last_update;
2115
2116                 // Don't cache when the last item was posted less then 15 minutes ago (Cache duration)
2117                 if ((time() - strtotime($owner['last-item'])) < 15*60) {
2118                         $result = Cache::get($cachekey);
2119                         if (!$nocache && !is_null($result)) {
2120                                 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created . ' (cached)', LOGGER_DEBUG);
2121                                 $last_update = $result['last_update'];
2122                                 return $result['feed'];
2123                         }
2124                 }
2125
2126                 if (!strlen($last_update)) {
2127                         $last_update = 'now -30 days';
2128                 }
2129
2130                 $check_date = DateTimeFormat::utc($last_update);
2131                 $authorid = Contact::getIdForURL($owner["url"], 0, true);
2132
2133                 $condition = ["`uid` = ? AND `created` > ? AND NOT `deleted`
2134                         AND NOT `private` AND `visible` AND `wall` AND `parent-network` IN (?, ?)",
2135                         $owner["uid"], $check_date, NETWORK_OSTATUS, NETWORK_DFRN];
2136
2137                 if ($filter === 'comments') {
2138                         $condition[0] .= " AND `object-type` = ? ";
2139                         $condition[] = ACTIVITY_OBJ_COMMENT;
2140                 }
2141
2142                 if ($owner['account-type'] != ACCOUNT_TYPE_COMMUNITY) {
2143                         $condition[0] .= " AND `contact-id` = ? AND `author-id` = ?";
2144                         $condition[] = $owner["id"];
2145                         $condition[] = $authorid;
2146                 }
2147
2148                 $params = ['order' => ['created' => true], 'limit' => $max_items];
2149
2150                 if ($filter === 'posts') {
2151                         $ret = Item::selectThread([], $condition, $params);
2152                 } else {
2153                         $ret = Item::select([], $condition, $params);
2154                 }
2155
2156                 $items = dba::inArray($ret);
2157
2158                 $doc = new DOMDocument('1.0', 'utf-8');
2159                 $doc->formatOutput = true;
2160
2161                 $root = self::addHeader($doc, $owner, $filter);
2162
2163                 foreach ($items as $item) {
2164                         if (Config::get('system', 'ostatus_debug')) {
2165                                 $item['body'] .= '🍼';
2166                         }
2167                         $entry = self::entry($doc, $item, $owner);
2168                         $root->appendChild($entry);
2169
2170                         if ($last_update < $item['created']) {
2171                                 $last_update = $item['created'];
2172                         }
2173                 }
2174
2175                 $feeddata = trim($doc->saveXML());
2176
2177                 $msg = ['feed' => $feeddata, 'last_update' => $last_update];
2178                 Cache::set($cachekey, $msg, CACHE_QUARTER_HOUR);
2179
2180                 logger('Feed duration: ' . number_format(microtime(true) - $stamp, 3) . ' - ' . $owner_nick . ' - ' . $filter . ' - ' . $previous_created, LOGGER_DEBUG);
2181
2182                 return $feeddata;
2183         }
2184
2185         /**
2186          * @brief Creates the XML for a salmon message
2187          *
2188          * @param array $item  Data of the item that is to be posted
2189          * @param array $owner Contact data of the poster
2190          *
2191          * @return string XML for the salmon
2192          */
2193         public static function salmon($item, $owner)
2194         {
2195                 $doc = new DOMDocument('1.0', 'utf-8');
2196                 $doc->formatOutput = true;
2197
2198                 if (Config::get('system', 'ostatus_debug')) {
2199                         $item['body'] .= '🐟';
2200                 }
2201
2202                 $entry = self::entry($doc, $item, $owner, true);
2203
2204                 $doc->appendChild($entry);
2205
2206                 return trim($doc->saveXML());
2207         }
2208 }