Release 1.0.1
[davical.git] / htdocs / always.php
blob6f90c09d62ffdf268a82b8d486d5cd47fa47a714
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']:'') );
29 @ob_flush();
31 set_exception_handler('early_exception_handler');
33 // Default some of the configurable values
34 $c->sysabbr = 'davical';
35 $c->admin_email = 'admin@davical.example.com';
36 $c->system_name = 'DAViCal CalDAV Server';
37 $c->domain_name = (isset($_SERVER['SERVER_NAME'])?$_SERVER['SERVER_NAME']:$_SERVER['SERVER_ADDR']);
38 $c->save_time_zone_defs = true;
39 $c->collections_always_exist = false;
40 $c->allow_get_email_visibility = false;
41 $c->permission_scan_depth = 2;
42 $c->expand_pdo_parameters = true;
43 $c->home_calendar_name = 'calendar';
44 $c->home_addressbook_name = 'addresses';
45 $c->enable_row_linking = true;
46 $c->enable_scheduling = false;
47 $c->http_auth_mode = 'Basic';
48 // $c->default_locale = array('es_MX', 'es_AR', 'es', 'pt'); // An array of locales to try, or just a single locale
49 // $c->local_tzid = 'Pacific/Auckland'; // Perhaps we should read from /etc/timezone - I wonder how standard that is?
50 $c->default_locale = 'en';
51 $c->locale_path = '../locale';
52 $c->base_url = preg_replace('#/[^/]+\.php.*$#', '', $_SERVER['SCRIPT_NAME']);
53 $c->base_directory = preg_replace('#/[^/]*$#', '', $_SERVER['DOCUMENT_ROOT']);
54 $c->default_privileges = array('read-free-busy', 'schedule-deliver');
56 $c->enable_auto_schedule = true;
58 $c->stylesheets = array( $c->base_url.'/davical.css' );
59 $c->images = $c->base_url . '/images';
61 // Add a default for newly created users
62 $c->template_usr = array( 'active' => true,
63 'locale' => 'en_GB',
64 'date_format_type' => 'E',
65 'email_ok' => date('Y-m-d')
68 $c->hide_TODO = true; // VTODO only visible to collection owner
69 $c->readonly_webdav_collections = true; // WebDAV access is readonly
71 // Kind of private configuration values
72 $c->total_query_time = 0;
74 $c->dbg = array();
77 // Utilities
78 if ( ! @include_once('AWLUtilities.php') ) {
79 $try_paths = array(
80 '../../awl/inc'
81 , '/usr/share/awl/inc' // Where it ends up on Debian
82 , '/usr/share/php/awl/inc' // Fedora's standard for PHP libraries
83 , '/usr/local/share/awl/inc'
85 foreach( $try_paths AS $awl_include_path ) {
86 if ( @file_exists($awl_include_path.'/AWLUtilities.php') ) {
87 set_include_path( $awl_include_path. PATH_SEPARATOR. get_include_path());
88 break;
91 if ( ! @include_once('AWLUtilities.php') ) {
92 echo "Could not find the AWL libraries. Are they installed? Check your include_path in php.ini!\n";
93 @ob_flush(); exit(0);
97 // Ensure that ../inc is in our included paths as early as possible
98 set_include_path( '../inc'. PATH_SEPARATOR. get_include_path());
101 /** We actually discovered this and worked around it earlier, but we can't log it until the utilties are loaded */
102 if ( !isset($_SERVER['SERVER_NAME']) ) {
103 @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..." );
107 * Calculate the simplest form of reference to this page, excluding the PATH_INFO following the script name.
109 $c->protocol_server_port = sprintf( '%s://%s%s',
110 (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'? 'https' : 'http'),
111 $_SERVER['SERVER_NAME'],
113 ( (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != 'on')
114 && (!isset($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == 80) )
115 || (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
116 && (!isset($_SERVER['SERVER_PORT']) || $_SERVER['SERVER_PORT'] == 443) )
117 ? ''
118 : ':'.$_SERVER['SERVER_PORT']
119 ) );
120 $c->protocol_server_port_script = $c->protocol_server_port . ($_SERVER['SCRIPT_NAME'] == '/index.php' ? '' : $_SERVER['SCRIPT_NAME']);
124 * We use @file_exists because things like open_basedir might noisily deny
125 * access which could break DAViCal completely by causing output to start
126 * too early.
128 ob_start( );
129 if ( @file_exists('/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php') ) {
130 include('/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php');
132 else if ( @file_exists('/etc/davical/config.php') ) {
133 include('/etc/davical/config.php');
135 else if ( @file_exists('/usr/local/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php') ) {
136 include('/usr/local/etc/davical/'.$_SERVER['SERVER_NAME'].'-conf.php');
138 else if ( @file_exists('/usr/local/etc/davical/config.php') ) {
139 include('/usr/local/etc/davical/config.php');
141 else if ( @file_exists('../config/config.php') ) {
142 include('../config/config.php');
144 else if ( @file_exists('config/config.php') ) {
145 include('config/config.php');
147 else {
148 include('davical_configuration_missing.php');
149 @ob_flush(); exit(0);
151 $config_warnings = trim(ob_get_contents());
152 ob_end_clean();
154 if ( !isset($c->page_title) ) $c->page_title = $c->system_name;
156 if ( isset($_SERVER['HTTP_X_DAVICAL_TESTCASE']) ) {
157 @dbg_error_log( 'LOG', '==========> Test case =%s=', $_SERVER['HTTP_X_DAVICAL_TESTCASE'] );
159 else if ( isset($c->dbg['script_start']) && $c->dbg['script_start'] ) {
160 // Only log this if more than a little debugging of some sort is turned on, somewhere
161 @dbg_error_log( 'LOG', '==========> method =%s= =%s= =%s= =%s= =%s=',
162 $_SERVER['REQUEST_METHOD'], $c->protocol_server_port_script, $_SERVER['PATH_INFO'], $c->base_url, $c->base_directory );
166 * Now that we have loaded the configuration file we can switch to a
167 * default site locale. This may be overridden by each user.
169 putenv("LANG=". $c->default_locale);
170 awl_set_locale($c->default_locale);
171 init_gettext( 'davical', $c->locale_path );
174 * Work out our version
177 $c->code_version = 0;
178 $c->want_awl_version = '0.50';
179 $c->version_string = '1.0.1'; // The actual version # is replaced into that during the build /release process
180 if ( isset($c->version_string) && preg_match( '/(\d+)\.(\d+)\.(\d+)(.*)/', $c->version_string, $matches) ) {
181 $c->code_major = $matches[1];
182 $c->code_minor = $matches[2];
183 $c->code_patch = $matches[3];
184 $c->code_version = (($c->code_major * 1000) + $c->code_minor).'.'.$c->code_patch;
185 dbg_error_log('caldav', 'Version (%d.%d.%d) == %s', $c->code_major, $c->code_minor, $c->code_patch, $c->code_version);
186 header( sprintf('Server: %d.%d', $c->code_major, $c->code_minor) );
190 * Force the domain name to what was in the configuration file
192 $_SERVER['SERVER_NAME'] = $c->domain_name;
194 require_once('AwlQuery.php');
196 $c->want_dbversion = array(1,2,11);
197 $c->schema_version = 0;
198 $qry = new AwlQuery( 'SELECT schema_major, schema_minor, schema_patch FROM awl_db_revision ORDER BY schema_id DESC LIMIT 1;' );
199 if ( $qry->Exec('always',__LINE__,__FILE__) && $row = $qry->Fetch() ) {
200 $c->schema_version = doubleval( sprintf( '%d%03d.%03d', $row->schema_major, $row->schema_minor, $row->schema_patch) );
201 $c->wanted_version = doubleval( sprintf( '%d%03d.%03d', $c->want_dbversion[0], $c->want_dbversion[1], $c->want_dbversion[2]) );
202 $c->schema_major = $row->schema_major;
203 $c->schema_minor = $row->schema_minor;
204 $c->schema_patch = $row->schema_patch;
205 if ( $c->schema_version < $c->wanted_version ) {
206 $c->messages[] = sprintf( 'Database schema needs upgrading. Current: %d.%d.%d, Desired: %d.%d.%d',
207 $row->schema_major, $row->schema_minor, $row->schema_patch, $c->want_dbversion[0], $c->want_dbversion[1], $c->want_dbversion[2]);
209 if ( isset($_SERVER['HTTP_X_DAVICAL_TESTCASE']) ) $qry->QDo('SET TIMEZONE TO \'Pacific/Auckland\'');
212 require_once('Principal.php');
215 * Return the HTTP status code description for a given code. Hopefully
216 * this is an efficient way to code this.
217 * @return string The text for a give HTTP status code, in english
219 function getStatusMessage($status) {
220 switch( $status ) {
221 case 100: $ans = 'Continue'; break;
222 case 101: $ans = 'Switching Protocols'; break;
223 case 200: $ans = 'OK'; break;
224 case 201: $ans = 'Created'; break;
225 case 202: $ans = 'Accepted'; break;
226 case 203: $ans = 'Non-Authoritative Information'; break;
227 case 204: $ans = 'No Content'; break;
228 case 205: $ans = 'Reset Content'; break;
229 case 206: $ans = 'Partial Content'; break;
230 case 207: $ans = 'Multi-Status'; break;
231 case 300: $ans = 'Multiple Choices'; break;
232 case 301: $ans = 'Moved Permanently'; break;
233 case 302: $ans = 'Found'; break;
234 case 303: $ans = 'See Other'; break;
235 case 304: $ans = 'Not Modified'; break;
236 case 305: $ans = 'Use Proxy'; break;
237 case 307: $ans = 'Temporary Redirect'; break;
238 case 400: $ans = 'Bad Request'; break;
239 case 401: $ans = 'Unauthorized'; break;
240 case 402: $ans = 'Payment Required'; break;
241 case 403: $ans = 'Forbidden'; break;
242 case 404: $ans = 'Not Found'; break;
243 case 405: $ans = 'Method Not Allowed'; break;
244 case 406: $ans = 'Not Acceptable'; break;
245 case 407: $ans = 'Proxy Authentication Required'; break;
246 case 408: $ans = 'Request Timeout'; break;
247 case 409: $ans = 'Conflict'; break;
248 case 410: $ans = 'Gone'; break;
249 case 411: $ans = 'Length Required'; break;
250 case 412: $ans = 'Precondition Failed'; break;
251 case 413: $ans = 'Request Entity Too Large'; break;
252 case 414: $ans = 'Request-URI Too Long'; break;
253 case 415: $ans = 'Unsupported Media Type'; break;
254 case 416: $ans = 'Requested Range Not Satisfiable'; break;
255 case 417: $ans = 'Expectation Failed'; break;
256 case 422: $ans = 'Unprocessable Entity'; break;
257 case 423: $ans = 'Locked'; break;
258 case 424: $ans = 'Failed Dependency'; break;
259 case 500: $ans = 'Internal Server Error'; break;
260 case 501: $ans = 'Not Implemented'; break;
261 case 502: $ans = 'Bad Gateway'; break;
262 case 503: $ans = 'Service Unavailable'; break;
263 case 504: $ans = 'Gateway Timeout'; break;
264 case 505: $ans = 'HTTP Version Not Supported'; break;
265 default: $ans = 'Unknown HTTP Status Code '.$status;
267 return $ans;
272 * Construct a URL from the supplied dav_name. The URL will be urlencoded,
273 * except for any '/' characters in it.
274 * @param string $partial_path The part of the path after the script name
276 function ConstructURL( $partial_path, $force_script = false ) {
277 global $c;
279 $partial_path = rawurlencode($partial_path);
280 $partial_path = str_replace( '%2F', '/', $partial_path);
282 if ( ! isset($c->_url_script_path) ) {
283 $c->protocol_server_port_script = str_replace( 'index.php', 'caldav.php', $c->protocol_server_port_script);
284 $c->_url_script_path = (preg_match('#/$#', $c->protocol_server_port_script) ? 'caldav.php' : '');
285 $c->_url_script_path = $c->protocol_server_port_script . $c->_url_script_path;
288 $url = $c->_url_script_path;
289 if ( $force_script ) {
290 if ( ! preg_match( '#/caldav\.php$#', $url ) ) $url .= '/caldav.php';
292 $url .= $partial_path;
293 $url = preg_replace( '#^(https?://.+)//#', '$1/', $url ); // Ensure we don't double any '/'
294 $url = preg_replace('#^https?://[^/]+#', '', $url ); // Remove any protocol + hostname portion
296 return $url;
301 * Deconstruct a dav_name from the supplied URL. The dav_name will be urldecoded.
303 * @param string $partial_path The part of the path after the script name
305 function DeconstructURL( $url, $force_script = false ) {
306 global $c;
308 $dav_name = rawurldecode($url);
310 /** Allow a path like .../username/calendar.ics to translate into the calendar URL */
311 if ( preg_match( '#^(/[^/]+/[^/]+).ics$#', $dav_name, $matches ) ) {
312 $dav_name = $matches[1]. '/';
315 /** remove any leading protocol/server/port/prefix... */
316 if ( !isset($c->deconstruction_base_path) ) $c->deconstruction_base_path = ConstructURL('/');
317 if ( preg_match( '%^(.*?)'.str_replace('%', '\\%',$c->deconstruction_base_path).'(.*)$%', $dav_name, $matches ) ) {
318 if ( $matches[1] == '' || $matches[1] == $c->protocol_server_port ) {
319 $dav_name = $matches[2];
323 /** strip doubled slashes */
324 if ( strstr($dav_name,'//') ) $dav_name = preg_replace( '#//+#', '/', $dav_name);
326 if ( substr($dav_name,0,1) != '/' ) $dav_name = '/'.$dav_name;
328 return $dav_name;
333 * Convert a date from ISO format into the sad old HTTP format.
334 * @param string $isodate The date to convert
336 function ISODateToHTTPDate( $isodate ) {
337 // Use strtotime since strptime is not available on Windows platform.
338 return( gmstrftime('%a, %d %b %Y %H:%M:%S GMT', strtotime($isodate)) );
342 * Convert a date into ISO format into the sparkly new ISO format.
343 * @param string $indate The date to convert
345 function DateToISODate( $indate, $in_utc=false ) {
346 // Use strtotime since strptime is not available on Windows platform.
347 if ( $in_utc ) return( gmdate('Ymd\THis\Z', strtotime($indate)) );
348 return( date('c', strtotime($indate)) );
352 * Given a privilege string, or an array of privilege strings, return a bit mask
353 * of the privileges.
354 * @param mixed $raw_privs The string (or array of strings) of privilege names
355 * @return integer A bit mask of the privileges.
357 define("DAVICAL_MAXPRIV", "65535");
358 define("DAVICAL_ADDRESSBOOK_MAXPRIV", "1023");
359 function privilege_to_bits( $raw_privs ) {
360 $out_priv = 0;
362 if ( gettype($raw_privs) == 'string' ) $raw_privs = array( $raw_privs );
364 if ( ! is_array($raw_privs) ) $raw_privs = array($raw_privs);
366 foreach( $raw_privs AS $priv ) {
367 $trim_priv = trim(strtolower(preg_replace( '/^.*:/', '', $priv)));
368 switch( $trim_priv ) {
369 case 'read' : $out_priv |= 1; break;
370 case 'write-properties' : $out_priv |= 2; break;
371 case 'write-content' : $out_priv |= 4; break;
372 case 'unlock' : $out_priv |= 8; break;
373 case 'read-acl' : $out_priv |= 16; break;
374 case 'read-current-user-privilege-set' : $out_priv |= 32; break;
375 case 'bind' : $out_priv |= 64; break;
376 case 'unbind' : $out_priv |= 128; break;
377 case 'write-acl' : $out_priv |= 256; break;
378 case 'read-free-busy' : $out_priv |= 512; break;
379 case 'schedule-deliver-invite' : $out_priv |= 1024; break;
380 case 'schedule-deliver-reply' : $out_priv |= 2048; break;
381 case 'schedule-query-freebusy' : $out_priv |= 4096; break;
382 case 'schedule-send-invite' : $out_priv |= 8192; break;
383 case 'schedule-send-reply' : $out_priv |= 16384; break;
384 case 'schedule-send-freebusy' : $out_priv |= 32768; break;
386 /** Aggregates of Privileges */
387 case 'write' : $out_priv |= 198; break; // 2 + 4 + 64 + 128
388 case 'schedule-deliver' : $out_priv |= 7168; break; // 1024 + 2048 + 4096
389 case 'schedule-send' : $out_priv |= 57344; break; // 8192 + 16384 + 32768
390 case 'all' : $out_priv = DAVICAL_MAXPRIV; break;
391 case 'fake_privilege_for_input' : break;
392 default:
393 dbg_error_log( 'ERROR', 'Cannot convert privilege of "%s" into bits.', $priv );
398 // 'all' will include future privileges
399 if ( ($out_priv & DAVICAL_MAXPRIV) >= DAVICAL_MAXPRIV ) $out_priv = pow(2,24) - 1;
400 return $out_priv;
405 * Given a bit mask of the privileges, will return an array of the
406 * text values of privileges.
407 * @param integer $raw_bits A bit mask of the privileges.
408 * @return mixed The string (or array of strings) of privilege names
410 function bits_to_privilege( $raw_bits, $resourcetype = 'resource' ) {
411 $out_priv = array();
413 if ( is_string($raw_bits) ) {
414 $raw_bits = bindec($raw_bits);
417 if ( ($raw_bits & DAVICAL_MAXPRIV) == DAVICAL_MAXPRIV ) $out_priv[] = 'all';
419 if ( ($raw_bits & 1) != 0 ) $out_priv[] = 'DAV::read';
420 if ( ($raw_bits & 8) != 0 ) $out_priv[] = 'DAV::unlock';
421 if ( ($raw_bits & 16) != 0 ) $out_priv[] = 'DAV::read-acl';
422 if ( ($raw_bits & 32) != 0 ) $out_priv[] = 'DAV::read-current-user-privilege-set';
423 if ( ($raw_bits & 256) != 0 ) $out_priv[] = 'DAV::write-acl';
424 if ( ($resourcetype == 'calendar' || $resourcetype == 'proxy' || $resourcetype == '*') && ($raw_bits & 512) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:read-free-busy';
426 if ( ($raw_bits & 198) != 0 ) {
427 if ( ($raw_bits & 198) == 198 ) $out_priv[] = 'DAV::write';
428 if ( ($raw_bits & 2) != 0 ) $out_priv[] = 'DAV::write-properties';
429 if ( ($raw_bits & 4) != 0 ) $out_priv[] = 'DAV::write-content';
430 if ( ($raw_bits & 64) != 0 ) $out_priv[] = 'DAV::bind';
431 if ( ($raw_bits & 128) != 0 ) $out_priv[] = 'DAV::unbind';
434 if ( ($resourcetype == 'schedule-inbox' || $resourcetype == '*') && ($raw_bits & 7168) != 0 ) {
435 if ( ($raw_bits & 7168) == 7168 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-deliver';
436 if ( ($raw_bits & 1024) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-deliver-invite';
437 if ( ($raw_bits & 2048) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-deliver-reply';
438 if ( ($raw_bits & 4096) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-query-freebusy';
441 if ( ($resourcetype == 'schedule-outbox' || $resourcetype == '*') && ($raw_bits & 57344) != 0 ) {
442 if ( ($raw_bits & 57344) == 57344 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send';
443 if ( ($raw_bits & 8192) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send-invite';
444 if ( ($raw_bits & 16384) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send-reply';
445 if ( ($raw_bits & 32768) != 0 ) $out_priv[] = 'urn:ietf:params:xml:ns:caldav:schedule-send-freebusy';
448 // dbg_error_log( 'DAVResource', ' Privilege bit "%s" is "%s".', $raw_bits, implode(', ', $out_priv) );
450 return $out_priv;
455 * Returns the array of privilege names converted into XMLElements
457 function privileges_to_XML( $privilege_names, &$xmldoc=null ) {
458 if ( !isset($xmldoc) && isset($GLOBALS['reply']) ) $xmldoc = $GLOBALS['reply'];
459 $privileges = array();
460 foreach( $privilege_names AS $k ) {
461 $privilege = new XMLElement('privilege');
462 if ( isset($xmldoc) )
463 $xmldoc->NSElement($privilege,$k);
464 else
465 $privilege->NewElement($k);
466 $privileges[] = $privilege;
468 return $privileges;