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