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