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