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