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