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