]> git.mxchange.org Git - friendica.git/blob - src/Protocol/OStatus.php
Merge branch 'develop' of https://github.com/friendica/friendica into redis_serialize
[friendica.git] / src / Protocol / OStatus.php
1 <?php
2 /**
3  * @file src/Protocol/OStatus.php
4  */
5 namespace Friendica\Protocol;
6
7 use dba;
8 use DOMDocument;
9 use DOMXPath;
10 use Friendica\Content\Text\BBCode;
11 use Friendica\Content\Text\HTML;
12 use Friendica\Core\Cache;
13 use Friendica\Core\Config;
14 use Friendica\Core\L10n;
15 use Friendica\Core\Lock;
16 use Friendica\Core\System;
17 use Friendica\Database\DBM;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\GContact;
21 use Friendica\Model\Item;
22 use Friendica\Model\User;
23 use Friendica\Network\Probe;
24 use Friendica\Object\Image;
25 use Friendica\Util\DateTimeFormat;
26 use Friendica\Util\Network;
27 use Friendica\Util\XML;
28
29 require_once 'include/dba.php';
30 require_once 'include/items.php';
31 require_once 'mod/share.php';
32 require_once 'include/enotify.php';
33 require_once 'include/api.php';
34 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-comment";
342                 $header["wall"] = 0;
343                 $header["origin"] = 0;
344                 $header["gravity"] = GRAVITY_COMMENT;
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 (Item::exists(['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["type"] = "activity";
453                                 $item["verb"] = ACTIVITY_LIKE;
454                                 $item["parent-uri"] = $orig_uri;
455                                 $item["gravity"] = GRAVITY_ACTIVITY;
456                                 $item["object-type"] = ACTIVITY_OBJ_NOTE;
457                         }
458
459                         // http://activitystrea.ms/schema/1.0/rsvp-yes
460                         if (!in_array($item["verb"], [ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE])) {
461                                 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true), LOGGER_DEBUG);
462                         }
463
464                         self::processPost($xpath, $entry, $item, $importer);
465
466                         if ($initialize && (count(self::$itemlist) > 0)) {
467                                 if (self::$itemlist[0]['uri'] == self::$itemlist[0]['parent-uri']) {
468                                         // We will import it everytime, when it is started by our contacts
469                                         $valid = !empty(self::$itemlist[0]['contact-id']);
470                                         if (!$valid) {
471                                                 // If not, then it depends on this setting
472                                                 $valid = !Config::get('system', 'ostatus_full_threads');
473                                                 if ($valid) {
474                                                         logger("Item with uri ".self::$itemlist[0]['uri']." will be imported due to the system settings.", LOGGER_DEBUG);
475                                                 }
476                                         } else {
477                                                 logger("Item with uri ".self::$itemlist[0]['uri']." belongs to a contact (".self::$itemlist[0]['contact-id']."). It will be imported.", LOGGER_DEBUG);
478                                         }
479                                         if ($valid) {
480                                                 // Never post a thread when the only interaction by our contact was a like
481                                                 $valid = false;
482                                                 $verbs = [ACTIVITY_POST, ACTIVITY_SHARE];
483                                                 foreach (self::$itemlist as $item) {
484                                                         if (!empty($item['contact-id']) && in_array($item['verb'], $verbs)) {
485                                                                 $valid = true;
486                                                         }
487                                                 }
488                                                 if ($valid) {
489                                                         logger("Item with uri ".self::$itemlist[0]['uri']." will be imported since the thread contains posts or shares.", LOGGER_DEBUG);
490                                                 }
491                                         }
492                                 } else {
493                                         // But we will only import complete threads
494                                         $valid = Item::exists(['uid' => $importer["uid"], 'uri' => self::$itemlist[0]['parent-uri']]);
495                                         if ($valid) {
496                                                 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);
497                                         }
498                                 }
499
500                                 if ($valid) {
501                                         $default_contact = 0;
502                                         $key = count(self::$itemlist);
503                                         for ($key = count(self::$itemlist) - 1; $key >= 0; $key--) {
504                                                 if (empty(self::$itemlist[$key]['contact-id'])) {
505                                                         self::$itemlist[$key]['contact-id'] = $default_contact;
506                                                 } else {
507                                                         $default_contact = $item['contact-id'];
508                                                 }
509                                         }
510                                         foreach (self::$itemlist as $item) {
511                                                 $found = Item::exists(['uid' => $importer["uid"], 'uri' => $item["uri"]]);
512                                                 if ($found) {
513                                                         logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already exists.", LOGGER_DEBUG);
514                                                 } elseif ($item['contact-id'] < 0) {
515                                                         logger("Item with uri ".$item["uri"]." is from a blocked contact.", LOGGER_DEBUG);
516                                                 } else {
517                                                         // We are having duplicated entries. Hopefully this solves it.
518                                                         if (Lock::acquire('ostatus_process_item_insert')) {
519                                                                 $ret = Item::insert($item);
520                                                                 Lock::release('ostatus_process_item_insert');
521                                                                 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"].' stored. Return value: '.$ret);
522                                                         } else {
523                                                                 $ret = Item::insert($item);
524                                                                 logger("We couldn't lock - but tried to store the item anyway. Return value is ".$ret);
525                                                         }
526                                                 }
527                                         }
528                                 }
529                                 self::$itemlist = [];
530                         }
531                         logger('Processing done for post with URI '.$item["uri"].' for user '.$importer["uid"].'.', LOGGER_DEBUG);
532                 }
533                 return true;
534         }
535
536         /**
537          * @param object $item item
538          * @return void
539          */
540         private static function deleteNotice($item)
541         {
542                 $condition = ['uid' => $item['uid'], 'author-id' => $item['author-id'], 'uri' => $item['uri']];
543                 if (!Item::exists($condition)) {
544                         logger('Item from '.$item['author-link'].' with uri '.$item['uri'].' for user '.$item['uid']." wasn't found. We don't delete it.");
545                         return;
546                 }
547
548                 Item::delete($condition);
549
550                 logger('Deleted item with uri '.$item['uri'].' for user '.$item['uid']);
551         }
552
553         /**
554          * @brief Processes the XML for a post
555          *
556          * @param object $xpath    The xpath object
557          * @param object $entry    The xml entry that is processed
558          * @param array  $item     The item array
559          * @param array  $importer user record of the importing user
560          * @return void
561          */
562         private static function processPost($xpath, $entry, &$item, $importer)
563         {
564                 $item["body"] = HTML::toBBCode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue);
565                 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
566                 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) || ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
567                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
568                         $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
569                 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
570                         $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
571                 }
572
573                 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
574                 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
575                 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
576                 $item['conversation-uri'] = $conversation;
577
578                 $conv = $xpath->query('ostatus:conversation', $entry);
579                 if (is_object($conv->item(0))) {
580                         foreach ($conv->item(0)->attributes as $attributes) {
581                                 if ($attributes->name == "ref") {
582                                         $item['conversation-uri'] = $attributes->textContent;
583                                 }
584                                 if ($attributes->name == "href") {
585                                         $item['conversation-href'] = $attributes->textContent;
586                                 }
587                         }
588                 }
589
590                 $related = "";
591
592                 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
593                 if (is_object($inreplyto->item(0))) {
594                         foreach ($inreplyto->item(0)->attributes as $attributes) {
595                                 if ($attributes->name == "ref") {
596                                         $item["parent-uri"] = $attributes->textContent;
597                                 }
598                                 if ($attributes->name == "href") {
599                                         $related = $attributes->textContent;
600                                 }
601                         }
602                 }
603
604                 $georsspoint = $xpath->query('georss:point', $entry);
605                 if (!empty($georsspoint) && ($georsspoint->length > 0)) {
606                         $item["coord"] = $georsspoint->item(0)->nodeValue;
607                 }
608
609                 $categories = $xpath->query('atom:category', $entry);
610                 if ($categories) {
611                         foreach ($categories as $category) {
612                                 foreach ($category->attributes as $attributes) {
613                                         if ($attributes->name == "term") {
614                                                 $term = $attributes->textContent;
615                                                 if (strlen($item["tag"])) {
616                                                         $item["tag"] .= ',';
617                                                 }
618                                                 $item["tag"] .= "#[url=".System::baseUrl()."/search?tag=".$term."]".$term."[/url]";
619                                         }
620                                 }
621                         }
622                 }
623
624                 $self = '';
625                 $add_body = '';
626
627                 $links = $xpath->query('atom:link', $entry);
628                 if ($links) {
629                         $link_data = self::processLinks($links, $item);
630                         $self = $link_data['self'];
631                         $add_body = $link_data['add_body'];
632                 }
633
634                 $repeat_of = "";
635
636                 $notice_info = $xpath->query('statusnet:notice_info', $entry);
637                 if ($notice_info && ($notice_info->length > 0)) {
638                         foreach ($notice_info->item(0)->attributes as $attributes) {
639                                 if ($attributes->name == "source") {
640                                         $item["app"] = strip_tags($attributes->textContent);
641                                 }
642                                 if ($attributes->name == "repeat_of") {
643                                         $repeat_of = $attributes->textContent;
644                                 }
645                         }
646                 }
647                 // Is it a repeated post?
648                 if (($repeat_of != "") || ($item["verb"] == ACTIVITY_SHARE)) {
649                         $link_data = self::processRepeatedItem($xpath, $entry, $item, $importer);
650                         if (!empty($link_data['add_body'])) {
651                                 $add_body .= $link_data['add_body'];
652                         }
653                 }
654
655                 $item["body"] .= $add_body;
656
657                 // Only add additional data when there is no picture in the post
658                 if (!strstr($item["body"], '[/img]')) {
659                         $item["body"] = add_page_info_to_body($item["body"]);
660                 }
661
662                 // Mastodon Content Warning
663                 if (($item["verb"] == ACTIVITY_POST) && $xpath->evaluate('boolean(atom:summary)', $entry)) {
664                         $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
665                         if (!empty($clear_text)) {
666                                 $item['content-warning'] = HTML::toBBCode($clear_text);
667                         }
668                 }
669
670                 if (($self != '') && empty($item['protocol'])) {
671                         self::fetchSelf($self, $item);
672                 }
673
674                 if (!empty($item["conversation-href"])) {
675                         self::fetchConversation($item['conversation-href'], $item['conversation-uri']);
676                 }
677
678                 if (isset($item["parent-uri"])) {
679                         if (!Item::exists(['uid' => $importer["uid"], 'uri' => $item['parent-uri']])) {
680                                 if ($related != '') {
681                                         self::fetchRelated($related, $item["parent-uri"], $importer);
682                                 }
683                         } else {
684                                 logger('Reply with URI '.$item["uri"].' already existed for user '.$importer["uid"].'.', LOGGER_DEBUG);
685                         }
686                 } else {
687                         $item["parent-uri"] = $item["uri"];
688                         $item["gravity"] = GRAVITY_PARENT;
689                         $item["type"] = "remote";
690                 }
691
692                 if (($item['author-link'] != '') && !empty($item['protocol'])) {
693                         $item = Conversation::insert($item);
694                 }
695
696                 self::$itemlist[] = $item;
697         }
698
699         /**
700          * @brief Fetch the conversation for posts
701          *
702          * @param string $conversation     The link to the conversation
703          * @param string $conversation_uri The conversation in "uri" format
704          * @return void
705          */
706         private static function fetchConversation($conversation, $conversation_uri)
707         {
708                 // Ensure that we only store a conversation once in a process
709                 if (isset(self::$conv_list[$conversation])) {
710                         return;
711                 }
712
713                 self::$conv_list[$conversation] = true;
714
715                 $conversation_data = Network::curl($conversation, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
716
717                 if (!$conversation_data['success']) {
718                         return;
719                 }
720
721                 $xml = '';
722
723                 if (stristr($conversation_data['header'], 'Content-Type: application/atom+xml')) {
724                         $xml = $conversation_data['body'];
725                 }
726
727                 if ($xml == '') {
728                         $doc = new DOMDocument();
729                         if (!@$doc->loadHTML($conversation_data['body'])) {
730                                 return;
731                         }
732                         $xpath = new DOMXPath($doc);
733
734                         $links = $xpath->query('//link');
735                         if ($links) {
736                                 $file = '';
737                                 foreach ($links as $link) {
738                                         $attribute = self::readAttributes($link);
739                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
740                                                 $file = $attribute['href'];
741                                         }
742                                 }
743                                 if ($file != '') {
744                                         $conversation_atom = Network::curl($attribute['href']);
745
746                                         if ($conversation_atom['success']) {
747                                                 $xml = $conversation_atom['body'];
748                                         }
749                                 }
750                         }
751                 }
752
753                 if ($xml == '') {
754                         return;
755                 }
756
757                 self::storeConversation($xml, $conversation, $conversation_uri);
758         }
759
760         /**
761          * @brief Store a feed in several conversation entries
762          *
763          * @param string $xml              The feed
764          * @param string $conversation     conversation
765          * @param string $conversation_uri conversation uri
766          * @return void
767          */
768         private static function storeConversation($xml, $conversation = '', $conversation_uri = '')
769         {
770                 $doc = new DOMDocument();
771                 @$doc->loadXML($xml);
772
773                 $xpath = new DOMXPath($doc);
774                 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
775                 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
776                 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
777
778                 $entries = $xpath->query('/atom:feed/atom:entry');
779
780                 // Now store the entries
781                 foreach ($entries as $entry) {
782                         $doc2 = new DOMDocument();
783                         $doc2->preserveWhiteSpace = false;
784                         $doc2->formatOutput = true;
785
786                         $conv_data = [];
787
788                         $conv_data['protocol'] = PROTOCOL_SPLITTED_CONV;
789                         $conv_data['network'] = NETWORK_OSTATUS;
790                         $conv_data['uri'] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
791
792                         $inreplyto = $xpath->query('thr:in-reply-to', $entry);
793                         if (is_object($inreplyto->item(0))) {
794                                 foreach ($inreplyto->item(0)->attributes as $attributes) {
795                                         if ($attributes->name == "ref") {
796                                                 $conv_data['reply-to-uri'] = $attributes->textContent;
797                                         }
798                                 }
799                         }
800
801                         $conv = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
802                         $conv_data['conversation-uri'] = $conv;
803
804                         $conv = $xpath->query('ostatus:conversation', $entry);
805                         if (is_object($conv->item(0))) {
806                                 foreach ($conv->item(0)->attributes as $attributes) {
807                                         if ($attributes->name == "ref") {
808                                                 $conv_data['conversation-uri'] = $attributes->textContent;
809                                         }
810                                         if ($attributes->name == "href") {
811                                                 $conv_data['conversation-href'] = $attributes->textContent;
812                                         }
813                                 }
814                         }
815
816                         if ($conversation != '') {
817                                 $conv_data['conversation-uri'] = $conversation;
818                         }
819
820                         if ($conversation_uri != '') {
821                                 $conv_data['conversation-uri'] = $conversation_uri;
822                         }
823
824                         $entry = $doc2->importNode($entry, true);
825
826                         $doc2->appendChild($entry);
827
828                         $conv_data['source'] = $doc2->saveXML();
829
830                         $condition = ['item-uri' => $conv_data['uri'],'protocol' => PROTOCOL_OSTATUS_FEED];
831                         if (dba::exists('conversation', $condition)) {
832                                 logger('Delete deprecated entry for URI '.$conv_data['uri'], LOGGER_DEBUG);
833                                 dba::delete('conversation', ['item-uri' => $conv_data['uri']]);
834                         }
835
836                         logger('Store conversation data for uri '.$conv_data['uri'], LOGGER_DEBUG);
837                         Conversation::insert($conv_data);
838                 }
839         }
840
841         /**
842          * @brief Fetch the own post so that it can be stored later
843          *
844          * We want to store the original data for later processing.
845          * This function is meant for cases where we process a feed with multiple entries.
846          * In that case we need to fetch the single posts here.
847          *
848          * @param string $self The link to the self item
849          * @param array  $item The item array
850          * @return void
851          */
852         private static function fetchSelf($self, &$item)
853         {
854                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $self, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
855                 if (dba::exists('conversation', $condition)) {
856                         logger('Conversation '.$item['uri'].' is already stored.', LOGGER_DEBUG);
857                         return;
858                 }
859
860                 $self_data = Network::curl($self);
861
862                 if (!$self_data['success']) {
863                         return;
864                 }
865
866                 // We reformat the XML to make it better readable
867                 $doc = new DOMDocument();
868                 $doc->loadXML($self_data['body']);
869                 $doc->preserveWhiteSpace = false;
870                 $doc->formatOutput = true;
871                 $xml = $doc->saveXML();
872
873                 $item["protocol"] = PROTOCOL_OSTATUS_SALMON;
874                 $item["source"] = $xml;
875
876                 logger('Conversation '.$item['uri'].' is now fetched.', LOGGER_DEBUG);
877         }
878
879         /**
880          * @brief Fetch related posts and processes them
881          *
882          * @param string $related     The link to the related item
883          * @param string $related_uri The related item in "uri" format
884          * @param array  $importer    user record of the importing user
885          * @return void
886          */
887         private static function fetchRelated($related, $related_uri, $importer)
888         {
889                 $condition = ['`item-uri` = ? AND `protocol` IN (?, ?)', $related_uri, PROTOCOL_DFRN, PROTOCOL_OSTATUS_SALMON];
890                 $conversation = dba::selectFirst('conversation', ['source', 'protocol'], $condition);
891                 if (DBM::is_result($conversation)) {
892                         $stored = true;
893                         $xml = $conversation['source'];
894                         if (self::process($xml, $importer, $contact, $hub, $stored, false)) {
895                                 logger('Got valid cached XML for URI '.$related_uri, LOGGER_DEBUG);
896                                 return;
897                         }
898                         if ($conversation['protocol'] == PROTOCOL_OSTATUS_SALMON) {
899                                 logger('Delete invalid cached XML for URI '.$related_uri, LOGGER_DEBUG);
900                                 dba::delete('conversation', ['item-uri' => $related_uri]);
901                         }
902                 }
903
904                 $stored = false;
905                 $related_data = Network::curl($related, false, $redirects, ['accept_content' => 'application/atom+xml, text/html']);
906
907                 if (!$related_data['success']) {
908                         return;
909                 }
910
911                 $xml = '';
912
913                 if (stristr($related_data['header'], 'Content-Type: application/atom+xml')) {
914                         logger('Directly fetched XML for URI '.$related_uri, LOGGER_DEBUG);
915                         $xml = $related_data['body'];
916                 }
917
918                 if ($xml == '') {
919                         $doc = new DOMDocument();
920                         if (!@$doc->loadHTML($related_data['body'])) {
921                                 return;
922                         }
923                         $xpath = new DOMXPath($doc);
924
925                         $atom_file = '';
926
927                         $links = $xpath->query('//link');
928                         if ($links) {
929                                 foreach ($links as $link) {
930                                         $attribute = self::readAttributes($link);
931                                         if (($attribute['rel'] == 'alternate') && ($attribute['type'] == 'application/atom+xml')) {
932                                                 $atom_file = $attribute['href'];
933                                         }
934                                 }
935                                 if ($atom_file != '') {
936                                         $related_atom = Network::curl($atom_file);
937
938                                         if ($related_atom['success']) {
939                                                 logger('Fetched XML for URI '.$related_uri, LOGGER_DEBUG);
940                                                 $xml = $related_atom['body'];
941                                         }
942                                 }
943                         }
944                 }
945
946                 // Workaround for older GNU Social servers
947                 if (($xml == '') && strstr($related, '/notice/')) {
948                         $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related).'.atom');
949
950                         if ($related_atom['success']) {
951                                 logger('GNU Social workaround to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
952                                 $xml = $related_atom['body'];
953                         }
954                 }
955
956                 // Even more worse workaround for GNU Social ;-)
957                 if ($xml == '') {
958                         $related_guess = OStatus::convertHref($related_uri);
959                         $related_atom = Network::curl(str_replace('/notice/', '/api/statuses/show/', $related_guess).'.atom');
960
961                         if ($related_atom['success']) {
962                                 logger('GNU Social workaround 2 to fetch XML for URI '.$related_uri, LOGGER_DEBUG);
963                                 $xml = $related_atom['body'];
964                         }
965                 }
966
967                 // Finally we take the data that we fetched from "ostatus:conversation"
968                 if ($xml == '') {
969                         $condition = ['item-uri' => $related_uri, 'protocol' => PROTOCOL_SPLITTED_CONV];
970                         $conversation = dba::selectFirst('conversation', ['source'], $condition);
971                         if (DBM::is_result($conversation)) {
972                                 $stored = true;
973                                 logger('Got cached XML from conversation for URI '.$related_uri, LOGGER_DEBUG);
974                                 $xml = $conversation['source'];
975                         }
976                 }
977
978                 if ($xml != '') {
979                         self::process($xml, $importer, $contact, $hub, $stored, false);
980                 } else {
981                         logger("XML couldn't be fetched for URI: ".$related_uri." - href: ".$related, LOGGER_DEBUG);
982                 }
983                 return;
984         }
985
986         /**
987          * @brief Processes the XML for a repeated post
988          *
989          * @param object $xpath    The xpath object
990          * @param object $entry    The xml entry that is processed
991          * @param array  $item     The item array
992          * @param array  $importer user record of the importing user
993          *
994          * @return array with data from links
995          */
996         private static function processRepeatedItem($xpath, $entry, &$item, $importer)
997         {
998                 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
999
1000                 if (!is_object($activityobjects)) {
1001                         return [];
1002                 }
1003
1004                 $link_data = [];
1005
1006                 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
1007
1008                 $links = $xpath->query("atom:link", $activityobjects);
1009                 if ($links) {
1010                         $link_data = self::processLinks($links, $item);
1011                 }
1012
1013                 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
1014                 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
1015                 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
1016
1017                 $orig_author = self::fetchAuthor($xpath, $activityobjects, $importer, $dummy, false);
1018
1019                 $item["author-name"] = $orig_author["author-name"];
1020                 $item["author-link"] = $orig_author["author-link"];
1021                 $item["author-avatar"] = $orig_author["author-avatar"];
1022
1023                 $item["body"] = HTML::toBBCode($orig_body);
1024                 $item["created"] = $orig_created;
1025                 $item["edited"] = $orig_edited;
1026
1027                 $item["uri"] = $orig_uri;
1028
1029                 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
1030
1031                 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
1032
1033                 $inreplyto = $xpath->query('thr:in-reply-to', $activityobjects);
1034                 if (is_object($inreplyto->item(0))) {
1035                         foreach ($inreplyto->item(0)->attributes as $attributes) {
1036                                 if ($attributes->name == "ref") {
1037                                         $item["parent-uri"] = $attributes->textContent;
1038                                 }
1039                         }
1040                 }
1041
1042                 return $link_data;
1043         }
1044
1045         /**
1046          * @brief Processes links in the XML
1047          *
1048          * @param object $links The xml data that contain links
1049          * @param array  $item  The item array
1050          *
1051          * @return array with data from the links
1052          */
1053         private static function processLinks($links, &$item)
1054         {
1055                 $link_data = ['add_body' => '', 'self' => ''];
1056
1057                 foreach ($links as $link) {
1058                         $attribute = self::readAttributes($link);
1059
1060                         if (($attribute['rel'] != "") && ($attribute['href'] != "")) {
1061                                 switch ($attribute['rel']) {
1062                                         case "alternate":
1063                                                 $item["plink"] = $attribute['href'];
1064                                                 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION)
1065                                                         || ($item["object-type"] == ACTIVITY_OBJ_EVENT)
1066                                                 ) {
1067                                                         $item["body"] .= add_page_info($attribute['href']);
1068                                                 }
1069                                                 break;
1070                                         case "ostatus:conversation":
1071                                                 $link_data['conversation'] = $attribute['href'];
1072                                                 $item['conversation-href'] = $link_data['conversation'];
1073                                                 if (!isset($item['conversation-uri'])) {
1074                                                         $item['conversation-uri'] = $item['conversation-href'];
1075                                                 }
1076                                                 break;
1077                                         case "enclosure":
1078                                                 $filetype = strtolower(substr($attribute['type'], 0, strpos($attribute['type'], '/')));
1079                                                 if ($filetype == 'image') {
1080                                                         $link_data['add_body'] .= "\n[img]".$attribute['href'].'[/img]';
1081                                                 } else {
1082                                                         if (strlen($item["attach"])) {
1083                                                                 $item["attach"] .= ',';
1084                                                         }
1085                                                         if (!isset($attribute['length'])) {
1086                                                                 $attribute['length'] = "0";
1087                                                         }
1088                                                         $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
1089                                                 }
1090                                                 break;
1091                                         case "related":
1092                                                 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
1093                                                         if (!isset($item["parent-uri"])) {
1094                                                                 $item["parent-uri"] = $attribute['href'];
1095                                                         }
1096                                                         $link_data['related'] = $attribute['href'];
1097                                                 } else {
1098                                                         $item["body"] .= add_page_info($attribute['href']);
1099                                                 }
1100                                                 break;
1101                                         case "self":
1102                                                 if ($item["plink"] == '') {
1103                                                         $item["plink"] = $attribute['href'];
1104                                                 }
1105                                                 $link_data['self'] = $attribute['href'];
1106                                                 break;
1107                                 }
1108                         }
1109                 }
1110                 return $link_data;
1111         }
1112
1113         /**
1114          * @brief Create an url out of an uri
1115          *
1116          * @param string $href URI in the format "parameter1:parameter1:..."
1117          *
1118          * @return string URL in the format http(s)://....
1119          */
1120         public static function convertHref($href)
1121         {
1122                 $elements = explode(":", $href);
1123
1124                 if ((count($elements) <= 2) || ($elements[0] != "tag")) {
1125                         return $href;
1126                 }
1127
1128                 $server = explode(",", $elements[1]);
1129                 $conversation = explode("=", $elements[2]);
1130
1131                 if ((count($elements) == 4) && ($elements[2] == "post")) {
1132                         return "http://".$server[0]."/notice/".$elements[3];
1133                 }
1134
1135                 if ((count($conversation) != 2) || ($conversation[1] =="")) {
1136                         return $href;
1137                 }
1138                 if ($elements[3] == "objectType=thread") {
1139                         return "http://".$server[0]."/conversation/".$conversation[1];
1140                 } else {
1141                         return "http://".$server[0]."/notice/".$conversation[1];
1142                 }
1143                 return $href;
1144         }
1145
1146         /**
1147          * @brief Checks if the current post is a reshare
1148          *
1149          * @param array $item The item array of thw post
1150          *
1151          * @return string The guid if the post is a reshare
1152          */
1153         private static function getResharedGuid($item)
1154         {
1155                 $body = trim($item["body"]);
1156
1157                 // Skip if it isn't a pure repeated messages
1158                 // Does it start with a share?
1159                 if (strpos($body, "[share") > 0) {
1160                         return "";
1161                 }
1162
1163                 // Does it end with a share?
1164                 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1165                         return "";
1166                 }
1167
1168                 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1169                 // Skip if there is no shared message in there
1170                 if ($body == $attributes) {
1171                         return false;
1172                 }
1173
1174                 $guid = "";
1175                 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1176                 if ($matches[1] != "") {
1177                         $guid = $matches[1];
1178                 }
1179
1180                 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1181                 if ($matches[1] != "") {
1182                         $guid = $matches[1];
1183                 }
1184
1185                 return $guid;
1186         }
1187
1188         /**
1189          * @brief Cleans the body of a post if it contains picture links
1190          *
1191          * @param string $body The body
1192          *
1193          * @return string The cleaned body
1194          */
1195         private static function formatPicturePost($body)
1196         {
1197                 $siteinfo = BBCode::getAttachedData($body);
1198
1199                 if (($siteinfo["type"] == "photo")) {
1200                         if (isset($siteinfo["preview"])) {
1201                                 $preview = $siteinfo["preview"];
1202                         } else {
1203                                 $preview = $siteinfo["image"];
1204                         }
1205
1206                         // Is it a remote picture? Then make a smaller preview here
1207                         $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1208
1209                         // Is it a local picture? Then make it smaller here
1210                         $preview = str_replace(["-0.jpg", "-0.png"], ["-2.jpg", "-2.png"], $preview);
1211                         $preview = str_replace(["-1.jpg", "-1.png"], ["-2.jpg", "-2.png"], $preview);
1212
1213                         if (isset($siteinfo["url"])) {
1214                                 $url = $siteinfo["url"];
1215                         } else {
1216                                 $url = $siteinfo["image"];
1217                         }
1218
1219                         $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1220                 }
1221
1222                 return $body;
1223         }
1224
1225         /**
1226          * @brief Adds the header elements to the XML document
1227          *
1228          * @param object $doc    XML document
1229          * @param array  $owner  Contact data of the poster
1230          * @param string $filter The related feed filter (activity, posts or comments)
1231          *
1232          * @return object header root element
1233          */
1234         private static function addHeader($doc, $owner, $filter)
1235         {
1236                 $a = get_app();
1237
1238                 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1239                 $doc->appendChild($root);
1240
1241                 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1242                 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1243                 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1244                 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1245                 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1246                 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1247                 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1248                 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1249
1250                 $title = '';
1251                 switch ($filter) {
1252                         case 'activity': $title = L10n::t('%s\'s timeline', $owner['name']); break;
1253                         case 'posts'   : $title = L10n::t('%s\'s posts'   , $owner['name']); break;
1254                         case 'comments': $title = L10n::t('%s\'s comments', $owner['name']); break;
1255                 }
1256
1257                 $attributes = ["uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION . "-" . DB_UPDATE_VERSION];
1258                 XML::addElement($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1259                 XML::addElement($doc, $root, "id", System::baseUrl() . "/profile/" . $owner["nick"]);
1260                 XML::addElement($doc, $root, "title", $title);
1261                 XML::addElement($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1262                 XML::addElement($doc, $root, "logo", $owner["photo"]);
1263                 XML::addElement($doc, $root, "updated", DateTimeFormat::utcNow(DateTimeFormat::ATOM));
1264
1265                 $author = self::addAuthor($doc, $owner);
1266                 $root->appendChild($author);
1267
1268                 $attributes = ["href" => $owner["url"], "rel" => "alternate", "type" => "text/html"];
1269                 XML::addElement($doc, $root, "link", "", $attributes);
1270
1271                 /// @TODO We have to find out what this is
1272                 /// $attributes = array("href" => System::baseUrl()."/sup",
1273                 ///             "rel" => "http://api.friendfeed.com/2008/03#sup",
1274                 ///             "type" => "application/json");
1275                 /// XML::addElement($doc, $root, "link", "", $attributes);
1276
1277                 self::hublinks($doc, $root, $owner["nick"]);
1278
1279                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "salmon"];
1280                 XML::addElement($doc, $root, "link", "", $attributes);
1281
1282                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies"];
1283                 XML::addElement($doc, $root, "link", "", $attributes);
1284
1285                 $attributes = ["href" => System::baseUrl() . "/salmon/" . $owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention"];
1286                 XML::addElement($doc, $root, "link", "", $attributes);
1287
1288                 $attributes = ["href" => System::baseUrl() . "/api/statuses/user_timeline/" . $owner["nick"] . ".atom",
1289                         "rel" => "self", "type" => "application/atom+xml"];
1290                 XML::addElement($doc, $root, "link", "", $attributes);
1291
1292                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1293                         $condition = ['uid' => $owner['uid'], 'self' => false, 'pending' => false,
1294                                         'archive' => false, 'hidden' => false, 'blocked' => false];
1295                         $members = dba::count('contact', $condition);
1296                         XML::addElement($doc, $root, "statusnet:group_info", "", ["member_count" => $members]);
1297                 }
1298
1299                 return $root;
1300         }
1301
1302         /**
1303          * @brief Add the link to the push hubs to the XML document
1304          *
1305          * @param object $doc  XML document
1306          * @param object $root XML root element where the hub links are added
1307          * @param object $nick nick
1308          * @return void
1309          */
1310         public static function hublinks($doc, $root, $nick)
1311         {
1312                 $h = System::baseUrl() . '/pubsubhubbub/'.$nick;
1313                 XML::addElement($doc, $root, "link", "", ["href" => $h, "rel" => "hub"]);
1314         }
1315
1316         /**
1317          * @brief Adds attachment data to the XML document
1318          *
1319          * @param object $doc  XML document
1320          * @param object $root XML root element where the hub links are added
1321          * @param array  $item Data of the item that is to be posted
1322          * @return void
1323          */
1324         private static function getAttachment($doc, $root, $item)
1325         {
1326                 $o = "";
1327                 $siteinfo = BBCode::getAttachedData($item["body"]);
1328
1329                 switch ($siteinfo["type"]) {
1330                         case 'photo':
1331                                 $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1332                                 if ($imgdata) {
1333                                         $attributes = ["rel" => "enclosure",
1334                                                         "href" => $siteinfo["image"],
1335                                                         "type" => $imgdata["mime"],
1336                                                         "length" => intval($imgdata["size"])];
1337                                         XML::addElement($doc, $root, "link", "", $attributes);
1338                                 }
1339                                 break;
1340                         case 'video':
1341                                 $attributes = ["rel" => "enclosure",
1342                                                 "href" => $siteinfo["url"],
1343                                                 "type" => "text/html; charset=UTF-8",
1344                                                 "length" => "",
1345                                                 "title" => $siteinfo["title"]];
1346                                 XML::addElement($doc, $root, "link", "", $attributes);
1347                                 break;
1348                         default:
1349                                 break;
1350                 }
1351
1352                 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo["type"] != "photo") && isset($siteinfo["image"])) {
1353                         $imgdata = Image::getInfoFromURL($siteinfo["image"]);
1354                         if ($imgdata) {
1355                                 $attributes = ["rel" => "enclosure",
1356                                                 "href" => $siteinfo["image"],
1357                                                 "type" => $imgdata["mime"],
1358                                                 "length" => intval($imgdata["size"])];
1359
1360                                 XML::addElement($doc, $root, "link", "", $attributes);
1361                         }
1362                 }
1363
1364                 $arr = explode('[/attach],', $item['attach']);
1365                 if (count($arr)) {
1366                         foreach ($arr as $r) {
1367                                 $matches = false;
1368                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1369                                 if ($cnt) {
1370                                         $attributes = ["rel" => "enclosure",
1371                                                         "href" => $matches[1],
1372                                                         "type" => $matches[3]];
1373
1374                                         if (intval($matches[2])) {
1375                                                 $attributes["length"] = intval($matches[2]);
1376                                         }
1377                                         if (trim($matches[4]) != "") {
1378                                                 $attributes["title"] = trim($matches[4]);
1379                                         }
1380                                         XML::addElement($doc, $root, "link", "", $attributes);
1381                                 }
1382                         }
1383                 }
1384         }
1385
1386         /**
1387          * @brief Adds the author element to the XML document
1388          *
1389          * @param object $doc   XML document
1390          * @param array  $owner Contact data of the poster
1391          *
1392          * @return object author element
1393          */
1394         private static function addAuthor($doc, $owner, $show_profile = true)
1395         {
1396                 $profile = dba::selectFirst('profile', ['homepage', 'publish'], ['uid' => $owner['uid'], 'is-default' => true]);
1397                 $author = $doc->createElement("author");
1398                 XML::addElement($doc, $author, "id", $owner["url"]);
1399                 if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1400                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_GROUP);
1401                 } else {
1402                         XML::addElement($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1403                 }
1404                 XML::addElement($doc, $author, "uri", $owner["url"]);
1405                 XML::addElement($doc, $author, "name", $owner["nick"]);
1406                 XML::addElement($doc, $author, "email", $owner["addr"]);
1407                 if ($show_profile) {
1408                         XML::addElement($doc, $author, "summary", BBCode::convert($owner["about"], false, 7));
1409                 }
1410
1411                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $owner["url"]];
1412                 XML::addElement($doc, $author, "link", "", $attributes);
1413
1414                 $attributes = [
1415                                 "rel" => "avatar",
1416                                 "type" => "image/jpeg", // To-Do?
1417                                 "media:width" => 175,
1418                                 "media:height" => 175,
1419                                 "href" => $owner["photo"]];
1420                 XML::addElement($doc, $author, "link", "", $attributes);
1421
1422                 if (isset($owner["thumb"])) {
1423                         $attributes = [
1424                                         "rel" => "avatar",
1425                                         "type" => "image/jpeg", // To-Do?
1426                                         "media:width" => 80,
1427                                         "media:height" => 80,
1428                                         "href" => $owner["thumb"]];
1429                         XML::addElement($doc, $author, "link", "", $attributes);
1430                 }
1431
1432                 XML::addElement($doc, $author, "poco:preferredUsername", $owner["nick"]);
1433                 XML::addElement($doc, $author, "poco:displayName", $owner["name"]);
1434                 if ($show_profile) {
1435                         XML::addElement($doc, $author, "poco:note", BBCode::convert($owner["about"], false, 7));
1436
1437                         if (trim($owner["location"]) != "") {
1438                                 $element = $doc->createElement("poco:address");
1439                                 XML::addElement($doc, $element, "poco:formatted", $owner["location"]);
1440                                 $author->appendChild($element);
1441                         }
1442                 }
1443
1444                 if (DBM::is_result($profile) && !$show_profile) {
1445                         if (trim($profile["homepage"]) != "") {
1446                                 $urls = $doc->createElement("poco:urls");
1447                                 XML::addElement($doc, $urls, "poco:type", "homepage");
1448                                 XML::addElement($doc, $urls, "poco:value", $profile["homepage"]);
1449                                 XML::addElement($doc, $urls, "poco:primary", "true");
1450                                 $author->appendChild($urls);
1451                         }
1452
1453                         XML::addElement($doc, $author, "followers", "", ["url" => System::baseUrl()."/viewcontacts/".$owner["nick"]]);
1454                         XML::addElement($doc, $author, "statusnet:profile_info", "", ["local_id" => $owner["uid"]]);
1455
1456                         if ($profile["publish"]) {
1457                                 XML::addElement($doc, $author, "mastodon:scope", "public");
1458                         }
1459                 }
1460
1461                 return $author;
1462         }
1463
1464         /**
1465          * @TODO Picture attachments should look like this:
1466          *      <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1467          *      class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1468          */
1469
1470         /**
1471          * @brief Returns the given activity if present - otherwise returns the "post" activity
1472          *
1473          * @param array $item Data of the item that is to be posted
1474          *
1475          * @return string activity
1476          */
1477         private static function constructVerb($item)
1478         {
1479                 if ($item['verb']) {
1480                         return $item['verb'];
1481                 }
1482
1483                 return ACTIVITY_POST;
1484         }
1485
1486         /**
1487          * @brief Returns the given object type if present - otherwise returns the "note" object type
1488          *
1489          * @param array $item Data of the item that is to be posted
1490          *
1491          * @return string Object type
1492          */
1493         private static function constructObjecttype($item)
1494         {
1495                 if (in_array($item['object-type'], [ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT]))
1496                         return $item['object-type'];
1497                 return ACTIVITY_OBJ_NOTE;
1498         }
1499
1500         /**
1501          * @brief Adds an entry element to the XML document
1502          *
1503          * @param object $doc      XML document
1504          * @param array  $item     Data of the item that is to be posted
1505          * @param array  $owner    Contact data of the poster
1506          * @param bool   $toplevel optional default false
1507          *
1508          * @return object Entry element
1509          */
1510         private static function entry($doc, $item, $owner, $toplevel = false)
1511         {
1512                 $xml = null;
1513
1514                 $repeated_guid = self::getResharedGuid($item);
1515                 if ($repeated_guid != "") {
1516                         $xml = self::reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel);
1517                 }
1518
1519                 if ($xml) {
1520                         return $xml;
1521                 }
1522
1523                 if ($item["verb"] == ACTIVITY_LIKE) {
1524                         return self::likeEntry($doc, $item, $owner, $toplevel);
1525                 } elseif (in_array($item["verb"], [ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"])) {
1526                         return self::followEntry($doc, $item, $owner, $toplevel);
1527                 } else {
1528                         return self::noteEntry($doc, $item, $owner, $toplevel);
1529                 }
1530         }
1531
1532         /**
1533          * @brief Adds a source entry to the XML document
1534          *
1535          * @param object $doc     XML document
1536          * @param array  $contact Array of the contact that is added
1537          *
1538          * @return object Source element
1539          */
1540         private static function sourceEntry($doc, $contact)
1541         {
1542                 $source = $doc->createElement("source");
1543                 XML::addElement($doc, $source, "id", $contact["poll"]);
1544                 XML::addElement($doc, $source, "title", $contact["name"]);
1545                 XML::addElement($doc, $source, "link", "", ["rel" => "alternate", "type" => "text/html", "href" => $contact["alias"]]);
1546                 XML::addElement($doc, $source, "link", "", ["rel" => "self", "type" => "application/atom+xml", "href" => $contact["poll"]]);
1547                 XML::addElement($doc, $source, "icon", $contact["photo"]);
1548                 XML::addElement($doc, $source, "updated", DateTimeFormat::utc($contact["success_update"]."+00:00", DateTimeFormat::ATOM));
1549
1550                 return $source;
1551         }
1552
1553         /**
1554          * @brief Fetches contact data from the contact or the gcontact table
1555          *
1556          * @param string $url   URL of the contact
1557          * @param array  $owner Contact data of the poster
1558          *
1559          * @return array Contact array
1560          */
1561         private static function contactEntry($url, $owner)
1562         {
1563                 $r = q(
1564                         "SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1565                         dbesc(normalise_link($url)),
1566                         intval($owner["uid"])
1567                 );
1568                 if (DBM::is_result($r)) {
1569                         $contact = $r[0];
1570                         $contact["uid"] = -1;
1571                 }
1572
1573                 if (!DBM::is_result($r)) {
1574                         $r = q(
1575                                 "SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1576                                 dbesc(normalise_link($url))
1577                         );
1578                         if (DBM::is_result($r)) {
1579                                 $contact = $r[0];
1580                                 $contact["uid"] = -1;
1581                                 $contact["success_update"] = $contact["updated"];
1582                         }
1583                 }
1584
1585                 if (!DBM::is_result($r)) {
1586                         $contact = owner;
1587                 }
1588
1589                 if (!isset($contact["poll"])) {
1590                         $data = Probe::uri($url);
1591                         $contact["poll"] = $data["poll"];
1592
1593                         if (!$contact["alias"]) {
1594                                 $contact["alias"] = $data["alias"];
1595                         }
1596                 }
1597
1598                 if (!isset($contact["alias"])) {
1599                         $contact["alias"] = $contact["url"];
1600                 }
1601
1602                 return $contact;
1603         }
1604
1605         /**
1606          * @brief Adds an entry element with reshared content
1607          *
1608          * @param object $doc           XML document
1609          * @param array  $item          Data of the item that is to be posted
1610          * @param array  $owner         Contact data of the poster
1611          * @param string $repeated_guid guid
1612          * @param bool   $toplevel      Is it for en entry element (false) or a feed entry (true)?
1613          *
1614          * @return object Entry element
1615          */
1616         private static function reshareEntry($doc, $item, $owner, $repeated_guid, $toplevel)
1617         {
1618                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1619                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1620                 }
1621
1622                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1623
1624                 $condition = ['uid' => $owner["uid"], 'guid' => $repeated_guid, 'private' => false,
1625                         'network' => [NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_OSTATUS]];
1626                 $repeated_item = Item::selectFirst([], $condition);
1627                 if (!DBM::is_result($repeated_item)) {
1628                         return false;
1629                 }
1630
1631                 $contact = self::contactEntry($repeated_item['author-link'], $owner);
1632
1633                 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1634
1635                 self::entryContent($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1636
1637                 $as_object = $doc->createElement("activity:object");
1638
1639                 XML::addElement($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1640
1641                 self::entryContent($doc, $as_object, $repeated_item, $owner, "", "", false);
1642
1643                 $author = self::addAuthor($doc, $contact, false);
1644                 $as_object->appendChild($author);
1645
1646                 $as_object2 = $doc->createElement("activity:object");
1647
1648                 XML::addElement($doc, $as_object2, "activity:object-type", self::constructObjecttype($repeated_item));
1649
1650                 $title = sprintf("New comment by %s", $contact["nick"]);
1651
1652                 self::entryContent($doc, $as_object2, $repeated_item, $owner, $title);
1653
1654                 $as_object->appendChild($as_object2);
1655
1656                 self::entryFooter($doc, $as_object, $item, $owner, false);
1657
1658                 $source = self::sourceEntry($doc, $contact);
1659
1660                 $as_object->appendChild($source);
1661
1662                 $entry->appendChild($as_object);
1663
1664                 self::entryFooter($doc, $entry, $item, $owner);
1665
1666                 return $entry;
1667         }
1668
1669         /**
1670          * @brief Adds an entry element with a "like"
1671          *
1672          * @param object $doc      XML document
1673          * @param array  $item     Data of the item that is to be posted
1674          * @param array  $owner    Contact data of the poster
1675          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1676          *
1677          * @return object Entry element with "like"
1678          */
1679         private static function likeEntry($doc, $item, $owner, $toplevel)
1680         {
1681                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1682                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1683                 }
1684
1685                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1686
1687                 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1688                 self::entryContent($doc, $entry, $item, $owner, "Favorite", $verb, false);
1689
1690                 $as_object = $doc->createElement("activity:object");
1691
1692                 $parent = Item::selectFirst([], ['uri' => $item["thr-parent"], 'uid' => $item["uid"]]);
1693
1694                 XML::addElement($doc, $as_object, "activity:object-type", self::constructObjecttype($parent));
1695
1696                 self::entryContent($doc, $as_object, $parent, $owner, "New entry");
1697
1698                 $entry->appendChild($as_object);
1699
1700                 self::entryFooter($doc, $entry, $item, $owner);
1701
1702                 return $entry;
1703         }
1704
1705         /**
1706          * @brief Adds the person object element to the XML document
1707          *
1708          * @param object $doc     XML document
1709          * @param array  $owner   Contact data of the poster
1710          * @param array  $contact Contact data of the target
1711          *
1712          * @return object author element
1713          */
1714         private static function addPersonObject($doc, $owner, $contact)
1715         {
1716                 $object = $doc->createElement("activity:object");
1717                 XML::addElement($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1718
1719                 if ($contact['network'] == NETWORK_PHANTOM) {
1720                         XML::addElement($doc, $object, "id", $contact['url']);
1721                         return $object;
1722                 }
1723
1724                 XML::addElement($doc, $object, "id", $contact["alias"]);
1725                 XML::addElement($doc, $object, "title", $contact["nick"]);
1726
1727                 $attributes = ["rel" => "alternate", "type" => "text/html", "href" => $contact["url"]];
1728                 XML::addElement($doc, $object, "link", "", $attributes);
1729
1730                 $attributes = [
1731                                 "rel" => "avatar",
1732                                 "type" => "image/jpeg", // To-Do?
1733                                 "media:width" => 175,
1734                                 "media:height" => 175,
1735                                 "href" => $contact["photo"]];
1736                 XML::addElement($doc, $object, "link", "", $attributes);
1737
1738                 XML::addElement($doc, $object, "poco:preferredUsername", $contact["nick"]);
1739                 XML::addElement($doc, $object, "poco:displayName", $contact["name"]);
1740
1741                 if (trim($contact["location"]) != "") {
1742                         $element = $doc->createElement("poco:address");
1743                         XML::addElement($doc, $element, "poco:formatted", $contact["location"]);
1744                         $object->appendChild($element);
1745                 }
1746
1747                 return $object;
1748         }
1749
1750         /**
1751          * @brief Adds a follow/unfollow entry element
1752          *
1753          * @param object $doc      XML document
1754          * @param array  $item     Data of the follow/unfollow message
1755          * @param array  $owner    Contact data of the poster
1756          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1757          *
1758          * @return object Entry element
1759          */
1760         private static function followEntry($doc, $item, $owner, $toplevel)
1761         {
1762                 $item["id"] = $item["parent"] = 0;
1763                 $item["created"] = $item["edited"] = date("c");
1764                 $item["private"] = true;
1765
1766                 $contact = Probe::uri($item['follow']);
1767
1768                 if ($contact['alias'] == '') {
1769                         $contact['alias'] = $contact["url"];
1770                 } else {
1771                         $item['follow'] = $contact['alias'];
1772                 }
1773
1774                 $r = q(
1775                         "SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1776                         intval($owner['uid']),
1777                         dbesc(normalise_link($contact["url"]))
1778                 );
1779
1780                 if (DBM::is_result($r)) {
1781                         $connect_id = $r[0]['id'];
1782                 } else {
1783                         $connect_id = 0;
1784                 }
1785
1786                 if ($item['verb'] == ACTIVITY_FOLLOW) {
1787                         $message = L10n::t('%s is now following %s.');
1788                         $title = L10n::t('following');
1789                         $action = "subscription";
1790                 } else {
1791                         $message = L10n::t('%s stopped following %s.');
1792                         $title = L10n::t('stopped following');
1793                         $action = "unfollow";
1794                 }
1795
1796                 $item["uri"] = $item['parent-uri'] = $item['thr-parent']
1797                                 = 'tag:'.get_app()->get_hostname().
1798                                 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1799                                 ':person:'.$connect_id.':'.$item['created'];
1800
1801                 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1802
1803                 self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1804
1805                 self::entryContent($doc, $entry, $item, $owner, $title);
1806
1807                 $object = self::addPersonObject($doc, $owner, $contact);
1808                 $entry->appendChild($object);
1809
1810                 self::entryFooter($doc, $entry, $item, $owner);
1811
1812                 return $entry;
1813         }
1814
1815         /**
1816          * @brief Adds a regular entry element
1817          *
1818          * @param object $doc      XML document
1819          * @param array  $item     Data of the item that is to be posted
1820          * @param array  $owner    Contact data of the poster
1821          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1822          *
1823          * @return object Entry element
1824          */
1825         private static function noteEntry($doc, $item, $owner, $toplevel)
1826         {
1827                 if (($item["id"] != $item["parent"]) && (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1828                         logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1829                 }
1830
1831                 $title = self::entryHeader($doc, $entry, $owner, $item, $toplevel);
1832
1833                 XML::addElement($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1834
1835                 self::entryContent($doc, $entry, $item, $owner, $title);
1836
1837                 self::entryFooter($doc, $entry, $item, $owner);
1838
1839                 return $entry;
1840         }
1841
1842         /**
1843          * @brief Adds a header element to the XML document
1844          *
1845          * @param object $doc      XML document
1846          * @param object $entry    The entry element where the elements are added
1847          * @param array  $owner    Contact data of the poster
1848          * @param bool   $toplevel Is it for en entry element (false) or a feed entry (true)?
1849          *
1850          * @return string The title for the element
1851          */
1852         private static function entryHeader($doc, &$entry, $owner, $item, $toplevel)
1853         {
1854                 /// @todo Check if this title stuff is really needed (I guess not)
1855                 if (!$toplevel) {
1856                         $entry = $doc->createElement("entry");
1857                         $title = sprintf("New note by %s", $owner["nick"]);
1858
1859                         if ($owner['account-type'] == ACCOUNT_TYPE_COMMUNITY) {
1860                                 $contact = self::contactEntry($item['author-link'], $owner);
1861                                 $author = self::addAuthor($doc, $contact, false);
1862                                 $entry->appendChild($author);
1863                         }
1864                 } else {
1865                         $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
1866
1867                         $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1868                         $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1869                         $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1870                         $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1871                         $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
1872                         $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1873                         $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1874                         $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1875
1876                         $author = self::addAuthor($doc, $owner);
1877                         $entry->appendChild($author);
1878
1879                         $title = sprintf("New comment by %s", $owner["nick"]);
1880                 }
1881                 return $title;
1882         }
1883
1884         /**
1885          * @brief Adds elements to the XML document
1886          *
1887          * @param object $doc      XML document
1888          * @param object $entry    Entry element where the content is added
1889          * @param array  $item     Data of the item that is to be posted
1890          * @param array  $owner    Contact data of the poster
1891          * @param string $title    Title for the post
1892          * @param string $verb     The activity verb
1893          * @param bool   $complete Add the "status_net" element?
1894          * @return void
1895          */
1896         private static function entryContent($doc, $entry, $item, $owner, $title, $verb = "", $complete = true)
1897         {
1898                 if ($verb == "") {
1899                         $verb = self::constructVerb($item);
1900                 }
1901
1902                 XML::addElement($doc, $entry, "id", $item["uri"]);
1903                 XML::addElement($doc, $entry, "title", $title);
1904
1905                 $body = self::formatPicturePost($item['body']);
1906
1907                 if ($item['title'] != "") {
1908                         $body = "[b]".$item['title']."[/b]\n\n".$body;
1909                 }
1910
1911                 $body = BBCode::convert($body, false, 7);
1912
1913                 XML::addElement($doc, $entry, "content", $body, ["type" => "html"]);
1914
1915                 XML::addElement($doc, $entry, "link", "", ["rel" => "alternate", "type" => "text/html",
1916                                                                 "href" => System::baseUrl()."/display/".$item["guid"]]
1917                 );
1918
1919                 if ($complete && ($item["id"] > 0)) {
1920                         XML::addElement($doc, $entry, "status_net", "", ["notice_id" => $item["id"]]);
1921                 }
1922
1923                 XML::addElement($doc, $entry, "activity:verb", $verb);
1924
1925                 XML::addElement($doc, $entry, "published", DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM));
1926                 XML::addElement($doc, $entry, "updated", DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM));
1927         }
1928
1929         /**
1930          * @brief Adds the elements at the foot of an entry to the XML document
1931          *
1932          * @param object $doc      XML document
1933          * @param object $entry    The entry element where the elements are added
1934          * @param array  $item     Data of the item that is to be posted
1935          * @param array  $owner    Contact data of the poster
1936          * @param bool   $complete default true
1937          * @return void
1938          */
1939         private static function entryFooter($doc, $entry, array $item, array $owner, $complete = true)
1940         {
1941                 $mentioned = [];
1942
1943                 if (($item['parent'] != $item['id']) || ($item['parent-uri'] !== $item['uri']) || (($item['thr-parent'] !== '') && ($item['thr-parent'] !== $item['uri']))) {
1944                         $parent = Item::selectFirst(['guid', 'author-link', 'owner-link'], ['id' => $item["parent"]]);
1945                         $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1946
1947                         $thrparent = Item::selectFirst(['guid', 'author-link', 'owner-link', 'plink'], ['uid' => $owner["uid"], 'uri' => $parent_item]);
1948
1949                         if (DBM::is_result($thrparent)) {
1950                                 $mentioned[$thrparent["author-link"]] = $thrparent["author-link"];
1951                                 $mentioned[$thrparent["owner-link"]] = $thrparent["owner-link"];
1952                                 $parent_plink = $thrparent["plink"];
1953                         } else {
1954                                 $mentioned[$parent["author-link"]] = $parent["author-link"];
1955                                 $mentioned[$parent["owner-link"]] = $parent["owner-link"];
1956                                 $parent_plink = System::baseUrl()."/display/".$parent["guid"];
1957                         }
1958
1959                         $attributes = [
1960                                         "ref" => $parent_item,
1961                                         "href" => $parent_plink];
1962                         XML::addElement($doc, $entry, "thr:in-reply-to", "", $attributes);
1963
1964                         $attributes = [
1965                                         "rel" => "related",
1966                                         "href" => $parent_plink];
1967                         XML::addElement($doc, $entry, "link", "", $attributes);
1968                 }
1969
1970                 if (intval($item["parent"]) > 0) {
1971                         $conversation_href = System::baseUrl()."/display/".$owner["nick"]."/".$item["parent"];
1972                         $conversation_uri = $conversation_href;
1973
1974                         if (isset($parent_item)) {
1975                                 $conversation = dba::selectFirst('conversation', ['conversation-uri', 'conversation-href'], ['item-uri' => $parent_item]);
1976                                 if (DBM::is_result($conversation)) {
1977                                         if ($r['conversation-uri'] != '') {
1978                                                 $conversation_uri = $conversation['conversation-uri'];
1979                                         }
1980                                         if ($r['conversation-href'] != '') {
1981                                                 $conversation_href = $conversation['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 = Item::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 }