3 * @file include/ostatus.php
8 require_once("include/Contact.php");
9 require_once("include/threads.php");
10 require_once("include/html2bbcode.php");
11 require_once("include/bbcode.php");
12 require_once("include/items.php");
13 require_once("mod/share.php");
14 require_once("include/enotify.php");
15 require_once("include/socgraph.php");
16 require_once("include/Photo.php");
17 require_once("include/Scrape.php");
18 require_once("include/follow.php");
19 require_once("include/api.php");
20 require_once("mod/proxy.php");
21 require_once("include/xml.php");
24 * @brief This class contain functions for the OStatus protocol
28 const OSTATUS_DEFAULT_POLL_INTERVAL = 30; // given in minutes
29 const OSTATUS_DEFAULT_POLL_TIMEFRAME = 1440; // given in minutes
30 const OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS = 14400; // given in minutes
33 * @brief Mix two paths together to possibly fix missing parts
35 * @param string $avatar Path to the avatar
36 * @param string $base Another path that is hopefully complete
38 * @return string fixed avatar path
40 public static function fix_avatar($avatar, $base) {
41 $base_parts = parse_url($base);
43 // Remove all parts that could create a problem
44 unset($base_parts['path']);
45 unset($base_parts['query']);
46 unset($base_parts['fragment']);
48 $avatar_parts = parse_url($avatar);
51 $parts = array_merge($base_parts, $avatar_parts);
53 // And put them together again
54 $scheme = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
55 $host = isset($parts['host']) ? $parts['host'] : '';
56 $port = isset($parts['port']) ? ':' . $parts['port'] : '';
57 $path = isset($parts['path']) ? $parts['path'] : '';
58 $query = isset($parts['query']) ? '?' . $parts['query'] : '';
59 $fragment = isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
61 $fixed = $scheme.$host.$port.$path.$query.$fragment;
63 logger('Base: '.$base.' - Avatar: '.$avatar.' - Fixed: '.$fixed, LOGGER_DATA);
69 * @brief Fetches author data
71 * @param object $xpath The xpath object
72 * @param object $context The xml context of the author detals
73 * @param array $importer user record of the importing user
74 * @param array $contact Called by reference, will contain the fetched contact
75 * @param bool $onlyfetch Only fetch the header without updating the contact entries
77 * @return array Array of author related entries for the item
79 private function fetchauthor($xpath, $context, $importer, &$contact, $onlyfetch) {
82 $author["author-link"] = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
83 $author["author-name"] = $xpath->evaluate('atom:author/atom:name/text()', $context)->item(0)->nodeValue;
85 $aliaslink = $author["author-link"];
87 $alternate = $xpath->query("atom:author/atom:link[@rel='alternate']", $context)->item(0)->attributes;
88 if (is_object($alternate))
89 foreach($alternate AS $attributes)
90 if ($attributes->name == "href")
91 $author["author-link"] = $attributes->textContent;
93 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `nurl` IN ('%s', '%s') AND `network` != '%s'",
94 intval($importer["uid"]), dbesc(normalise_link($author["author-link"])),
95 dbesc(normalise_link($aliaslink)), dbesc(NETWORK_STATUSNET));
98 $author["contact-id"] = $r[0]["id"];
100 $author["contact-id"] = $contact["id"];
102 $avatarlist = array();
103 $avatars = $xpath->query("atom:author/atom:link[@rel='avatar']", $context);
104 foreach($avatars AS $avatar) {
107 foreach($avatar->attributes AS $attributes) {
108 if ($attributes->name == "href")
109 $href = $attributes->textContent;
110 if ($attributes->name == "width")
111 $width = $attributes->textContent;
113 if (($width > 0) AND ($href != ""))
114 $avatarlist[$width] = $href;
116 if (count($avatarlist) > 0) {
118 $author["author-avatar"] = self::fix_avatar(current($avatarlist), $author["author-link"]);
121 $displayname = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
122 if ($displayname != "")
123 $author["author-name"] = $displayname;
125 $author["owner-name"] = $author["author-name"];
126 $author["owner-link"] = $author["author-link"];
127 $author["owner-avatar"] = $author["author-avatar"];
129 // Only update the contacts if it is an OStatus contact
130 if ($r AND !$onlyfetch AND ($contact["network"] == NETWORK_OSTATUS)) {
132 // Update contact data
134 // This query doesn't seem to work
135 // $value = $xpath->query("atom:link[@rel='salmon']", $context)->item(0)->nodeValue;
137 // $contact["notify"] = $value;
139 // This query doesn't seem to work as well - I hate these queries
140 // $value = $xpath->query("atom:link[@rel='self' and @type='application/atom+xml']", $context)->item(0)->nodeValue;
142 // $contact["poll"] = $value;
144 $value = $xpath->evaluate('atom:author/atom:uri/text()', $context)->item(0)->nodeValue;
146 $contact["alias"] = $value;
148 $value = $xpath->evaluate('atom:author/poco:displayName/text()', $context)->item(0)->nodeValue;
150 $contact["name"] = $value;
152 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
154 $contact["nick"] = $value;
156 $value = $xpath->evaluate('atom:author/poco:note/text()', $context)->item(0)->nodeValue;
158 $contact["about"] = html2bbcode($value);
160 $value = $xpath->evaluate('atom:author/poco:address/poco:formatted/text()', $context)->item(0)->nodeValue;
162 $contact["location"] = $value;
164 if (($contact["name"] != $r[0]["name"]) OR ($contact["nick"] != $r[0]["nick"]) OR ($contact["about"] != $r[0]["about"]) OR
165 ($contact["alias"] != $r[0]["alias"]) OR ($contact["location"] != $r[0]["location"])) {
167 logger("Update contact data for contact ".$contact["id"], LOGGER_DEBUG);
169 q("UPDATE `contact` SET `name` = '%s', `nick` = '%s', `alias` = '%s', `about` = '%s', `location` = '%s', `name-date` = '%s' WHERE `id` = %d",
170 dbesc($contact["name"]), dbesc($contact["nick"]), dbesc($contact["alias"]),
171 dbesc($contact["about"]), dbesc($contact["location"]),
172 dbesc(datetime_convert()), intval($contact["id"]));
175 if (isset($author["author-avatar"]) AND ($author["author-avatar"] != $r[0]['avatar'])) {
176 logger("Update profile picture for contact ".$contact["id"], LOGGER_DEBUG);
178 update_contact_avatar($author["author-avatar"], $importer["uid"], $contact["id"]);
181 // Ensure that we are having this contact (with uid=0)
182 $cid = get_contact($author["author-link"], 0);
185 // Update it with the current values
186 q("UPDATE `contact` SET `url` = '%s', `name` = '%s', `nick` = '%s', `alias` = '%s',
187 `about` = '%s', `location` = '%s',
188 `success_update` = '%s', `last-update` = '%s'
190 dbesc($author["author-link"]), dbesc($contact["name"]), dbesc($contact["nick"]),
191 dbesc($contact["alias"]), dbesc($contact["about"]), dbesc($contact["location"]),
192 dbesc(datetime_convert()), dbesc(datetime_convert()), intval($cid));
195 update_contact_avatar($author["author-avatar"], 0, $cid);
198 $contact["generation"] = 2;
199 $contact["hide"] = false; // OStatus contacts are never hidden
200 $contact["photo"] = $author["author-avatar"];
201 $gcid = update_gcontact($contact);
203 link_gcontact($gcid, $contact["uid"], $contact["id"]);
210 * @brief Fetches author data from a given XML string
212 * @param string $xml The XML
213 * @param array $importer user record of the importing user
215 * @return array Array of author related entries for the item
217 public static function salmon_author($xml, $importer) {
222 $doc = new DOMDocument();
223 @$doc->loadXML($xml);
225 $xpath = new DomXPath($doc);
226 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
227 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
228 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
229 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
230 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
231 $xpath->registerNamespace('poco', NAMESPACE_POCO);
232 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
233 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
235 $entries = $xpath->query('/atom:entry');
237 foreach ($entries AS $entry) {
239 $author = self::fetchauthor($xpath, $entry, $importer, $contact, true);
245 * @brief Read attributes from element
247 * @param object $element Element object
249 * @return array attributes
251 private static function read_attributes($element) {
252 $attribute = array();
254 foreach ($element->attributes AS $attributes) {
255 $attribute[$attributes->name] = $attributes->textContent;
262 * @brief Imports an XML string containing OStatus elements
264 * @param string $xml The XML
265 * @param array $importer user record of the importing user
267 * @param array $hub Called by reference, returns the fetched hub data
269 public static function import($xml,$importer,&$contact, &$hub) {
270 /// @todo this function is too long. It has to be split in many parts
272 logger("Import OStatus message", LOGGER_DEBUG);
277 //$tempfile = tempnam(get_temppath(), "import");
278 //file_put_contents($tempfile, $xml);
280 $doc = new DOMDocument();
281 @$doc->loadXML($xml);
283 $xpath = new DomXPath($doc);
284 $xpath->registerNamespace('atom', NAMESPACE_ATOM1);
285 $xpath->registerNamespace('thr', NAMESPACE_THREAD);
286 $xpath->registerNamespace('georss', NAMESPACE_GEORSS);
287 $xpath->registerNamespace('activity', NAMESPACE_ACTIVITY);
288 $xpath->registerNamespace('media', NAMESPACE_MEDIA);
289 $xpath->registerNamespace('poco', NAMESPACE_POCO);
290 $xpath->registerNamespace('ostatus', NAMESPACE_OSTATUS);
291 $xpath->registerNamespace('statusnet', NAMESPACE_STATUSNET);
294 $hub_attributes = $xpath->query("/atom:feed/atom:link[@rel='hub']")->item(0)->attributes;
295 if (is_object($hub_attributes)) {
296 foreach ($hub_attributes AS $hub_attribute) {
297 if ($hub_attribute->name == "href") {
298 $hub = $hub_attribute->textContent;
299 logger("Found hub ".$hub, LOGGER_DEBUG);
304 $header["uid"] = $importer["uid"];
305 $header["network"] = NETWORK_OSTATUS;
306 $header["type"] = "remote";
308 $header["origin"] = 0;
309 $header["gravity"] = GRAVITY_PARENT;
311 // it could either be a received post or a post we fetched by ourselves
312 // depending on that, the first node is different
313 $first_child = $doc->firstChild->tagName;
315 if ($first_child == "feed") {
316 $entries = $xpath->query('/atom:feed/atom:entry');
317 $header["protocol"] = PROTOCOL_OSTATUS_FEED;
319 $entries = $xpath->query('/atom:entry');
320 $header["protocol"] = PROTOCOL_OSTATUS_SALMON;
323 $conversationlist = array();
326 // Reverse the order of the entries
327 $entrylist = array();
329 foreach ($entries AS $entry) {
330 $entrylist[] = $entry;
332 foreach (array_reverse($entrylist) AS $entry) {
337 if ($first_child == "feed") {
338 $author = self::fetchauthor($xpath, $doc->firstChild, $importer, $contact, false);
340 $author = self::fetchauthor($xpath, $entry, $importer, $contact, false);
342 $value = $xpath->evaluate('atom:author/poco:preferredUsername/text()', $context)->item(0)->nodeValue;
346 $nickname = $author["author-name"];
348 $item = array_merge($header, $author);
351 $item["uri"] = $xpath->query('atom:id/text()', $entry)->item(0)->nodeValue;
353 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
354 intval($importer["uid"]), dbesc($item["uri"]));
355 if (dbm::is_result($r)) {
356 logger("Item with uri ".$item["uri"]." for user ".$importer["uid"]." already existed under id ".$r[0]["id"], LOGGER_DEBUG);
360 $item["body"] = add_page_info_to_body(html2bbcode($xpath->query('atom:content/text()', $entry)->item(0)->nodeValue));
361 $item["object-type"] = $xpath->query('activity:object-type/text()', $entry)->item(0)->nodeValue;
362 $item["verb"] = $xpath->query('activity:verb/text()', $entry)->item(0)->nodeValue;
364 // Mastodon Content Warning
365 if (($item["verb"] == ACTIVITY_POST) AND $xpath->evaluate('boolean(atom:summary)', $entry)) {
366 $clear_text = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
368 $item["body"] = html2bbcode($clear_text) . '[spoiler]' . $item["body"] . '[/spoiler]';
371 if (($item["object-type"] == ACTIVITY_OBJ_BOOKMARK) OR ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
372 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
373 $item["body"] = $xpath->query('atom:summary/text()', $entry)->item(0)->nodeValue;
374 } elseif ($item["object-type"] == ACTIVITY_OBJ_QUESTION) {
375 $item["title"] = $xpath->query('atom:title/text()', $entry)->item(0)->nodeValue;
377 $item["source"] = $xml;
381 if ($item["verb"] == "qvitter-delete-notice" || $item["verb"] == ACTIVITY_DELETE) {
382 // ignore "Delete" messages (by now)
383 logger("Ignore delete message ".print_r($item, true));
387 if ($item["verb"] == ACTIVITY_JOIN) {
388 // ignore "Join" messages
389 logger("Ignore join message ".print_r($item, true));
393 if ($item["verb"] == ACTIVITY_FOLLOW) {
394 new_follower($importer, $contact, $item, $nickname);
398 if ($item["verb"] == NAMESPACE_OSTATUS."/unfollow") {
399 lose_follower($importer, $contact, $item, $dummy);
403 if ($item["verb"] == ACTIVITY_FAVORITE) {
404 $orig_uri = $xpath->query("activity:object/atom:id", $entry)->item(0)->nodeValue;
405 logger("Favorite ".$orig_uri." ".print_r($item, true));
407 $item["verb"] = ACTIVITY_LIKE;
408 $item["parent-uri"] = $orig_uri;
409 $item["gravity"] = GRAVITY_LIKE;
412 if ($item["verb"] == NAMESPACE_OSTATUS."/unfavorite") {
413 // Ignore "Unfavorite" message
414 logger("Ignore unfavorite message ".print_r($item, true));
418 // http://activitystrea.ms/schema/1.0/rsvp-yes
419 if (!in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_LIKE, ACTIVITY_SHARE))) {
420 logger("Unhandled verb ".$item["verb"]." ".print_r($item, true));
422 $item["created"] = $xpath->query('atom:published/text()', $entry)->item(0)->nodeValue;
423 $item["edited"] = $xpath->query('atom:updated/text()', $entry)->item(0)->nodeValue;
424 $conversation = $xpath->query('ostatus:conversation/text()', $entry)->item(0)->nodeValue;
425 $item['conversation-uri'] = $conversation;
427 $conv = $xpath->query('ostatus:conversation', $entry);
428 if (is_object($conv->item(0))) {
429 foreach ($conv->item(0)->attributes AS $attributes) {
430 if ($attributes->name == "ref") {
431 $item['conversation-uri'] = $attributes->textContent;
433 if ($attributes->name == "href") {
434 $item['conversation-href'] = $attributes->textContent;
441 $inreplyto = $xpath->query('thr:in-reply-to', $entry);
442 if (is_object($inreplyto->item(0))) {
443 foreach ($inreplyto->item(0)->attributes AS $attributes) {
444 if ($attributes->name == "ref") {
445 $item["parent-uri"] = $attributes->textContent;
447 if ($attributes->name == "href") {
448 $related = $attributes->textContent;
453 $georsspoint = $xpath->query('georss:point', $entry);
455 $item["coord"] = $georsspoint->item(0)->nodeValue;
457 $categories = $xpath->query('atom:category', $entry);
459 foreach ($categories AS $category) {
460 foreach ($category->attributes AS $attributes) {
461 if ($attributes->name == "term") {
462 $term = $attributes->textContent;
463 if(strlen($item["tag"])) {
466 $item["tag"] .= "#[url=".App::get_baseurl()."/search?tag=".$term."]".$term."[/url]";
475 $links = $xpath->query('atom:link', $entry);
477 foreach ($links AS $link) {
478 $attribute = self::read_attributes($link);
480 if (($attribute['rel'] != "") AND ($attribute['href'] != "")) {
481 switch ($attribute['rel']) {
483 $item["plink"] = $attribute['href'];
484 if (($item["object-type"] == ACTIVITY_OBJ_QUESTION) OR
485 ($item["object-type"] == ACTIVITY_OBJ_EVENT)) {
486 $item["body"] .= add_page_info($attribute['href']);
489 case "ostatus:conversation":
490 $conversation = $attribute['href'];
491 $item['conversation-href'] = $conversation;
492 if (!isset($item['conversation-uri'])) {
493 $item['conversation-uri'] = $item['conversation-href'];
497 $enclosure = $attribute['href'];
498 if (strlen($item["attach"])) {
499 $item["attach"] .= ',';
501 if (!isset($attribute['length'])) {
502 $attribute['length'] = "0";
504 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
507 if ($item["object-type"] != ACTIVITY_OBJ_BOOKMARK) {
508 if (!isset($item["parent-uri"])) {
509 $item["parent-uri"] = $attribute['href'];
511 if ($related == "") {
512 $related = $attribute['href'];
515 $item["body"] .= add_page_info($attribute['href']);
519 $self = $attribute['href'];
522 // Notification check
523 if ($importer["nurl"] == normalise_link($attribute['href'])) {
535 $notice_info = $xpath->query('statusnet:notice_info', $entry);
536 if ($notice_info AND ($notice_info->length > 0)) {
537 foreach ($notice_info->item(0)->attributes AS $attributes) {
538 if ($attributes->name == "source") {
539 $item["app"] = strip_tags($attributes->textContent);
541 if ($attributes->name == "local_id") {
542 $local_id = $attributes->textContent;
544 if ($attributes->name == "repeat_of") {
545 $repeat_of = $attributes->textContent;
550 // Is it a repeated post?
551 if (($repeat_of != "") OR ($item["verb"] == ACTIVITY_SHARE)) {
552 $activityobjects = $xpath->query('activity:object', $entry)->item(0);
554 if (is_object($activityobjects)) {
556 $orig_uri = $xpath->query("activity:object/atom:id", $activityobjects)->item(0)->nodeValue;
557 if (!isset($orig_uri)) {
558 $orig_uri = $xpath->query('atom:id/text()', $activityobjects)->item(0)->nodeValue;
560 $orig_links = $xpath->query("activity:object/atom:link[@rel='alternate']", $activityobjects);
561 if ($orig_links AND ($orig_links->length > 0)) {
562 foreach ($orig_links->item(0)->attributes AS $attributes) {
563 if ($attributes->name == "href") {
564 $orig_link = $attributes->textContent;
568 if (!isset($orig_link)) {
569 $orig_link = $xpath->query("atom:link[@rel='alternate']", $activityobjects)->item(0)->nodeValue;
571 if (!isset($orig_link)) {
572 $orig_link = self::convert_href($orig_uri);
574 $orig_body = $xpath->query('activity:object/atom:content/text()', $activityobjects)->item(0)->nodeValue;
575 if (!isset($orig_body)) {
576 $orig_body = $xpath->query('atom:content/text()', $activityobjects)->item(0)->nodeValue;
578 $orig_created = $xpath->query('atom:published/text()', $activityobjects)->item(0)->nodeValue;
579 $orig_edited = $xpath->query('atom:updated/text()', $activityobjects)->item(0)->nodeValue;
581 $orig_contact = $contact;
582 $orig_author = self::fetchauthor($xpath, $activityobjects, $importer, $orig_contact, false);
584 $item["author-name"] = $orig_author["author-name"];
585 $item["author-link"] = $orig_author["author-link"];
586 $item["author-avatar"] = $orig_author["author-avatar"];
588 $item["body"] = add_page_info_to_body(html2bbcode($orig_body));
589 $item["created"] = $orig_created;
590 $item["edited"] = $orig_edited;
592 $item["uri"] = $orig_uri;
594 if (!isset($item["plink"])) {
595 $item["plink"] = $orig_link;
598 $item["verb"] = $xpath->query('activity:verb/text()', $activityobjects)->item(0)->nodeValue;
600 $item["object-type"] = $xpath->query('activity:object/activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
601 if (!isset($item["object-type"])) {
602 $item["object-type"] = $xpath->query('activity:object-type/text()', $activityobjects)->item(0)->nodeValue;
605 $enclosures = $xpath->query("atom:link[@rel='alternate']", $activityobjects);
607 foreach ($enclosures AS $link) {
608 $attribute = self::read_attributes($link);
610 $enclosure = $attribute['href'];
611 if (strlen($item["attach"])) {
612 $item["attach"] .= ',';
614 if (!isset($attribute['length'])) {
615 $attribute['length'] = "0";
617 $item["attach"] .= '[attach]href="'.$attribute['href'].'" length="'.$attribute['length'].'" type="'.$attribute['type'].'" title="'.$attribute['title'].'"[/attach]';
624 //if ($enclosure != "")
625 // $item["body"] .= add_page_info($enclosure);
627 if (isset($item["parent-uri"])) {
628 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
629 intval($importer["uid"]), dbesc($item["parent-uri"]));
631 // Only fetch missing stuff if it is a comment or reshare.
632 if (in_array($item["verb"], array(ACTIVITY_POST, ACTIVITY_SHARE)) AND
633 !dbm::is_result($r) AND ($related != "")) {
634 $reply_path = str_replace("/notice/", "/api/statuses/show/", $related).".atom";
636 if ($reply_path != $related) {
637 logger("Fetching related items for user ".$importer["uid"]." from ".$reply_path, LOGGER_DEBUG);
638 $reply_xml = fetch_url($reply_path);
640 $reply_contact = $contact;
641 self::import($reply_xml,$importer,$reply_contact, $reply_hub);
643 // After the import try to fetch the parent item again
644 $r = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
645 intval($importer["uid"]), dbesc($item["parent-uri"]));
648 if (dbm::is_result($r)) {
649 $item["type"] = 'remote-comment';
650 $item["gravity"] = GRAVITY_COMMENT;
653 $item["parent-uri"] = $item["uri"];
655 $item_id = self::completion($conversation, $importer["uid"], $item, $self);
658 logger("Error storing item", LOGGER_DEBUG);
662 logger("Item was stored with id ".$item_id, LOGGER_DEBUG);
667 * @brief Create an url out of an uri
669 * @param string $href URI in the format "parameter1:parameter1:..."
671 * @return string URL in the format http(s)://....
673 public static function convert_href($href) {
674 $elements = explode(":",$href);
676 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
679 $server = explode(",", $elements[1]);
680 $conversation = explode("=", $elements[2]);
682 if ((count($elements) == 4) AND ($elements[2] == "post"))
683 return "http://".$server[0]."/notice/".$elements[3];
685 if ((count($conversation) != 2) OR ($conversation[1] ==""))
688 if ($elements[3] == "objectType=thread")
689 return "http://".$server[0]."/conversation/".$conversation[1];
691 return "http://".$server[0]."/notice/".$conversation[1];
697 * @brief Checks if there are entries in conversations that aren't present on our side
699 * @param bool $mentions Fetch conversations where we are mentioned
700 * @param bool $override Override the interval setting
702 public static function check_conversations($mentions = false, $override = false) {
703 $last = get_config('system','ostatus_last_poll');
705 $poll_interval = intval(get_config('system','ostatus_poll_interval'));
706 if (!$poll_interval) {
707 $poll_interval = self::OSTATUS_DEFAULT_POLL_INTERVAL;
710 // Don't poll if the interval is set negative
711 if (($poll_interval < 0) AND !$override) {
716 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
717 if (!$poll_timeframe) {
718 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME;
721 $poll_timeframe = intval(get_config('system','ostatus_poll_timeframe'));
722 if (!$poll_timeframe) {
723 $poll_timeframe = self::OSTATUS_DEFAULT_POLL_TIMEFRAME_MENTIONS;
728 if ($last AND !$override) {
729 $next = $last + ($poll_interval * 60);
730 if ($next > time()) {
731 logger('poll interval not reached');
736 logger('cron_start');
738 $start = date("Y-m-d H:i:s", time() - ($poll_timeframe * 60));
741 $conversations = q("SELECT `term`.`oid`, `term`.`url`, `term`.`uid` FROM `term`
742 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `term`.`oid` AND `thread`.`uid` = `term`.`uid`
743 WHERE `term`.`type` = 7 AND `term`.`term` > '%s' AND `thread`.`mention`
744 GROUP BY `term`.`url`, `term`.`uid`, `term`.`oid`, `term`.`term` ORDER BY `term`.`term` DESC", dbesc($start));
746 $conversations = q("SELECT `oid`, `url`, `uid` FROM `term`
747 WHERE `type` = 7 AND `term` > '%s'
748 GROUP BY `url`, `uid`, `oid`, `term` ORDER BY `term` DESC", dbesc($start));
751 foreach ($conversations AS $conversation) {
752 self::completion($conversation['url'], $conversation['uid']);
757 set_config('system','ostatus_last_poll', time());
761 * @brief Updates the gcontact table with actor data from the conversation
763 * @param object $actor The actor object that contains the contact data
765 private function conv_fetch_actor($actor) {
767 // We set the generation to "3" since the data here is not as reliable as the data we get on other occasions
768 $contact = array("network" => NETWORK_OSTATUS, "generation" => 3);
770 if (isset($actor->url))
771 $contact["url"] = $actor->url;
773 if (isset($actor->displayName))
774 $contact["name"] = $actor->displayName;
776 if (isset($actor->portablecontacts_net->displayName))
777 $contact["name"] = $actor->portablecontacts_net->displayName;
779 if (isset($actor->portablecontacts_net->preferredUsername))
780 $contact["nick"] = $actor->portablecontacts_net->preferredUsername;
782 if (isset($actor->id))
783 $contact["alias"] = $actor->id;
785 if (isset($actor->summary))
786 $contact["about"] = $actor->summary;
788 if (isset($actor->portablecontacts_net->note))
789 $contact["about"] = $actor->portablecontacts_net->note;
791 if (isset($actor->portablecontacts_net->addresses->formatted))
792 $contact["location"] = $actor->portablecontacts_net->addresses->formatted;
795 if (isset($actor->image->url))
796 $contact["photo"] = $actor->image->url;
798 if (isset($actor->image->width))
799 $avatarwidth = $actor->image->width;
801 if (is_array($actor->status_net->avatarLinks))
802 foreach ($actor->status_net->avatarLinks AS $avatar) {
803 if ($avatarsize < $avatar->width) {
804 $contact["photo"] = $avatar->url;
805 $avatarsize = $avatar->width;
809 $contact["hide"] = false; // OStatus contacts are never hidden
810 update_gcontact($contact);
814 * @brief Fetches the conversation url for a given item link or conversation id
816 * @param string $self The link to the posting
817 * @param string $conversation_id The conversation id
819 * @return string The conversation url
821 private function fetch_conversation($self, $conversation_id = "") {
823 if ($conversation_id != "") {
824 $elements = explode(":", $conversation_id);
826 if ((count($elements) <= 2) OR ($elements[0] != "tag"))
827 return $conversation_id;
833 $json = str_replace(".atom", ".json", $self);
835 $raw = fetch_url($json);
839 $data = json_decode($raw);
840 if (!is_object($data))
843 $conversation_id = $data->statusnet_conversation_id;
845 $pos = strpos($self, "/api/statuses/show/");
846 $base_url = substr($self, 0, $pos);
848 return $base_url."/conversation/".$conversation_id;
852 * @brief Fetches actor details of a given actor and user id
854 * @param string $actor The actor url
855 * @param int $uid The user id
856 * @param int $contact_id The default contact-id
858 * @return array Array with actor details
860 private function get_actor_details($actor, $uid, $contact_id) {
864 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s' AND `network` != '%s'",
865 $uid, normalise_link($actor), NETWORK_STATUSNET);
868 $contact = q("SELECT `id`, `rel`, `network` FROM `contact` WHERE `uid` = %d AND `alias` IN ('%s', '%s') AND `network` != '%s'",
869 $uid, $actor, normalise_link($actor), NETWORK_STATUSNET);
872 logger("Found contact for url ".$actor, LOGGER_DEBUG);
873 $details["contact_id"] = $contact[0]["id"];
874 $details["network"] = $contact[0]["network"];
876 $details["not_following"] = !in_array($contact[0]["rel"], array(CONTACT_IS_SHARING, CONTACT_IS_FRIEND));
878 logger("No contact found for user ".$uid." and url ".$actor, LOGGER_DEBUG);
880 // Adding a global contact
881 /// @TODO Use this data for the post
882 $details["global_contact_id"] = get_contact($actor, 0);
884 logger("Global contact ".$global_contact_id." found for url ".$actor, LOGGER_DEBUG);
886 $details["contact_id"] = $contact_id;
887 $details["network"] = NETWORK_OSTATUS;
889 $details["not_following"] = true;
896 * @brief Stores an item and completes the thread
898 * @param string $conversation_url The URI of the conversation
899 * @param integer $uid The user id
900 * @param array $item Data of the item that is to be posted
902 * @return integer The item id of the posted item array
904 private function completion($conversation_url, $uid, $item = array(), $self = "") {
906 /// @todo This function is totally ugly and has to be rewritten totally
908 // Import all threads or only threads that were started by our followers?
909 $all_threads = !get_config('system','ostatus_full_threads');
913 $conversation_url = self::fetch_conversation($self, $conversation_url);
915 // If the thread shouldn't be completed then store the item and go away
916 // Don't do a completion on liked content
917 if (((intval(get_config('system','ostatus_poll_interval')) == -2) AND (count($item) > 0)) OR
918 ($item["verb"] == ACTIVITY_LIKE) OR ($conversation_url == "")) {
919 $item_stored = item_store($item, $all_threads);
921 } elseif (count($item) > 0) {
922 $item = store_conversation($item);
926 $parents = q("SELECT `item`.`id`, `item`.`parent`, `item`.`uri`, `item`.`contact-id`, `item`.`type`,
927 `item`.`verb`, `item`.`visible` FROM `term`
928 STRAIGHT_JOIN `item` AS `thritem` ON `thritem`.`parent` = `term`.`oid`
929 STRAIGHT_JOIN `item` ON `item`.`parent` = `thritem`.`parent`
930 WHERE `term`.`uid` = %d AND `term`.`otype` = %d AND `term`.`type` = %d AND `term`.`url` = '%s'",
931 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
933 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
935 $parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
936 (SELECT `parent` FROM `item` WHERE `id` IN
937 (SELECT `oid` FROM `term` WHERE `uid` = %d AND `otype` = %d AND `type` = %d AND `url` = '%s'))",
938 intval($uid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION), dbesc($conversation_url));
941 $parent = $parents[0];
942 elseif (count($item) > 0) {
944 $parent["type"] = "remote";
945 $parent["verb"] = ACTIVITY_POST;
946 $parent["visible"] = 1;
949 $r = q("SELECT `id` FROM `contact` WHERE `self` AND `uid`=%d", $uid);
955 $parent["parent"] = 0;
957 $parent["contact-id"] = $r[0]["id"];
958 $parent["type"] = "remote";
959 $parent["verb"] = ACTIVITY_POST;
960 $parent["visible"] = 1;
963 $conv = str_replace("/conversation/", "/api/statusnet/conversation/", $conversation_url).".as";
967 logger('fetching conversation url '.$conv.' (Self: '.$self.') for user '.$uid);
970 $conv_arr = z_fetch_url($conv."?page=".$pageno);
972 // If it is a non-ssl site and there is an error, then try ssl or vice versa
973 if (!$conv_arr["success"] AND (substr($conv, 0, 7) == "http://")) {
974 $conv = str_replace("http://", "https://", $conv);
975 $conv_as = fetch_url($conv."?page=".$pageno);
976 } elseif (!$conv_arr["success"] AND (substr($conv, 0, 8) == "https://")) {
977 $conv = str_replace("https://", "http://", $conv);
978 $conv_as = fetch_url($conv."?page=".$pageno);
980 $conv_as = $conv_arr["body"];
982 $conv_as = str_replace(',"statusnet:notice_info":', ',"statusnet_notice_info":', $conv_as);
983 $conv_as = json_decode($conv_as);
985 $no_of_items = sizeof($items);
987 if (@is_array($conv_as->items))
988 foreach ($conv_as->items AS $single_item)
989 $items[$single_item->id] = $single_item;
991 if ($no_of_items == sizeof($items))
998 logger('fetching conversation done. Found '.count($items).' items');
1000 if (!sizeof($items)) {
1001 if (count($item) > 0) {
1002 $item_stored = item_store($item, $all_threads);
1005 logger("Conversation ".$conversation_url." couldn't be fetched. Item uri ".$item["uri"]." stored: ".$item_stored, LOGGER_DEBUG);
1006 self::store_conversation($item_id, $conversation_url);
1009 return($item_stored);
1014 $items = array_reverse($items);
1016 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self`", intval($uid));
1021 foreach ($items as $single_conv) {
1023 // Update the gcontact table
1024 self::conv_fetch_actor($single_conv->actor);
1026 // Test - remove before flight
1027 //$tempfile = tempnam(get_temppath(), "conversation");
1028 //file_put_contents($tempfile, json_encode($single_conv));
1032 if (isset($single_conv->object->id))
1033 $single_conv->id = $single_conv->object->id;
1035 $plink = self::convert_href($single_conv->id);
1036 if (isset($single_conv->object->url))
1037 $plink = self::convert_href($single_conv->object->url);
1039 if (@!$single_conv->id)
1042 logger("Got id ".$single_conv->id, LOGGER_DEBUG);
1044 if ($first_id == "") {
1045 $first_id = $single_conv->id;
1047 // The first post of the conversation isn't our first post. There are three options:
1048 // 1. Our conversation hasn't the "real" thread starter
1049 // 2. This first post is a post inside our thread
1050 // 3. This first post is a post inside another thread
1051 if (($first_id != $parent["uri"]) AND ($parent["uri"] != "")) {
1055 $new_parents = q("SELECT `id`, `parent`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `id` IN
1056 (SELECT `parent` FROM `item`
1057 WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s')) LIMIT 1",
1058 intval($uid), dbesc($first_id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1060 if ($new_parents[0]["parent"] == $parent["parent"]) {
1061 // Option 2: This post is already present inside our thread - but not as thread starter
1062 logger("Option 2: uri present in our thread: ".$first_id, LOGGER_DEBUG);
1063 $first_id = $parent["uri"];
1065 // Option 3: Not so good. We have mixed parents. We have to see how to clean this up.
1066 // For now just take the new parent.
1067 $parent = $new_parents[0];
1068 $first_id = $parent["uri"];
1069 logger("Option 3: mixed parents for uri ".$first_id, LOGGER_DEBUG);
1072 // Option 1: We hadn't got the real thread starter
1073 // We have to clean up our existing messages.
1075 $parent["uri"] = $first_id;
1076 logger("Option 1: we have a new parent: ".$first_id, LOGGER_DEBUG);
1078 } elseif ($parent["uri"] == "") {
1080 $parent["uri"] = $first_id;
1084 $parent_uri = $parent["uri"];
1086 // "context" only seems to exist on older servers
1087 if (isset($single_conv->context->inReplyTo->id)) {
1088 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1089 intval($uid), dbesc($single_conv->context->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1091 $parent_uri = $single_conv->context->inReplyTo->id;
1094 // This is the current way
1095 if (isset($single_conv->object->inReplyTo->id)) {
1096 $parent_exists = q("SELECT `id` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1097 intval($uid), dbesc($single_conv->object->inReplyTo->id), dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1099 $parent_uri = $single_conv->object->inReplyTo->id;
1102 $message_exists = q("SELECT `id`, `parent`, `uri` FROM `item` WHERE `uid` = %d AND `uri` = '%s' AND `network` IN ('%s','%s') LIMIT 1",
1103 intval($uid), dbesc($single_conv->id),
1104 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
1105 if ($message_exists) {
1106 logger("Message ".$single_conv->id." already existed on the system", LOGGER_DEBUG);
1108 if ($parent["id"] != 0) {
1109 $existing_message = $message_exists[0];
1111 // We improved the way we fetch OStatus messages, this shouldn't happen very often now
1112 /// @TODO We have to change the shadow copies as well. This way here is really ugly.
1113 if ($existing_message["parent"] != $parent["id"]) {
1114 logger('updating id '.$existing_message["id"].' with parent '.$existing_message["parent"].' to parent '.$parent["id"].' uri '.$parent["uri"].' thread '.$parent_uri, LOGGER_DEBUG);
1116 // Update the parent id of the selected item
1117 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `id` = %d",
1118 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["id"]));
1120 // Update the parent uri in the thread - but only if it points to itself
1121 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE `id` = %d AND `uri` = `thr-parent`",
1122 dbesc($parent_uri), intval($existing_message["id"]));
1124 // try to change all items of the same parent
1125 $r = q("UPDATE `item` SET `parent` = %d, `parent-uri` = '%s' WHERE `parent` = %d",
1126 intval($parent["id"]), dbesc($parent["uri"]), intval($existing_message["parent"]));
1128 // Update the parent uri in the thread - but only if it points to itself
1129 $r = q("UPDATE `item` SET `thr-parent` = '%s' WHERE (`parent` = %d) AND (`uri` = `thr-parent`)",
1130 dbesc($parent["uri"]), intval($existing_message["parent"]));
1132 // Now delete the thread
1133 delete_thread($existing_message["parent"]);
1137 // The item we are having on the system is the one that we wanted to store via the item array
1138 if (isset($item["uri"]) AND ($item["uri"] == $existing_message["uri"])) {
1146 if (is_array($single_conv->to))
1147 foreach($single_conv->to AS $to)
1148 if ($importer["nurl"] == normalise_link($to->id))
1151 $actor = $single_conv->actor->id;
1152 if (isset($single_conv->actor->url))
1153 $actor = $single_conv->actor->url;
1155 $details = self::get_actor_details($actor, $uid, $parent["contact-id"]);
1157 // Do we only want to import threads that were started by our contacts?
1158 if ($details["not_following"] AND $new_parent AND get_config('system','ostatus_full_threads')) {
1159 logger("Don't import uri ".$first_id." because user ".$uid." doesn't follow the person ".$actor, LOGGER_DEBUG);
1164 $arr["network"] = $details["network"];
1165 $arr["uri"] = $single_conv->id;
1166 $arr["plink"] = $plink;
1168 $arr["contact-id"] = $details["contact_id"];
1169 $arr["parent-uri"] = $parent_uri;
1170 $arr["created"] = $single_conv->published;
1171 $arr["edited"] = $single_conv->published;
1172 $arr["owner-name"] = $single_conv->actor->displayName;
1173 if ($arr["owner-name"] == '')
1174 $arr["owner-name"] = $single_conv->actor->contact->displayName;
1175 if ($arr["owner-name"] == '')
1176 $arr["owner-name"] = $single_conv->actor->portablecontacts_net->displayName;
1178 $arr["owner-link"] = $actor;
1179 $arr["owner-avatar"] = self::fix_avatar($single_conv->actor->image->url, $arr["owner-link"]);
1181 $arr["author-name"] = $arr["owner-name"];
1182 $arr["author-link"] = $arr["owner-link"];
1183 $arr["author-avatar"] = $arr["owner-avatar"];
1184 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->content));
1186 if (isset($single_conv->status_net->conversation)) {
1187 $arr['conversation-uri'] = $single_conv->status_net->conversation;
1190 if (isset($single_conv->status_net->notice_info->source))
1191 $arr["app"] = strip_tags($single_conv->status_net->notice_info->source);
1192 elseif (isset($single_conv->statusnet->notice_info->source))
1193 $arr["app"] = strip_tags($single_conv->statusnet->notice_info->source);
1194 elseif (isset($single_conv->statusnet_notice_info->source))
1195 $arr["app"] = strip_tags($single_conv->statusnet_notice_info->source);
1196 elseif (isset($single_conv->provider->displayName))
1197 $arr["app"] = $single_conv->provider->displayName;
1199 $arr["app"] = "OStatus";
1202 $arr["source"] = json_encode($single_conv);
1203 $arr["protocol"] = PROTOCOL_GS_CONVERSATION;
1205 $arr["verb"] = $parent["verb"];
1206 $arr["visible"] = $parent["visible"];
1207 $arr["location"] = $single_conv->location->displayName;
1208 $arr["coord"] = trim($single_conv->location->lat." ".$single_conv->location->lon);
1210 // Is it a reshared item?
1211 if (isset($single_conv->verb) AND ($single_conv->verb == "share") AND isset($single_conv->object)) {
1212 if (is_array($single_conv->object))
1213 $single_conv->object = $single_conv->object[0];
1215 logger("Found reshared item ".$single_conv->object->id);
1217 // $single_conv->object->context->conversation;
1219 if (isset($single_conv->object->object->id))
1220 $arr["uri"] = $single_conv->object->object->id;
1222 $arr["uri"] = $single_conv->object->id;
1224 if (isset($single_conv->object->object->url))
1225 $plink = self::convert_href($single_conv->object->object->url);
1227 $plink = self::convert_href($single_conv->object->url);
1229 if (isset($single_conv->object->object->content))
1230 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->object->content));
1232 $arr["body"] = add_page_info_to_body(html2bbcode($single_conv->object->content));
1234 $arr["plink"] = $plink;
1236 $arr["created"] = $single_conv->object->published;
1237 $arr["edited"] = $single_conv->object->published;
1239 $arr["author-name"] = $single_conv->object->actor->displayName;
1240 if ($arr["owner-name"] == '') {
1241 $arr["author-name"] = $single_conv->object->actor->contact->displayName;
1243 $arr["author-link"] = $single_conv->object->actor->url;
1244 $arr["author-avatar"] = self::fix_avatar($single_conv->object->actor->image->url, $arr["author-link"]);
1246 $arr["app"] = $single_conv->object->provider->displayName."#";
1247 //$arr["verb"] = $single_conv->object->verb;
1249 $arr["location"] = $single_conv->object->location->displayName;
1250 $arr["coord"] = trim($single_conv->object->location->lat." ".$single_conv->object->location->lon);
1253 if ($arr["location"] == "")
1254 unset($arr["location"]);
1256 if ($arr["coord"] == "")
1257 unset($arr["coord"]);
1259 // Copy fields from given item array
1260 if (isset($item["uri"]) AND (($item["uri"] == $arr["uri"]) OR ($item["uri"] == $single_conv->id))) {
1261 $copy_fields = array("owner-name", "owner-link", "owner-avatar", "author-name", "author-link", "author-avatar",
1262 "gravity", "body", "object-type", "object", "verb", "created", "edited", "coord", "tag",
1263 "title", "attach", "app", "type", "location", "contact-id", "uri");
1264 foreach ($copy_fields AS $field)
1265 if (isset($item[$field]))
1266 $arr[$field] = $item[$field];
1270 $newitem = item_store($arr);
1272 logger("Item wasn't stored ".print_r($arr, true), LOGGER_DEBUG);
1276 if (isset($item["uri"]) AND ($item["uri"] == $arr["uri"])) {
1278 $item_stored = $newitem;
1281 logger('Stored new item '.$plink.' for parent '.$arr["parent-uri"].' under id '.$newitem, LOGGER_DEBUG);
1283 // Add the conversation entry (but don't fetch the whole conversation)
1284 self::store_conversation($newitem, $conversation_url);
1286 // If the newly created item is the top item then change the parent settings of the thread
1287 // This shouldn't happen anymore. This is supposed to be absolote.
1288 if ($arr["uri"] == $first_id) {
1289 logger('setting new parent to id '.$newitem);
1290 $new_parents = q("SELECT `id`, `uri`, `contact-id`, `type`, `verb`, `visible` FROM `item` WHERE `uid` = %d AND `id` = %d LIMIT 1",
1291 intval($uid), intval($newitem));
1293 $parent = $new_parents[0];
1297 if (($item_stored < 0) AND (count($item) > 0)) {
1299 if (get_config('system','ostatus_full_threads')) {
1300 $details = self::get_actor_details($item["owner-link"], $uid, $item["contact-id"]);
1301 if ($details["not_following"]) {
1302 logger("Don't import uri ".$item["uri"]." because user ".$uid." doesn't follow the person ".$item["owner-link"], LOGGER_DEBUG);
1307 $item_stored = item_store($item, $all_threads);
1309 logger("Uri ".$item["uri"]." wasn't found in conversation ".$conversation_url, LOGGER_DEBUG);
1310 self::store_conversation($item_stored, $conversation_url);
1314 return($item_stored);
1318 * @brief Stores conversation data into the database
1320 * @param integer $itemid The id of the item
1321 * @param string $conversation_url The uri of the conversation
1323 private function store_conversation($itemid, $conversation_url) {
1325 $conversation_url = self::convert_href($conversation_url);
1327 $messages = q("SELECT `uid`, `parent`, `created`, `received`, `guid` FROM `item` WHERE `id` = %d LIMIT 1", intval($itemid));
1330 $message = $messages[0];
1332 // Store conversation url if not done before
1333 $conversation = q("SELECT `url` FROM `term` WHERE `uid` = %d AND `oid` = %d AND `otype` = %d AND `type` = %d",
1334 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION));
1336 if (!$conversation) {
1337 $r = q("INSERT INTO `term` (`uid`, `oid`, `otype`, `type`, `term`, `url`, `created`, `received`, `guid`) VALUES (%d, %d, %d, %d, '%s', '%s', '%s', '%s', '%s')",
1338 intval($message["uid"]), intval($itemid), intval(TERM_OBJ_POST), intval(TERM_CONVERSATION),
1339 dbesc($message["created"]), dbesc($conversation_url), dbesc($message["created"]), dbesc($message["received"]), dbesc($message["guid"]));
1340 logger('Storing conversation url '.$conversation_url.' for id '.$itemid);
1345 * @brief Checks if the current post is a reshare
1347 * @param array $item The item array of thw post
1349 * @return string The guid if the post is a reshare
1351 private function get_reshared_guid($item) {
1352 $body = trim($item["body"]);
1354 // Skip if it isn't a pure repeated messages
1355 // Does it start with a share?
1356 if (strpos($body, "[share") > 0)
1359 // Does it end with a share?
1360 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1363 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1364 // Skip if there is no shared message in there
1365 if ($body == $attributes)
1369 preg_match("/guid='(.*?)'/ism", $attributes, $matches);
1370 if ($matches[1] != "")
1371 $guid = $matches[1];
1373 preg_match('/guid="(.*?)"/ism', $attributes, $matches);
1374 if ($matches[1] != "")
1375 $guid = $matches[1];
1381 * @brief Cleans the body of a post if it contains picture links
1383 * @param string $body The body
1385 * @return string The cleaned body
1387 private function format_picture_post($body) {
1388 $siteinfo = get_attached_data($body);
1390 if (($siteinfo["type"] == "photo")) {
1391 if (isset($siteinfo["preview"]))
1392 $preview = $siteinfo["preview"];
1394 $preview = $siteinfo["image"];
1396 // Is it a remote picture? Then make a smaller preview here
1397 $preview = proxy_url($preview, false, PROXY_SIZE_SMALL);
1399 // Is it a local picture? Then make it smaller here
1400 $preview = str_replace(array("-0.jpg", "-0.png"), array("-2.jpg", "-2.png"), $preview);
1401 $preview = str_replace(array("-1.jpg", "-1.png"), array("-2.jpg", "-2.png"), $preview);
1403 if (isset($siteinfo["url"]))
1404 $url = $siteinfo["url"];
1406 $url = $siteinfo["image"];
1408 $body = trim($siteinfo["text"])." [url]".$url."[/url]\n[img]".$preview."[/img]";
1415 * @brief Adds the header elements to the XML document
1417 * @param object $doc XML document
1418 * @param array $owner Contact data of the poster
1420 * @return object header root element
1422 private function add_header($doc, $owner) {
1426 $root = $doc->createElementNS(NAMESPACE_ATOM1, 'feed');
1427 $doc->appendChild($root);
1429 $root->setAttribute("xmlns:thr", NAMESPACE_THREAD);
1430 $root->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
1431 $root->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
1432 $root->setAttribute("xmlns:media", NAMESPACE_MEDIA);
1433 $root->setAttribute("xmlns:poco", NAMESPACE_POCO);
1434 $root->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
1435 $root->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
1436 $root->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
1438 $attributes = array("uri" => "https://friendi.ca", "version" => FRIENDICA_VERSION."-".DB_UPDATE_VERSION);
1439 xml::add_element($doc, $root, "generator", FRIENDICA_PLATFORM, $attributes);
1440 xml::add_element($doc, $root, "id", App::get_baseurl()."/profile/".$owner["nick"]);
1441 xml::add_element($doc, $root, "title", sprintf("%s timeline", $owner["name"]));
1442 xml::add_element($doc, $root, "subtitle", sprintf("Updates from %s on %s", $owner["name"], $a->config["sitename"]));
1443 xml::add_element($doc, $root, "logo", $owner["photo"]);
1444 xml::add_element($doc, $root, "updated", datetime_convert("UTC", "UTC", "now", ATOM_TIME));
1446 $author = self::add_author($doc, $owner);
1447 $root->appendChild($author);
1449 $attributes = array("href" => $owner["url"], "rel" => "alternate", "type" => "text/html");
1450 xml::add_element($doc, $root, "link", "", $attributes);
1452 /// @TODO We have to find out what this is
1453 /// $attributes = array("href" => App::get_baseurl()."/sup",
1454 /// "rel" => "http://api.friendfeed.com/2008/03#sup",
1455 /// "type" => "application/json");
1456 /// xml::add_element($doc, $root, "link", "", $attributes);
1458 self::hublinks($doc, $root);
1460 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "salmon");
1461 xml::add_element($doc, $root, "link", "", $attributes);
1463 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-replies");
1464 xml::add_element($doc, $root, "link", "", $attributes);
1466 $attributes = array("href" => App::get_baseurl()."/salmon/".$owner["nick"], "rel" => "http://salmon-protocol.org/ns/salmon-mention");
1467 xml::add_element($doc, $root, "link", "", $attributes);
1469 $attributes = array("href" => App::get_baseurl()."/api/statuses/user_timeline/".$owner["nick"].".atom",
1470 "rel" => "self", "type" => "application/atom+xml");
1471 xml::add_element($doc, $root, "link", "", $attributes);
1477 * @brief Add the link to the push hubs to the XML document
1479 * @param object $doc XML document
1480 * @param object $root XML root element where the hub links are added
1482 public static function hublinks($doc, $root) {
1483 $hub = get_config('system','huburl');
1487 $hubs = explode(',', $hub);
1489 foreach($hubs as $h) {
1493 if ($h === '[internal]')
1494 $h = App::get_baseurl() . '/pubsubhubbub';
1495 xml::add_element($doc, $root, "link", "", array("href" => $h, "rel" => "hub"));
1502 * @brief Adds attachement data to the XML document
1504 * @param object $doc XML document
1505 * @param object $root XML root element where the hub links are added
1506 * @param array $item Data of the item that is to be posted
1508 private function get_attachment($doc, $root, $item) {
1510 $siteinfo = get_attached_data($item["body"]);
1512 switch ($siteinfo["type"]) {
1514 $imgdata = get_photo_info($siteinfo["image"]);
1515 $attributes = array("rel" => "enclosure",
1516 "href" => $siteinfo["image"],
1517 "type" => $imgdata["mime"],
1518 "length" => intval($imgdata["size"]));
1519 xml::add_element($doc, $root, "link", "", $attributes);
1522 $attributes = array("rel" => "enclosure",
1523 "href" => $siteinfo["url"],
1524 "type" => "text/html; charset=UTF-8",
1526 "title" => $siteinfo["title"]);
1527 xml::add_element($doc, $root, "link", "", $attributes);
1533 if (($siteinfo["type"] != "photo") AND isset($siteinfo["image"])) {
1534 $imgdata = get_photo_info($siteinfo["image"]);
1535 $attributes = array("rel" => "enclosure",
1536 "href" => $siteinfo["image"],
1537 "type" => $imgdata["mime"],
1538 "length" => intval($imgdata["size"]));
1540 xml::add_element($doc, $root, "link", "", $attributes);
1543 $arr = explode('[/attach],', $item['attach']);
1545 foreach ($arr as $r) {
1547 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1549 $attributes = array("rel" => "enclosure",
1550 "href" => $matches[1],
1551 "type" => $matches[3]);
1553 if (intval($matches[2])) {
1554 $attributes["length"] = intval($matches[2]);
1556 if (trim($matches[4]) != "") {
1557 $attributes["title"] = trim($matches[4]);
1559 xml::add_element($doc, $root, "link", "", $attributes);
1566 * @brief Adds the author element to the XML document
1568 * @param object $doc XML document
1569 * @param array $owner Contact data of the poster
1571 * @return object author element
1573 private function add_author($doc, $owner) {
1575 $r = q("SELECT `homepage`, `publish` FROM `profile` WHERE `uid` = %d AND `is-default` LIMIT 1", intval($owner["uid"]));
1579 $author = $doc->createElement("author");
1580 xml::add_element($doc, $author, "id", $owner["url"]);
1581 xml::add_element($doc, $author, "activity:object-type", ACTIVITY_OBJ_PERSON);
1582 xml::add_element($doc, $author, "uri", $owner["url"]);
1583 xml::add_element($doc, $author, "name", $owner["nick"]);
1584 xml::add_element($doc, $author, "email", $owner["addr"]);
1585 xml::add_element($doc, $author, "summary", bbcode($owner["about"], false, false, 7));
1587 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $owner["url"]);
1588 xml::add_element($doc, $author, "link", "", $attributes);
1590 $attributes = array(
1592 "type" => "image/jpeg", // To-Do?
1593 "media:width" => 175,
1594 "media:height" => 175,
1595 "href" => $owner["photo"]);
1596 xml::add_element($doc, $author, "link", "", $attributes);
1598 if (isset($owner["thumb"])) {
1599 $attributes = array(
1601 "type" => "image/jpeg", // To-Do?
1602 "media:width" => 80,
1603 "media:height" => 80,
1604 "href" => $owner["thumb"]);
1605 xml::add_element($doc, $author, "link", "", $attributes);
1608 xml::add_element($doc, $author, "poco:preferredUsername", $owner["nick"]);
1609 xml::add_element($doc, $author, "poco:displayName", $owner["name"]);
1610 xml::add_element($doc, $author, "poco:note", bbcode($owner["about"], false, false, 7));
1612 if (trim($owner["location"]) != "") {
1613 $element = $doc->createElement("poco:address");
1614 xml::add_element($doc, $element, "poco:formatted", $owner["location"]);
1615 $author->appendChild($element);
1618 if (trim($profile["homepage"]) != "") {
1619 $urls = $doc->createElement("poco:urls");
1620 xml::add_element($doc, $urls, "poco:type", "homepage");
1621 xml::add_element($doc, $urls, "poco:value", $profile["homepage"]);
1622 xml::add_element($doc, $urls, "poco:primary", "true");
1623 $author->appendChild($urls);
1626 if (count($profile)) {
1627 xml::add_element($doc, $author, "followers", "", array("url" => App::get_baseurl()."/viewcontacts/".$owner["nick"]));
1628 xml::add_element($doc, $author, "statusnet:profile_info", "", array("local_id" => $owner["uid"]));
1631 if ($profile["publish"]) {
1632 xml::add_element($doc, $author, "mastodon:scope", "public");
1638 * @TODO Picture attachments should look like this:
1639 * <a href="https://status.pirati.ca/attachment/572819" title="https://status.pirati.ca/file/heluecht-20151202T222602-rd3u49p.gif"
1640 * class="attachment thumbnail" id="attachment-572819" rel="nofollow external">https://status.pirati.ca/attachment/572819</a>
1645 * @brief Returns the given activity if present - otherwise returns the "post" activity
1647 * @param array $item Data of the item that is to be posted
1649 * @return string activity
1651 function construct_verb($item) {
1653 return $item['verb'];
1654 return ACTIVITY_POST;
1658 * @brief Returns the given object type if present - otherwise returns the "note" object type
1660 * @param array $item Data of the item that is to be posted
1662 * @return string Object type
1664 function construct_objecttype($item) {
1665 if (in_array($item['object-type'], array(ACTIVITY_OBJ_NOTE, ACTIVITY_OBJ_COMMENT)))
1666 return $item['object-type'];
1667 return ACTIVITY_OBJ_NOTE;
1671 * @brief Adds an entry element to the XML document
1673 * @param object $doc XML document
1674 * @param array $item Data of the item that is to be posted
1675 * @param array $owner Contact data of the poster
1676 * @param bool $toplevel
1678 * @return object Entry element
1680 private function entry($doc, $item, $owner, $toplevel = false) {
1681 $repeated_guid = self::get_reshared_guid($item);
1682 if ($repeated_guid != "")
1683 $xml = self::reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel);
1688 if ($item["verb"] == ACTIVITY_LIKE) {
1689 return self::like_entry($doc, $item, $owner, $toplevel);
1690 } elseif (in_array($item["verb"], array(ACTIVITY_FOLLOW, NAMESPACE_OSTATUS."/unfollow"))) {
1691 return self::follow_entry($doc, $item, $owner, $toplevel);
1693 return self::note_entry($doc, $item, $owner, $toplevel);
1698 * @brief Adds a source entry to the XML document
1700 * @param object $doc XML document
1701 * @param array $contact Array of the contact that is added
1703 * @return object Source element
1705 private function source_entry($doc, $contact) {
1706 $source = $doc->createElement("source");
1707 xml::add_element($doc, $source, "id", $contact["poll"]);
1708 xml::add_element($doc, $source, "title", $contact["name"]);
1709 xml::add_element($doc, $source, "link", "", array("rel" => "alternate",
1710 "type" => "text/html",
1711 "href" => $contact["alias"]));
1712 xml::add_element($doc, $source, "link", "", array("rel" => "self",
1713 "type" => "application/atom+xml",
1714 "href" => $contact["poll"]));
1715 xml::add_element($doc, $source, "icon", $contact["photo"]);
1716 xml::add_element($doc, $source, "updated", datetime_convert("UTC","UTC",$contact["success_update"]."+00:00",ATOM_TIME));
1722 * @brief Fetches contact data from the contact or the gcontact table
1724 * @param string $url URL of the contact
1725 * @param array $owner Contact data of the poster
1727 * @return array Contact array
1729 private function contact_entry($url, $owner) {
1731 $r = q("SELECT * FROM `contact` WHERE `nurl` = '%s' AND `uid` IN (0, %d) ORDER BY `uid` DESC LIMIT 1",
1732 dbesc(normalise_link($url)), intval($owner["uid"]));
1735 $contact["uid"] = -1;
1739 $r = q("SELECT * FROM `gcontact` WHERE `nurl` = '%s' LIMIT 1",
1740 dbesc(normalise_link($url)));
1743 $contact["uid"] = -1;
1744 $contact["success_update"] = $contact["updated"];
1751 if (!isset($contact["poll"])) {
1752 $data = probe_url($url);
1753 $contact["poll"] = $data["poll"];
1755 if (!$contact["alias"])
1756 $contact["alias"] = $data["alias"];
1759 if (!isset($contact["alias"]))
1760 $contact["alias"] = $contact["url"];
1766 * @brief Adds an entry element with reshared content
1768 * @param object $doc XML document
1769 * @param array $item Data of the item that is to be posted
1770 * @param array $owner Contact data of the poster
1771 * @param $repeated_guid
1772 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1774 * @return object Entry element
1776 private function reshare_entry($doc, $item, $owner, $repeated_guid, $toplevel) {
1778 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1779 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1782 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1784 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `guid` = '%s' AND NOT `private` AND `network` IN ('%s', '%s', '%s') LIMIT 1",
1785 intval($owner["uid"]), dbesc($repeated_guid),
1786 dbesc(NETWORK_DFRN), dbesc(NETWORK_DIASPORA), dbesc(NETWORK_OSTATUS));
1788 $repeated_item = $r[0];
1792 $contact = self::contact_entry($repeated_item['author-link'], $owner);
1794 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1796 $title = $owner["nick"]." repeated a notice by ".$contact["nick"];
1798 self::entry_content($doc, $entry, $item, $owner, $title, ACTIVITY_SHARE, false);
1800 $as_object = $doc->createElement("activity:object");
1802 xml::add_element($doc, $as_object, "activity:object-type", NAMESPACE_ACTIVITY_SCHEMA."activity");
1804 self::entry_content($doc, $as_object, $repeated_item, $owner, "", "", false);
1806 $author = self::add_author($doc, $contact);
1807 $as_object->appendChild($author);
1809 $as_object2 = $doc->createElement("activity:object");
1811 xml::add_element($doc, $as_object2, "activity:object-type", self::construct_objecttype($repeated_item));
1813 $title = sprintf("New comment by %s", $contact["nick"]);
1815 self::entry_content($doc, $as_object2, $repeated_item, $owner, $title);
1817 $as_object->appendChild($as_object2);
1819 self::entry_footer($doc, $as_object, $item, $owner, false);
1821 $source = self::source_entry($doc, $contact);
1823 $as_object->appendChild($source);
1825 $entry->appendChild($as_object);
1827 self::entry_footer($doc, $entry, $item, $owner);
1833 * @brief Adds an entry element with a "like"
1835 * @param object $doc XML document
1836 * @param array $item Data of the item that is to be posted
1837 * @param array $owner Contact data of the poster
1838 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1840 * @return object Entry element with "like"
1842 private function like_entry($doc, $item, $owner, $toplevel) {
1844 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1845 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1848 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1850 $verb = NAMESPACE_ACTIVITY_SCHEMA."favorite";
1851 self::entry_content($doc, $entry, $item, $owner, "Favorite", $verb, false);
1853 $as_object = $doc->createElement("activity:object");
1855 $parent = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
1856 dbesc($item["thr-parent"]), intval($item["uid"]));
1857 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
1859 xml::add_element($doc, $as_object, "activity:object-type", self::construct_objecttype($parent[0]));
1861 self::entry_content($doc, $as_object, $parent[0], $owner, "New entry");
1863 $entry->appendChild($as_object);
1865 self::entry_footer($doc, $entry, $item, $owner);
1871 * @brief Adds the person object element to the XML document
1873 * @param object $doc XML document
1874 * @param array $owner Contact data of the poster
1875 * @param array $contact Contact data of the target
1877 * @return object author element
1879 private function add_person_object($doc, $owner, $contact) {
1881 $object = $doc->createElement("activity:object");
1882 xml::add_element($doc, $object, "activity:object-type", ACTIVITY_OBJ_PERSON);
1884 if ($contact['network'] == NETWORK_PHANTOM) {
1885 xml::add_element($doc, $object, "id", $contact['url']);
1889 xml::add_element($doc, $object, "id", $contact["alias"]);
1890 xml::add_element($doc, $object, "title", $contact["nick"]);
1892 $attributes = array("rel" => "alternate", "type" => "text/html", "href" => $contact["url"]);
1893 xml::add_element($doc, $object, "link", "", $attributes);
1895 $attributes = array(
1897 "type" => "image/jpeg", // To-Do?
1898 "media:width" => 175,
1899 "media:height" => 175,
1900 "href" => $contact["photo"]);
1901 xml::add_element($doc, $object, "link", "", $attributes);
1903 xml::add_element($doc, $object, "poco:preferredUsername", $contact["nick"]);
1904 xml::add_element($doc, $object, "poco:displayName", $contact["name"]);
1906 if (trim($contact["location"]) != "") {
1907 $element = $doc->createElement("poco:address");
1908 xml::add_element($doc, $element, "poco:formatted", $contact["location"]);
1909 $object->appendChild($element);
1916 * @brief Adds a follow/unfollow entry element
1918 * @param object $doc XML document
1919 * @param array $item Data of the follow/unfollow message
1920 * @param array $owner Contact data of the poster
1921 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1923 * @return object Entry element
1925 private function follow_entry($doc, $item, $owner, $toplevel) {
1927 $item["id"] = $item["parent"] = 0;
1928 $item["created"] = $item["edited"] = date("c");
1929 $item["private"] = true;
1931 $contact = Probe::uri($item['follow']);
1933 if ($contact['alias'] == '') {
1934 $contact['alias'] = $contact["url"];
1936 $item['follow'] = $contact['alias'];
1939 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
1940 intval($owner['uid']), dbesc(normalise_link($contact["url"])));
1942 if (dbm::is_result($r)) {
1943 $connect_id = $r[0]['id'];
1948 if ($item['verb'] == ACTIVITY_FOLLOW) {
1949 $message = t('%s is now following %s.');
1950 $title = t('following');
1951 $action = "subscription";
1953 $message = t('%s stopped following %s.');
1954 $title = t('stopped following');
1955 $action = "unfollow";
1958 $item["uri"] = $item['parent-uri'] = $item['thr-parent'] =
1959 'tag:'.get_app()->get_hostname().
1960 ','.date('Y-m-d').':'.$action.':'.$owner['uid'].
1961 ':person:'.$connect_id.':'.$item['created'];
1963 $item["body"] = sprintf($message, $owner["nick"], $contact["nick"]);
1965 self::entry_header($doc, $entry, $owner, $toplevel);
1967 self::entry_content($doc, $entry, $item, $owner, $title);
1969 $object = self::add_person_object($doc, $owner, $contact);
1970 $entry->appendChild($object);
1972 self::entry_footer($doc, $entry, $item, $owner);
1978 * @brief Adds a regular entry element
1980 * @param object $doc XML document
1981 * @param array $item Data of the item that is to be posted
1982 * @param array $owner Contact data of the poster
1983 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
1985 * @return object Entry element
1987 private function note_entry($doc, $item, $owner, $toplevel) {
1989 if (($item["id"] != $item["parent"]) AND (normalise_link($item["author-link"]) != normalise_link($owner["url"]))) {
1990 logger("OStatus entry is from author ".$owner["url"]." - not from ".$item["author-link"].". Quitting.", LOGGER_DEBUG);
1993 $title = self::entry_header($doc, $entry, $owner, $toplevel);
1995 xml::add_element($doc, $entry, "activity:object-type", ACTIVITY_OBJ_NOTE);
1997 self::entry_content($doc, $entry, $item, $owner, $title);
1999 self::entry_footer($doc, $entry, $item, $owner);
2005 * @brief Adds a header element to the XML document
2007 * @param object $doc XML document
2008 * @param object $entry The entry element where the elements are added
2009 * @param array $owner Contact data of the poster
2010 * @param bool $toplevel Is it for en entry element (false) or a feed entry (true)?
2012 * @return string The title for the element
2014 private function entry_header($doc, &$entry, $owner, $toplevel) {
2015 /// @todo Check if this title stuff is really needed (I guess not)
2017 $entry = $doc->createElement("entry");
2018 $title = sprintf("New note by %s", $owner["nick"]);
2020 $entry = $doc->createElementNS(NAMESPACE_ATOM1, "entry");
2022 $entry->setAttribute("xmlns:thr", NAMESPACE_THREAD);
2023 $entry->setAttribute("xmlns:georss", NAMESPACE_GEORSS);
2024 $entry->setAttribute("xmlns:activity", NAMESPACE_ACTIVITY);
2025 $entry->setAttribute("xmlns:media", NAMESPACE_MEDIA);
2026 $entry->setAttribute("xmlns:poco", NAMESPACE_POCO);
2027 $entry->setAttribute("xmlns:ostatus", NAMESPACE_OSTATUS);
2028 $entry->setAttribute("xmlns:statusnet", NAMESPACE_STATUSNET);
2029 $entry->setAttribute("xmlns:mastodon", NAMESPACE_MASTODON);
2031 $author = self::add_author($doc, $owner);
2032 $entry->appendChild($author);
2034 $title = sprintf("New comment by %s", $owner["nick"]);
2040 * @brief Adds elements to the XML document
2042 * @param object $doc XML document
2043 * @param object $entry Entry element where the content is added
2044 * @param array $item Data of the item that is to be posted
2045 * @param array $owner Contact data of the poster
2046 * @param string $title Title for the post
2047 * @param string $verb The activity verb
2048 * @param bool $complete Add the "status_net" element?
2050 private function entry_content($doc, $entry, $item, $owner, $title, $verb = "", $complete = true) {
2053 $verb = self::construct_verb($item);
2055 xml::add_element($doc, $entry, "id", $item["uri"]);
2056 xml::add_element($doc, $entry, "title", $title);
2058 $body = self::format_picture_post($item['body']);
2060 if ($item['title'] != "")
2061 $body = "[b]".$item['title']."[/b]\n\n".$body;
2063 $body = bbcode($body, false, false, 7);
2065 xml::add_element($doc, $entry, "content", $body, array("type" => "html"));
2067 xml::add_element($doc, $entry, "link", "", array("rel" => "alternate", "type" => "text/html",
2068 "href" => App::get_baseurl()."/display/".$item["guid"]));
2070 if ($complete AND ($item["id"] > 0))
2071 xml::add_element($doc, $entry, "status_net", "", array("notice_id" => $item["id"]));
2073 xml::add_element($doc, $entry, "activity:verb", $verb);
2075 xml::add_element($doc, $entry, "published", datetime_convert("UTC","UTC",$item["created"]."+00:00",ATOM_TIME));
2076 xml::add_element($doc, $entry, "updated", datetime_convert("UTC","UTC",$item["edited"]."+00:00",ATOM_TIME));
2080 * @brief Adds the elements at the foot of an entry to the XML document
2082 * @param object $doc XML document
2083 * @param object $entry The entry element where the elements are added
2084 * @param array $item Data of the item that is to be posted
2085 * @param array $owner Contact data of the poster
2088 private function entry_footer($doc, $entry, $item, $owner, $complete = true) {
2090 $mentioned = array();
2092 if (($item['parent'] != $item['id']) OR ($item['parent-uri'] !== $item['uri']) OR (($item['thr-parent'] !== '') AND ($item['thr-parent'] !== $item['uri']))) {
2093 $parent = q("SELECT `guid`, `author-link`, `owner-link` FROM `item` WHERE `id` = %d", intval($item["parent"]));
2094 $parent_item = (($item['thr-parent']) ? $item['thr-parent'] : $item['parent-uri']);
2096 $thrparent = q("SELECT `guid`, `author-link`, `owner-link`, `plink` FROM `item` WHERE `uid` = %d AND `uri` = '%s'",
2097 intval($owner["uid"]),
2098 dbesc($parent_item));
2100 $mentioned[$thrparent[0]["author-link"]] = $thrparent[0]["author-link"];
2101 $mentioned[$thrparent[0]["owner-link"]] = $thrparent[0]["owner-link"];
2102 $parent_plink = $thrparent[0]["plink"];
2104 $mentioned[$parent[0]["author-link"]] = $parent[0]["author-link"];
2105 $mentioned[$parent[0]["owner-link"]] = $parent[0]["owner-link"];
2106 $parent_plink = App::get_baseurl()."/display/".$parent[0]["guid"];
2109 $attributes = array(
2110 "ref" => $parent_item,
2111 "href" => $parent_plink);
2112 xml::add_element($doc, $entry, "thr:in-reply-to", "", $attributes);
2114 $attributes = array(
2116 "href" => $parent_plink);
2117 xml::add_element($doc, $entry, "link", "", $attributes);
2120 if (intval($item["parent"]) > 0) {
2121 $conversation_href = App::get_baseurl()."/display/".$owner["nick"]."/".$item["parent"];
2122 $conversation_uri = $conversation_href;
2124 if (isset($parent_item)) {
2125 $r = dba::fetch_first("SELECT `conversation-uri`, `conversation-href` FROM `conversation` WHERE `item-uri` = ?", $parent_item);
2126 if (dbm::is_result($r)) {
2127 if ($r['conversation-uri'] != '') {
2128 $conversation_uri = $r['conversation-uri'];
2130 if ($r['conversation-href'] != '') {
2131 $conversation_href = $r['conversation-href'];
2136 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:conversation", "href" => $conversation_href));
2138 $attributes = array(
2139 "href" => $conversation_href,
2140 "local_id" => $item["parent"],
2141 "ref" => $conversation_uri);
2143 xml::add_element($doc, $entry, "ostatus:conversation", $conversation_uri, $attributes);
2146 $tags = item_getfeedtags($item);
2149 foreach($tags as $t)
2151 $mentioned[$t[1]] = $t[1];
2153 // Make sure that mentions are accepted (GNU Social has problems with mixing HTTP and HTTPS)
2154 $newmentions = array();
2155 foreach ($mentioned AS $mention) {
2156 $newmentions[str_replace("http://", "https://", $mention)] = str_replace("http://", "https://", $mention);
2157 $newmentions[str_replace("https://", "http://", $mention)] = str_replace("https://", "http://", $mention);
2159 $mentioned = $newmentions;
2161 foreach ($mentioned AS $mention) {
2162 $r = q("SELECT `forum`, `prv` FROM `contact` WHERE `uid` = %d AND `nurl` = '%s'",
2163 intval($owner["uid"]),
2164 dbesc(normalise_link($mention)));
2165 if ($r[0]["forum"] OR $r[0]["prv"])
2166 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2167 "ostatus:object-type" => ACTIVITY_OBJ_GROUP,
2168 "href" => $mention));
2170 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2171 "ostatus:object-type" => ACTIVITY_OBJ_PERSON,
2172 "href" => $mention));
2175 if (!$item["private"]) {
2176 xml::add_element($doc, $entry, "link", "", array("rel" => "ostatus:attention",
2177 "href" => "http://activityschema.org/collection/public"));
2178 xml::add_element($doc, $entry, "link", "", array("rel" => "mentioned",
2179 "ostatus:object-type" => "http://activitystrea.ms/schema/1.0/collection",
2180 "href" => "http://activityschema.org/collection/public"));
2181 xml::add_element($doc, $entry, "mastodon:scope", "public");
2185 foreach($tags as $t)
2187 xml::add_element($doc, $entry, "category", "", array("term" => $t[2]));
2189 self::get_attachment($doc, $entry, $item);
2191 if ($complete AND ($item["id"] > 0)) {
2192 $app = $item["app"];
2196 $attributes = array("local_id" => $item["id"], "source" => $app);
2198 if (isset($parent["id"]))
2199 $attributes["repeat_of"] = $parent["id"];
2201 if ($item["coord"] != "")
2202 xml::add_element($doc, $entry, "georss:point", $item["coord"]);
2204 xml::add_element($doc, $entry, "statusnet:notice_info", "", $attributes);
2209 * @brief Creates the XML feed for a given nickname
2211 * @param App $a The application class
2212 * @param string $owner_nick Nickname of the feed owner
2213 * @param string $last_update Date of the last update
2215 * @return string XML feed
2217 public static function feed(App $a, $owner_nick, $last_update) {
2219 $r = q("SELECT `contact`.*, `user`.`nickname`, `user`.`timezone`, `user`.`page-flags`
2220 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
2221 WHERE `contact`.`self` AND `user`.`nickname` = '%s' LIMIT 1",
2222 dbesc($owner_nick));
2228 if(!strlen($last_update))
2229 $last_update = 'now -30 days';
2231 $check_date = datetime_convert('UTC','UTC',$last_update,'Y-m-d H:i:s');
2232 $authorid = get_contact($owner["url"], 0);
2234 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item` USE INDEX (`uid_contactid_created`)
2235 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2236 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d AND
2237 `item`.`author-id` = %d AND `item`.`created` > '%s' AND
2238 NOT `item`.`deleted` AND NOT `item`.`private` AND
2239 `thread`.`network` IN ('%s', '%s')
2240 ORDER BY `item`.`created` DESC LIMIT 300",
2241 intval($owner["uid"]), intval($owner["id"]),
2242 intval($authorid), dbesc($check_date),
2243 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN));
2245 /* 2016-10-23: The old query will be kept until we are sure that the query above is a good and fast replacement
2247 $items = q("SELECT `item`.*, `item`.`id` AS `item_id` FROM `item`
2248 STRAIGHT_JOIN `thread` ON `thread`.`iid` = `item`.`parent`
2249 LEFT JOIN `item` AS `thritem` ON `thritem`.`uri`=`item`.`thr-parent` AND `thritem`.`uid`=`item`.`uid`
2250 WHERE `item`.`uid` = %d AND `item`.`received` > '%s' AND NOT `item`.`private` AND NOT `item`.`deleted`
2251 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = '' AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
2252 AND ((`item`.`wall` AND (`item`.`parent` = `item`.`id`))
2253 OR (`item`.`network` = '%s' AND ((`thread`.`network` IN ('%s', '%s')) OR (`thritem`.`network` IN ('%s', '%s')))) AND `thread`.`mention`)
2254 AND ((`item`.`owner-link` IN ('%s', '%s') AND (`item`.`parent` = `item`.`id`))
2255 OR (`item`.`author-link` IN ('%s', '%s')))
2256 ORDER BY `item`.`id` DESC
2258 intval($owner["uid"]), dbesc($check_date), dbesc(NETWORK_DFRN),
2259 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2260 //dbesc(NETWORK_OSTATUS), dbesc(NETWORK_OSTATUS),
2261 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2262 dbesc(NETWORK_OSTATUS), dbesc(NETWORK_DFRN),
2263 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"])),
2264 dbesc($owner["nurl"]), dbesc(str_replace("http://", "https://", $owner["nurl"]))
2267 $doc = new DOMDocument('1.0', 'utf-8');
2268 $doc->formatOutput = true;
2270 $root = self::add_header($doc, $owner);
2272 foreach ($items AS $item) {
2273 $entry = self::entry($doc, $item, $owner);
2274 $root->appendChild($entry);
2277 return(trim($doc->saveXML()));
2281 * @brief Creates the XML for a salmon message
2283 * @param array $item Data of the item that is to be posted
2284 * @param array $owner Contact data of the poster
2286 * @return string XML for the salmon
2288 public static function salmon($item,$owner) {
2290 $doc = new DOMDocument('1.0', 'utf-8');
2291 $doc->formatOutput = true;
2293 $entry = self::entry($doc, $item, $owner, true);
2295 $doc->appendChild($entry);
2297 return(trim($doc->saveXML()));