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