Also need to change collection_id...
[davical.git] / htdocs / feed.php
blob151da22c8dc1db3b955decd4f9c9cd8c5b1e59b3
1 <?php
2 /**
3 * A script for returning a feed (currently Atom) of recent changes to a calendar collection
4 * @author Leho Kraav <leho@kraav.com>
5 * @author Andrew McMillan <andrew@morphoss.com>
6 * @license GPL v2 or later
7 */
8 require_once("./always.php");
9 dbg_error_log( "feed", " User agent: %s", ((isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : "Unfortunately Mulberry and Chandler don't send a 'User-agent' header with their requests :-(")) );
10 dbg_log_array( "headers", '_SERVER', $_SERVER, true );
12 require_once('AwlCache.php');
14 require_once("HTTPAuthSession.php");
15 $session = new HTTPAuthSession();
17 require_once('CalDAVRequest.php');
18 $request = new CalDAVRequest();
20 require_once("vComponent.php");
21 require_once("DAVResource.php");
24 /**
25 * Function for creating anchor links out of plain text.
26 * Source: http://stackoverflow.com/questions/1960461/convert-plain-text-hyperlinks-into-html-hyperlinks-in-php
28 function hyperlink( $text ) {
29 return preg_replace( '@(https?://([-\w\.]+[-\w])+(:\d+)?(/([\w/_\.#-]*(\?\S+)?[^\.\s])?)?)@', '<a href="$1" target="_blank">$1</a>', htmlspecialchars($text) );
32 function caldav_get_feed( $request, $collection ) {
33 global $c, $session;
35 dbg_error_log("feed", "GET method handler");
37 $collection->NeedPrivilege( array('DAV::read') );
39 if ( ! $collection->Exists() ) {
40 $request->DoResponse( 404, translate("Resource Not Found.") );
43 if ( !$collection->IsCollection()
44 || !$collection->IsCalendar() && !(isset($c->get_includes_subcollections) && $c->get_includes_subcollections) ) {
45 $request->DoResponse( 405, translate("Feeds are only supported for calendars at present.") );
48 // Try and pull the answer out of a hat
49 $cache = getCacheInstance();
50 $cache_ns = 'collection-'.$collection->dav_name();
51 $cache_key = 'feed'.$session->user_no;
52 $response = $cache->get( $cache_ns, $cache_key );
53 if ( $response !== false ) return $response;
55 $principal = $collection->GetProperty('principal');
57 /**
58 * The CalDAV specification does not define GET on a collection, but typically this is
59 * used as a .ics download for the whole collection, which is what we do also.
61 $sql = 'SELECT caldav_data, caldav_type, caldav_data.user_no, caldav_data.dav_name,';
62 $sql .= ' caldav_data.modified, caldav_data.created, ';
63 $sql .= ' summary, dtstart, dtend, calendar_item.description ';
64 $sql .= ' FROM collection INNER JOIN caldav_data USING(collection_id) INNER JOIN calendar_item USING ( dav_id ) WHERE ';
65 if ( isset($c->get_includes_subcollections) && $c->get_includes_subcollections ) {
66 $sql .= ' (collection.dav_name ~ :path_match ';
67 $sql .= ' OR collection.collection_id IN (SELECT bound_source_id FROM dav_binding WHERE dav_binding.dav_name ~ :path_match)) ';
68 $params = array( ':path_match' => '^'.$request->path );
70 else {
71 $sql .= ' caldav_data.collection_id = :collection_id ';
72 $params = array( ':collection_id' => $collection->resource_id() );
74 $sql .= ' ORDER BY caldav_data.created DESC';
75 $sql .= ' LIMIT '.(isset($c->feed_item_limit) ? $c->feed_item_limit : 15);
76 $qry = new AwlQuery( $sql, $params );
77 if ( !$qry->Exec("GET",__LINE__,__FILE__) ) {
78 $request->DoResponse( 500, translate("Database Error") );
81 /**
82 * Here we are constructing the feed response for this collection, including
83 * the timezones that are referred to by the events we have selected.
84 * Library used: http://framework.zend.com/manual/en/zend.feed.writer.html
86 require_once('AtomFeed.php');
87 $feed = new AtomFeed();
89 $feed->setTitle('DAViCal Atom Feed: '. $collection->GetProperty('displayname'));
90 $url = $c->protocol_server_port . $collection->url();
91 $url = preg_replace( '{/$}', '.ics', $url);
92 $feed->setLink($url);
93 $feed->setFeedLink($c->protocol_server_port_script . $request->path, 'atom');
94 $feed->addAuthor(array(
95 'name' => $principal->GetProperty('displayname'),
96 'email' => $principal->GetProperty('email'),
97 'uri' => $c->protocol_server_port . $principal->url(),
98 ));
99 $feed_description = $collection->GetProperty('description');
100 if ( isset($feed_description) && $feed_description != '' ) $feed->setDescription($feed_description);
102 require_once('RRule-v2.php');
104 $need_zones = array();
105 $timezones = array();
106 while( $event = $qry->Fetch() ) {
107 if ( $event->caldav_type != 'VEVENT' && $event->caldav_type != 'VTODO' && $event->caldav_type != 'VJOURNAL') {
108 dbg_error_log( 'feed', 'Skipping peculiar "%s" component in VCALENDAR', $event->caldav_type );
109 continue;
111 $is_todo = ($event->caldav_type == 'VTODO');
113 $ical = new vComponent( $event->caldav_data );
114 $event_data = $ical->GetComponents('VTIMEZONE', false);
116 $item = $feed->createEntry();
117 $item->setId( $c->protocol_server_port_script . ConstructURL($event->dav_name) );
119 $dt_created = new RepeatRuleDateTime( $event->created );
120 $item->setDateCreated( $dt_created->epoch() );
122 $dt_modified = new RepeatRuleDateTime( $event->modified );
123 $item->setDateModified( $dt_modified->epoch() );
125 $summary = $event->summary;
126 $p_title = ($summary != '' ? $summary : translate('No summary'));
127 if ( $is_todo ) $p_title = "TODO: " . $p_title;
128 $item->setTitle($p_title);
130 $content = "";
132 $dt_start = new RepeatRuleDateTime($event->dtstart);
133 if ( $dt_start != null ) {
134 $p_time = '<strong>' . translate('Time') . ':</strong> ' . strftime(translate('%F %T'), $dt_start->epoch());
136 $dt_end = new RepeatRuleDateTime($event->dtend);
137 if ( $dt_end != null ) {
138 $p_time .= ' - ' . ( $dt_end->AsDate() == $dt_start->AsDate()
139 # Translators: his is the formatting of just the time. See http://php.net/manual/en/function.strftime.php
140 ? strftime(translate('%T'), $dt_end->epoch())
141 # Translators: this is the formatting of a date with time. See http://php.net/manual/en/function.strftime.php
142 : strftime(translate('%F %T'), $dt_end->epoch())
145 $content .= $p_time;
148 $p_location = $event_data[0]->GetProperty('LOCATION');
149 if ( $p_location != null )
150 $content .= '<br />'
151 .'<strong>' . translate('Location') . '</strong>: ' . hyperlink($p_location->Value());
153 $p_attach = $event_data[0]->GetProperty('ATTACH');
154 if ( $p_attach != null )
155 $content .= '<br />'
156 .'<strong>' . translate('Attachment') . '</strong>: ' . hyperlink($p_attach->Value());
158 $p_url = $event_data[0]->GetProperty('URL');
159 if ( $p_url != null )
160 $content .= '<br />'
161 .'<strong>' . translate('URL') . '</strong>: ' . hyperlink($p_url->Value());
163 $p_cat = $event_data[0]->GetProperty('CATEGORIES');
164 if ( $p_cat != null ) {
165 $content .= '<br />' .'<strong>' . translate('Categories') . '</strong>: ' . $p_cat->Value();
166 $categories = explode(',',$p_cat->Value());
167 foreach( $categories AS $category ) {
168 $item->addCategory( array('term' => trim($category)) );
172 $p_description = $event->description;
173 if ( $p_description != '' ) {
174 $content .= '<br />'
175 .'<br />'
176 .'<strong>' . translate('Description') . '</strong>:<br />' . ( nl2br(hyperlink($p_description)) )
178 $item->setDescription($p_description);
181 $item->setContent($content);
182 $feed->addEntry($item);
183 //break;
185 $last_modified = new RepeatRuleDateTime($collection->GetProperty('modified'));
186 $feed->setDateModified($last_modified->epoch());
187 $response = $feed->export('atom');
188 $cache->set( $cache_ns, $cache_key, $response );
189 return $response;
192 if ( $request->method == 'GET' ) {
193 $collection = new DAVResource($request->path);
194 $response = caldav_get_feed( $request, $collection );
195 header( 'Content-Length: '.strlen($response) );
196 header( 'Etag: '.$collection->unique_tag() );
197 $request->DoResponse( 200, ($request->method == 'HEAD' ? '' : $response), 'text/xml; charset="utf-8"' );
199 else {
200 dbg_error_log( 'feed', 'Unhandled request method >>%s<<', $request->method );
201 dbg_log_array( 'feed', '_SERVER', $_SERVER, true );
202 dbg_error_log( 'feed', 'RAW: %s', str_replace("\n", '',str_replace("\r", '', $request->raw_post)) );
205 $request->DoResponse( 500, translate('The application program does not understand that request.') );
207 /* vim: set ts=2 sw=2 tw=0 :*/