More fixes to CalDAV Scheduling
[davical.git] / inc / always.php.in
blob05a9ac229a5b843a57368474cf977bb680e23c18
1 <?php
2 /**
3 * @package davical
4 * @author Andrew McMillan <andrew@mcmillan.net.nz>
5 * @copyright Catalyst .Net Ltd, Morphoss Ltd <http://www.morphoss.com/>
6 * @license http://gnu.org/copyleft/gpl.html GNU GPL v2 or later
7 */
9 if ( preg_match('{/always.php$}', $_SERVER['SCRIPT_NAME'] ) ) header('Location: index.php');
11 // Ensure the configuration starts out as an empty object.
12 $c = (object) array();
13 $c->script_start_time = microtime(true);
15 // Ditto for a few other global things
16 unset($session); unset($request); unset($dbconn); unset($_awl_dbconn); unset($include_properties);
18 // An ultra-simple exception handler to catch errors that occur
19 // before we get a more functional exception handler in place...
20 function early_exception_handler($e) {
21 echo "Exception [".$e->getCode()."] ".$e->getmessage()."\n";
22 echo "At line ", $e->getLine(), " of ", $e->getFile(), "\n";
23 echo "================= Stack Trace ===================\n";
25 $trace = array_reverse($e->getTrace());
26 foreach( $trace AS $k => $v ) {
27 printf( "%s[%d] %s%s%s()\n", $v['file'], $v['line'], (isset($v['class'])?$v['class']:''), (isset($v['type'])?$v['type']:''), (isset($v['function'])?$v['function']:'') );
30 set_exception_handler('early_exception_handler');
32 // Default some of the configurable values
33 $c->sysabbr = 'davical';
34 $c->admin_email = 'admin@davical.example.com';
35 $c->system_name = 'DAViCal CalDAV Server';
36 $c->domain_name = (isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:$_SERVER['SERVER_ADDR']);
37 $c->save_time_zone_defs = true;
38 $c->collections_always_exist = false;
39 $c->allow_get_email_visibility = false;
40 $c->permission_scan_depth = 2;
41 $c->expand_pdo_parameters = true;
42 $c->home_calendar_name = 'calendar';
43 $c->home_addressbook_name = 'addresses';
44 $c->enable_row_linking = true;
45 $c->enable_scheduling = false;
46 $c->http_auth_mode = 'Basic';
47 // $c->default_locale = array('es_MX', 'es_AR', 'es', 'pt'); // An array of locales to try, or just a single locale
48 // $c->local_tzid = 'Pacific/Auckland'; // Perhaps we should read from /etc/timezone - I wonder how standard that is?
49 $c->default_locale = 'en';
50 $c->locale_path = '../locale';
51 $c->base_url = preg_replace('#/[^/]+\.php.*$#', '', $_SERVER['SCRIPT_NAME']);
52 $c->base_directory = preg_replace('#/[^/]*$#', '', $_SERVER['DOCUMENT_ROOT']);
53 $c->default_privileges = array('read-free-busy', 'schedule-deliver');
55 $c->enable_auto_schedule = true;
57 $c->stylesheets = array( $c->base_url.'/davical.css' );
58 $c->images = $c->base_url . '/images';
60 // Add a default for newly created users
61 $c->template_usr = array( 'active' => true,
62 'locale' => 'en_GB',
63 'date_format_type' => 'E',
64 'email_ok' => date('Y-m-d')
67 $c->hide_TODO = true; // VTODO only visible to collection owner
68 $c->readonly_webdav_collections = true; // WebDAV access is readonly
70 // Kind of private configuration values
71 $c->total_query_time = 0;
73 $c->dbg = array();
76 // Utilities
77 if ( ! @include_once('AWLUtilities.php') ) {
78 $try_paths = array(
79 '../../awl/inc'
80 , '/usr/share/awl/inc' // Where it ends up on Debian
81 , '/usr/share/php/awl/inc' // Fedora's standard for PHP libraries
82 , '/usr/local/share/awl/inc'
84 foreach( $try_paths AS $awl_include_path ) {
85 if ( @file_exists($awl_include_path.'/AWLUtilities.php') ) {
86 set_include_path( $awl_include_path. PATH_SEPARATOR. get_include_path());
87 break;
90 if ( ! @include_once('AWLUtilities.php') ) {
91 echo "Could not find the AWL libraries. Are they installed? Check your include_path in php.ini!\n";
92 exit;
96 // Ensure that ../inc is in our included paths as early as possible
97 set_include_path( '../inc'. PATH_SEPARATOR. get_include_path());
100 /** We actually discovered this and worked around it earlier, but we can't log it until the utilties are loaded */
101 if ( !isset($_SERVER['SERVER_NAME']) ) {
102 @dbg_error_log( 'WARN', "Your webserver is not setting the SERVER_NAME parameter. You may need to set \$c->domain_name in your configuration. Using IP address meanhwhile..." );
106 * Calculate the simplest form of reference to this page, excluding the PATH_INFO following the script name.
108 $c->protocol_server_port = sprintf( '%s://%s%s',
109 (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? 'https' : 'http'),
110 $_SERVER['SERVER_NAME'],
112 ( (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')
113 && (!isset($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == 80) )
114 || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
115 && (!isset($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == 443) )
116 ? ''
117 : ':'.$_SERVER['SERVER_PORT']
118 ) );
119 $c->protocol_server_port_script = $c->protocol_server_port . ($_SERVER['SCRIPT_NAME'] == '/index.php' ? '' : $_SERVER['SCRIPT_NAME']);
123 * We use @file_exists because things like open_basedir might noisily deny
124 * access which could break DAViCal completely by causing output to start
125 * too early.
127 ob_start( );
128 if ( @file_exists('/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php') ) {
129 include('/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php');
131 else if ( @file_exists('/etc/davical/config.php') ) {
132 include('/etc/davical/config.php');
134 else if ( @file_exists('/usr/local/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php') ) {
135 include('/usr/local/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php');
137 else if ( @file_exists('/usr/local/etc/davical/config.php') ) {
138 include('/usr/local/etc/davical/config.php');
140 else if ( @file_exists('../config/config.php') ) {
141 include('../config/config.php');
143 else if ( @file_exists('config/config.php') ) {
144 include('config/config.php');
146 else {
147 include('davical_configuration_missing.php');
148 exit;
150 $config_warnings = trim(ob_get_contents());
151 ob_end_clean();
153 if ( !isset($c->page_title) ) $c->page_title = $c->system_name;
155 if ( isset($_SERVER['HTTP_X_DAVICAL_TESTCASE']) ) {
156 @dbg_error_log( 'LOG', '==========> Test case =%s=', $_SERVER['HTTP_X_DAVICAL_TESTCASE'] );
158 else if ( isset($c->dbg['script_start']) && $c->dbg['script_start'] ) {
159 // Only log this if more than a little debugging of some sort is turned on, somewhere
160 @dbg_error_log( 'LOG', '==========> method =%s= =%s= =%s= =%s= =%s=',
161 $_SERVER['REQUEST_METHOD'], $c->protocol_server_port_script, $_SERVER['PATH_INFO'], $c->base_url, $c->base_directory );
165 * Now that we have loaded the configuration file we can switch to a
166 * default site locale. This may be overridden by each user.
168 putenv("LANG=". $c->default_locale);
169 awl_set_locale($c->default_locale);
170 init_gettext( 'davical', $c->locale_path );
173 * Work out our version
176 $c->code_version = 0;
177 $c->want_awl_version = 0.46;
178 $c->version_string = '0.9.9.4'; // The actual version # is replaced into that during the build /release process
179 if ( isset($c->version_string) && preg_match( '/(\d+)\.(\d+)\.(\d+)(.*)/', $c->version_string, $matches) ) {
180 $c->code_major = $matches[1];
181 $c->code_minor = $matches[2];
182 $c->code_patch = $matches[3];
183 $c->code_version = (($c->code_major * 1000) + $c->code_minor).'.'.$c->code_patch;
184 dbg_error_log('caldav', 'Version (%d.%d.%d) == %s', $c->code_major, $c->code_minor, $c->code_patch, $c->code_version);
185 header( sprintf('Server: %d.%d', $c->code_major, $c->code_minor) );
189 * Force the domain name to what was in the configuration file
191 $_SERVER['SERVER_NAME'] = $c->domain_name;
193 require_once('AwlQuery.php');
195 $c->want_dbversion = array(1,2,9);
196 $c->schema_version = 0;
197 $qry = new AwlQuery( 'SELECT schema_major, schema_minor, schema_patch FROM awl_db_revision ORDER BY schema_id DESC LIMIT 1;' );
198 if ( $qry->Exec('always',__LINE__,__FILE__) && $row = $qry->Fetch() ) {
199 $c->schema_version = doubleval( sprintf( '%d%03d.%03d', $row->schema_major, $row->schema_minor, $row->schema_patch) );
200 $c->wanted_version = doubleval( sprintf( '%d%03d.%03d', $c->want_dbversion[0], $c->want_dbversion[1], $c->want_dbversion[2]) );
201 $c->schema_major = $row->schema_major;
202 $c->schema_minor = $row->schema_minor;
203 $c->schema_patch = $row->schema_patch;
204 if ( $c->schema_version < $c->wanted_version ) {
205 $c->messages[] = sprintf( 'Database schema needs upgrading. Current: %d.%d.%d, Desired: %d.%d.%d',
206 $row->schema_major, $row->schema_minor, $row->schema_patch, $c->want_dbversion[0], $c->want_dbversion[1], $c->want_dbversion[2]);
208 if ( isset($_SERVER['HTTP_X_DAVICAL_TESTCASE']) ) $qry->QDo('SET TIMEZONE TO \'Pacific/Auckland\'');
211 require_once('Principal.php');
214 * Return the HTTP status code description for a given code. Hopefully
215 * this is an efficient way to code this.
216 * @return string The text for a give HTTP status code, in english
218 function getStatusMessage($status) {
219 switch( $status ) {
220 case 100: $ans = 'Continue'; break;
221 case 101: $ans = 'Switching Protocols'; break;
222 case 200: $ans = 'OK'; break;
223 case 201: $ans = 'Created'; break;
224 case 202: $ans = 'Accepted'; break;
225 case 203: $ans = 'Non-Authoritative Information'; break;
226 case 204: $ans = 'No Content'; break;
227 case 205: $ans = 'Reset Content'; break;
228 case 206: $ans = 'Partial Content'; break;
229 case 207: $ans = 'Multi-Status'; break;
230 case 300: $ans = 'Multiple Choices'; break;
231 case 301: $ans = 'Moved Permanently'; break;
232 case 302: $ans = 'Found'; break;
233 case 303: $ans = 'See Other'; break;
234 case 304: $ans = 'Not Modified'; break;
235 case 305: $ans = 'Use Proxy'; break;
236 case 307: $ans = 'Temporary Redirect'; break;
237 case 400: $ans = 'Bad Request'; break;
238 case 401: $ans = 'Unauthorized'; break;
239 case 402: $ans = 'Payment Required'; break;
240 case 403: $ans = 'Forbidden'; break;
241 case 404: $ans = 'Not Found'; break;
242 case 405: $ans = 'Method Not Allowed'; break;
243 case 406: $ans = 'Not Acceptable'; break;
244 case 407: $ans = 'Proxy Authentication Required'; break;
245 case 408: $ans = 'Request Timeout'; break;
246 case 409: $ans = 'Conflict'; break;
247 case 410: $ans = 'Gone'; break;
248 case 411: $ans = 'Length Required'; break;
249 case 412: $ans = 'Precondition Failed'; break;
250 case 413: $ans = 'Request Entity Too Large'; break;
251 case 414: $ans = 'Request-URI Too Long'; break;
252 case 415: $ans = 'Unsupported Media Type'; break;
253 case 416: $ans = 'Requested Range Not Satisfiable'; break;
254 case 417: $ans = 'Expectation Failed'; break;
255 case 422: $ans = 'Unprocessable Entity'; break;
256 case 423: $ans = 'Locked'; break;
257 case 424: $ans = 'Failed Dependency'; break;
258 case 500: $ans = 'Internal Server Error'; break;
259 case 501: $ans = 'Not Implemented'; break;
260 case 502: $ans = 'Bad Gateway'; break;
261 case 503: $ans = 'Service Unavailable'; break;
262 case 504: $ans = 'Gateway Timeout'; break;
263 case 505: $ans = 'HTTP Version Not Supported'; break;
264 default: $ans = 'Unknown HTTP Status Code '.$status;
266 return $ans;
271 * Construct a URL from the supplied dav_name. The URL will be urlencoded,
272 * except for any '/' characters in it.
273 * @param string $partial_path The part of the path after the script name
275 function ConstructURL( $partial_path, $force_script = false ) {
276 global $c;
278 $partial_path = rawurlencode($partial_path);
279 $partial_path = str_replace( '%2F', '/', $partial_path);
281 if ( ! isset($c->_url_script_path) ) {
282 $c->protocol_server_port_script = str_replace( 'index.php', 'caldav.php', $c->protocol_server_port_script);
283 $c->_url_script_path = (preg_match('#/$#', $c->protocol_server_port_script) ? 'caldav.php' : '');
284 $c->_url_script_path = $c->protocol_server_port_script . $c->_url_script_path;
287 $url = $c->_url_script_path;
288 if ( $force_script ) {
289 if ( ! preg_match( '#/caldav\.php$#', $url ) ) $url .= '/caldav.php';
291 $url .= $partial_path;
292 $url = preg_replace( '#^(https?://.+)//#', '$1/', $url ); // Ensure we don't double any '/'
293 $url = preg_replace('#^https?://[^/]+#', '', $url ); // Remove any protocol + hostname portion
295 return $url;
300 * Deconstruct a dav_name from the supplied URL. The dav_name will be urldecoded.
302 * @param string $partial_path The part of the path after the script name
304 function DeconstructURL( $url, $force_script = false ) {
305 global $c;
307 $dav_name = rawurldecode($url);
309 /** Allow a path like .../username/calendar.ics to translate into the calendar URL */
310 if ( preg_match( '#^(/[^/]+/[^/]+).ics$#', $dav_name, $matches ) ) {
311 $dav_name = $matches[1]. '/';
314 /** remove any leading protocol/server/port/prefix... */
315 if ( !isset($c->deconstruction_base_path) ) $c->deconstruction_base_path = ConstructURL('/');
316 if ( preg_match( '%^(.*?)'.str_replace('%', '\\%',$c->deconstruction_base_path).'(.*)$%', $dav_name, $matches ) ) {
317 if ( $matches[1] == '' || $matches[1] == $c->protocol_server_port ) {
318 $dav_name = $matches[2];
322 /** strip doubled slashes */
323 if ( strstr($dav_name,'//') ) $dav_name = preg_replace( '#//+#', '/', $dav_name);
325 if ( substr($dav_name,0,1) != '/' ) $dav_name = '/'.$dav_name;
327 return $dav_name;
332 * Convert a date from ISO format into the sad old HTTP format.
333 * @param string $isodate The date to convert
335 function ISODateToHTTPDate( $isodate ) {
336 // Use strtotime since strptime is not available on Windows platform.
337 return( gmstrftime('%a, %d %b %Y %H:%M:%S GMT', strtotime($isodate)) );
341 * Convert a date into ISO format into the sparkly new ISO format.
342 * @param string $indate The date to convert
344 function DateToISODate( $indate, $in_utc=false ) {
345 // Use strtotime since strptime is not available on Windows platform.
346 if ( $in_utc ) return( gmdate('Ymd\THis\Z', strtotime($indate)) );
347 return( date('c', strtotime($indate)) );
351 * Given a privilege string, or an array of privilege strings, return a bit mask
352 * of the privileges.
353 * @param mixed $raw_privs The string (or array of strings) of privilege names
354 * @return integer A bit mask of the privileges.
356 define("DAVICAL_MAXPRIV", "65535");
357 define("DAVICAL_ADDRESSBOOK_MAXPRIV", "1023");
358 function privilege_to_bits( $raw_privs ) {
359 $out_priv = 0;
361 if ( gettype($raw_privs) == 'string' ) $raw_privs = array( $raw_privs );
363 if ( ! is_array($raw_privs) ) $raw_privs = array($raw_privs);
365 foreach( $raw_privs AS $priv ) {
366 $trim_priv = trim(strtolower(preg_replace( '/^.*:/', '', $priv)));
367 switch( $trim_priv ) {
368 case 'read' : $out_priv |= 1; break;
369 case 'write-properties' : $out_priv |= 2; break;
370 case 'write-content' : $out_priv |= 4; break;
371 case 'unlock' : $out_priv |= 8; break;
372 case 'read-acl' : $out_priv |= 16; break;
373 case 'read-current-user-privilege-set' : $out_priv |= 32; break;
374 case 'bind' : $out_priv |= 64; break;
375 case 'unbind' : $out_priv |= 128; break;
376 case 'write-acl' : $out_priv |= 256; break;
377 case 'read-free-busy' : $out_priv |= 512; break;
378 case 'schedule-deliver-invite' : $out_priv |= 1024; break;
379 case 'schedule-deliver-reply' : $out_priv |= 2048; break;
380 case 'schedule-query-freebusy' : $out_priv |= 4096; break;
381 case 'schedule-send-invite' : $out_priv |= 8192; break;
382 case 'schedule-send-reply' : $out_priv |= 16384; break;
383 case 'schedule-send-freebusy' : $out_priv |= 32768; break;
385 /** Aggregates of Privileges */
386 case 'write' : $out_priv |= 198; break; // 2 + 4 + 64 + 128
387 case 'schedule-deliver' : $out_priv |= 7168; break; // 1024 + 2048 + 4096
388 case 'schedule-send' : $out_priv |= 57344; break; // 8192 + 16384 + 32768
389 case 'all' : $out_priv = DAVICAL_MAXPRIV; break;
390 case 'fake_privilege_for_input' : break;
391 default:
392 dbg_error_log( 'ERROR', 'Cannot convert privilege of "%s" into bits.', $priv );
397 // 'all' will include future privileges
398 if ( ($out_priv & DAVICAL_MAXPRIV) >= DAVICAL_MAXPRIV ) $out_priv = pow(2,24) - 1;
399 return $out_priv;
404 * Given a bit mask of the privileges, will return an array of the
405 * text values of privileges.
406 * @param integer $raw_bits A bit mask of the privileges.
407 * @return mixed The string (or array of strings) of privilege names
409 function bits_to_privilege( $raw_bits, $resourcetype = 'resource' ) {
410 $out_priv = array();
412 if ( is_string($raw_bits) ) {
413 $raw_bits = bindec($raw_bits);
416 if ( ($raw_bits & DAVICAL_MAXPRIV) == DAVICAL_MAXPRIV ) $out_priv[] = 'all';
418 if ( ($raw_bits & 1) != 0 ) $out_priv[] = 'DAV::read';
419 if ( ($raw_bits & 8) != 0 ) $out_priv[] = 'DAV::unlock';
420 if ( ($raw_bits & 16) != 0 ) $out_priv[] = 'DAV::read-acl';
421 if ( ($raw_bits & 32) != 0 ) $out_priv[] = 'DAV::read-current-user-privilege-set';
422 if ( ($raw_bits & 256) != 0 ) $out_priv[] = 'DAV::write-acl';
423 if ( ($resourcetype == 'calendar' || $resourcetype == 'proxy' || $resourcetype == '*') && ($raw_bits & 512) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:read-free-busy';
425 if ( ($raw_bits & 198) != 0 ) {
426 if ( ($raw_bits & 198) == 198 ) $out_priv[] = 'DAV::write';
427 if ( ($raw_bits & 2) != 0 ) $out_priv[] = 'DAV::write-properties';
428 if ( ($raw_bits & 4) != 0 ) $out_priv[] = 'DAV::write-content';
429 if ( ($raw_bits & 64) != 0 ) $out_priv[] = 'DAV::bind';
430 if ( ($raw_bits & 128) != 0 ) $out_priv[] = 'DAV::unbind';
433 if ( ($resourcetype == 'schedule-inbox' || $resourcetype == '*') && ($raw_bits & 7168) != 0 ) {
434 if ( ($raw_bits & 7168) == 7168 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-deliver';
435 if ( ($raw_bits & 1024) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-deliver-invite';
436 if ( ($raw_bits & 2048) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-deliver-reply';
437 if ( ($raw_bits & 4096) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-query-freebusy';
440 if ( ($resourcetype == 'schedule-outbox' || $resourcetype == '*') && ($raw_bits & 57344) != 0 ) {
441 if ( ($raw_bits & 57344) == 57344 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send';
442 if ( ($raw_bits & 8192) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send-invite';
443 if ( ($raw_bits & 16384) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send-reply';
444 if ( ($raw_bits & 32768) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send-freebusy';
447 // dbg_error_log( 'DAVResource', ' Privilege bit "%s" is "%s".', $raw_bits, implode(', ', $out_priv) );
449 return $out_priv;
454 * Returns the array of privilege names converted into XMLElements
456 function privileges_to_XML( $privilege_names, &$xmldoc=null ) {
457 if ( !isset($xmldoc) && isset($GLOBALS['reply']) ) $xmldoc = $GLOBALS['reply'];
458 $privileges = array();
459 foreach( $privilege_names AS $k ) {
460 $privilege = new XMLElement('privilege');
461 if ( isset($xmldoc) )
462 $xmldoc->NSElement($privilege,$k);
463 else
464 $privilege->NewElement($k);
465 $privileges[] = $privilege;
467 return $privileges;