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