]> git.datanom.net - webcal.git/blame - utils/helper.php
Initial upload
[webcal.git] / utils / helper.php
CommitLineData
a5eae6b7
MR
1<?php
2/* $Id$ */
3include_once 'config.inc.php';
4require_once 'persistens.php';
5
6define('MICRO', 1);
7define('MINOR', 8);
8define('MAJOR', 0);
9
10$VERSION = MAJOR.".".MINOR.".".MICRO;
11$CURRENT_VERSION = $VERSION;
12$PREFIX = TOP_FOLDER."/install/".DBDRIVER;
13$PATCH_SET = array(
14 "173" => "db_upgrade_0_7_3.sql",
15 "174" => "db_upgrade_0_7_4.sql",
16 "175" => "db_upgrade_0_7_5.sql",
17 "180" => "db_upgrade_0_8_0.sql",
18 "181" => "db_upgrade_0_8_1.sql",
19);
20
21$pwd = WEB_ROOT;
22if ($pwd[strlen($pwd)-1] == '/')
23 $pwd = substr($pwd, 0, -1);
24
25function string2int($str) {
26 if (is_numeric($str))
27 return $str;
28 if (is_string($str)) {
29 $parts = explode(".", $str);
30 $str = 0;
31 for ($i = 0; $i < count($parts); $i++) {
32 $num = ($i == 0) ? $parts[$i] + 1 : $parts[$i];
33 $str += (pow(10, count($parts) - $i - 1) * $num);
34 }
35 }
36 return $str;
37}
38
39function getServerUrl($root = WEB_ROOT, $cwd = "") {
40 $root = (! empty($root) && $root[0] == '/') ? substr($root, 1) : $root;
41 $root = (! empty($root) && $root[strlen($root) - 1] == '/') ? substr($root, 0, -1) : $root;
42 $cwd = (! empty($cwd) && $cwd[0] == '/') ? substr($cwd, 1) : $cwd;
43 $cwd = (! empty($cwd) && $cwd[strlen($cwd) - 1] == '/') ? substr($cwd, 0, -1) : $cwd;
44
45 //echo var_export($_SERVER, true);
46 $protocol = ((isset($_SERVER['HTTPS']) && ! empty($_SERVER['HTTPS'])) || (isset($_SERVER['HTTPS']) && strcasecmp("on", $_SERVER['HTTPS']) === 0)
47 || (isset($_SERVER['HTTP_SCHEME']) && strcasecmp("https", $_SERVER['HTTP_SCHEME']) === 0)) ? "https" : "http";
48 //echo "$protocol<br/>";
49 $server = ($_SERVER['SERVER_PORT'] == 80 || $_SERVER['SERVER_PORT'] == 443)?
50 $_SERVER['SERVER_NAME'] : $_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'];
51 $url = (! empty($cwd)) ? "$protocol://$server/$cwd" : "$protocol://$server";
52
53 return "$url/$root";
54}
55
56function getServerUri() {
57 return TOP_FOLDER;
58}
59
60function createKey($key) {
61 $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
62 $public = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);
63 $ks = mcrypt_enc_get_key_size($td);
64 mcrypt_module_close($td);
65
66 /* Create key */
67 $secret = substr($key, 0, $ks);
68 return array($secret, $public);
69}
70
71function encode($text) {
72 /* Intialize encryption */
73 $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
74 $iv = $_SESSION['authenticate']->getPublicKey();
75 $key = $_SESSION['authenticate']->getSecretKey();
76
77 mcrypt_generic_init($td, $key, $iv);
78
79 /* Encrypt data */
80 $ciffer = mcrypt_generic($td, $text);
81 $encrypted = quoted_printable_encode($ciffer);
82
83 /* Terminate encryption handler */
84 mcrypt_generic_deinit($td);
85 mcrypt_module_close($td);
86
87 return $encrypted;
88}
89
90function decode($text) {
91 $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');
92 $iv = $_SESSION['authenticate']->getPublicKey();
93 $key = $_SESSION['authenticate']->getSecretKey();
94
95 /* Initialize encryption module for decryption */
96 mcrypt_generic_init($td, $key, $iv);
97
98 /* Decrypt encrypted string */
99 $ciffer = quoted_printable_decode($text);
100 $decrypted = mdecrypt_generic($td, $ciffer);
101
102 /* Terminate decryption handle and close module */
103 mcrypt_generic_deinit($td);
104 mcrypt_module_close($td);
105
106 return $decrypted;
107}
108
109function implode_cal($text) {
110 $infos = explode("\n", $text);
111 foreach ($infos as $info) {
112 $row = explode('=', $info);
113 $result[$row[0]] = $row[1];
114 }
115 return $result;
116}
117
118// taken from roundcubemail
119if (!function_exists("quoted_printable_encode")) {
120 function quoted_printable_encode($text) {
121 $length=strlen($text);
122 for ($whitespace= "", $line=0,$encode= "",
123 $index=0;$index<$length;$index++) {
124 $character=substr($text,$index,1);
125 $order=Ord($character);
126 $encode=0;
127 switch($order) {
128 case 9:
129 case 32:
130 if ($header_charset== "") {
131 $previous_whitespace=$whitespace;
132 $whitespace=$character;
133 $character= "";
134 }
135 else {
136 if ($order==32)
137 $character= "_";
138 else
139 $encode=1;
140 }
141 break;
142 case 10:
143 case 13:
144 if ($whitespace!= "") {
145 if ($line+3>75) {
146 $encoded.= "=\n";
147 $line=0;
148 }
149 $encoded.=sprintf( "=%02X",Ord($whitespace));
150 $line+=3;
151 $whitespace= "";
152 }
153 $encoded.=$character;
154 $line=0;
155 continue 2;
156 default:
157 if ($order > 127 || $order < 32 || $character == "="
158 || ($character == "?" || $character == "_" ||
159 $character == "(" || $character== ")"))
160 $encode=1;
161 break;
162 }
163 if ($whitespace!= "") {
164 if ($line+1>75) {
165 $encoded.= "=\n";
166 $line=0;
167 }
168 $encoded.=$whitespace;
169 $line++;
170 $whitespace= "";
171 }
172 if ($character!= "") {
173 if($encode) {
174 $character=sprintf( "=%02X",$order);
175 $encoded_length=3;
176 }
177 else
178 $encoded_length=1;
179 if ($line+$encoded_length > 75) {
180 $encoded.= "=\n";
181 $line=0;
182 }
183 $encoded.=$character;
184 $line+=$encoded_length;
185 }
186 }
187 if ($whitespace!= "") {
188 if ($line+3>75)
189 $encoded.= "=\n";
190 $encoded.=sprintf( "=%02X",Ord($whitespace));
191 }
192 return $encoded;
193 }
194}
195
196function newUpdates() {
197 global $VERSION, $CURRENT_VERSION;
198
199 $con = Persistens::getInstance(DBDRIVER);
200 try {
201 $res = $con->getVersion();
202 }
203 catch (Exception $e) {
204 ReportError($e);
205 }
206 $version = $res['version'];
207 $version = string2int($version);
208 if (! is_numeric($version)) {
209 ReportError("Invalid version format");
210 exit;
211 }
212 $CURRENT_VERSION = $version;
213 //file_put_contents('/tmp/updates', string2int($VERSION)." > $version", FILE_APPEND);
214 return string2int($VERSION) > $version;
215}
216
217function upgrade() {
218 global $VERSION, $PATCH_SET, $CURRENT_VERSION, $PREFIX;
219 $table = 'backup';
220
221 $version = string2int($CURRENT_VERSION);
222 $con = Persistens::getInstance(DBDRIVER);
223 try {
224 $res = $con->getVersion();
225 }
226 catch (Exception $e) {
227 ReportError($e);
228 exit;
229 }
230 if (($num = $con->nextTableNumber('backup')) > 0)
231 $table .= $num;
232
233 if ($version < 173) {
234 if (($res = $con->execute(
235 "create table $table as select * from calendar")) !== true) {
236 ReportError($res);
237 exit;
238 }
239 $rows = $con->getCalendarConfig();
240 if (! is_array($rows)) {
241 ReportError($rows);
242 exit;
243 }
244 foreach($rows as $row) {
245 if (function_exists(quoted_printable_encode))
246 $ciffer = quoted_printable_encode($row['config']);
247 else
248 $ciffer = webcal_quoted_printable_encode($row['config']);
249 if (($res = $con->execute("begin transaction")) !== true) {
250 ReportError($res);
251 exit;
252 }
253 if (($res = $con->execute(
254 "update calendar set config = '$ciffer' where id = " .
255 $row['id'])) !== true) {
256 $con->execute("rollback");
257 ReportError($res."<br/>A backup of your calendar data can be found in table backup");
258 exit;
259 }
260 }
261 $con->execute("commit");
262 }
263 if ($version >= 174) {
264 // remove pgsql.php from root. Accidentally placed there in release 0.7.4
265 if (file_exists(TOP_FOLDER."/pgsql.php"))
266 unlink(TOP_FOLDER."/pgsql.php");
267 // patch config.inc.php
268 if (substr(PHP_OS, 0, 3) !== 'WIN') {
269 $oldcwd = getcwd();
270 $cwd = TOP_FOLDER.'/install';
271 chdir($cwd);
272 if ($version < 181) {
273 exec("patch -p0 < config.inc.php.patch");
274 }
275 if ($version > 180) {
276 exec("patch -p0 < config.inc.php1.patch");
277 }
278 chdir($oldcwd);
279 }
280 }
281 foreach ($PATCH_SET as $set => $file) {
282 $content = array();
283 //echo "$set -> $file<br/>";
284 if ($version < $set) {
285 //echo $PREFIX."_".$file."<br/>";
286 if (! file_exists($PREFIX."_".$file))
287 continue;
288 $sql = file_get_contents($PREFIX."_".$file);
289 $raw_lines = explode("\n", $sql);
290 foreach ($raw_lines as $line) {
291 if (preg_match("/^--/", $line))
292 continue;
293 $content[] = $line;
294 }
295 $lines = explode(";", join("\n", $content));
296 if (count($lines) > 0) {
297 if (($res = $con->execute("begin transaction")) !== true) {
298 ReportError($res);
299 exit;
300 }
301 foreach ($lines as $line) {
302 $line = trim($line);
303 if (preg_match("/^\s*$/", $line) || preg_match("/^--/", $line))
304 continue;
305 if (($res = $con->execute($line)) !== true) {
306 ReportError($res);
307 $con->execute("rollback");
308 exit;
309 }
310 }
311 $con->execute("commit");
312 }
313 }
314 else
315 continue;
316 }
317}
318
319function ReportError($msg) {
320 // be sure that the supplied parameter is a string and not empty
321 if (empty ($msg) || !is_string ($msg)) {
322 throw new ErrorException ('Invalid parameter supplied to ReportError', 0, E_ERROR);
323 }
324
325 // retrieve error settings
326 $display = strtolower(ini_get('display_errors'));
327 $log = strtolower(ini_get('log_errors'));
328
329 // check if we're displaying errors
330 if ($display === 'on' || $display === '1' || $display === 1 || $display === 'true' || $display === true) {
331 echo $msg;
332 }
333 else {
334 $pwd = WEB_ROOT;
335 if ($pwd[strlen($pwd)-1] == '/')
336 $pwd = substr($pwd, 0, -1);
337 print '<?xml version="1.0" encoding="utf-8"?>
338<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
339 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
340<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
341 <head>
342 <title>Web Calendar</title>
343 <link rel="stylesheet" type="text/css"
344 href="'.$pwd.'/css/top_level.css" />
345 <link rel="shortcut icon"
346 href="'.$pwd.'/pixmaps/favicon.ico" />
347 </head>
348 <body>
349 <div id="error_msg">
350 <p>
351 The application has triggered an error which is not
352 recoverable. The execution has therefore been cancelled.
353 <br/><br/>
354 The error is logged and the webmaster will handle
355 the error in due time.
356 <br/><br/>
357 To help fix the application you are welcome to notify
358 the <a href="mailto:'.$_SERVER['SERVER_ADMIN'].'
359 ?subject='.TITLE.': error report['.
360 $_SERVER['SERVER_NAME'].']">webmaster</a>
361 by email with a detailed description containing the
362 following information:
363 <br/><br/>
364 1) What did you do just before this message occurred<br/>
365 2) What did you expect to happen<br/>
366 3) Your browser name and version number.<br/>
367 </p>
368 </div>
369 </body>
370</html>';
371 }
372
373 // check if we're logging errors
374 if ($log === 'on' || $log === '1' || $log === 1 || $log === 'true' || $log === true) {
375 $result = error_log ($msg);
376
377 // check for error while logging
378 if (!$result) {
379 throw new ErrorException ('Attempt to write message to error log failed in ReportError', 0, E_ERROR);
380 }
381 }
382}
383
384function create_user_data($uid, $pwd, $role) {
385 $data = array();
386
387 $data['uid'] = $uid;
388 $data['pwd'] = sha1($pwd);
389 $data['userrole'] = $role;
390 $keys = createKey(sha1("{$data['uid']}{$data['pwd']}"));
391 $data['seckey'] = $keys[0];
392 $data['pubkey'] = $keys[1];
393 $data['timezone'] = TIMEZONE;
394 $data['view'] = VIEW_STYLE;
395 $data['timeout'] = TIMEOUT;
396 $data['week_start'] = WEEK_START_SUNDAY;
397 $data['start'] = START_HOUR;
398 $data['end'] = END_HOUR;
399
400 return $data;
401}
402
403function popup_window($text = '', $redirect = NULL, $form_elem = array(), $title = NULL) {
404 $con = Persistens::getInstance(DBDRIVER);
405 if (! is_array($res = $con->getVersion())) {
406 ErrorReport($res);
407 }
408
409 $title = ($title) ? $title : TITLE;
410 /* deprecated */
411 if (count($form_elem) < 1) {
412 $form = NULL;
413 $input = NULL;
414 }
415 else {
416 $form = key($form_elem);
417 $input = $form_elem[$form];
418 }
419 /* end deprecated */
420 $referer = ($redirect) ? urldecode($redirect) : WEB_ROOT;
421 //print "$referer<br/>";
422 //exit;
423 $pwd = WEB_ROOT;
424$head = <<<__HEAD
425<?xml version="1.0" encoding="utf-8"?>
426<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
427 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
428<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
429<head>
430<title>$title</title>
431<meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8"/>
432<meta http-equiv="content-style-type" content="text/css"/>
433<link rel="stylesheet" type="text/css" href="$pwd/css/top_level.css" />
434<link rel="shortcut icon" href="$pwd/pixmaps/favicon.ico" />
435<style type="text/css">
436<!--
437#display_overlay_holder {
438 width: 100%;
439 height: 100%;
440 position: absolute;
441 top: 0px;
442 left: 0px;
443 display:none;
444}
445#display_overlay_bg {
446 position: absolute;
447 left: 0px;
448 top: 0px;
449 width: 100%;
450 height: 100%;
451 background-color:#000000;
452 opacity: 0.55;
453 filter: alpha(opacity=85);
454}
455#display_horizon {
456 position: absolute;
457 top: 45%;
458 left: 0px;
459 width: 100%;
460 height: 1px;
461 overflow: visible;
462}
463#display_content {
464 position: absolute;
465 width: 400px;
466 height: 250px;
467 left: 50%;
468 margin-left: -200px;
469 top: -125px;
470 background-color: #CCCCCC;
471}
472#text_content {
473 font-size: 0.8em;
474 color: blue;
475}
476-->
477</style>
478<script type="text/javascript" src="$pwd/js/helper.js"></script>
479</head>
480<body onload="show_the_overlay()">
481<table style="width: 100%;">
482<tr>
483<td style="width: 33%"><img src="$pwd/pixmaps/calendar.png" alt="calendar.png" /></td>
484<td style="width: 33%; text-align: center;"><a href="$pwd/logout.php"><img style="border: 0" src="$pwd/pixmaps/exit.png" width="32" height="32" alt="Logout" /><br/>Logout</a></td>
485<td style="text-align: right"><span style="font-size: 1.6em">DAViCal Web Calendar</span><br/> - A Web Interface for <a href="javascript: newwin('http://www.davical.org/');">DAViCal</a></td>
486</tr>
487</table>
488__HEAD;
489$display = <<<_DISPLAY
490<div id="display_overlay_holder">
491 <div id="display_overlay_bg" />
492 <div id="display_horizon">
493 <div id="display_content">
494 <div id="text_content">
495 $text
496 <br/><br/><br/>
497 <p style="text-align: center;">
498 <button type="button" onclick="hide_the_overlay('$referer')">Cancel</button>
499 </p>
500 </div>
501 </div>
502 </div>
503</div>
504_DISPLAY;
505$foot = <<<_FOOTER
506<div id="footer">
507<p>
508 $title {$res[0]} - &copy; 2010, 2011 Michael Rasmussen<br/>Released under GPLv3
509 <a href="http://validator.w3.org/check?uri=referer">
510 <img src="http://www.w3.org/Icons/valid-xhtml10-blue.png"
511 alt="Valid XHTML 1.0 Strict" height="31" width="88" />
512 </a>
513 <a href="http://jigsaw.w3.org/css-validator/check/referer">
514 <img src="http://www.w3.org/Icons/valid-css2-blue.png"
515 alt="Valid CSS 2.0" height="31" width="88" />
516 </a>
517</p>
518</div>
519_FOOTER;
520 ob_start();
521 print $head;
522 include TOP_FOLDER.'/include/menu.inc.php';
523 print "<div id=\"ui\">&nbsp;</div>";
524 print $foot;
525 print $display;
526 print "</body></html>";
527
528 return ob_get_clean();
529}
530
531function construct_URL($query_string, $attributes = array()) {
532 $test = trim($query_string);
533 if (empty($test))
534 return array();
535 $current = NULL;
536 $query = array();
537 $query_str = urldecode($query_string);
538 //print "$query_str<br/>";
539 $q = explode('&', $query_str);
540 //print_r($q); echo "<br/>";
541 foreach ($q as $elem) {
542 $s = explode('=', $elem);
543 //print_r($s); echo "<br/>";
544 if (! $current && in_array($s[0], $attributes)) {
545 if (count($s) > 2) {
546 $key = array_shift($s);
547 $value = array_shift($s);
548 $value .= '=';
549 //print "kv: $key $value<br/>";
550 while ($s) {
551 $value .= array_shift($s);
552 $value .= '&';
553 $value .= array_shift($s);
554 }
555 $current = $key;
556 }
557 else {
558 $key = array_shift($s);
559 $value = array_shift($s);
560 }
561 $query[$key] = $value;
562 //print_r($query); echo "<br/>";
563 }
564 else if ($current) {
565 $value = $query[$current];
566 while ($s) {
567 $value .= array_shift($s);
568 $value .= '=';
569 $value .= array_shift($s);
570 }
571 $query[$current] = $value;
572 $current = NULL;
573 //print_r($query); echo "<br/>";
574 }
575 else {
576 $key = array_shift($s);
577 $value = array_shift($s);
578 $query[$key] = $value;
579 //print_r($query); echo "<br/>";
580 }
581 }
582 //print_r($query); echo "<br/>";
583 //exit;
584 // urlencode if nessasary
585 foreach ($query as $key => $value) {
586 if (strpos($value, '&') !== FALSE)
587 $value = urlencode($value);
588 $query_array[$key] = $value;
589 }
590 return $query_array;
591}
592
593//Begin main function definition
594function ErrorsAsExceptions($level, $msg, $fileName, $lineNumber) {
595 // do nothing if error reporting is turned off
596 if (error_reporting() === 0) {
597 return;
598 }
599
600 // be sure received error is supposed to be reported
601 if (error_reporting() & $level) {
602 try {
603 // report error to appropriate channels
604 ReportError(/*$reportMsg*/$msg);
605 }
606 catch (ErrorException $e) {
607 // ignore errors while reporting
608 }
609
610 // go ahead and throw the exception
611 throw new ErrorException($msg, 0, $level, $fileName, $lineNumber);
612 }
613}
614
615set_error_handler('ErrorsAsExceptions');
This page took 0.105599 seconds and 5 git commands to generate.