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