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