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