3 * @file include/ostatus.php
6 require_once("include/Contact.php");
7 require_once("include/threads.php");
8 require_once("include/html2bbcode.php");
9 require_once("include/bbcode.php");
10 require_once("include/items.php");
11 require_once("mod/share.php");
12 require_once("include/enotify.php");
13 require_once("include/socgraph.php");
14 require_once("include/Photo.php");
15 require_once("include/Scrape.php");
16 require_once("include/follow.php");
17 require_once("include/api.php");
18 require_once("mod/proxy.php");
19 require_once("include/xml.php");
22 * @brief This class contain functions for the OStatus protocol
26 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
27 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
28 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
31 * @brief Mix two paths together to possibly fix missing parts
33 * @param string $avatar Path to the avatar
34 * @param string $base Another path that is hopefully complete
36 * @return string fixed avatar path
38 public static function fix_avatar($avatar, $base) {
39 $base_parts = parse_url($base);
41 // Remove all parts that could create a problem
42 unset($base_parts['path']);
43 unset($base_parts['query']);
44 unset($base_parts['fragment']);
46 $avatar_parts = parse_url($avatar);
49 $parts = array_merge($base_parts, $avatar_parts);
51 // And put them together again
52 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
53 $host = isset($parts['host']) ? $parts['host'] : '';
54 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
55 $path = isset($parts['path']) ? $parts['path'] : '';
56 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
57 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
59 $fixed = $scheme.$host.$port.$path.$query.$fragment;
61 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
67 * @brief Fetches author data
69 * @param object $xpath The xpath object
70 * @param object $context The xml context of the author detals
71 * @param array $importer user record of the importing user
72 * @param array $contact Called by reference, will contain the fetched contact
73 * @param bool $onlyfetch Only fetch the header without updating the contact entries
75 * @return array Array of author related entries for the item
77 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
80 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
81 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
83 $aliaslink = $author["author-link"];
85 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
86 if (is_object($alternate))
87 foreach($alternate AS $attributes)
88 if ($attributes->name == "href")
89 $author["author-link"] = $attributes->textContent;
91 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
92 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
93 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
96 $author["contact-id"] = $r[0]["id"];
98 $author["contact-id"] = $contact["id"];
100 $avatarlist = array();
101 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
102 foreach($avatars AS $avatar) {
105 foreach($avatar->attributes AS $attributes) {
106 if ($attributes->name == "href")
107 $href = $attributes->textContent;
108 if ($attributes->name == "width")
109 $width = $attributes->textContent;
111 if (($width > 0) AND ($href != ""))
112 $avatarlist[$width] = $href;
114 if (count($avatarlist) > 0) {
116 $author["author-avatar"] = self::fix_avatar(current($avatarlist), $author["author-link"]);
119 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
120 if ($displayname != "")
121 $author["author-name"] = $displayname;
123 $author["owner-name"] = $author["author-name"];
124 $author["owner-link"] = $author["author-link"];
125 $author["owner-avatar"] = $author["author-avatar"];
127 // Only update the contacts if it is an OStatus contact
128 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
130 // Update contact data
132 // This query doesn't seem to work
133 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
135 // $contact["notify"] = $value;
137 // This query doesn't seem to work as well - I hate these queries
138 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
140 // $contact["poll"] = $value;
142 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
144 $contact["alias"] = $value;
146 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
148 $contact["name"] = $value;
150 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
152 $contact["nick"] = $value;
154 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
156 $contact["about"] = html2bbcode($value);
158 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
160 $contact["location"] = $value;
162 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
163 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
165 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
167 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
168 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
169 dbesc($contact["about"]), dbesc($contact["location"]),
170 dbesc(datetime_convert()), intval($contact["id"]));
173 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
174 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
176 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
179 // Ensure that we are having this contact (with uid=0)
180 $cid = get_contact($author["author-link"], 0);
183 // Update it with the current values
184 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
185 `about` = '%s', `location` = '%s',
186 `success_update` = '%s', `last-update` = '%s'
188 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
189 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
190 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
193 update_contact_avatar($author["author-avatar"], 0, $cid);
196 $contact["generation"] = 2;
197 $contact["hide"] = false; // OStatus contacts are never hidden
198 $contact["photo"] = $author["author-avatar"];
199 $gcid = update_gcontact($contact);
201 link_gcontact($gcid, $contact["uid"], $contact["id"]);
208 * @brief Fetches author data from a given XML string
210 * @param string $xml The XML
211 * @param array $importer user record of the importing user
213 * @return array Array of author related entries for the item
215 public static function salmon_author($xml, $importer) {
220 $doc = new DOMDocument();
221 @$doc->loadXML($xml);
223 $xpath = new DomXPath($doc);
224 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
225 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
226 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
227 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
228 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
229 $xpath->registerNamespace('poco', NAMESPACE_POCO);
230 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
231 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
233 $entries = $xpath->query('/atom:entry');
235 foreach ($entries AS $entry) {
237 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
243 * @brief Read attributes from element
245 * @param object $element Element object
247 * @return array attributes
249 private static function read_attributes($element) {
250 $attribute = array();
252 foreach ($element->attributes AS $attributes) {
253 $attribute[$attributes->name] = $attributes->textContent;
260 * @brief Imports an XML string containing OStatus elements
262 * @param string $xml The XML
263 * @param array $importer user record of the importing user
265 * @param array $hub Called by reference, returns the fetched hub data
267 public static function import($xml,$importer,&$contact, &$hub) {
268 /// @todo this function is too long. It has to be split in many parts
270 logger("Import OStatus message", LOGGER_DEBUG);
275 //$tempfile = tempnam(get_temppath(), "import");
276 //file_put_contents($tempfile, $xml);
278 $doc = new DOMDocument();
279 @$doc->loadXML($xml);
281 $xpath = new DomXPath($doc);
282 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
283 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
284 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
285 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
286 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
287 $xpath->registerNamespace('poco', NAMESPACE_POCO);
288 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
289 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
292 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
293 if (is_object($hub_attributes)) {
294 foreach ($hub_attributes AS $hub_attribute) {
295 if ($hub_attribute->name == "href") {
296 $hub = $hub_attribute->textContent;
297 logger("Found hub ".$hub, LOGGER_DEBUG);
302 $header["uid"] = $importer["uid"];
303 $header["network"] = NETWORK_OSTATUS;
304 $header["type"] = "remote";
306 $header["origin"] = 0;
307 $header["gravity"] = GRAVITY_PARENT;
309 // it could either be a received post or a post we fetched by ourselves
310 // depending on that, the first node is different
311 $first_child = $doc->firstChild->tagName;
313 if ($first_child == "feed") {
314 $entries = $xpath->query('/atom:feed/atom:entry');
315 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
317 $entries = $xpath->query('/atom:entry');
318 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
321 $conversationlist = array();
324 // Reverse the order of the entries
325 $entrylist = array();
327 foreach ($entries AS $entry) {
328 $entrylist[] = $entry;
330 foreach (array_reverse($entrylist) AS $entry) {
335 if ($first_child == "feed") {
336 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
338 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
340 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
344 $nickname = $author["author-name"];
346 $item = array_merge($header, $author);
349 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
351 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
352 intval($importer["uid"]), dbesc($item["uri"]));
353 if (dbm::is_result($r)) {
354 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
358 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
359 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
360 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
362 // Mastodon Content Warning
363 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
364 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
366 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
369 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
370 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
371 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
372 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
373 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
375 $item["source"] = $xml;
379 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
380 // ignore "Delete" messages (by now)
381 logger("Ignore delete message ".print_r($item, true));
385 if ($item["verb"] == ACTIVITY_JOIN) {
386 // ignore "Join" messages
387 logger("Ignore join message ".print_r($item, true));
391 if ($item["verb"] == ACTIVITY_FOLLOW) {
392 new_follower($importer, $contact, $item, $nickname);
396 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
397 lose_follower($importer, $contact, $item, $dummy);
401 if ($item["verb"] == ACTIVITY_FAVORITE) {
402 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
403 logger("Favorite ".$orig_uri." ".print_r($item, true));
405 $item["verb"] = ACTIVITY_LIKE;
406 $item["parent-uri"] = $orig_uri;
407 $item["gravity"] = GRAVITY_LIKE;
410 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
411 // Ignore "Unfavorite" message
412 logger("Ignore unfavorite message ".print_r($item, true));
416 // http://activitystrea.ms/schema/1.0/rsvp-yes
417 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
418 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
420 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
421 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
422 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
423 $item['conversation-uri'] = $conversation;
425 $conv = $xpath->query('ostatus:conversation', $entry);
426 if (is_object($conv->item(0))) {
427 foreach ($conv->item(0)->attributes AS $attributes) {
428 if ($attributes->name == "ref") {
429 $item['conversation-uri'] = $attributes->textContent;
431 if ($attributes->name == "href") {
432 $item['conversation-href'] = $attributes->textContent;
439 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
440 if (is_object($inreplyto->item(0))) {
441 foreach ($inreplyto->item(0)->attributes AS $attributes) {
442 if ($attributes->name == "ref") {
443 $item["parent-uri"] = $attributes->textContent;
445 if ($attributes->name == "href") {
446 $related = $attributes->textContent;
451 $georsspoint = $xpath->query('georss:point', $entry);
453 $item["coord"] = $georsspoint->item(0)->nodeValue;
455 $categories = $xpath->query('atom:category', $entry);
457 foreach ($categories AS $category) {
458 foreach ($category->attributes AS $attributes) {
459 if ($attributes->name == "term") {
460 $term = $attributes->textContent;
461 if(strlen($item["tag"])) {
464 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
473 $links = $xpath->query('atom:link', $entry);
475 foreach ($links AS $link) {
476 $attribute = self::read_attributes($link);
478 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
479 switch ($attribute['rel']) {
481 $item["plink"] = $attribute['href'];
482 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
483 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
484 $item["body"] .= add_page_info($attribute['href']);
487 case "ostatus:conversation":
488 $conversation = $attribute['href'];
489 $item['conversation-href'] = $conversation;
490 if (!isset($item['conversation-uri'])) {
491 $item['conversation-uri'] = $item['conversation-href'];
495 $enclosure = $attribute['href'];
496 if (strlen($item["attach"])) {
497 $item["attach"] .= ',';
499 if (!isset($attribute['length'])) {
500 $attribute['length'] = "0";
502 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
505 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
506 if (!isset($item["parent-uri"])) {
507 $item["parent-uri"] = $attribute['href'];
509 if ($related == "") {
510 $related = $attribute['href'];
513 $item["body"] .= add_page_info($attribute['href']);
517 $self = $attribute['href'];
520 // Notification check
521 if ($importer["nurl"] == normalise_link($attribute['href'])) {
533 $notice_info = $xpath->query('statusnet:notice_info', $entry);
534 if ($notice_info AND ($notice_info->length > 0)) {
535 foreach ($notice_info->item(0)->attributes AS $attributes) {
536 if ($attributes->name == "source") {
537 $item["app"] = strip_tags($attributes->textContent);
539 if ($attributes->name == "local_id") {
540 $local_id = $attributes->textContent;
542 if ($attributes->name == "repeat_of") {
543 $repeat_of = $attributes->textContent;
548 // Is it a repeated post?
549 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
550 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
552 if (is_object($activityobjects)) {
554 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
555 if (!isset($orig_uri)) {
556 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
558 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
559 if ($orig_links AND ($orig_links->length > 0)) {
560 foreach ($orig_links->item(0)->attributes AS $attributes) {
561 if ($attributes->name == "href") {
562 $orig_link = $attributes->textContent;
566 if (!isset($orig_link)) {
567 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
569 if (!isset($orig_link)) {
570 $orig_link = self::convert_href($orig_uri);
572 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
573 if (!isset($orig_body)) {
574 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
576 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
577 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
579 $orig_contact = $contact;
580 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
582 $item["author-name"] = $orig_author["author-name"];
583 $item["author-link"] = $orig_author["author-link"];
584 $item["author-avatar"] = $orig_author["author-avatar"];
586 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
587 $item["created"] = $orig_created;
588 $item["edited"] = $orig_edited;
590 $item["uri"] = $orig_uri;
592 if (!isset($item["plink"])) {
593 $item["plink"] = $orig_link;
596 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
598 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
599 if (!isset($item["object-type"])) {
600 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
603 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
605 foreach ($enclosures AS $link) {
606 $attribute = self::read_attributes($link);
608 $enclosure = $attribute['href'];
609 if (strlen($item["attach"])) {
610 $item["attach"] .= ',';
612 if (!isset($attribute['length'])) {
613 $attribute['length'] = "0";
615 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
622 //if ($enclosure != "")
623 // $item["body"] .= add_page_info($enclosure);
625 if (isset($item["parent-uri"])) {
626 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
627 intval($importer["uid"]), dbesc($item["parent-uri"]));
629 // Only fetch missing stuff if it is a comment or reshare.
630 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
631 !dbm::is_result($r) AND ($related != "")) {
632 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
634 if ($reply_path != $related) {
635 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
636 $reply_xml = fetch_url($reply_path);
638 $reply_contact = $contact;
639 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
641 // After the import try to fetch the parent item again
642 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
643 intval($importer["uid"]), dbesc($item["parent-uri"]));
646 if (dbm::is_result($r)) {
647 $item["type"] = 'remote-comment';
648 $item["gravity"] = GRAVITY_COMMENT;
651 $item["parent-uri"] = $item["uri"];
653 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
656 logger("Error storing item", LOGGER_DEBUG);
660 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
665 * @brief Create an url out of an uri
667 * @param string $href URI in the format "parameter1:parameter1:..."
669 * @return string URL in the format http(s)://....
671 public static function convert_href($href) {
672 $elements = explode(":",$href);
674 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
677 $server = explode(",", $elements[1]);
678 $conversation = explode("=", $elements[2]);
680 if ((count($elements) == 4) AND ($elements[2] == "post"))
681 return "http://".$server[0]."/notice/".$elements[3];
683 if ((count($conversation) != 2) OR ($conversation[1] ==""))
686 if ($elements[3] == "objectType=thread")
687 return "http://".$server[0]."/conversation/".$conversation[1];
689 return "http://".$server[0]."/notice/".$conversation[1];
695 * @brief Checks if there are entries in conversations that aren't present on our side
697 * @param bool $mentions Fetch conversations where we are mentioned
698 * @param bool $override Override the interval setting
700 public static function check_conversations($mentions = false, $override = false) {
701 $last = get_config('system','ostatus_last_poll');
703 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
704 if (!$poll_interval) {
705 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
708 // Don't poll if the interval is set negative
709 if (($poll_interval < 0) AND !$override) {
714 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
715 if (!$poll_timeframe) {
716 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
719 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
720 if (!$poll_timeframe) {
721 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
726 if ($last AND !$override) {
727 $next = $last + ($poll_interval * 60);
728 if ($next > time()) {
729 logger('poll interval not reached');
734 logger('cron_start');
736 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
739 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
740 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
741 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
742 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
744 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
745 WHERE `type` = 7 AND `term` > '%s'
746 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
749 foreach ($conversations AS $conversation) {
750 self::completion($conversation['url'], $conversation['uid']);
755 set_config('system','ostatus_last_poll', time());
759 * @brief Updates the gcontact table with actor data from the conversation
761 * @param object $actor The actor object that contains the contact data
763 private function conv_fetch_actor($actor) {
765 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
766 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
768 if (isset($actor->url))
769 $contact["url"] = $actor->url;
771 if (isset($actor->displayName))
772 $contact["name"] = $actor->displayName;
774 if (isset($actor->portablecontacts_net->displayName))
775 $contact["name"] = $actor->portablecontacts_net->displayName;
777 if (isset($actor->portablecontacts_net->preferredUsername))
778 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
780 if (isset($actor->id))
781 $contact["alias"] = $actor->id;
783 if (isset($actor->summary))
784 $contact["about"] = $actor->summary;
786 if (isset($actor->portablecontacts_net->note))
787 $contact["about"] = $actor->portablecontacts_net->note;
789 if (isset($actor->portablecontacts_net->addresses->formatted))
790 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
793 if (isset($actor->image->url))
794 $contact["photo"] = $actor->image->url;
796 if (isset($actor->image->width))
797 $avatarwidth = $actor->image->width;
799 if (is_array($actor->status_net->avatarLinks))
800 foreach ($actor->status_net->avatarLinks AS $avatar) {
801 if ($avatarsize < $avatar->width) {
802 $contact["photo"] = $avatar->url;
803 $avatarsize = $avatar->width;
807 $contact["hide"] = false; // OStatus contacts are never hidden
808 update_gcontact($contact);
812 * @brief Fetches the conversation url for a given item link or conversation id
814 * @param string $self The link to the posting
815 * @param string $conversation_id The conversation id
817 * @return string The conversation url
819 private function fetch_conversation($self, $conversation_id = "") {
821 if ($conversation_id != "") {
822 $elements = explode(":", $conversation_id);
824 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
825 return $conversation_id;
831 $json = str_replace(".atom", ".json", $self);
833 $raw = fetch_url($json);
837 $data = json_decode($raw);
838 if (!is_object($data))
841 $conversation_id = $data->statusnet_conversation_id;
843 $pos = strpos($self, "/api/statuses/show/");
844 $base_url = substr($self, 0, $pos);
846 return $base_url."/conversation/".$conversation_id;
850 * @brief Fetches actor details of a given actor and user id
852 * @param string $actor The actor url
853 * @param int $uid The user id
854 * @param int $contact_id The default contact-id
856 * @return array Array with actor details
858 private function get_actor_details($actor, $uid, $contact_id) {
862 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
863 $uid, normalise_link($actor), NETWORK_STATUSNET);
866 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
867 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
870 logger("Found contact for url ".$actor, LOGGER_DEBUG);
871 $details["contact_id"] = $contact[0]["id"];
872 $details["network"] = $contact[0]["network"];
874 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
876 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
878 // Adding a global contact
879 /// @TODO Use this data for the post
880 $details["global_contact_id"] = get_contact($actor, 0);
882 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
884 $details["contact_id"] = $contact_id;
885 $details["network"] = NETWORK_OSTATUS;
887 $details["not_following"] = true;
894 * @brief Stores an item and completes the thread
896 * @param string $conversation_url The URI of the conversation
897 * @param integer $uid The user id
898 * @param array $item Data of the item that is to be posted
900 * @return integer The item id of the posted item array
902 private function completion($conversation_url, $uid, $item = array(), $self = "") {
904 /// @todo This function is totally ugly and has to be rewritten totally
906 // Import all threads or only threads that were started by our followers?
907 $all_threads = !get_config('system','ostatus_full_threads');
911 $conversation_url = self::fetch_conversation($self, $conversation_url);
913 // If the thread shouldn't be completed then store the item and go away
914 // Don't do a completion on liked content
915 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
916 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
917 $item_stored = item_store($item, $all_threads);
922 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
923 `item`.`verb`, `item`.`visible` FROM `term`
924 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
925 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
926 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
927 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
929 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
931 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
932 (SELECT `parent` FROM `item` WHERE `id` IN
933 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
934 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
937 $parent = $parents[0];
938 elseif (count($item) > 0) {
940 $parent["type"] = "remote";
941 $parent["verb"] = ACTIVITY_POST;
942 $parent["visible"] = 1;
945 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
951 $parent["parent"] = 0;
953 $parent["contact-id"] = $r[0]["id"];
954 $parent["type"] = "remote";
955 $parent["verb"] = ACTIVITY_POST;
956 $parent["visible"] = 1;
959 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
963 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
966 $conv_arr = z_fetch_url($conv."?page=".$pageno);
968 // If it is a non-ssl site and there is an error, then try ssl or vice versa
969 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
970 $conv = str_replace("http://", "https://", $conv);
971 $conv_as = fetch_url($conv."?page=".$pageno);
972 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
973 $conv = str_replace("https://", "http://", $conv);
974 $conv_as = fetch_url($conv."?page=".$pageno);
976 $conv_as = $conv_arr["body"];
978 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
979 $conv_as = json_decode($conv_as);
981 $no_of_items = sizeof($items);
983 if (@is_array($conv_as->items))
984 foreach ($conv_as->items AS $single_item)
985 $items[$single_item->id] = $single_item;
987 if ($no_of_items == sizeof($items))
994 logger('fetching conversation done. Found '.count($items).' items');
996 if (!sizeof($items)) {
997 if (count($item) > 0) {
998 $item_stored = item_store($item, $all_threads);
1001 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1002 self::store_conversation($item_id, $conversation_url);
1005 return($item_stored);
1010 $items = array_reverse($items);
1012 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1017 foreach ($items as $single_conv) {
1019 // Update the gcontact table
1020 self::conv_fetch_actor($single_conv->actor);
1022 // Test - remove before flight
1023 //$tempfile = tempnam(get_temppath(), "conversation");
1024 //file_put_contents($tempfile, json_encode($single_conv));
1028 if (isset($single_conv->object->id))
1029 $single_conv->id = $single_conv->object->id;
1031 $plink = self::convert_href($single_conv->id);
1032 if (isset($single_conv->object->url))
1033 $plink = self::convert_href($single_conv->object->url);
1035 if (@!$single_conv->id)
1038 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1040 if ($first_id == "") {
1041 $first_id = $single_conv->id;
1043 // The first post of the conversation isn't our first post. There are three options:
1044 // 1. Our conversation hasn't the "real" thread starter
1045 // 2. This first post is a post inside our thread
1046 // 3. This first post is a post inside another thread
1047 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1051 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1052 (SELECT `parent` FROM `item`
1053 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1054 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1056 if ($new_parents[0]["parent"] == $parent["parent"]) {
1057 // Option 2: This post is already present inside our thread - but not as thread starter
1058 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1059 $first_id = $parent["uri"];
1061 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1062 // For now just take the new parent.
1063 $parent = $new_parents[0];
1064 $first_id = $parent["uri"];
1065 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1068 // Option 1: We hadn't got the real thread starter
1069 // We have to clean up our existing messages.
1071 $parent["uri"] = $first_id;
1072 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1074 } elseif ($parent["uri"] == "") {
1076 $parent["uri"] = $first_id;
1080 $parent_uri = $parent["uri"];
1082 // "context" only seems to exist on older servers
1083 if (isset($single_conv->context->inReplyTo->id)) {
1084 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1085 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1087 $parent_uri = $single_conv->context->inReplyTo->id;
1090 // This is the current way
1091 if (isset($single_conv->object->inReplyTo->id)) {
1092 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1093 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1095 $parent_uri = $single_conv->object->inReplyTo->id;
1098 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1099 intval($uid), dbesc($single_conv->id),
1100 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1101 if ($message_exists) {
1102 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1104 if ($parent["id"] != 0) {
1105 $existing_message = $message_exists[0];
1107 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1108 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1109 if ($existing_message["parent"] != $parent["id"]) {
1110 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1112 // Update the parent id of the selected item
1113 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1114 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1116 // Update the parent uri in the thread - but only if it points to itself
1117 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1118 dbesc($parent_uri), intval($existing_message["id"]));
1120 // try to change all items of the same parent
1121 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1122 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1124 // Update the parent uri in the thread - but only if it points to itself
1125 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1126 dbesc($parent["uri"]), intval($existing_message["parent"]));
1128 // Now delete the thread
1129 delete_thread($existing_message["parent"]);
1133 // The item we are having on the system is the one that we wanted to store via the item array
1134 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1142 if (is_array($single_conv->to))
1143 foreach($single_conv->to AS $to)
1144 if ($importer["nurl"] == normalise_link($to->id))
1147 $actor = $single_conv->actor->id;
1148 if (isset($single_conv->actor->url))
1149 $actor = $single_conv->actor->url;
1151 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1153 // Do we only want to import threads that were started by our contacts?
1154 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1155 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1160 $arr["network"] = $details["network"];
1161 $arr["uri"] = $single_conv->id;
1162 $arr["plink"] = $plink;
1164 $arr["contact-id"] = $details["contact_id"];
1165 $arr["parent-uri"] = $parent_uri;
1166 $arr["created"] = $single_conv->published;
1167 $arr["edited"] = $single_conv->published;
1168 $arr["owner-name"] = $single_conv->actor->displayName;
1169 if ($arr["owner-name"] == '')
1170 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1171 if ($arr["owner-name"] == '')
1172 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1174 $arr["owner-link"] = $actor;
1175 $arr["owner-avatar"] = self::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1177 $arr["author-name"] = $arr["owner-name"];
1178 $arr["author-link"] = $arr["owner-link"];
1179 $arr["author-avatar"] = $arr["owner-avatar"];
1180 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1182 if (isset($single_conv->status_net->conversation)) {
1183 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1186 if (isset($single_conv->status_net->notice_info->source))
1187 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1188 elseif (isset($single_conv->statusnet->notice_info->source))
1189 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1190 elseif (isset($single_conv->statusnet_notice_info->source))
1191 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1192 elseif (isset($single_conv->provider->displayName))
1193 $arr["app"] = $single_conv->provider->displayName;
1195 $arr["app"] = "OStatus";
1198 $arr["source"] = json_encode($single_conv);
1199 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1201 $arr["verb"] = $parent["verb"];
1202 $arr["visible"] = $parent["visible"];
1203 $arr["location"] = $single_conv->location->displayName;
1204 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1206 // Is it a reshared item?
1207 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1208 if (is_array($single_conv->object))
1209 $single_conv->object = $single_conv->object[0];
1211 logger("Found reshared item ".$single_conv->object->id);
1213 // $single_conv->object->context->conversation;
1215 if (isset($single_conv->object->object->id))
1216 $arr["uri"] = $single_conv->object->object->id;
1218 $arr["uri"] = $single_conv->object->id;
1220 if (isset($single_conv->object->object->url))
1221 $plink = self::convert_href($single_conv->object->object->url);
1223 $plink = self::convert_href($single_conv->object->url);
1225 if (isset($single_conv->object->object->content))
1226 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1228 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1230 $arr["plink"] = $plink;
1232 $arr["created"] = $single_conv->object->published;
1233 $arr["edited"] = $single_conv->object->published;
1235 $arr["author-name"] = $single_conv->object->actor->displayName;
1236 if ($arr["owner-name"] == '') {
1237 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1239 $arr["author-link"] = $single_conv->object->actor->url;
1240 $arr["author-avatar"] = self::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1242 $arr["app"] = $single_conv->object->provider->displayName."#";
1243 //$arr["verb"] = $single_conv->object->verb;
1245 $arr["location"] = $single_conv->object->location->displayName;
1246 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1249 if ($arr["location"] == "")
1250 unset($arr["location"]);
1252 if ($arr["coord"] == "")
1253 unset($arr["coord"]);
1255 // Copy fields from given item array
1256 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1257 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1258 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1259 "title", "attach", "app", "type", "location", "contact-id", "uri");
1260 foreach ($copy_fields AS $field)
1261 if (isset($item[$field]))
1262 $arr[$field] = $item[$field];
1266 $newitem = item_store($arr);
1268 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1272 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1274 $item_stored = $newitem;
1277 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1279 // Add the conversation entry (but don't fetch the whole conversation)
1280 self::store_conversation($newitem, $conversation_url);
1282 // If the newly created item is the top item then change the parent settings of the thread
1283 // This shouldn't happen anymore. This is supposed to be absolote.
1284 if ($arr["uri"] == $first_id) {
1285 logger('setting new parent to id '.$newitem);
1286 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1287 intval($uid), intval($newitem));
1289 $parent = $new_parents[0];
1293 if (($item_stored < 0) AND (count($item) > 0)) {
1295 if (get_config('system','ostatus_full_threads')) {
1296 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1297 if ($details["not_following"]) {
1298 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1303 $item_stored = item_store($item, $all_threads);
1305 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1306 self::store_conversation($item_stored, $conversation_url);
1310 return($item_stored);
1314 * @brief Stores conversation data into the database
1316 * @param integer $itemid The id of the item
1317 * @param string $conversation_url The uri of the conversation
1319 private function store_conversation($itemid, $conversation_url) {
1321 $conversation_url = self::convert_href($conversation_url);
1323 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1326 $message = $messages[0];
1328 // Store conversation url if not done before
1329 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1330 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1332 if (!$conversation) {
1333 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1334 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1335 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1336 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1341 * @brief Checks if the current post is a reshare
1343 * @param array $item The item array of thw post
1345 * @return string The guid if the post is a reshare
1347 private function get_reshared_guid($item) {
1348 $body = trim($item["body"]);
1350 // Skip if it isn't a pure repeated messages
1351 // Does it start with a share?
1352 if (strpos($body, "[share") > 0)
1355 // Does it end with a share?
1356 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1359 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1360 // Skip if there is no shared message in there
1361 if ($body == $attributes)
1365 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1366 if ($matches[1] != "")
1367 $guid = $matches[1];
1369 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1370 if ($matches[1] != "")
1371 $guid = $matches[1];
1377 * @brief Cleans the body of a post if it contains picture links
1379 * @param string $body The body
1381 * @return string The cleaned body
1383 private function format_picture_post($body) {
1384 $siteinfo = get_attached_data($body);
1386 if (($siteinfo["type"] == "photo")) {
1387 if (isset($siteinfo["preview"]))
1388 $preview = $siteinfo["preview"];
1390 $preview = $siteinfo["image"];
1392 // Is it a remote picture? Then make a smaller preview here
1393 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1395 // Is it a local picture? Then make it smaller here
1396 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1397 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1399 if (isset($siteinfo["url"]))
1400 $url = $siteinfo["url"];
1402 $url = $siteinfo["image"];
1404 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1411 * @brief Adds the header elements to the XML document
1413 * @param object $doc XML document
1414 * @param array $owner Contact data of the poster
1416 * @return object header root element
1418 private function add_header($doc, $owner) {
1422 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1423 $doc->appendChild($root);
1425 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1426 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1427 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1428 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1429 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1430 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1431 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1432 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1434 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1435 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1436 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1437 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1438 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1439 xml::add_element($doc, $root, "logo", $owner["photo"]);
1440 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1442 $author = self::add_author($doc, $owner);
1443 $root->appendChild($author);
1445 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1446 xml::add_element($doc, $root, "link", "", $attributes);
1448 /// @TODO We have to find out what this is
1449 /// $attributes = array("href" => App::get_baseurl()."/sup",
1450 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1451 /// "type" => "application/json");
1452 /// xml::add_element($doc, $root, "link", "", $attributes);
1454 self::hublinks($doc, $root);
1456 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1457 xml::add_element($doc, $root, "link", "", $attributes);
1459 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1460 xml::add_element($doc, $root, "link", "", $attributes);
1462 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1463 xml::add_element($doc, $root, "link", "", $attributes);
1465 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1466 "rel" => "self", "type" => "application/atom+xml");
1467 xml::add_element($doc, $root, "link", "", $attributes);
1473 * @brief Add the link to the push hubs to the XML document
1475 * @param object $doc XML document
1476 * @param object $root XML root element where the hub links are added
1478 public static function hublinks($doc, $root) {
1479 $hub = get_config('system','huburl');
1483 $hubs = explode(',', $hub);
1485 foreach($hubs as $h) {
1489 if ($h === '[internal]')
1490 $h = App::get_baseurl() . '/pubsubhubbub';
1491 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1498 * @brief Adds attachement data to the XML document
1500 * @param object $doc XML document
1501 * @param object $root XML root element where the hub links are added
1502 * @param array $item Data of the item that is to be posted
1504 private function get_attachment($doc, $root, $item) {
1506 $siteinfo = get_attached_data($item["body"]);
1508 switch ($siteinfo["type"]) {
1510 $imgdata = get_photo_info($siteinfo["image"]);
1511 $attributes = array("rel" => "enclosure",
1512 "href" => $siteinfo["image"],
1513 "type" => $imgdata["mime"],
1514 "length" => intval($imgdata["size"]));
1515 xml::add_element($doc, $root, "link", "", $attributes);
1518 $attributes = array("rel" => "enclosure",
1519 "href" => $siteinfo["url"],
1520 "type" => "text/html; charset=UTF-8",
1522 "title" => $siteinfo["title"]);
1523 xml::add_element($doc, $root, "link", "", $attributes);
1529 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1530 $imgdata = get_photo_info($siteinfo["image"]);
1531 $attributes = array("rel" => "enclosure",
1532 "href" => $siteinfo["image"],
1533 "type" => $imgdata["mime"],
1534 "length" => intval($imgdata["size"]));
1536 xml::add_element($doc, $root, "link", "", $attributes);
1539 $arr = explode('[/attach],', $item['attach']);
1541 foreach ($arr as $r) {
1543 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1545 $attributes = array("rel" => "enclosure",
1546 "href" => $matches[1],
1547 "type" => $matches[3]);
1549 if (intval($matches[2])) {
1550 $attributes["length"] = intval($matches[2]);
1552 if (trim($matches[4]) != "") {
1553 $attributes["title"] = trim($matches[4]);
1555 xml::add_element($doc, $root, "link", "", $attributes);
1562 * @brief Adds the author element to the XML document
1564 * @param object $doc XML document
1565 * @param array $owner Contact data of the poster
1567 * @return object author element
1569 private function add_author($doc, $owner) {
1571 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1575 $author = $doc->createElement("author");
1576 xml::add_element($doc, $author, "id", $owner["url"]);
1577 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1578 xml::add_element($doc, $author, "uri", $owner["url"]);
1579 xml::add_element($doc, $author, "name", $owner["nick"]);
1580 xml::add_element($doc, $author, "email", $owner["addr"]);
1581 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1583 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1584 xml::add_element($doc, $author, "link", "", $attributes);
1586 $attributes = array(
1588 "type" => "image/jpeg", // To-Do?
1589 "media:width" => 175,
1590 "media:height" => 175,
1591 "href" => $owner["photo"]);
1592 xml::add_element($doc, $author, "link", "", $attributes);
1594 if (isset($owner["thumb"])) {
1595 $attributes = array(
1597 "type" => "image/jpeg", // To-Do?
1598 "media:width" => 80,
1599 "media:height" => 80,
1600 "href" => $owner["thumb"]);
1601 xml::add_element($doc, $author, "link", "", $attributes);
1604 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1605 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1606 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1608 if (trim($owner["location"]) != "") {
1609 $element = $doc->createElement("poco:address");
1610 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1611 $author->appendChild($element);
1614 if (trim($profile["homepage"]) != "") {
1615 $urls = $doc->createElement("poco:urls");
1616 xml::add_element($doc, $urls, "poco:type", "homepage");
1617 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1618 xml::add_element($doc, $urls, "poco:primary", "true");
1619 $author->appendChild($urls);
1622 if (count($profile)) {
1623 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1624 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1627 if ($profile["publish"]) {
1628 xml::add_element($doc, $author, "mastodon:scope", "public");
1634 * @TODO Picture attachments should look like this:
1635 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1636 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1641 * @brief Returns the given activity if present - otherwise returns the "post" activity
1643 * @param array $item Data of the item that is to be posted
1645 * @return string activity
1647 function construct_verb($item) {
1649 return $item['verb'];
1650 return ACTIVITY_POST;
1654 * @brief Returns the given object type if present - otherwise returns the "note" object type
1656 * @param array $item Data of the item that is to be posted
1658 * @return string Object type
1660 function construct_objecttype($item) {
1661 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1662 return $item['object-type'];
1663 return ACTIVITY_OBJ_NOTE;
1667 * @brief Adds an entry element to the XML document
1669 * @param object $doc XML document
1670 * @param array $item Data of the item that is to be posted
1671 * @param array $owner Contact data of the poster
1672 * @param bool $toplevel
1674 * @return object Entry element
1676 private function entry($doc, $item, $owner, $toplevel = false) {
1677 $repeated_guid = self::get_reshared_guid($item);
1678 if ($repeated_guid != "")
1679 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1684 if ($item["verb"] == ACTIVITY_LIKE) {
1685 return self::like_entry($doc, $item, $owner, $toplevel);
1686 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1687 return self::follow_entry($doc, $item, $owner, $toplevel);
1689 return self::note_entry($doc, $item, $owner, $toplevel);
1694 * @brief Adds a source entry to the XML document
1696 * @param object $doc XML document
1697 * @param array $contact Array of the contact that is added
1699 * @return object Source element
1701 private function source_entry($doc, $contact) {
1702 $source = $doc->createElement("source");
1703 xml::add_element($doc, $source, "id", $contact["poll"]);
1704 xml::add_element($doc, $source, "title", $contact["name"]);
1705 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1706 "type" => "text/html",
1707 "href" => $contact["alias"]));
1708 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1709 "type" => "application/atom+xml",
1710 "href" => $contact["poll"]));
1711 xml::add_element($doc, $source, "icon", $contact["photo"]);
1712 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1718 * @brief Fetches contact data from the contact or the gcontact table
1720 * @param string $url URL of the contact
1721 * @param array $owner Contact data of the poster
1723 * @return array Contact array
1725 private function contact_entry($url, $owner) {
1727 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1728 dbesc(normalise_link($url)), intval($owner["uid"]));
1731 $contact["uid"] = -1;
1735 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1736 dbesc(normalise_link($url)));
1739 $contact["uid"] = -1;
1740 $contact["success_update"] = $contact["updated"];
1747 if (!isset($contact["poll"])) {
1748 $data = probe_url($url);
1749 $contact["poll"] = $data["poll"];
1751 if (!$contact["alias"])
1752 $contact["alias"] = $data["alias"];
1755 if (!isset($contact["alias"]))
1756 $contact["alias"] = $contact["url"];
1762 * @brief Adds an entry element with reshared content
1764 * @param object $doc XML document
1765 * @param array $item Data of the item that is to be posted
1766 * @param array $owner Contact data of the poster
1767 * @param $repeated_guid
1768 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1770 * @return object Entry element
1772 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1774 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1775 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1778 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1780 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1781 intval($owner["uid"]), dbesc($repeated_guid),
1782 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1784 $repeated_item = $r[0];
1788 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1790 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1792 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1794 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1796 $as_object = $doc->createElement("activity:object");
1798 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1800 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1802 $author = self::add_author($doc, $contact);
1803 $as_object->appendChild($author);
1805 $as_object2 = $doc->createElement("activity:object");
1807 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1809 $title = sprintf("New comment by %s", $contact["nick"]);
1811 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1813 $as_object->appendChild($as_object2);
1815 self::entry_footer($doc, $as_object, $item, $owner, false);
1817 $source = self::source_entry($doc, $contact);
1819 $as_object->appendChild($source);
1821 $entry->appendChild($as_object);
1823 self::entry_footer($doc, $entry, $item, $owner);
1829 * @brief Adds an entry element with a "like"
1831 * @param object $doc XML document
1832 * @param array $item Data of the item that is to be posted
1833 * @param array $owner Contact data of the poster
1834 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1836 * @return object Entry element with "like"
1838 private function like_entry($doc, $item, $owner, $toplevel) {
1840 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1841 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1844 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1846 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1847 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1849 $as_object = $doc->createElement("activity:object");
1851 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1852 dbesc($item["thr-parent"]), intval($item["uid"]));
1853 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1855 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1857 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1859 $entry->appendChild($as_object);
1861 self::entry_footer($doc, $entry, $item, $owner);
1867 * @brief Adds the person object element to the XML document
1869 * @param object $doc XML document
1870 * @param array $owner Contact data of the poster
1871 * @param array $contact Contact data of the target
1873 * @return object author element
1875 private function add_person_object($doc, $owner, $contact) {
1877 $object = $doc->createElement("activity:object");
1878 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1880 if ($contact['network'] == NETWORK_PHANTOM) {
1881 xml::add_element($doc, $object, "id", $contact['url']);
1885 xml::add_element($doc, $object, "id", $contact["alias"]);
1886 xml::add_element($doc, $object, "title", $contact["nick"]);
1888 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1889 xml::add_element($doc, $object, "link", "", $attributes);
1891 $attributes = array(
1893 "type" => "image/jpeg", // To-Do?
1894 "media:width" => 175,
1895 "media:height" => 175,
1896 "href" => $contact["photo"]);
1897 xml::add_element($doc, $object, "link", "", $attributes);
1899 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1900 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1902 if (trim($contact["location"]) != "") {
1903 $element = $doc->createElement("poco:address");
1904 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1905 $object->appendChild($element);
1912 * @brief Adds a follow/unfollow entry element
1914 * @param object $doc XML document
1915 * @param array $item Data of the follow/unfollow message
1916 * @param array $owner Contact data of the poster
1917 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1919 * @return object Entry element
1921 private function follow_entry($doc, $item, $owner, $toplevel) {
1923 $item["id"] = $item["parent"] = 0;
1924 $item["created"] = $item["edited"] = date("c");
1925 $item["private"] = true;
1927 $contact = Probe::uri($item['follow']);
1929 if ($contact['alias'] == '') {
1930 $contact['alias'] = $contact["url"];
1932 $item['follow'] = $contact['alias'];
1935 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1936 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1938 if (dbm::is_result($r)) {
1939 $connect_id = $r[0]['id'];
1944 if ($item['verb'] == ACTIVITY_FOLLOW) {
1945 $message = t('%s is now following %s.');
1946 $title = t('following');
1947 $action = "subscription";
1949 $message = t('%s stopped following %s.');
1950 $title = t('stopped following');
1951 $action = "unfollow";
1954 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1955 'tag:'.get_app()->get_hostname().
1956 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1957 ':person:'.$connect_id.':'.$item['created'];
1959 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1961 self::entry_header($doc, $entry, $owner, $toplevel);
1963 self::entry_content($doc, $entry, $item, $owner, $title);
1965 $object = self::add_person_object($doc, $owner, $contact);
1966 $entry->appendChild($object);
1968 self::entry_footer($doc, $entry, $item, $owner);
1974 * @brief Adds a regular entry element
1976 * @param object $doc XML document
1977 * @param array $item Data of the item that is to be posted
1978 * @param array $owner Contact data of the poster
1979 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1981 * @return object Entry element
1983 private function note_entry($doc, $item, $owner, $toplevel) {
1985 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1986 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1989 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1991 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1993 self::entry_content($doc, $entry, $item, $owner, $title);
1995 self::entry_footer($doc, $entry, $item, $owner);
2001 * @brief Adds a header element to the XML document
2003 * @param object $doc XML document
2004 * @param object $entry The entry element where the elements are added
2005 * @param array $owner Contact data of the poster
2006 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2008 * @return string The title for the element
2010 private function entry_header($doc, &$entry, $owner, $toplevel) {
2011 /// @todo Check if this title stuff is really needed (I guess not)
2013 $entry = $doc->createElement("entry");
2014 $title = sprintf("New note by %s", $owner["nick"]);
2016 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2018 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2019 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2020 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2021 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2022 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2023 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2024 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2025 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2027 $author = self::add_author($doc, $owner);
2028 $entry->appendChild($author);
2030 $title = sprintf("New comment by %s", $owner["nick"]);
2036 * @brief Adds elements to the XML document
2038 * @param object $doc XML document
2039 * @param object $entry Entry element where the content is added
2040 * @param array $item Data of the item that is to be posted
2041 * @param array $owner Contact data of the poster
2042 * @param string $title Title for the post
2043 * @param string $verb The activity verb
2044 * @param bool $complete Add the "status_net" element?
2046 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2049 $verb = self::construct_verb($item);
2051 xml::add_element($doc, $entry, "id", $item["uri"]);
2052 xml::add_element($doc, $entry, "title", $title);
2054 $body = self::format_picture_post($item['body']);
2056 if ($item['title'] != "")
2057 $body = "[b]".$item['title']."[/b]\n\n".$body;
2059 $body = bbcode($body, false, false, 7);
2061 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2063 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2064 "href" => App::get_baseurl()."/display/".$item["guid"]));
2066 if ($complete AND ($item["id"] > 0))
2067 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2069 xml::add_element($doc, $entry, "activity:verb", $verb);
2071 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2072 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2076 * @brief Adds the elements at the foot of an entry to the XML document
2078 * @param object $doc XML document
2079 * @param object $entry The entry element where the elements are added
2080 * @param array $item Data of the item that is to be posted
2081 * @param array $owner Contact data of the poster
2084 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2086 $mentioned = array();
2088 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2089 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2090 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2092 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2093 intval($owner["uid"]),
2094 dbesc($parent_item));
2096 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2097 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2098 $parent_plink = $thrparent[0]["plink"];
2100 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2101 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2102 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2105 $attributes = array(
2106 "ref" => $parent_item,
2107 "href" => $parent_plink);
2108 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2110 $attributes = array(
2112 "href" => $parent_plink);
2113 xml::add_element($doc, $entry, "link", "", $attributes);
2116 if (intval($item["parent"]) > 0) {
2117 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2118 $conversation_uri = $conversation_href;
2120 if (isset($parent_item)) {
2121 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2122 if (dbm::is_result($r)) {
2123 if ($r['conversation-uri'] != '') {
2124 $conversation_uri = $r['conversation-uri'];
2126 if ($r['conversation-href'] != '') {
2127 $conversation_href = $r['conversation-href'];
2132 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2134 $attributes = array(
2135 "href" => $conversation_href,
2136 "local_id" => $item["parent"],
2137 "ref" => $conversation_uri);
2139 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2142 $tags = item_getfeedtags($item);
2145 foreach($tags as $t)
2147 $mentioned[$t[1]] = $t[1];
2149 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2150 $newmentions = array();
2151 foreach ($mentioned AS $mention) {
2152 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2153 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2155 $mentioned = $newmentions;
2157 foreach ($mentioned AS $mention) {
2158 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2159 intval($owner["uid"]),
2160 dbesc(normalise_link($mention)));
2161 if ($r[0]["forum"] OR $r[0]["prv"])
2162 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2163 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2164 "href" => $mention));
2166 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2167 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2168 "href" => $mention));
2171 if (!$item["private"]) {
2172 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2173 "href" => "http://activityschema.org/collection/public"));
2174 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2175 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2176 "href" => "http://activityschema.org/collection/public"));
2177 xml::add_element($doc, $entry, "mastodon:scope", "public");
2181 foreach($tags as $t)
2183 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2185 self::get_attachment($doc, $entry, $item);
2187 if ($complete AND ($item["id"] > 0)) {
2188 $app = $item["app"];
2192 $attributes = array("local_id" => $item["id"], "source" => $app);
2194 if (isset($parent["id"]))
2195 $attributes["repeat_of"] = $parent["id"];
2197 if ($item["coord"] != "")
2198 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2200 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2205 * @brief Creates the XML feed for a given nickname
2207 * @param app $a The application class
2208 * @param string $owner_nick Nickname of the feed owner
2209 * @param string $last_update Date of the last update
2211 * @return string XML feed
2213 public static function feed(App $a, $owner_nick, $last_update) {
2215 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2216 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2217 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2218 dbesc($owner_nick));
2224 if(!strlen($last_update))
2225 $last_update = 'now -30 days';
2227 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2228 $authorid = get_contact($owner["url"], 0);
2230 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2231 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2232 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2233 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2234 NOT `item`.`deleted` AND NOT `item`.`private` AND
2235 `thread`.`network` IN ('%s', '%s')
2236 ORDER BY `item`.`created` DESC LIMIT 300",
2237 intval($owner["uid"]), intval($owner["id"]),
2238 intval($authorid), dbesc($check_date),
2239 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2241 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2243 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2244 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2245 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2246 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2247 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2248 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2249 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2250 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2251 OR (`item`.`author-link` IN ('%s', '%s')))
2252 ORDER BY `item`.`id` DESC
2254 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2255 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2256 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2257 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2258 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2259 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2260 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2263 $doc = new DOMDocument('1.0', 'utf-8');
2264 $doc->formatOutput = true;
2266 $root = self::add_header($doc, $owner);
2268 foreach ($items AS $item) {
2269 $entry = self::entry($doc, $item, $owner);
2270 $root->appendChild($entry);
2273 return(trim($doc->saveXML()));
2277 * @brief Creates the XML for a salmon message
2279 * @param array $item Data of the item that is to be posted
2280 * @param array $owner Contact data of the poster
2282 * @return string XML for the salmon
2284 public static function salmon($item,$owner) {
2286 $doc = new DOMDocument('1.0', 'utf-8');
2287 $doc->formatOutput = true;
2289 $entry = self::entry($doc, $item, $owner, true);
2291 $doc->appendChild($entry);
2293 return(trim($doc->saveXML()));