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