PageRenderTime 83ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/gforge/plugins/webcalendar/www/includes/functions.php

https://github.com/mathieu/fusionforge
PHP | 4856 lines | 3734 code | 198 blank | 924 comment | 861 complexity | 2e66508705879474cd63b39f9a15e631 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, GPL-2.0
  1. <?php
  2. /**
  3. * All of WebCalendar's functions
  4. *
  5. * @author Craig Knudsen <cknudsen@cknudsen.com>
  6. * @copyright Craig Knudsen, <cknudsen@cknudsen.com>, http://www.k5n.us/cknudsen
  7. * @license http://www.gnu.org/licenses/gpl.html GNU GPL
  8. * @package WebCalendar
  9. */
  10. if ( empty ( $PHP_SELF ) && ! empty ( $_SERVER ) &&
  11. ! empty ( $_SERVER['PHP_SELF'] ) ) {
  12. $PHP_SELF = $_SERVER['PHP_SELF'];
  13. }
  14. if ( ! empty ( $PHP_SELF ) && preg_match ( "/\/includes\//", $PHP_SELF ) ) {
  15. die ( "You can't access this file directly!" );
  16. }
  17. /**#@+
  18. * Used for activity log
  19. * @global string
  20. */
  21. $LOG_CREATE = "C";
  22. $LOG_APPROVE = "A";
  23. $LOG_REJECT = "X";
  24. $LOG_UPDATE = "U";
  25. $LOG_DELETE = "D";
  26. $LOG_NOTIFICATION = "N";
  27. $LOG_REMINDER = "R";
  28. /**#@-*/
  29. /**
  30. * Number of seconds in a day
  31. *
  32. * @global int $ONE_DAY
  33. */
  34. $ONE_DAY = 86400;
  35. /**
  36. * Array containing the number of days in each month in a non-leap year
  37. *
  38. * @global array $days_per_month
  39. */
  40. $days_per_month = array ( 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  41. /**
  42. * Array containing the number of days in each month in a leap year
  43. *
  44. * @global array $ldays_per_month
  45. */
  46. $ldays_per_month = array ( 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  47. /**
  48. * Array of global variables which are not allowed to by set via HTTP GET/POST
  49. *
  50. * This is a security precaution to prevent users from overriding any global
  51. * variables
  52. *
  53. * @global array $noSet
  54. */
  55. $noSet = array (
  56. "is_admin" => 1,
  57. "db_type" => 1,
  58. "db_host" => 1,
  59. "db_login" => 1,
  60. "db_password" => 1,
  61. "db_persistent" => 1,
  62. "PROGRAM_NAME" => 1,
  63. "PROGRAM_URL" => 1,
  64. "readonly" => 1,
  65. "single_user" => 1,
  66. "single_user_login" => 1,
  67. "use_http_auth" => 1,
  68. "user_inc" => 1,
  69. "includedir" => 1,
  70. "NONUSER_PREFIX" => 1,
  71. "languages" => 1,
  72. "browser_languages" => 1,
  73. "pub_acc_enabled" => 1,
  74. "user_can_update_password" => 1,
  75. "admin_can_add_user" => 1,
  76. "admin_can_delete_user" => 1,
  77. );
  78. // This code is a temporary hack to make the application work when
  79. // register_globals is set to Off in php.ini (the default setting in
  80. // PHP 4.2.0 and after).
  81. if ( empty ( $HTTP_GET_VARS ) ) $HTTP_GET_VARS = $_GET;
  82. if ( ! empty ( $HTTP_GET_VARS ) ) {
  83. while (list($key, $val) = @each($HTTP_GET_VARS)) {
  84. // don't allow anything to have <script> in it...
  85. if ( ! is_array ( $val ) ) {
  86. if ( preg_match ( "/<\s*script/i", $val ) ) {
  87. echo "Security violation!"; exit;
  88. }
  89. }
  90. if ( $key == "login" ) {
  91. if ( strstr ( $PHP_SELF, "login.php" ) ) {
  92. //$GLOBALS[$key] = $val;
  93. $GLOBALS[$key] = $val;
  94. }
  95. } else {
  96. if ( empty ( $noSet[$key] ) ) {
  97. $GLOBALS[$key] = $val;
  98. //echo "XXX $key<br />\n";
  99. }
  100. }
  101. //echo "GET var '$key' = '$val' <br />\n";
  102. }
  103. reset ( $HTTP_GET_VARS );
  104. }
  105. if ( empty ( $HTTP_POST_VARS ) ) $HTTP_POST_VARS = $_POST;
  106. if ( ! empty ( $HTTP_POST_VARS ) ) {
  107. while (list($key, $val) = @each($HTTP_POST_VARS)) {
  108. // don't allow anything to have <script> in it... except 'template'
  109. if ( ! is_array ( $val ) && $key != 'template' ) {
  110. if ( preg_match ( "/<\s*script/i", $val ) ) {
  111. echo "Security violation!"; exit;
  112. }
  113. }
  114. if ( empty ( $noSet[$key] ) ) {
  115. $GLOBALS[$key] = $val;
  116. }
  117. }
  118. reset ( $HTTP_POST_VARS );
  119. }
  120. //while (list($key, $val) = @each($HTTP_POST_FILES)) {
  121. // $GLOBALS[$key] = $val;
  122. //}
  123. //while (list($key, $val) = @each($HTTP_SESSION_VARS)) {
  124. // $GLOBALS[$key] = $val;
  125. //}
  126. if ( empty ( $HTTP_COOKIE_VARS ) ) $HTTP_COOKIE_VARS = $_COOKIE;
  127. if ( ! empty ( $HTTP_COOKIE_VARS ) ) {
  128. while (list($key, $val) = @each($HTTP_COOKIE_VARS)) {
  129. if ( empty ( $noSet[$key] ) && substr($key,0,12) == "webcalendar_" ) {
  130. $GLOBALS[$key] = $val;
  131. }
  132. //echo "COOKIE var '$key' = '$val' <br />\n";
  133. }
  134. reset ( $HTTP_COOKIE_VARS );
  135. }
  136. // Don't allow a user to put "login=XXX" in the URL if they are not
  137. // coming from the login.php page.
  138. if ( empty ( $PHP_SELF ) && ! empty ( $_SERVER['PHP_SELF'] ) )
  139. $PHP_SELF = $_SERVER['PHP_SELF']; // backward compatibility
  140. if ( empty ( $PHP_SELF ) )
  141. $PHP_SELF = ''; // this happens when running send_reminders.php from CL
  142. if ( ! strstr ( $PHP_SELF, "login.php" ) && ! empty ( $GLOBALS["login"] ) ) {
  143. $GLOBALS["login"] = "";
  144. }
  145. // Define an array to use to jumble up the key: $offsets
  146. // We define a unique key to scramble the cookie we generate.
  147. // We use the admin install password that the user set to make
  148. // the salt unique for each WebCalendar install.
  149. if ( ! empty ( $settings ) && ! empty ( $settings['install_password'] ) ) {
  150. $salt = $settings['install_password'];
  151. } else {
  152. $salt = md5 ( $db_login );
  153. }
  154. $salt_len = strlen ( $salt );
  155. if ( ! empty ( $db_password ) ) {
  156. $salt2 = md5 ( $db_password );
  157. } else {
  158. $salt2 = md5 ( "oogabooga" );
  159. }
  160. $salt2_len = strlen ( $salt2 );
  161. $offsets = array ();
  162. for ( $i = 0; $i < $salt_len || $i < $salt2_len; $i++ ) {
  163. $offsets[$i] = 0;
  164. if ( $i < $salt_len )
  165. $offsets[$i] += ord ( substr ( $salt, $i, 1 ) );
  166. if ( $i < $salt2_len )
  167. $offsets[$i] += ord ( substr ( $salt2, $i, 1 ) );
  168. $offsets[$i] %= 128;
  169. }
  170. /* debugging code...
  171. for ( $i = 0; $i < count ( $offsets ); $i++ ) {
  172. echo "offset $i: $offsets[$i] <br />\n";
  173. }
  174. */
  175. /*
  176. * Functions start here. All non-function code should be above this
  177. *
  178. * Note to developers:
  179. * Documentation is generated from the function comments below.
  180. * When adding/updating functions, please follow the following conventions
  181. * seen below. Your cooperation in this matter is appreciated :-)
  182. *
  183. * If you want your documentation to link to the db documentation,
  184. * just make sure you mention the db table name followed by "table"
  185. * on the same line. Here's an example:
  186. * Retrieve preferences from the webcal_user_pref table.
  187. *
  188. */
  189. /**
  190. * Gets the value resulting from an HTTP POST method.
  191. *
  192. * <b>Note:</b> The return value will be affected by the value of
  193. * <var>magic_quotes_gpc</var> in the php.ini file.
  194. *
  195. * @param string $name Name used in the HTML form
  196. *
  197. * @return string The value used in the HTML form
  198. *
  199. * @see getGetValue
  200. */
  201. function getPostValue ( $name ) {
  202. global $HTTP_POST_VARS;
  203. if ( isset ( $_POST ) && is_array ( $_POST ) && ! empty ( $_POST[$name] ) ) {
  204. $HTTP_POST_VARS[$name] = $_POST[$name];
  205. return $_POST[$name];
  206. } else if ( ! isset ( $HTTP_POST_VARS ) ) {
  207. return null;
  208. } else if ( ! isset ( $HTTP_POST_VARS[$name] ) ) {
  209. return null;
  210. }
  211. return ( $HTTP_POST_VARS[$name] );
  212. }
  213. /**
  214. * Gets the value resulting from an HTTP GET method.
  215. *
  216. * <b>Note:</b> The return value will be affected by the value of
  217. * <var>magic_quotes_gpc</var> in the php.ini file.
  218. *
  219. * If you need to enforce a specific input format (such as numeric input), then
  220. * use the {@link getValue()} function.
  221. *
  222. * @param string $name Name used in the HTML form or found in the URL
  223. *
  224. * @return string The value used in the HTML form (or URL)
  225. *
  226. * @see getPostValue
  227. */
  228. function getGetValue ( $name ) {
  229. global $HTTP_GET_VARS;
  230. if ( isset ( $_GET ) && is_array ( $_GET ) && ! empty ( $_GET[$name] ) ) {
  231. $HTTP_GET_VARS[$name] = $_GET[$name];
  232. return $_GET[$name];
  233. } else if ( ! isset ( $HTTP_GET_VARS ) ) {
  234. return null;
  235. } else if ( ! isset ( $HTTP_GET_VARS[$name] ) ) {
  236. return null;
  237. }
  238. return ( $HTTP_GET_VARS[$name] );
  239. }
  240. /**
  241. * Gets the value resulting from either HTTP GET method or HTTP POST method.
  242. *
  243. * <b>Note:</b> The return value will be affected by the value of
  244. * <var>magic_quotes_gpc</var> in the php.ini file.
  245. *
  246. * <b>Note:</b> If you need to get an integer value, yuou can use the
  247. * getIntValue function.
  248. *
  249. * @param string $name Name used in the HTML form or found in the URL
  250. * @param string $format A regular expression format that the input must match.
  251. * If the input does not match, an empty string is
  252. * returned and a warning is sent to the browser. If The
  253. * <var>$fatal</var> parameter is true, then execution
  254. * will also stop when the input does not match the
  255. * format.
  256. * @param bool $fatal Is it considered a fatal error requiring execution to
  257. * stop if the value retrieved does not match the format
  258. * regular expression?
  259. *
  260. * @return string The value used in the HTML form (or URL)
  261. *
  262. * @uses getGetValue
  263. * @uses getPostValue
  264. */
  265. function getValue ( $name, $format="", $fatal=false ) {
  266. $val = getPostValue ( $name );
  267. if ( ! isset ( $val ) )
  268. $val = getGetValue ( $name );
  269. // for older PHP versions...
  270. if ( ! isset ( $val ) && get_magic_quotes_gpc () == 1 &&
  271. ! empty ( $GLOBALS[$name] ) )
  272. $val = $GLOBALS[$name];
  273. if ( ! isset ( $val ) )
  274. return "";
  275. if ( ! empty ( $format ) && ! preg_match ( "/^" . $format . "$/", $val ) ) {
  276. // does not match
  277. if ( $fatal ) {
  278. die_miserable_death ( "Fatal Error: Invalid data format for $name" );
  279. }
  280. // ignore value
  281. return "";
  282. }
  283. return $val;
  284. }
  285. /**
  286. * Gets an integer value resulting from an HTTP GET or HTTP POST method.
  287. *
  288. * <b>Note:</b> The return value will be affected by the value of
  289. * <var>magic_quotes_gpc</var> in the php.ini file.
  290. *
  291. * @param string $name Name used in the HTML form or found in the URL
  292. * @param bool $fatal Is it considered a fatal error requiring execution to
  293. * stop if the value retrieved does not match the format
  294. * regular expression?
  295. *
  296. * @return string The value used in the HTML form (or URL)
  297. *
  298. * @uses getValue
  299. */
  300. function getIntValue ( $name, $fatal=false ) {
  301. $val = getValue ( $name, "-?[0-9]+", $fatal );
  302. return $val;
  303. }
  304. /**
  305. * Loads default system settings (which can be updated via admin.php).
  306. *
  307. * System settings are stored in the webcal_config table.
  308. *
  309. * <b>Note:</b> If the setting for <var>server_url</var> is not set, the value
  310. * will be calculated and stored in the database.
  311. *
  312. * @global string User's login name
  313. * @global bool Readonly
  314. * @global string HTTP hostname
  315. * @global int Server's port number
  316. * @global string Request string
  317. * @global array Server variables
  318. */
  319. function load_global_settings () {
  320. global $login, $readonly, $HTTP_HOST, $SERVER_PORT, $REQUEST_URI, $_SERVER;
  321. // Note: when running from the command line (send_reminders.php),
  322. // these variables are (obviously) not set.
  323. // TODO: This type of checking should be moved to a central locationm
  324. // like init.php.
  325. if ( isset ( $_SERVER ) && is_array ( $_SERVER ) ) {
  326. if ( empty ( $HTTP_HOST ) && isset ( $_SERVER["HTTP_POST"] ) )
  327. $HTTP_HOST = $_SERVER["HTTP_HOST"];
  328. if ( empty ( $SERVER_PORT ) && isset ( $_SERVER["SERVER_PORT"] ) )
  329. $SERVER_PORT = $_SERVER["SERVER_PORT"];
  330. if ( empty ( $REQUEST_URI ) && isset ( $_SERVER["REQUEST_URI"] ) )
  331. $REQUEST_URI = $_SERVER["REQUEST_URI"];
  332. }
  333. $res = dbi_query ( "SELECT cal_setting, cal_value FROM webcal_config" );
  334. if ( $res ) {
  335. while ( $row = dbi_fetch_row ( $res ) ) {
  336. $setting = $row[0];
  337. $value = $row[1];
  338. //echo "Setting '$setting' to '$value' <br />\n";
  339. $GLOBALS[$setting] = $value;
  340. }
  341. dbi_free_result ( $res );
  342. }
  343. // If app name not set.... default to "Title". This gets translated
  344. // later since this function is typically called before translate.php
  345. // is included.
  346. // Note: We usually use translate($application_name) instead of
  347. // translate("Title").
  348. if ( empty ( $GLOBALS["application_name"] ) )
  349. $GLOBALS["application_name"] = "Title";
  350. // If $server_url not set, then calculate one for them, then store it
  351. // in the database.
  352. if ( empty ( $GLOBALS["server_url"] ) ) {
  353. if ( ! empty ( $HTTP_HOST ) && ! empty ( $REQUEST_URI ) ) {
  354. $ptr = strrpos ( $REQUEST_URI, "/" );
  355. if ( $ptr > 0 ) {
  356. $uri = substr ( $REQUEST_URI, 0, $ptr + 1 );
  357. $server_url = "http://" . $HTTP_HOST;
  358. if ( ! empty ( $SERVER_PORT ) && $SERVER_PORT != 80 )
  359. $server_url .= ":" . $SERVER_PORT;
  360. $server_url .= $uri;
  361. dbi_query ( "INSERT INTO webcal_config ( cal_setting, cal_value ) ".
  362. "VALUES ( 'server_url', '$server_url' )" );
  363. $GLOBALS["server_url"] = $server_url;
  364. }
  365. }
  366. }
  367. // If no font settings, then set some
  368. if ( empty ( $GLOBALS["FONTS"] ) ) {
  369. if ( $GLOBALS["LANGUAGE"] == "Japanese" )
  370. $GLOBALS["FONTS"] = "Osaka, Arial, Helvetica, sans-serif";
  371. else
  372. $GLOBALS["FONTS"] = "Arial, Helvetica, sans-serif";
  373. }
  374. }
  375. /**
  376. * Gets the list of active plugins.
  377. *
  378. * Should be called after {@link load_global_settings()} and {@link load_user_preferences()}.
  379. *
  380. * @internal cek: ignored since I am not sure this will ever be used...
  381. *
  382. * @return array Active plugins
  383. *
  384. * @ignore
  385. */
  386. function get_plugin_list ( $include_disabled=false ) {
  387. // first get list of available plugins
  388. $sql = "SELECT cal_setting FROM webcal_config " .
  389. "WHERE cal_setting LIKE '%.plugin_status'";
  390. if ( ! $include_disabled )
  391. $sql .= " AND cal_value = 'Y'";
  392. $sql .= " ORDER BY cal_setting";
  393. $res = dbi_query ( $sql );
  394. $plugins = array ();
  395. if ( $res ) {
  396. while ( $row = dbi_fetch_row ( $res ) ) {
  397. $e = explode ( ".", $row[0] );
  398. if ( $e[0] != "" ) {
  399. $plugins[] = $e[0];
  400. }
  401. }
  402. dbi_free_result ( $res );
  403. } else {
  404. echo translate("Database error") . ": " . dbi_error (); exit;
  405. }
  406. if ( count ( $plugins ) == 0 ) {
  407. $plugins[] = "webcalendar";
  408. }
  409. return $plugins;
  410. }
  411. /**
  412. * Get plugins available to the current user.
  413. *
  414. * Do this by getting a list of all plugins that are not disabled by the
  415. * administrator and make sure this user has not disabled any of them.
  416. *
  417. * It's done this was so that when an admin adds a new plugin, it shows up on
  418. * each users system automatically (until they disable it).
  419. *
  420. * @return array Plugins available to current user
  421. *
  422. * @ignore
  423. */
  424. function get_user_plugin_list () {
  425. $ret = array ();
  426. $all_plugins = get_plugin_list ();
  427. for ( $i = 0; $i < count ( $all_plugins ); $i++ ) {
  428. if ( $GLOBALS[$all_plugins[$i] . ".disabled"] != "N" )
  429. $ret[] = $all_plugins[$i];
  430. }
  431. return $ret;
  432. }
  433. /**
  434. * Identify user's browser.
  435. *
  436. * Returned value will be one of:
  437. * - "Mozilla/5" = Mozilla (open source Mozilla 5.0)
  438. * - "Mozilla/[3,4]" = Netscape (3.X, 4.X)
  439. * - "MSIE 4" = MSIE (4.X)
  440. *
  441. * @return string String identifying browser
  442. *
  443. * @ignore
  444. */
  445. function get_web_browser () {
  446. if ( ereg ( "MSIE [0-9]", getenv ( "HTTP_USER_AGENT" ) ) )
  447. return "MSIE";
  448. if ( ereg ( "Mozilla/[234]", getenv ( "HTTP_USER_AGENT" ) ) )
  449. return "Netscape";
  450. if ( ereg ( "Mozilla/[5678]", getenv ( "HTTP_USER_AGENT" ) ) )
  451. return "Mozilla";
  452. return "Unknown";
  453. }
  454. /**
  455. * Logs a debug message.
  456. *
  457. * Generally, we do not leave calls to this function in the code. It is used
  458. * for debugging only.
  459. *
  460. * @param string $msg Text to be logged
  461. */
  462. function do_debug ( $msg ) {
  463. // log to /tmp/webcal-debug.log
  464. //error_log ( date ( "Y-m-d H:i:s" ) . "> $msg\n",
  465. // 3, "/tmp/webcal-debug.log" );
  466. //error_log ( date ( "Y-m-d H:i:s" ) . "> $msg\n",
  467. // 2, "sockieman:2000" );
  468. }
  469. /**
  470. * Gets user's preferred view.
  471. *
  472. * The user's preferred view is stored in the $STARTVIEW global variable. This
  473. * is loaded from the user preferences (or system settings if there are no user
  474. * prefererences.)
  475. *
  476. * @param string $indate Date to pass to preferred view in YYYYMMDD format
  477. * @param string $args Arguments to include in the URL (such as "user=joe")
  478. *
  479. * @return string URL of the user's preferred view
  480. */
  481. function get_preferred_view ( $indate="", $args="" ) {
  482. global $STARTVIEW, $thisdate;
  483. $url = empty ( $STARTVIEW ) ? "month.php" : $STARTVIEW;
  484. // We used to just store "month" in $STARTVIEW without the ".php"
  485. // This is just to prevent users from getting a "404 not found" if
  486. // they have not updated their preferences.
  487. if ( $url == "month" || $url == "day" || $url == "week" || $url == "year" )
  488. $url .= ".php";
  489. $url = str_replace ( '&amp;', '&', $url );
  490. $url = str_replace ( '&', '&amp;', $url );
  491. $xdate = empty ( $indate ) ? $thisdate : $indate;
  492. if ( ! empty ( $xdate ) ) {
  493. if ( strstr ( $url, "?" ) )
  494. $url .= '&amp;' . "date=$xdate";
  495. else
  496. $url .= '?' . "date=$xdate";
  497. }
  498. if ( ! empty ( $args ) ) {
  499. if ( strstr ( $url, "?" ) )
  500. $url .= '&amp;' . $args;
  501. else
  502. $url .= '?' . $args;
  503. }
  504. return $url;
  505. }
  506. /**
  507. * Sends a redirect to the user's preferred view.
  508. *
  509. * The user's preferred view is stored in the $STARTVIEW global variable. This
  510. * is loaded from the user preferences (or system settings if there are no user
  511. * prefererences.)
  512. *
  513. * @param string $indate Date to pass to preferred view in YYYYMMDD format
  514. * @param string $args Arguments to include in the URL (such as "user=joe")
  515. */
  516. function send_to_preferred_view ( $indate="", $args="" ) {
  517. $url = get_preferred_view ( $indate, $args );
  518. do_redirect ( $url );
  519. }
  520. /** Sends a redirect to the specified page.
  521. *
  522. * The database connection is closed and execution terminates in this function.
  523. *
  524. * <b>Note:</b> MS IIS/PWS has a bug in which it does not allow us to send a
  525. * cookie and a redirect in the same HTTP header. When we detect that the web
  526. * server is IIS, we accomplish the redirect using meta-refresh. See the
  527. * following for more info on the IIS bug:
  528. *
  529. * {@link http://www.faqts.com/knowledge_base/view.phtml/aid/9316/fid/4}
  530. *
  531. * @param string $url The page to redirect to. In theory, this should be an
  532. * absolute URL, but all browsers accept relative URLs (like
  533. * "month.php").
  534. *
  535. * @global string Type of webserver
  536. * @global array Server variables
  537. * @global resource Database connection
  538. */
  539. function do_redirect ( $url ) {
  540. global $SERVER_SOFTWARE, $_SERVER, $c;
  541. // Replace any '&amp;' with '&' since we don't want that in the HTTP
  542. // header.
  543. $url = str_replace ( '&amp;', '&', $url );
  544. if ( empty ( $SERVER_SOFTWARE ) )
  545. $SERVER_SOFTWARE = $_SERVER["SERVER_SOFTWARE"];
  546. //echo "SERVER_SOFTWARE = $SERVER_SOFTWARE <br />\n"; exit;
  547. if ( ( substr ( $SERVER_SOFTWARE, 0, 5 ) == "Micro" ) ||
  548. ( substr ( $SERVER_SOFTWARE, 0, 3 ) == "WN/" ) ) {
  549. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html
  550. PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
  551. \"DTD/xhtml1-transitional.dtd\">
  552. <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
  553. <head>\n<title>Redirect</title>\n" .
  554. "<meta http-equiv=\"refresh\" content=\"0; url=$url\" />\n</head>\n<body>\n" .
  555. "Redirecting to.. <a href=\"" . $url . "\">here</a>.</body>\n</html>";
  556. } else {
  557. Header ( "Location: $url" );
  558. //print "<javascript>window.location.href='index.php';</script>" ;
  559. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html
  560. PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
  561. \"DTD/xhtml1-transitional.dtd\">
  562. <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
  563. <head>\n<title>Redirect</title>\n</head>\n<body>\n" .
  564. "Redirecting to aa... <a href=\"" . $url . "\">here</a>.</body>\n</html>";
  565. }
  566. dbi_close ( $c );
  567. exit;
  568. }
  569. /**
  570. * Sends an HTTP login request to the browser and stops execution.
  571. */
  572. function send_http_login () {
  573. global $lang_file, $application_name;
  574. if ( strlen ( $lang_file ) ) {
  575. Header ( "WWW-Authenticate: Basic realm=\"" . translate("Title") . "\"");
  576. Header ( "HTTP/1.0 401 Unauthorized" );
  577. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html
  578. PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
  579. \"DTD/xhtml1-transitional.dtd\">
  580. <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
  581. <head>\n<title>Unauthorized</title>\n</head>\n<body>\n" .
  582. "<h2>" . translate("Title") . "</h2>\n" .
  583. translate("You are not authorized") .
  584. "\n</body>\n</html>";
  585. } else {
  586. Header ( "WWW-Authenticate: Basic realm=\"WebCalendar\"");
  587. Header ( "HTTP/1.0 401 Unauthorized" );
  588. echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!DOCTYPE html
  589. PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"
  590. \"DTD/xhtml1-transitional.dtd\">
  591. <html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
  592. <head>\n<title>Unauthorized</title>\n</head>\n<body>\n" .
  593. "<h2>WebCalendar</h2>\n" .
  594. "You are not authorized" .
  595. "\n</body>\n</html>";
  596. }
  597. exit;
  598. }
  599. /**
  600. * Generates a cookie that saves the last calendar view.
  601. *
  602. * Cookie is based on the current <var>$REQUEST_URI</var>.
  603. *
  604. * We save this cookie so we can return to this same page after a user
  605. * edits/deletes/etc an event.
  606. *
  607. * @global string Request string
  608. */
  609. function remember_this_view () {
  610. global $REQUEST_URI;
  611. if ( empty ( $REQUEST_URI ) )
  612. $REQUEST_URI = $_SERVER["REQUEST_URI"];
  613. // do not use anything with friendly in the URI
  614. if ( strstr ( $REQUEST_URI, "friendly=" ) )
  615. return;
  616. SetCookie ( "webcalendar_last_view", $REQUEST_URI );
  617. }
  618. /**
  619. * Gets the last page stored using {@link remember_this_view()}.
  620. *
  621. * @return string The URL of the last view or an empty string if it cannot be
  622. * determined.
  623. *
  624. * @global array Cookies
  625. */
  626. function get_last_view () {
  627. global $HTTP_COOKIE_VARS;
  628. $val = '';
  629. if ( isset ( $_COOKIE["webcalendar_last_view"] ) ) {
  630. $HTTP_COOKIE_VARS["webcalendar_last_view"] = $_COOKIE["webcalendar_last_view"];
  631. $val = $_COOKIE["webcalendar_last_view"];
  632. } else if ( isset ( $HTTP_COOKIE_VARS["webcalendar_last_view"] ) ) {
  633. $val = $HTTP_COOKIE_VARS["webcalendar_last_view"];
  634. }
  635. $val = str_replace ( "&", "&amp;", $val );
  636. return $val;
  637. }
  638. /**
  639. * Sends HTTP headers that tell the browser not to cache this page.
  640. *
  641. * Different browser use different mechanisms for this, so a series of HTTP
  642. * header directives are sent.
  643. *
  644. * <b>Note:</b> This function needs to be called before any HTML output is sent
  645. * to the browser.
  646. */
  647. function send_no_cache_header () {
  648. header ( "Expires: Mon, 26 Jul 1997 05:00:00 GMT" );
  649. header ( "Last-Modified: " . gmdate ( "D, d M Y H:i:s" ) . " GMT" );
  650. header ( "Cache-Control: no-store, no-cache, must-revalidate" );
  651. header ( "Cache-Control: post-check=0, pre-check=0", false );
  652. header ( "Pragma: no-cache" );
  653. }
  654. /**
  655. * Loads the current user's preferences as global variables from the webcal_user_pref table.
  656. *
  657. * Also loads the list of views for this user (not really a preference, but
  658. * this is a convenient place to put this...)
  659. *
  660. * <b>Notes:</b>
  661. * - If <var>$allow_color_customization</var> is set to 'N', then we ignore any
  662. * color preferences.
  663. * - Other default values will also be set if the user has not saved a
  664. * preference and no global value has been set by the administrator in the
  665. * system settings.
  666. */
  667. function load_user_preferences () {
  668. global $login, $browser, $views, $prefarray, $is_assistant,
  669. $has_boss, $user, $is_nonuser_admin, $allow_color_customization;
  670. $lang_found = false;
  671. $colors = array (
  672. "BGCOLOR" => 1,
  673. "H2COLOR" => 1,
  674. "THBG" => 1,
  675. "THFG" => 1,
  676. "CELLBG" => 1,
  677. "TODAYCELLBG" => 1,
  678. "WEEKENDBG" => 1,
  679. "POPUP_BG" => 1,
  680. "POPUP_FG" => 1,
  681. );
  682. $browser = get_web_browser ();
  683. $browser_lang = get_browser_language ();
  684. $prefarray = array ();
  685. // Note: default values are set in config.php
  686. $res = dbi_query (
  687. "SELECT cal_setting, cal_value FROM webcal_user_pref " .
  688. "WHERE cal_login = '$login'" );
  689. if ( $res ) {
  690. while ( $row = dbi_fetch_row ( $res ) ) {
  691. $setting = $row[0];
  692. $value = $row[1];
  693. if ( $allow_color_customization == 'N' ) {
  694. if ( isset ( $colors[$setting] ) )
  695. continue;
  696. }
  697. $sys_setting = "sys_" . $setting;
  698. // save system defaults
  699. if ( ! empty ( $GLOBALS[$setting] ) )
  700. $GLOBALS["sys_" . $setting] = $GLOBALS[$setting];
  701. $GLOBALS[$setting] = $value;
  702. $prefarray[$setting] = $value;
  703. if ( $setting == "LANGUAGE" )
  704. $lang_found = true;
  705. }
  706. dbi_free_result ( $res );
  707. }
  708. // get views for this user and global views
  709. $res = dbi_query (
  710. "SELECT cal_view_id, cal_name, cal_view_type, cal_is_global " .
  711. "FROM webcal_view " .
  712. "WHERE cal_owner = '$login' OR cal_is_global = 'Y' " .
  713. "ORDER BY cal_name" );
  714. if ( $res ) {
  715. $views = array ();
  716. while ( $row = dbi_fetch_row ( $res ) ) {
  717. if ( $row[2] == 'S' )
  718. $url = "view_t.php?timeb=1&amp;id=$row[0]";
  719. else if ( $row[2] == 'T' )
  720. $url = "view_t.php?timeb=0&amp;id=$row[0]";
  721. else
  722. $url = "view_" . strtolower ( $row[2] ) . ".php?id=$row[0]";
  723. $v = array (
  724. "cal_view_id" => $row[0],
  725. "cal_name" => $row[1],
  726. "cal_view_type" => $row[2],
  727. "cal_is_global" => $row[3],
  728. "url" => $url
  729. );
  730. $views[] = $v;
  731. }
  732. dbi_free_result ( $res );
  733. }
  734. // If user has not set a language preference, then use their browser
  735. // settings to figure it out, and save it in the database for future
  736. // use (email reminders).
  737. if ( ! $lang_found && strlen ( $login ) && $login != "__public__" ) {
  738. $LANGUAGE = $browser_lang;
  739. dbi_query ( "INSERT INTO webcal_user_pref " .
  740. "( cal_login, cal_setting, cal_value ) VALUES " .
  741. "( '$login', 'LANGUAGE', '$LANGUAGE' )" );
  742. }
  743. if ( empty ( $GLOBALS["DATE_FORMAT_MY"] ) )
  744. $GLOBALS["DATE_FORMAT_MY"] = "__month__ __yyyy__";
  745. if ( empty ( $GLOBALS["DATE_FORMAT_MD"] ) )
  746. $GLOBALS["DATE_FORMAT_MD"] = "__month__ __dd__";
  747. $is_assistant = empty ( $user ) ? false :
  748. user_is_assistant ( $login, $user );
  749. $has_boss = user_has_boss ( $login );
  750. $is_nonuser_admin = ($user) ? user_is_nonuser_admin ( $login, $user ) : false;
  751. if ( $is_nonuser_admin ) load_nonuser_preferences ($user);
  752. }
  753. /**
  754. * Gets the list of external users for an event from the webcal_entry_ext_user table in an HTML format.
  755. *
  756. * @param int $event_id Event ID
  757. * @param int $use_mailto When set to 1, email address will contain an href
  758. * link with a mailto URL.
  759. *
  760. * @return string The list of external users for an event formatte in HTML.
  761. */
  762. function event_get_external_users ( $event_id, $use_mailto=0 ) {
  763. global $error;
  764. $ret = "";
  765. $res = dbi_query ( "SELECT cal_fullname, cal_email " .
  766. "FROM webcal_entry_ext_user " .
  767. "WHERE cal_id = $event_id " .
  768. "ORDER by cal_fullname" );
  769. if ( $res ) {
  770. while ( $row = dbi_fetch_row ( $res ) ) {
  771. if ( strlen ( $ret ) )
  772. $ret .= "\n";
  773. // Remove [\d] if duplicate name
  774. $trow = trim( preg_replace( '/\[[\d]]/' , "", $row[0] ) );
  775. $ret .= $trow;
  776. if ( strlen ( $row[1] ) ) {
  777. if ( $use_mailto ) {
  778. $ret .= " <a href=\"mailto:$row[1]\">&lt;" .
  779. htmlentities ( $row[1] ) . "&gt;</a>";
  780. } else {
  781. $ret .= " &lt;". htmlentities ( $row[1] ) . "&gt;";
  782. }
  783. }
  784. }
  785. dbi_free_result ( $res );
  786. } else {
  787. echo translate("Database error") .": " . dbi_error ();
  788. echo "<br />\nSQL:<br />\n$sql";
  789. exit;
  790. }
  791. return $ret;
  792. }
  793. /**
  794. * Adds something to the activity log for an event.
  795. *
  796. * The information will be saved to the webcal_entry_log table.
  797. *
  798. * @param int $event_id Event ID
  799. * @param string $user Username of user doing this
  800. * @param string $user_cal Username of user whose calendar is affected
  801. * @param string $type Type of activity we are logging:
  802. * - $LOG_CREATE
  803. * - $LOG_APPROVE
  804. * - $LOG_REJECT
  805. * - $LOG_UPDATE
  806. * - $LOG_DELETE
  807. * - $LOG_NOTIFICATION
  808. * - $LOG_REMINDER
  809. * @param string $text Text comment to add with activity log entry
  810. */
  811. function activity_log ( $event_id, $user, $user_cal, $type, $text ) {
  812. $next_id = 1;
  813. if ( empty ( $type ) ) {
  814. echo "Error: type not set for activity log!";
  815. // but don't exit since we may be in mid-transaction
  816. return;
  817. }
  818. $res = dbi_query ( "SELECT MAX(cal_log_id) FROM webcal_entry_log" );
  819. if ( $res ) {
  820. if ( $row = dbi_fetch_row ( $res ) ) {
  821. $next_id = $row[0] + 1;
  822. }
  823. dbi_free_result ( $res );
  824. }
  825. $date = date ( "Ymd" );
  826. $time = date ( "Gis" );
  827. $sql_text = empty ( $text ) ? "NULL" : "'$text'";
  828. $sql_user_cal = empty ( $user_cal ) ? "NULL" : "'$user_cal'";
  829. $sql = "INSERT INTO webcal_entry_log ( " .
  830. "cal_log_id, cal_entry_id, cal_login, cal_user_cal, cal_type, " .
  831. "cal_date, cal_time, cal_text ) VALUES ( $next_id, $event_id, " .
  832. "'$user', $sql_user_cal, '$type', $date, $time, $sql_text )";
  833. if ( ! dbi_query ( $sql ) ) {
  834. echo "Database error: " . dbi_error ();
  835. echo "<br />\nSQL:<br />\n$sql";
  836. exit;
  837. }
  838. }
  839. /**
  840. * Gets a list of users.
  841. *
  842. * If groups are enabled, this will restrict the list of users to only those
  843. * users who are in the same group(s) as the user (unless the user is an admin
  844. * user). We allow admin users to see all users because they can also edit
  845. * someone else's events (so they may need access to users who are not in the
  846. * same groups that they are in).
  847. *
  848. * @return array Array of users, where each element in the array is an array
  849. * with the following keys:
  850. * - cal_login
  851. * - cal_lastname
  852. * - cal_firstname
  853. * - cal_is_admin
  854. * - cal_is_admin
  855. * - cal_email
  856. * - cal_password
  857. * - cal_fullname
  858. */
  859. function get_my_users () {
  860. global $login, $is_admin, $groups_enabled, $user_sees_only_his_groups;
  861. if ( $groups_enabled == "Y" && $user_sees_only_his_groups == "Y" &&
  862. ! $is_admin ) {
  863. // get groups that current user is in
  864. $res = dbi_query ( "SELECT cal_group_id FROM webcal_group_user " .
  865. "WHERE cal_login = '$login'" );
  866. $groups = array ();
  867. if ( $res ) {
  868. while ( $row = dbi_fetch_row ( $res ) ) {
  869. $groups[] = $row[0];
  870. }
  871. dbi_fetch_row ( $res );
  872. }
  873. $u = user_get_users ();
  874. $u_byname = array ();
  875. for ( $i = 0; $i < count ( $u ); $i++ ) {
  876. $name = $u[$i]['cal_login'];
  877. $u_byname[$name] = $u[$i];
  878. }
  879. $ret = array ();
  880. if ( count ( $groups ) == 0 ) {
  881. // Eek. User is in no groups... Return only themselves
  882. $ret[] = $u_byname[$login];
  883. return $ret;
  884. }
  885. // get list of users in the same groups as current user
  886. $sql = "SELECT DISTINCT(webcal_group_user.cal_login), cal_lastname, cal_firstname from webcal_group_user " .
  887. "LEFT JOIN webcal_user ON webcal_group_user.cal_login = webcal_user.cal_login " .
  888. "WHERE cal_group_id ";
  889. if ( count ( $groups ) == 1 )
  890. $sql .= "= " . $groups[0];
  891. else {
  892. $sql .= "IN ( " . implode ( ", ", $groups ) . " )";
  893. }
  894. $sql .= " ORDER BY cal_lastname, cal_firstname, webcal_group_user.cal_login";
  895. //echo "SQL: $sql <br />\n";
  896. $res = dbi_query ( $sql );
  897. if ( $res ) {
  898. while ( $row = dbi_fetch_row ( $res ) ) {
  899. $ret[] = $u_byname[$row[0]];
  900. }
  901. dbi_free_result ( $res );
  902. }
  903. return $ret;
  904. } else {
  905. // groups not enabled... return all users
  906. //echo "No groups. ";
  907. return user_get_users ();
  908. }
  909. }
  910. /**
  911. * Gets a preference setting for the specified user.
  912. *
  913. * If no value is found in the database, then the system default setting will
  914. * be returned.
  915. *
  916. * @param string $user User login we are getting preference for
  917. * @param string $setting Name of the setting
  918. *
  919. * @return string The value found in the webcal_user_pref table for the
  920. * specified setting or the sytem default if no user settings
  921. * was found.
  922. */
  923. function get_pref_setting ( $user, $setting ) {
  924. $ret = '';
  925. // set default
  926. if ( ! isset ( $GLOBALS["sys_" .$setting] ) ) {
  927. // this could happen if the current user has not saved any pref. yet
  928. if ( ! empty ( $GLOBALS[$setting] ) )
  929. $ret = $GLOBALS[$setting];
  930. } else {
  931. $ret = $GLOBALS["sys_" .$setting];
  932. }
  933. $sql = "SELECT cal_value FROM webcal_user_pref " .
  934. "WHERE cal_login = '" . $user . "' AND " .
  935. "cal_setting = '" . $setting . "'";
  936. //echo "SQL: $sql <br />\n";
  937. $res = dbi_query ( $sql );
  938. if ( $res ) {
  939. if ( $row = dbi_fetch_row ( $res ) )
  940. $ret = $row[0];
  941. dbi_free_result ( $res );
  942. }
  943. return $ret;
  944. }
  945. /**
  946. * Gets browser-specified language preference.
  947. *
  948. * @return string Preferred language
  949. *
  950. * @ignore
  951. */
  952. function get_browser_language () {
  953. global $HTTP_ACCEPT_LANGUAGE, $browser_languages;
  954. $ret = "";
  955. if ( empty ( $HTTP_ACCEPT_LANGUAGE ) &&
  956. isset ( $_SERVER["HTTP_ACCEPT_LANGUAGE"] ) )
  957. $HTTP_ACCEPT_LANGUAGE = $_SERVER["HTTP_ACCEPT_LANGUAGE"];
  958. if ( empty ( $HTTP_ACCEPT_LANGUAGE ) ) {
  959. return "none";
  960. } else {
  961. $langs = explode ( ",", $HTTP_ACCEPT_LANGUAGE );
  962. for ( $i = 0; $i < count ( $langs ); $i++ ) {
  963. $l = strtolower ( trim ( ereg_replace(';.*', '', $langs[$i] ) ) );
  964. $ret .= "\"$l\" ";
  965. if ( ! empty ( $browser_languages[$l] ) ) {
  966. return $browser_languages[$l];
  967. }
  968. }
  969. }
  970. //if ( strlen ( $HTTP_ACCEPT_LANGUAGE ) )
  971. // return "none ($HTTP_ACCEPT_LANGUAGE not supported)";
  972. //else
  973. return "none";
  974. }
  975. /**
  976. * Loads current user's layer info into layer global variable.
  977. *
  978. * If the system setting <var>$allow_view_other</var> is not set to 'Y', then
  979. * we ignore all layer functionality. If <var>$force</var> is 0, we only load
  980. * layers if the current user preferences have layers turned on.
  981. *
  982. * @param string $user Username of user to load layers for
  983. * @param int $force If set to 1, then load layers for this user even if
  984. * user preferences have layers turned off.
  985. */
  986. function load_user_layers ($user="",$force=0) {
  987. global $login;
  988. global $layers;
  989. global $LAYERS_STATUS, $allow_view_other;
  990. if ( $user == "" )
  991. $user = $login;
  992. $layers = array ();
  993. if ( empty ( $allow_view_other ) || $allow_view_other != 'Y' )
  994. return; // not allowed to view others' calendars, so cannot use layers
  995. if ( $force || ( ! empty ( $LAYERS_STATUS ) && $LAYERS_STATUS != "N" ) ) {
  996. $res = dbi_query (
  997. "SELECT cal_layerid, cal_layeruser, cal_color, cal_dups " .
  998. "FROM webcal_user_layers " .
  999. "WHERE cal_login = '$user' ORDER BY cal_layerid" );
  1000. if ( $res ) {
  1001. $count = 1;
  1002. while ( $row = dbi_fetch_row ( $res ) ) {
  1003. $layers[$row[0]] = array (
  1004. "cal_layerid" => $row[0],
  1005. "cal_layeruser" => $row[1],
  1006. "cal_color" => $row[2],
  1007. "cal_dups" => $row[3]
  1008. );
  1009. $count++;
  1010. }
  1011. dbi_free_result ( $res );
  1012. }
  1013. } else {
  1014. //echo "Not loading!";
  1015. }
  1016. }
  1017. /**
  1018. * Generates the HTML used in an event popup for the site_extras fields of an event.
  1019. *
  1020. * @param int $id Event ID
  1021. *
  1022. * @return string The HTML to be used within the event popup for any site_extra
  1023. * fields found for the specified event
  1024. */
  1025. function site_extras_for_popup ( $id ) {
  1026. global $site_extras_in_popup, $site_extras;
  1027. // These are needed in case the site_extras.php file was already
  1028. // included.
  1029. global $EXTRA_TEXT, $EXTRA_MULTILINETEXT, $EXTRA_URL, $EXTRA_DATE,
  1030. $EXTRA_EMAIL, $EXTRA_USER, $EXTRA_REMINDER, $EXTRA_SELECTLIST;
  1031. global $EXTRA_REMINDER_WITH_DATE, $EXTRA_REMINDER_WITH_OFFSET,
  1032. $EXTRA_REMINDER_DEFAULT_YES;
  1033. $ret = '';
  1034. if ( $site_extras_in_popup != 'Y' )
  1035. return '';
  1036. include_once 'includes/site_extras.php';
  1037. $extras = get_site_extra_fields ( $id );
  1038. for ( $i = 0; $i < count ( $site_extras ); $i++ ) {
  1039. $extra_name = $site_extras[$i][0];
  1040. $extra_type = $site_extras[$i][2];
  1041. $extra_arg1 = $site_extras[$i][3];
  1042. $extra_arg2 = $site_extras[$i][4];
  1043. if ( ! empty ( $extras[$extra_name]['cal_name'] ) ) {
  1044. $ret .= "<dt>" . translate ( $site_extras[$i][1] ) . ":</dt>\n<dd>";
  1045. if ( $extra_type == $EXTRA_DATE ) {
  1046. if ( $extras[$extra_name]['cal_date'] > 0 )
  1047. $ret .= date_to_str ( $extras[$extra_name]['cal_date'] );
  1048. } else if ( $extra_type == $EXTRA_TEXT ||
  1049. $extra_type == $EXTRA_MULTILINETEXT ) {
  1050. $ret .= nl2br ( $extras[$extra_name]['cal_data'] );
  1051. } else if ( $extra_type == $EXTRA_REMINDER ) {
  1052. if ( $extras[$extra_name]['cal_remind'] <= 0 )
  1053. $ret .= translate ( "No" );
  1054. else {
  1055. $ret .= translate ( "Yes" );
  1056. if ( ( $extra_arg2 & $EXTRA_REMINDER_WITH_DATE ) > 0 ) {
  1057. $ret .= "&nbsp;&nbsp;-&nbsp;&nbsp;";
  1058. $ret .= date_to_str ( $extras[$extra_name]['cal_date'] );
  1059. } else if ( ( $extra_arg2 & $EXTRA_REMINDER_WITH_OFFSET ) > 0 ) {
  1060. $ret .= "&nbsp;&nbsp;-&nbsp;&nbsp;";
  1061. $minutes = $extras[$extra_name]['cal_data'];
  1062. $d = (int) ( $minutes / ( 24 * 60 ) );
  1063. $minutes -= ( $d * 24 * 60 );
  1064. $h = (int) ( $minutes / 60 );
  1065. $minutes -= ( $h * 60 );
  1066. if ( $d > 0 )
  1067. $ret .= $d . "&nbsp;" . translate("days") . "&nbsp;";
  1068. if ( $h > 0 )
  1069. $ret .= $h . "&nbsp;" . translate("hours") . "&nbsp;";
  1070. if ( $minutes > 0 )
  1071. $ret .= $minutes . "&nbsp;" . translate("minutes");
  1072. $ret .= "&nbsp;" . translate("before event" );
  1073. }
  1074. }
  1075. } else {
  1076. $ret .= $extras[$extra_name]['cal_data'];
  1077. }
  1078. $ret .= "</dd>\n";
  1079. }
  1080. }
  1081. return $ret;
  1082. }
  1083. /**
  1084. * Builds the HTML for the event popup.
  1085. *
  1086. * @param string $popupid CSS id to use for event popup
  1087. * @param string $user Username of user the event pertains to
  1088. * @param string $description Event description
  1089. * @param string $time Time of the event (already formatted in a display format)
  1090. * @param string $site_extras HTML for any site_extras for this event
  1091. *
  1092. * @return string The HTML for the event popup
  1093. */
  1094. function build_event_popup ( $popupid, $user, $description, $time, $site_extras='' ) {
  1095. global $login, $popup_fullnames, $popuptemp_fullname;
  1096. $ret = "<dl id=\"$popupid\" class=\"popup\">\n";
  1097. if ( empty ( $popup_fullnames ) )
  1098. $popup_fullnames = array ();
  1099. if ( $user != $login ) {
  1100. if ( empty ( $popup_fullnames[$user] ) ) {
  1101. user_load_variables ( $user, "popuptemp_" );
  1102. $popup_fullnames[$user] = $popuptemp_fullname;
  1103. }
  1104. $ret .= "<dt>" . translate ("User") .
  1105. ":</dt>\n<dd>$popup_fullnames[$user]</dd>\n";
  1106. }
  1107. if ( strlen ( $time ) )
  1108. $ret .= "<dt>" . translate ("Time") . ":</dt>\n<dd>$time</dd>\n";
  1109. $ret .= "<dt>" . translate ("Description") . ":</dt>\n<dd>";
  1110. if ( ! empty ( $GLOBALS['allow_html_description'] ) &&
  1111. $GLOBALS['allow_html_description'] == 'Y' ) {
  1112. $str = str_replace ( "&", "&amp;", $description );
  1113. $str = str_replace ( "&amp;amp;", "&amp;", $str );
  1114. // If there is no html found, then go ahead and replace
  1115. // the line breaks ("\n") with the html break.
  1116. if ( strstr ( $str, "<" ) && strstr ( $str, ">" ) ) {
  1117. // found some html...
  1118. $ret .= $str;
  1119. } else {
  1120. // no html, replace line breaks
  1121. $ret .= nl2br ( $str );
  1122. }
  1123. } else {
  1124. // html not allowed in description, escape everything
  1125. $ret .= nl2br ( htmlspecialchars ( $description ) );
  1126. }
  1127. $ret .= "</dd>\n";
  1128. if ( ! empty ( $site_extras ) )
  1129. $ret .= $site_extras;
  1130. $ret .= "</dl>\n";
  1131. return $ret;
  1132. }
  1133. /**
  1134. * Prints out a date selection box for use in a form.
  1135. *
  1136. * @param string $prefix Prefix to use in front of form element names
  1137. * @param int $date Currently selected date (in YYYYMMDD format)
  1138. *
  1139. * @uses date_selection_html
  1140. */
  1141. function print_date_selection ( $prefix, $date ) {
  1142. print date_selection_html ( $prefix, $date );
  1143. }
  1144. /**
  1145. * Generate HTML for a date selection for use in a form.
  1146. *
  1147. * @param string $prefix Prefix to use in front of form element names
  1148. * @param int $date Currently selected date (in YYYYMMDD format)
  1149. *
  1150. * @return string HTML for the selection box
  1151. */
  1152. function date_selection_html ( $prefix, $date ) {
  1153. $ret = "";
  1154. $num_years = 20;
  1155. if ( strlen ( $date ) != 8 )
  1156. $date = date ( "Ymd" );
  1157. $thisyear = $year = substr ( $date, 0, 4 );
  1158. $thismonth = $month = substr ( $date, 4, 2 );
  1159. $thisday = $day = substr ( $date, 6, 2 );
  1160. if ( $thisyear - date ( "Y" ) >= ( $num_years - 1 ) )
  1161. $num_years = $thisyear - date ( "Y" ) + 2;
  1162. $ret .= "<select name=\"" . $prefix . "day\">\n";
  1163. for ( $i = 1; $i <= 31; $i++ )
  1164. $ret .= "<option value=\"$i\"" .
  1165. ( $i == $thisday ? " selected=\"selected\"" : "" ) . ">$i</option>\n";
  1166. $ret .= "</select>\n<select name=\"" . $prefix . "month\">\n";
  1167. for ( $i = 1; $i <= 12; $i++ ) {
  1168. $m = month_short_name ( $i - 1 );
  1169. $ret .= "<option value=\"$i\"" .
  1170. ( $i == $thismonth ? " selected=\"selected\"" : "" ) . ">$m</option>\n";
  1171. }
  1172. $ret .= "</select>\n<select name=\"" . $prefix . "year\">\n";
  1173. for ( $i = -10; $i < $num_years; $i++ ) {
  1174. $y = $thisyear + $i;
  1175. $ret .= "<option value=\"$y\"" .
  1176. ( $y == $thisyear ? " selected=\"selected\"" : "" ) . ">$y</option>\n";
  1177. }
  1178. $ret .= "</select>\n";
  1179. $ret .= "<input type=\"button\" onclick=\"selectDate( '" .
  1180. $prefix . "day','" . $prefix . "month','" . $prefix . "year',$date, event)\" value=\"" .
  1181. translate("Select") . "...\" />\n";
  1182. return $ret;
  1183. }
  1184. /**
  1185. * Prints out a minicalendar for a month.
  1186. *
  1187. * @todo Make day.php NOT be a special case
  1188. *
  1189. * @param int $thismonth Number of the month to print
  1190. * @param int $thisyear Number of the year
  1191. * @param bool $showyear Show the year in the calendar's title?
  1192. * @param bool $show_weeknums Show week numbers to the left of each row?
  1193. * @param string $minical_id id attribute for the minical table
  1194. * @param string $month_link URL and query string for month link that should
  1195. * come before the date specification (e.g.
  1196. * month.php? or view_l.php?id=7&amp;)
  1197. */
  1198. function display_small_month ( $thismonth, $thisyear, $showyear,
  1199. $show_weeknums=false, $minical_id='', $month_link='month.php?' ) {
  1200. global $WEEK_START, $user, $login, $boldDays, $get_unapproved;
  1201. global $DISPLAY_WEEKNUMBER;
  1202. global $SCRIPT, $thisday; // Needed for day.php
  1203. global $caturl, $today;
  1204. if ( $user != $login && ! empty ( $user ) ) {
  1205. $u_url = "user=$user" . "&amp;";
  1206. } else {
  1207. $u_url = '';
  1208. }
  1209. //start the minical table for each month
  1210. echo "\n<table class=\"minical\"";
  1211. if ( $minical_id != '' ) {
  1212. echo " id=\"$minical_id\"";
  1213. }
  1214. echo ">\n";
  1215. $monthstart = mktime(2,0,0,$thismonth,1,$thisyear);
  1216. $monthend = mktime(2,0,0,$thismonth + 1,0,$thisyear);
  1217. if ( $SCRIPT == 'day.php' ) {
  1218. $month_ago = date ( "Ymd",
  1219. mktime ( 3, 0, 0, $thismonth - 1, $thisday, $thisyear ) );
  1220. $month_ahead = date ( "Ymd",
  1221. mktime ( 3, 0, 0, $thismonth + 1, $thisday, $thisyear ) );
  1222. echo "<caption>$thisday</caption>\n";
  1223. echo "<thead>\n";
  1224. echo "<tr class=\"monthnav\"><th colspan=\"7\">\n";
  1225. echo "<a title=\"" .
  1226. translate("Previous") . "\" class=\"prev\" href=\"day.php?" . $u_url .
  1227. "date=$month_ago$caturl\"><img src=\"leftarrowsmall.gif\" alt=\"" .
  1228. translate("Previous") . "\" /></a>\n";
  1229. echo "<a title=\"" .
  1230. translate("Next") . "\" class=\"next\" href=\"day.php?" . $u_url .
  1231. "date=$month_ahead$caturl\"><img src=\"rightarrowsmall.gif\" alt=\"" .
  1232. translate("Next") . "\" /></a>\n";
  1233. echo month_name ( $thismonth - 1 );
  1234. if ( $showyear != '' ) {
  1235. echo " $thisyear";
  1236. }
  1237. echo "</th></tr>\n<tr>\n";
  1238. } else { //not day script
  1239. //print the month name
  1240. echo "<caption><a href=\"{$month_link}{$u_url}year=$thisyear&amp;month=$thismonth\">";
  1241. echo month_name ( $thismonth - 1 ) .
  1242. ( $showyear ? " $thisyear" : "" );
  1243. echo "</a></caption>\n";
  1244. echo "<thead>\n<tr>\n";
  1245. }
  1246. //determine if the week starts on sunday or monday
  1247. if ( $WEEK_START == "1" ) {
  1248. $wkstart = get_monday_before ( $thisyear, $thismonth, 1 );
  1249. } else {
  1250. $wkstart = get_sunday_before ( $thisyear, $thismonth, 1 );
  1251. }
  1252. //print the headers to display the day of the week (sun, mon, tues, etc.)
  1253. // if we're showing week numbers we need an extra column
  1254. if ( $show_weeknums && $DISPLAY_WEEKNUMBER == 'Y' )
  1255. echo "<th class=\"empty\">&nbsp;</th>\n";
  1256. //if the week doesn't start on monday, print the day
  1257. if ( $WEEK_START == 0 ) echo "<th>" .
  1258. weekday_short_name ( 0 ) . "</th>\n";
  1259. //cycle through each day of the week until gone
  1260. for ( $i = 1; $i < 7; $i++ ) {
  1261. echo "<th>" . weekday_short_name ( $i ) . "</th>\n";
  1262. }
  1263. //if the week DOES start on monday, print sunday
  1264. if ( $WEEK_START == 1 )
  1265. echo "<th>" . weekday_short_name ( 0 ) . "</th>\n";
  1266. //end the header row
  1267. echo "</tr>\n</thead>\n<tbody>\n";
  1268. for ($i = $wkstart; date("Ymd",$i) <= date ("Ymd",$monthend);
  1269. $i += (24 * 3600 * 7) ) {
  1270. echo "<tr>\n";
  1271. if ( $show_weeknums && $DISPLAY_WEEKNUMBER == 'Y' ) {
  1272. echo "<td class=\"weeknumber\"><a href=\"week.php?" . $u_url .
  1273. "date=".date("Ymd", $i)."\">(" . week_number($i) . ")</a></td>\n";
  1274. }
  1275. for ($j = 0; $j < 7; $j++) {
  1276. $date = $i + ($j * 24 * 3600);
  1277. $dateYmd = date ( "Ymd", $date );
  1278. $hasEvents = false;
  1279. if ( $boldDays ) {
  1280. $ev = get_entries ( $user, $dateYmd, $get_unapproved );
  1281. if ( count ( $ev ) > 0 ) {
  1282. $hasEvents = true;
  1283. } else {
  1284. $rep = get_repeating_entries ( $user, $dateYmd, $get_unapproved );
  1285. if ( count ( $rep ) > 0 )
  1286. $hasEvents = true;
  1287. }
  1288. }
  1289. if ( $dateYmd >= date ("Ymd",$monthstart) &&
  1290. $dateYmd <= date ("Ymd",$monthend) ) {
  1291. echo "<td";
  1292. $wday = date ( 'w', $date );
  1293. $class = '';
  1294. //add class="weekend" if it's saturday or sunday
  1295. if ( $wday == 0 || $wday == 6 ) {
  1296. $class = "weekend";
  1297. }
  1298. //if the day being viewed is today's date AND script = day.php
  1299. if ( $dateYmd == $thisyear . $thismonth . $thisday &&
  1300. $SCRIPT == 'day.php' ) {
  1301. //if it's also a weekend, add a space between class names to combine styles
  1302. if ( $class != '' ) {
  1303. $class .= ' ';
  1304. }
  1305. $class .= "selectedday";
  1306. }
  1307. if ( $hasEvents ) {
  1308. if ( $class != '' ) {
  1309. $class .= ' ';
  1310. }
  1311. $class .= "hasevents";
  1312. }
  1313. if ( $class != '' ) {
  1314. echo " class=\"$class\"";
  1315. }
  1316. if ( date ( "Ymd", $date ) == date ( "Ymd", $today ) ){
  1317. echo " id=\"today\"";
  1318. }
  1319. echo "><a href=\"day.php?" .$u_url . "date=" . $dateYmd .
  1320. "\">";
  1321. echo date ( "d", $date ) . "</a></td>\n";
  1322. } else {
  1323. echo "<td class=\"empty\">&nbsp;</td>\n";
  1324. }
  1325. } // end for $j
  1326. echo "</tr>\n";
  1327. } // end for $i
  1328. echo "</tbody>\n</table>\n";
  1329. }
  1330. /**
  1331. * Prints the HTML for one day's events in the month view.
  1332. *
  1333. * @param int $id Event ID
  1334. * @param int $date Date of event (relevant in repeating events) in
  1335. * YYYYMMDD format
  1336. * @param int $time Time (in HHMMSS format)
  1337. * @param int $duration Event duration in minutes
  1338. * @param string $name Event name
  1339. * @param string $description Long description of event
  1340. * @param string $status Event status
  1341. * @param int $pri Event priority
  1342. * @param string $access Event access
  1343. * @param string $event_owner Username of user associated with this event
  1344. * @param int $event_cat Category of event for <var>$event_owner</var>
  1345. *
  1346. * @staticvar int Used to ensure all event popups have a unique id
  1347. *
  1348. * @uses build_event_popup
  1349. */
  1350. function print_entry ( $id, $date, $time, $duration,
  1351. $name, $description, $status,
  1352. $pri, $access, $event_owner, $event_cat=-1 ) {
  1353. global $eventinfo, $login, $user, $PHP_SELF, $TZ_OFFSET;
  1354. static $key = 0;
  1355. global $layers;
  1356. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  1357. $class = "layerentry";
  1358. } else {
  1359. $class = "entry";
  1360. if ( $status == "W" ) $class = "unapprovedentry";
  1361. }
  1362. // if we are looking at a view, then always use "entry"
  1363. if ( strstr ( $PHP_SELF, "view_m.php" ) ||
  1364. strstr ( $PHP_SELF, "view_w.php" ) ||
  1365. strstr ( $PHP_SELF, "view_v.php" ) ||
  1366. strstr ( $PHP_SELF, "view_t.php" ) )
  1367. $class = "entry";
  1368. if ( $pri == 3 ) echo "<strong>";
  1369. $popupid = "eventinfo-$id-$key";
  1370. $key++;
  1371. echo "<a title=\"" .
  1372. translate("View this entry") . "\" class=\"$class\" href=\"view_entry.php?id=$id&amp;date=$date";
  1373. if ( strlen ( $user ) > 0 )
  1374. echo "&amp;user=" . $user;
  1375. echo "\" onmouseover=\"window.status='" .
  1376. translate("View this entry") .
  1377. "'; show(event, '$popupid'); return true;\" onmouseout=\"window.status=''; hide('$popupid'); return true;\">";
  1378. $icon = "circle.gif";
  1379. $catIcon = '';
  1380. if ( $event_cat > 0 ) {
  1381. $catIcon = "icons/cat-" . $event_cat . ".gif";
  1382. if ( ! file_exists ( $catIcon ) )
  1383. $catIcon = '';
  1384. }
  1385. if ( empty ( $catIcon ) ) {
  1386. echo "<img src=\"$icon\" class=\"bullet\" alt=\"" .
  1387. translate("View this entry") . "\" />";
  1388. } else {
  1389. // Use category icon
  1390. echo "<img src=\"$catIcon\" alt=\"" .
  1391. translate("View this entry") . "\" /><br />";
  1392. }
  1393. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  1394. if ($layers) foreach ($layers as $layer) {
  1395. if ($layer['cal_layeruser'] == $event_owner) {
  1396. echo("<span style=\"color:" . $layer['cal_color'] . ";\">");
  1397. }
  1398. }
  1399. }
  1400. $timestr = "";
  1401. if ( $duration == ( 24 * 60 ) ) {
  1402. $timestr = translate("All day event");
  1403. } else if ( $time != -1 ) {
  1404. $timestr = display_time ( $time );
  1405. $time_short = preg_replace ("/(:00)/", '', $timestr);
  1406. echo $time_short . "&raquo;&nbsp;";
  1407. if ( $duration > 0 ) {
  1408. // calc end time
  1409. $h = (int) ( $time / 10000 );
  1410. $m = ( $time / 100 ) % 100;
  1411. $m += $duration;
  1412. $d = $duration;
  1413. while ( $m >= 60 ) {
  1414. $h++;
  1415. $m -= 60;
  1416. }
  1417. $end_time = sprintf ( "%02d%02d00", $h, $m );
  1418. $timestr .= " - " . display_time ( $end_time );
  1419. }
  1420. }
  1421. if ( $login != $user && $access == 'R' && strlen ( $user ) ) {
  1422. echo "(" . translate("Private") . ")";
  1423. } else if ( $login != $event_owner && $access == 'R' &&
  1424. strlen ( $event_owner ) ) {
  1425. echo "(" . translate("Private") . ")";
  1426. } else {
  1427. echo htmlspecialchars ( $name );
  1428. }
  1429. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  1430. if ($layers) foreach ($layers as $layer) {
  1431. if($layer['cal_layeruser'] == $event_owner) {
  1432. echo "</span>";
  1433. }
  1434. }
  1435. }
  1436. echo "</a>\n";
  1437. if ( $pri == 3 ) echo "</strong>\n"; //end font-weight span
  1438. echo "<br />";
  1439. if ( $login != $user && $access == 'R' && strlen ( $user ) )
  1440. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  1441. translate("This event is confidential"), "" );
  1442. else
  1443. if ( $login != $event_owner && $access == 'R' && strlen ( $event_owner ) )
  1444. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  1445. translate("This event is confidential"), "" );
  1446. else
  1447. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  1448. $description, $timestr, site_extras_for_popup ( $id ) );
  1449. }
  1450. /**
  1451. * Gets any site-specific fields for an entry that are stored in the database in the webcal_site_extras table.
  1452. *
  1453. * @param int $eventid Event ID
  1454. *
  1455. * @return array Array with the keys as follows:
  1456. * - <var>cal_name</var>
  1457. * - <var>cal_type</var>
  1458. * - <var>cal_date</var>
  1459. * - <var>cal_remind</var>
  1460. * - <var>cal_data</var>
  1461. */
  1462. function get_site_extra_fields ( $eventid ) {
  1463. $sql = "SELECT cal_name, cal_type, cal_date, cal_remind, cal_data " .
  1464. "FROM webcal_site_extras " .
  1465. "WHERE cal_id = $eventid";
  1466. $res = dbi_query ( $sql );
  1467. $extras = array ();
  1468. if ( $res ) {
  1469. while ( $row = dbi_fetch_row ( $res ) ) {
  1470. // save by cal_name (e.g. "URL")
  1471. $extras[$row[0]] = array (
  1472. "cal_name" => $row[0],
  1473. "cal_type" => $row[1],
  1474. "cal_date" => $row[2],
  1475. "cal_remind" => $row[3],
  1476. "cal_data" => $row[4]
  1477. );
  1478. }
  1479. dbi_free_result ( $res );
  1480. }
  1481. return $extras;
  1482. }
  1483. /**
  1484. * Reads all the events for a user for the specified range of dates.
  1485. *
  1486. * This is only called once per page request to improve performance. All the
  1487. * events get loaded into the array <var>$events</var> sorted by time of day
  1488. * (not date).
  1489. *
  1490. * @param string $user Username
  1491. * @param string $startdate Start date range, inclusive (in YYYYMMDD format)
  1492. * @param string $enddate End date range, inclusive (in YYYYMMDD format)
  1493. * @param int $cat_id Category ID to filter on
  1494. *
  1495. * @return array Array of events
  1496. *
  1497. * @uses query_events
  1498. */
  1499. function read_events ( $user, $startdate, $enddate, $cat_id = '' ) {
  1500. global $login;
  1501. global $layers;
  1502. global $TZ_OFFSET;
  1503. $sy = substr ( $startdate, 0, 4 );
  1504. $sm = substr ( $startdate, 4, 2 );
  1505. $sd = substr ( $startdate, 6, 2 );
  1506. $ey = substr ( $enddate, 0, 4 );
  1507. $em = substr ( $enddate, 4, 2 );
  1508. $ed = substr ( $enddate, 6, 2 );
  1509. if ( $startdate == $enddate ) {
  1510. if ( $TZ_OFFSET == 0 ) {
  1511. $date_filter = " AND webcal_entry.cal_date = $startdate";
  1512. } else if ( $TZ_OFFSET > 0 ) {
  1513. $prev_day = mktime ( 3, 0, 0, $sm, $sd - 1, $sy );
  1514. $cutoff = 24 - $TZ_OFFSET . "0000";
  1515. $date_filter = " AND ( ( webcal_entry.cal_date = $startdate AND " .
  1516. "( webcal_entry.cal_time <= $cutoff OR " .
  1517. "webcal_entry.cal_time = -1 ) ) OR " .
  1518. "( webcal_entry.cal_date = " . date("Ymd", $prev_day ) .
  1519. " AND webcal_entry.cal_time >= $cutoff ) )";
  1520. } else {
  1521. $next_day = mktime ( 3, 0, 0, $sm, $sd + 1, $sy );
  1522. $cutoff = ( 0 - $TZ_OFFSET ) * 10000;
  1523. $date_filter = " AND ( ( webcal_entry.cal_date = $startdate AND " .
  1524. "( webcal_entry.cal_time > $cutoff OR " .
  1525. "webcal_entry.cal_time = -1 ) ) OR " .
  1526. "( webcal_entry.cal_date = " . date("Ymd", $next_day ) .
  1527. " AND webcal_entry.cal_time <= $cutoff ) )";
  1528. }
  1529. } else {
  1530. if ( $TZ_OFFSET == 0 ) {
  1531. $date_filter = " AND webcal_entry.cal_date >= $startdate " .
  1532. "AND webcal_entry.cal_date <= $enddate";
  1533. } else if ( $TZ_OFFSET > 0 ) {
  1534. $prev_day = date ( ( "Ymd" ), mktime ( 3, 0, 0, $sm, $sd - 1, $sy ) );
  1535. $enddate_minus1 = date ( ( "Ymd" ), mktime ( 3, 0, 0, $em, $ed - 1, $ey ) );
  1536. $cutoff = 24 - $TZ_OFFSET . "0000";
  1537. $date_filter = " AND ( ( webcal_entry.cal_date >= $startdate " .
  1538. "AND webcal_entry.cal_date <= $enddate AND " .
  1539. "webcal_entry.cal_time = -1 ) OR " .
  1540. "( webcal_entry.cal_date = $prev_day AND " .
  1541. "webcal_entry.cal_time >= $cutoff ) OR " .
  1542. "( webcal_entry.cal_date = $enddate AND " .
  1543. "webcal_entry.cal_time < $cutoff ) OR " .
  1544. "( webcal_entry.cal_date >= $startdate AND " .
  1545. "webcal_entry.cal_date <= $enddate_minus1 ) )";
  1546. } else {
  1547. // TZ_OFFSET < 0
  1548. $next_day = date ( ( "Ymd" ), mktime ( 3, 0, 0, $sm, $sd + 1, $sy ) );
  1549. $enddate_plus1 =
  1550. date ( ( "Ymd" ), mktime ( 3, 0, 0, $em, $ed + 1, $ey ) );
  1551. $cutoff = ( 0 - $TZ_OFFSET ) * 10000;
  1552. $date_filter = " AND ( ( webcal_entry.cal_date >= $startdate " .
  1553. "AND webcal_entry.cal_date <= $enddate AND " .
  1554. "webcal_entry.cal_time = -1 ) OR " .
  1555. "( webcal_entry.cal_date = $startdate AND " .
  1556. "webcal_entry.cal_time > $cutoff ) OR " .
  1557. "( webcal_entry.cal_date = $enddate_plus1 AND " .
  1558. "webcal_entry.cal_time <= $cutoff ) OR " .
  1559. "( webcal_entry.cal_date > $startdate AND " .
  1560. "webcal_entry.cal_date < $enddate_plus1 ) )";
  1561. }
  1562. }
  1563. return query_events ( $user, false, $date_filter, $cat_id );
  1564. }
  1565. /**
  1566. * Gets all the events for a specific date.
  1567. *
  1568. * Events are retreived from the array of pre-loaded events (which was loaded
  1569. * all at once to improve performance).
  1570. *
  1571. * The returned events will be sorted by time of day.
  1572. *
  1573. * @param string $user Username
  1574. * @param string $date Date to get events for in YYYYMMDD format
  1575. * @param bool $get_unapproved Load unapproved events?
  1576. *
  1577. * @return array Array of events
  1578. */
  1579. function get_entries ( $user, $date, $get_unapproved=true ) {
  1580. global $events, $TZ_OFFSET;
  1581. $n = 0;
  1582. $ret = array ();
  1583. //echo "<br />\nChecking " . count ( $events ) . " events. TZ_OFFSET = $TZ_OFFSET, get_unapproved=" . $get_unapproved . "<br />\n";
  1584. //print_r ( $events );
  1585. for ( $i = 0; $i < count ( $events ); $i++ ) {
  1586. // In case of data corruption (or some other bug...)
  1587. if ( empty ( $events[$i] ) || empty ( $events[$i]['cal_id'] ) )
  1588. continue;
  1589. if ( ( ! $get_unapproved ) && $events[$i]['cal_status'] == 'W' ) {
  1590. // ignore this event
  1591. //don't adjust anything if no TZ offset or ALL Day Event or Untimed
  1592. } else if ( empty ( $TZ_OFFSET) || ( $events[$i]['cal_time'] <= 0 ) ) {
  1593. if ( $events[$i]['cal_date'] == $date )
  1594. $ret[$n++] = $events[$i];
  1595. } else if ( $TZ_OFFSET > 0 ) {
  1596. $cutoff = ( 24 - $TZ_OFFSET ) * 10000;
  1597. //echo "<br /> cal_time " . $events[$i]['cal_time'] . "<br />\n";
  1598. $sy = substr ( $date, 0, 4 );
  1599. $sm = substr ( $date, 4, 2 );
  1600. $sd = substr ( $date, 6, 2 );
  1601. $prev_day = date ( ( "Ymd" ), mktime ( 3, 0, 0, $sm, $sd - 1, $sy ) );
  1602. //echo "prev_date = $prev_day <br />\n";
  1603. if ( $events[$i]['cal_date'] == $date &&
  1604. $events[$i]['cal_time'] == -1 ) {
  1605. $ret[$n++] = $events[$i];
  1606. //echo "added event $events[$i][cal_id] <br />\n";
  1607. } else if ( $events[$i]['cal_date'] == $date &&
  1608. $events[$i]['cal_time'] < $cutoff ) {
  1609. $ret[$n++] = $events[$i];
  1610. //echo "added event {$events[$i][cal_id]} <br />\n";
  1611. } else if ( $events[$i]['cal_date'] == $prev_day &&
  1612. $events[$i]['cal_time'] >= $cutoff ) {
  1613. $ret[$n++] = $events[$i];
  1614. //echo "added event {$events[$i][cal_id]} <br />\n";
  1615. }
  1616. } else {
  1617. //TZ < 0
  1618. $cutoff = ( 0 - $TZ_OFFSET ) * 10000;
  1619. //echo "<br />\ncal_time " . $events[$i]['cal_time'] . "<br />\n";
  1620. $sy = substr ( $date, 0, 4 );
  1621. $sm = substr ( $date, 4, 2 );
  1622. $sd = substr ( $date, 6, 2 );
  1623. $next_day = date ( ( "Ymd" ), mktime ( 3, 0, 0, $sm, $sd + 1, $sy ) );
  1624. //echo "next_date = $next_day <br />\n";
  1625. if ( $events[$i]['cal_time'] == -1 ) {
  1626. if ( $events[$i]['cal_date'] == $date ) {
  1627. $ret[$n++] = $events[$i];
  1628. //echo "added event $events[$i][cal_id] <br />\n";
  1629. }
  1630. } else {
  1631. if ( $events[$i]['cal_date'] == $date &&
  1632. $events[$i]['cal_time'] > $cutoff ) {
  1633. $ret[$n++] = $events[$i];
  1634. //echo "added event $events[$i][cal_id] <br />\n";
  1635. } else if ( $events[$i]['cal_date'] == $next_day &&
  1636. $events[$i]['cal_time'] <= $cutoff ) {
  1637. $ret[$n++] = $events[$i];
  1638. //echo "added event $events[$i][cal_id] <br />\n";
  1639. }
  1640. }
  1641. }
  1642. }
  1643. return $ret;
  1644. }
  1645. /**
  1646. * Reads events visible to a user.
  1647. *
  1648. * Includes layers and possibly public access if enabled
  1649. *
  1650. * @param string $user Username
  1651. * @param bool $want_repeated Get repeating events?
  1652. * @param string $date_filter SQL phrase starting with AND, to be appended to
  1653. * the WHERE clause. May be empty string.
  1654. * @param int $cat_id Category ID to filter on. May be empty.
  1655. *
  1656. * @return array Array of events sorted by time of day
  1657. */
  1658. function query_events ( $user, $want_repeated, $date_filter, $cat_id = '' ) {
  1659. global $login;
  1660. global $layers, $public_access_default_visible;
  1661. $result = array ();
  1662. $layers_byuser = array ();
  1663. $sql = "SELECT webcal_entry.cal_name, webcal_entry.cal_description, "
  1664. . "webcal_entry.cal_date, webcal_entry.cal_time, "
  1665. . "webcal_entry.cal_id, webcal_entry.cal_ext_for_id, "
  1666. . "webcal_entry.cal_priority, "
  1667. . "webcal_entry.cal_access, webcal_entry.cal_duration, "
  1668. . "webcal_entry_user.cal_status, "
  1669. . "webcal_entry_user.cal_category, "
  1670. . "webcal_entry_user.cal_login ";
  1671. if ( $want_repeated ) {
  1672. $sql .= ", "
  1673. . "webcal_entry_repeats.cal_type, webcal_entry_repeats.cal_end, "
  1674. . "webcal_entry_repeats.cal_frequency, webcal_entry_repeats.cal_days "
  1675. . "FROM webcal_entry, webcal_entry_repeats, webcal_entry_user "
  1676. . "WHERE webcal_entry.cal_id = webcal_entry_repeats.cal_id AND ";
  1677. } else {
  1678. $sql .= "FROM webcal_entry, webcal_entry_user WHERE ";
  1679. }
  1680. $sql .= "webcal_entry.cal_id = webcal_entry_user.cal_id " .
  1681. "AND webcal_entry_user.cal_status IN ('A','W') ";
  1682. if ( $cat_id != '' ) $sql .= "AND webcal_entry_user.cal_category LIKE '$cat_id' ";
  1683. if ( strlen ( $user ) > 0 )
  1684. $sql .= "AND (webcal_entry_user.cal_login = '" . $user . "' ";
  1685. if ( $user == $login && strlen ( $user ) > 0 ) {
  1686. if ($layers) foreach ($layers as $layer) {
  1687. $layeruser = $layer['cal_layeruser'];
  1688. $sql .= "OR webcal_entry_user.cal_login = '" . $layeruser . "' ";
  1689. // while we are parsing the whole layers array, build ourselves
  1690. // a new array that will help when we have to check for dups
  1691. $layers_byuser["$layeruser"] = $layer['cal_dups'];
  1692. }
  1693. }
  1694. if ( $user == $login && strlen ( $user ) &&
  1695. $public_access_default_visible == 'Y' ) {
  1696. $sql .= "OR webcal_entry_user.cal_login = '__public__' ";
  1697. }
  1698. if ( strlen ( $user ) > 0 )
  1699. $sql .= ") ";
  1700. $sql .= $date_filter;
  1701. // now order the results by time and by entry id.
  1702. $sql .= " ORDER BY webcal_entry.cal_time, webcal_entry.cal_id";
  1703. //echo "<strong>SQL:</strong> $sql<br />\n";
  1704. $res = dbi_query ( $sql );
  1705. if ( $res ) {
  1706. $i = 0;
  1707. $checkdup_id = -1;
  1708. $first_i_this_id = -1;
  1709. while ( $row = dbi_fetch_row ( $res ) ) {
  1710. if ($row[9] == 'R' || $row[9] == 'D') {
  1711. continue; // don't show rejected/deleted ones
  1712. }
  1713. $item = array (
  1714. "cal_name" => $row[0],
  1715. "cal_description" => $row[1],
  1716. "cal_date" => $row[2],
  1717. "cal_time" => $row[3],
  1718. "cal_id" => $row[4],
  1719. "cal_ext_for_id" => $row[5],
  1720. "cal_priority" => $row[6],
  1721. "cal_access" => $row[7],
  1722. "cal_duration" => $row[8],
  1723. "cal_status" => $row[9],
  1724. "cal_category" => $row[10],
  1725. "cal_login" => $row[11],
  1726. "cal_exceptions" => array()
  1727. );
  1728. if ( $want_repeated && ! empty ( $row[12] ) ) {
  1729. $item['cal_type'] = empty ( $row[12] ) ? "" : $row[12];
  1730. $item['cal_end'] = empty ( $row[13] ) ? "" : $row[13];
  1731. $item['cal_frequency'] = empty ( $row[14] ) ? "" : $row[14];
  1732. $item['cal_days'] = empty ( $row[15] ) ? "" : $row[15];
  1733. }
  1734. if ( $item['cal_id'] != $checkdup_id ) {
  1735. $checkdup_id = $item['cal_id'];
  1736. $first_i_this_id = $i;
  1737. }
  1738. if ( $item['cal_login'] == $user ) {
  1739. // Insert this one before all other ones with this ID.
  1740. my_array_splice ( $result, $first_i_this_id, 0, array($item) );
  1741. $i++;
  1742. if ($first_i_this_id + 1 < $i) {
  1743. // There's another one with the same ID as the one we inserted.
  1744. // Check for dup and if so, delete it.
  1745. $other_item = $result[$first_i_this_id + 1];
  1746. if ($layers_byuser[$other_item['cal_login']] == 'N') {
  1747. // NOTE: array_splice requires PHP4
  1748. my_array_splice ( $result, $first_i_this_id + 1, 1, "" );
  1749. $i--;
  1750. }
  1751. }
  1752. } else {
  1753. if ($i == $first_i_this_id
  1754. || ( ! empty ( $layers_byuser[$item['cal_login']] ) &&
  1755. $layers_byuser[$item['cal_login']] != 'N' ) ) {
  1756. // This item either is the first one with its ID, or allows dups.
  1757. // Add it to the end of the array.
  1758. $result [$i++] = $item;
  1759. }
  1760. }
  1761. }
  1762. dbi_free_result ( $res );
  1763. }
  1764. // Now load event exceptions and store as array in 'cal_exceptions' field
  1765. if ( $want_repeated ) {
  1766. for ( $i = 0; $i < count ( $result ); $i++ ) {
  1767. if ( ! empty ( $result[$i]['cal_id'] ) ) {
  1768. $res = dbi_query ( "SELECT cal_date FROM webcal_entry_repeats_not " .
  1769. "WHERE cal_id = " . $result[$i]['cal_id'] );
  1770. while ( $row = dbi_fetch_row ( $res ) ) {
  1771. $result[$i]['cal_exceptions'][] = $row[0];
  1772. }
  1773. }
  1774. }
  1775. }
  1776. return $result;
  1777. }
  1778. /**
  1779. * Reads all the repeated events for a user.
  1780. *
  1781. * This is only called once per page request to improve performance. All the
  1782. * events get loaded into the array <var>$repeated_events</var> sorted by time of day (not
  1783. * date).
  1784. *
  1785. * This will load all the repeated events into memory.
  1786. *
  1787. * <b>Notes:</b>
  1788. * - To get which events repeat on a specific date, use
  1789. * {@link get_repeating_entries()}.
  1790. * - To get all the dates that one specific event repeats on, call
  1791. * {@link get_all_dates()}.
  1792. *
  1793. * @param string $user Username
  1794. * @param int $cat_id Category ID to filter on (May be empty)
  1795. * @param string $date Cutoff date for repeating event endtimes in YYYYMMDD
  1796. * format (may be empty)
  1797. *
  1798. * @return Array of repeating events sorted by time of day
  1799. *
  1800. * @uses query_events
  1801. */
  1802. function read_repeated_events ( $user, $cat_id = '', $date = '' ) {
  1803. global $login;
  1804. global $layers;
  1805. $filter = ($date != '') ? "AND (webcal_entry_repeats.cal_end >= $date OR webcal_entry_repeats.cal_end IS NULL) " : '';
  1806. return query_events ( $user, true, $filter, $cat_id );
  1807. }
  1808. /**
  1809. * Returns all the dates a specific event will fall on accounting for the repeating.
  1810. *
  1811. * Any event with no end will be assigned one.
  1812. *
  1813. * @param string $date Initial date in raw format
  1814. * @param string $rpt_type Repeating type as stored in the database
  1815. * @param string $end End date
  1816. * @param string $days Days events occurs on (for weekly)
  1817. * @param array $ex_dates Array of exception dates for this event in YYYYMMDD format
  1818. * @param int $freq Frequency of repetition
  1819. *
  1820. * @return array Array of dates (in UNIX time format)
  1821. */
  1822. function get_all_dates ( $date, $rpt_type, $end, $days, $ex_days, $freq=1 ) {
  1823. global $conflict_repeat_months, $days_per_month, $ldays_per_month;
  1824. global $ONE_DAY;
  1825. //echo "get_all_dates ( $date, '$rpt_type', $end, '$days', [array], $freq ) <br>\n";
  1826. $currentdate = floor($date/$ONE_DAY)*$ONE_DAY;
  1827. $realend = floor($end/$ONE_DAY)*$ONE_DAY;
  1828. $dateYmd = date ( "Ymd", $date );
  1829. if ($end=='NULL') {
  1830. // Check for $conflict_repeat_months months into future for conflicts
  1831. $thismonth = substr($dateYmd, 4, 2);
  1832. $thisyear = substr($dateYmd, 0, 4);
  1833. $thisday = substr($dateYmd, 6, 2);
  1834. $thismonth += $conflict_repeat_months;
  1835. if ($thismonth > 12) {
  1836. $thisyear++;
  1837. $thismonth -= 12;
  1838. }
  1839. $realend = mktime(3,0,0,$thismonth,$thisday,$thisyear);
  1840. }
  1841. $ret = array();
  1842. $ret[0] = $date;
  1843. //do iterative checking here.
  1844. //I floored the $realend so I check it against the floored date
  1845. if ($rpt_type && $currentdate < $realend) {
  1846. $cdate = $date;
  1847. if (!$freq) $freq = 1;
  1848. $n = 1;
  1849. if ($rpt_type == 'daily') {
  1850. //we do inclusive counting on end dates.
  1851. $cdate += $ONE_DAY * $freq;
  1852. while ($cdate <= $realend+$ONE_DAY) {
  1853. if ( ! is_exception ( $cdate, $ex_days ) )
  1854. $ret[$n++]=$cdate;
  1855. $cdate += $ONE_DAY * $freq;
  1856. }
  1857. } else if ($rpt_type == 'weekly') {
  1858. $daysarray = array();
  1859. $r=0;
  1860. $dow = date("w",$date);
  1861. $cdate = $date - ($dow * $ONE_DAY);
  1862. for ($i = 0; $i < 7; $i++) {
  1863. $isDay = substr($days, $i, 1);
  1864. if (strcmp($isDay,"y")==0) {
  1865. $daysarray[$r++]=$i * $ONE_DAY;
  1866. }
  1867. }
  1868. //we do inclusive counting on end dates.
  1869. while ($cdate <= $realend+$ONE_DAY) {
  1870. //add all of the days of the week.
  1871. for ($j=0; $j<$r;$j++) {
  1872. $td = $cdate + $daysarray[$j];
  1873. if ($td >= $date) {
  1874. if ( ! is_exception ( $td, $ex_days ) )
  1875. $ret[$n++] = $td;
  1876. }
  1877. }
  1878. //skip to the next week in question.
  1879. $cdate += ( $ONE_DAY * 7 ) * $freq;
  1880. }
  1881. } else if ($rpt_type == 'monthlyByDay') {
  1882. $dow = date('w', $date);
  1883. $thismonth = substr($dateYmd, 4, 2);
  1884. $thisyear = substr($dateYmd, 0, 4);
  1885. $week = floor(date("d", $date)/7);
  1886. $thismonth+=$freq;
  1887. //dow1 is the weekday that the 1st of the month falls on
  1888. $dow1 = date('w',mktime (3,0,0,$thismonth,1,$thisyear));
  1889. $t = $dow - $dow1;
  1890. if ($t < 0) $t += 7;
  1891. $day = 7*$week + $t + 1;
  1892. $cdate = mktime (3,0,0,$thismonth,$day,$thisyear);
  1893. while ($cdate <= $realend+$ONE_DAY) {
  1894. if ( ! is_exception ( $cdate, $ex_days ) )
  1895. $ret[$n++] = $cdate;
  1896. $thismonth+=$freq;
  1897. //dow1 is the weekday that the 1st of the month falls on
  1898. $dow1time = mktime ( 3, 0, 0, $thismonth, 1, $thisyear );
  1899. $dow1 = date ( 'w', $dow1time );
  1900. $t = $dow - $dow1;
  1901. if ($t < 0) $t += 7;
  1902. $day = 7*$week + $t + 1;
  1903. $cdate = mktime (3,0,0,$thismonth,$day,$thisyear);
  1904. }
  1905. } else if ($rpt_type == 'monthlyByDayR') {
  1906. // by weekday of month reversed (i.e., last Monday of month)
  1907. $dow = date('w', $date);
  1908. $thisday = substr($dateYmd, 6, 2);
  1909. $thismonth = substr($dateYmd, 4, 2);
  1910. $thisyear = substr($dateYmd, 0, 4);
  1911. // get number of days in this month
  1912. $daysthismonth = $thisyear % 4 == 0 ? $ldays_per_month[$thismonth] :
  1913. $days_per_month[$thismonth];
  1914. // how many weekdays like this one remain in the month?
  1915. // 0=last one, 1=one more after this one, etc.
  1916. $whichWeek = floor ( ( $daysthismonth - $thisday ) / 7 );
  1917. // find first repeat date
  1918. $thismonth += $freq;
  1919. if ( $thismonth > 12 ) {
  1920. $thisyear++;
  1921. $thismonth -= 12;
  1922. }
  1923. // get weekday for last day of month
  1924. $dowLast += date('w',mktime (3,0,0,$thismonth + 1, -1,$thisyear));
  1925. if ( $dowLast >= $dow ) {
  1926. // last weekday is in last week of this month
  1927. $day = $daysthismonth - ( $dowLast - $dow ) -
  1928. ( 7 * $whichWeek );
  1929. } else {
  1930. // last weekday is NOT in last week of this month
  1931. $day = $daysthismonth - ( $dowLast - $dow ) -
  1932. ( 7 * ( $whichWeek + 1 ) );
  1933. }
  1934. $cdate = mktime (3,0,0,$thismonth,$day,$thisyear);
  1935. while ($cdate <= $realend+$ONE_DAY) {
  1936. if ( ! is_exception ( $cdate, $ex_days ) )
  1937. $ret[$n++] = $cdate;
  1938. $thismonth += $freq;
  1939. if ( $thismonth > 12 ) {
  1940. $thisyear++;
  1941. $thismonth -= 12;
  1942. }
  1943. // get weekday for last day of month
  1944. $dowLast += date('w',mktime (3,0,0,$thismonth + 1, -1,$thisyear));
  1945. if ( $dowLast >= $dow ) {
  1946. // last weekday is in last week of this month
  1947. $day = $daysthismonth - ( $dowLast - $dow ) -
  1948. ( 7 * $whichWeek );
  1949. } else {
  1950. // last weekday is NOT in last week of this month
  1951. $day = $daysthismonth - ( $dowLast - $dow ) -
  1952. ( 7 * ( $whichWeek + 1 ) );
  1953. }
  1954. $cdate = mktime (3,0,0,$thismonth,$day,$thisyear);
  1955. }
  1956. } else if ($rpt_type == 'monthlyByDate') {
  1957. $thismonth = substr($dateYmd, 4, 2);
  1958. $thisyear = substr($dateYmd, 0, 4);
  1959. $thisday = substr($dateYmd, 6, 2);
  1960. $hour = date('H',$date);
  1961. $minute = date('i',$date);
  1962. $thismonth += $freq;
  1963. $cdate = mktime (3,0,0,$thismonth,$thisday,$thisyear);
  1964. while ($cdate <= $realend+$ONE_DAY) {
  1965. if ( ! is_exception ( $cdate, $ex_days ) )
  1966. $ret[$n++] = $cdate;
  1967. $thismonth += $freq;
  1968. $cdate = mktime (3,0,0,$thismonth,$thisday,$thisyear);
  1969. }
  1970. } else if ($rpt_type == 'yearly') {
  1971. $thismonth = substr($dateYmd, 4, 2);
  1972. $thisyear = substr($dateYmd, 0, 4);
  1973. $thisday = substr($dateYmd, 6, 2);
  1974. $hour = date('H',$date);
  1975. $minute = date('i',$date);
  1976. $thisyear += $freq;
  1977. $cdate = mktime (3,0,0,$thismonth,$thisday,$thisyear);
  1978. while ($cdate <= $realend+$ONE_DAY) {
  1979. if ( ! is_exception ( $cdate, $ex_days ) )
  1980. $ret[$n++] = $cdate;
  1981. $thisyear += $freq;
  1982. $cdate = mktime (3,0,0,$thismonth,$thisday,$thisyear);
  1983. }
  1984. }
  1985. }
  1986. return $ret;
  1987. }
  1988. /**
  1989. * Gets all the repeating events for the specified date.
  1990. *
  1991. * <b>Note:</b>
  1992. * The global variable <var>$repeated_events</var> needs to be
  1993. * set by calling {@link read_repeated_events()} first.
  1994. *
  1995. * @param string $user Username
  1996. * @param string $date Date to get events for in YYYYMMDD format
  1997. * @param bool $get_unapproved Include unapproved events in results?
  1998. *
  1999. * @return mixed The query result resource on queries (which can then be
  2000. * passed to {@link dbi_fetch_row()} to obtain the results), or
  2001. * true/false on insert or delete queries.
  2002. *
  2003. * @global array Array of repeating events retreived using {@link read_repeated_events()}
  2004. */
  2005. function get_repeating_entries ( $user, $dateYmd, $get_unapproved=true ) {
  2006. global $repeated_events;
  2007. $n = 0;
  2008. $ret = array ();
  2009. //echo count($repeated_events)."<br />\n";
  2010. for ( $i = 0; $i < count ( $repeated_events ); $i++ ) {
  2011. if ( $repeated_events[$i]['cal_status'] == 'A' || $get_unapproved ) {
  2012. if ( repeated_event_matches_date ( $repeated_events[$i], $dateYmd ) ) {
  2013. // make sure this is not an exception date...
  2014. $unixtime = date_to_epoch ( $dateYmd );
  2015. if ( ! is_exception ( $unixtime, $repeated_events[$i]['cal_exceptions'] ) )
  2016. $ret[$n++] = $repeated_events[$i];
  2017. }
  2018. }
  2019. }
  2020. return $ret;
  2021. }
  2022. /**
  2023. * Determines whether the event passed in will fall on the date passed.
  2024. *
  2025. * @param array $event The event as an array
  2026. * @param string $dateYmd Date to check in YYYYMMDD format
  2027. *
  2028. * @return bool Does <var>$event</var> occur on <var>$dateYmd</var>?
  2029. */
  2030. function repeated_event_matches_date($event,$dateYmd) {
  2031. global $days_per_month, $ldays_per_month, $ONE_DAY;
  2032. // only repeat after the beginning, and if there is an end
  2033. // before the end
  2034. $date = date_to_epoch ( $dateYmd );
  2035. $thisyear = substr($dateYmd, 0, 4);
  2036. $start = date_to_epoch ( $event['cal_date'] );
  2037. $end = date_to_epoch ( $event['cal_end'] );
  2038. $freq = $event['cal_frequency'];
  2039. $thismonth = substr($dateYmd, 4, 2);
  2040. if ($event['cal_end'] && $dateYmd > date("Ymd",$end) )
  2041. return false;
  2042. if ( $dateYmd <= date("Ymd",$start) )
  2043. return false;
  2044. $id = $event['cal_id'];
  2045. if ($event['cal_type'] == 'daily') {
  2046. if ( (floor(($date - $start)/$ONE_DAY)%$freq) )
  2047. return false;
  2048. return true;
  2049. } else if ($event['cal_type'] == 'weekly') {
  2050. $dow = date("w", $date);
  2051. $dow1 = date("w", $start);
  2052. $isDay = substr($event['cal_days'], $dow, 1);
  2053. $wstart = $start - ($dow1 * $ONE_DAY);
  2054. if (floor(($date - $wstart)/604800)%$freq)
  2055. return false;
  2056. return (strcmp($isDay,"y") == 0);
  2057. } else if ($event['cal_type'] == 'monthlyByDay') {
  2058. $dowS = date("w", $start);
  2059. $dow = date("w", $date);
  2060. // do this comparison first in hopes of best performance
  2061. if ( $dowS != $dow )
  2062. return false;
  2063. $mthS = date("m", $start);
  2064. $yrS = date("Y", $start);
  2065. $dayS = floor(date("d", $start));
  2066. $dowS1 = ( date ( "w", $start - ( $ONE_DAY * ( $dayS - 1 ) ) ) + 35 ) % 7;
  2067. $days_in_first_weekS = ( 7 - $dowS1 ) % 7;
  2068. $whichWeekS = floor ( ( $dayS - $days_in_first_weekS ) / 7 );
  2069. if ( $dowS >= $dowS1 && $days_in_first_weekS )
  2070. $whichWeekS++;
  2071. //echo "dayS=$dayS;dowS=$dowS;dowS1=$dowS1;wWS=$whichWeekS<br />\n";
  2072. $mth = date("m", $date);
  2073. $yr = date("Y", $date);
  2074. $day = date("d", $date);
  2075. $dow1 = ( date ( "w", $date - ( $ONE_DAY * ( $day - 1 ) ) ) + 35 ) % 7;
  2076. $days_in_first_week = ( 7 - $dow1 ) % 7;
  2077. $whichWeek = floor ( ( $day - $days_in_first_week ) / 7 );
  2078. if ( $dow >= $dow1 && $days_in_first_week )
  2079. $whichWeek++;
  2080. //echo "day=$day;dow=$dow;dow1=$dow1;wW=$whichWeek<br />\n";
  2081. if ((($yr - $yrS)*12 + $mth - $mthS) % $freq)
  2082. return false;
  2083. return ( $whichWeek == $whichWeekS );
  2084. } else if ($event['cal_type'] == 'monthlyByDayR') {
  2085. $dowS = date("w", $start);
  2086. $dow = date("w", $date);
  2087. // do this comparison first in hopes of best performance
  2088. if ( $dowS != $dow )
  2089. return false;
  2090. $dayS = ceil(date("d", $start));
  2091. $mthS = ceil(date("m", $start));
  2092. $yrS = date("Y", $start);
  2093. $daysthismonthS = $mthS % 4 == 0 ? $ldays_per_month[$mthS] :
  2094. $days_per_month[$mthS];
  2095. $whichWeekS = floor ( ( $daysthismonthS - $dayS ) / 7 );
  2096. $day = ceil(date("d", $date));
  2097. $mth = ceil(date("m", $date));
  2098. $yr = date("Y", $date);
  2099. $daysthismonth = $mth % 4 == 0 ? $ldays_per_month[$mth] :
  2100. $days_per_month[$mth];
  2101. $whichWeek = floor ( ( $daysthismonth - $day ) / 7 );
  2102. if ((($yr - $yrS)*12 + $mth - $mthS) % $freq)
  2103. return false;
  2104. return ( $whichWeekS == $whichWeek );
  2105. } else if ($event['cal_type'] == 'monthlyByDate') {
  2106. $mthS = date("m", $start);
  2107. $yrS = date("Y", $start);
  2108. $mth = date("m", $date);
  2109. $yr = date("Y", $date);
  2110. if ((($yr - $yrS)*12 + $mth - $mthS) % $freq)
  2111. return false;
  2112. return (date("d", $date) == date("d", $start));
  2113. }
  2114. else if ($event['cal_type'] == 'yearly') {
  2115. $yrS = date("Y", $start);
  2116. $yr = date("Y", $date);
  2117. if (($yr - $yrS)%$freq)
  2118. return false;
  2119. return (date("dm", $date) == date("dm", $start));
  2120. } else {
  2121. // unknown repeat type
  2122. return false;
  2123. }
  2124. return false;
  2125. }
  2126. /**
  2127. * Converts a date to a timestamp.
  2128. *
  2129. * @param string $d Date in YYYYMMDD format
  2130. *
  2131. * @return int Timestamp representing 3:00 (or 4:00 if during Daylight Saving
  2132. * Time) in the morning on that day
  2133. */
  2134. function date_to_epoch ( $d ) {
  2135. if ( $d == 0 )
  2136. return 0;
  2137. $T = mktime ( 3, 0, 0, substr ( $d, 4, 2 ), substr ( $d, 6, 2 ), substr ( $d, 0, 4 ) );
  2138. $lt = localtime($T);
  2139. if ($lt[8]) {
  2140. return mktime ( 4, 0, 0, substr ( $d, 4, 2 ), substr ( $d, 6, 2 ), substr ( $d, 0, 4 ) );
  2141. } else {
  2142. return $T;
  2143. }
  2144. }
  2145. /**
  2146. * Checks if a date is an exception for an event.
  2147. *
  2148. * @param string $date Date in YYYYMMDD format
  2149. * @param array $exdays Array of dates in YYYYMMDD format
  2150. *
  2151. * @ignore
  2152. */
  2153. function is_exception ( $date, $ex_days ) {
  2154. $size = count ( $ex_days );
  2155. $count = 0;
  2156. $date = date ( "Ymd", $date );
  2157. //echo "Exception $date check.. count is $size <br />\n";
  2158. while ( $count < $size ) {
  2159. //echo "Exception date: $ex_days[$count] <br />\n";
  2160. if ( $date == $ex_days[$count++] )
  2161. return true;
  2162. }
  2163. return false;
  2164. }
  2165. /**
  2166. * Gets the Sunday of the week that the specified date is in.
  2167. *
  2168. * If the date specified is a Sunday, then that date is returned.
  2169. *
  2170. * @param int $year Year
  2171. * @param int $month Month (1-12)
  2172. * @param int $day Day of the month
  2173. *
  2174. * @return int The date (in UNIX timestamp format)
  2175. *
  2176. * @see get_monday_before
  2177. */
  2178. function get_sunday_before ( $year, $month, $day ) {
  2179. $weekday = date ( "w", mktime ( 3, 0, 0, $month, $day, $year ) );
  2180. $newdate = mktime ( 3, 0, 0, $month, $day - $weekday, $year );
  2181. return $newdate;
  2182. }
  2183. /**
  2184. * Gets the Monday of the week that the specified date is in.
  2185. *
  2186. * If the date specified is a Monday, then that date is returned.
  2187. *
  2188. * @param int $year Year
  2189. * @param int $month Month (1-12)
  2190. * @param int $day Day of the month
  2191. *
  2192. * @return int The date (in UNIX timestamp format)
  2193. *
  2194. * @see get_sunday_before
  2195. */
  2196. function get_monday_before ( $year, $month, $day ) {
  2197. $weekday = date ( "w", mktime ( 3, 0, 0, $month, $day, $year ) );
  2198. if ( $weekday == 0 )
  2199. return mktime ( 3, 0, 0, $month, $day - 6, $year );
  2200. if ( $weekday == 1 )
  2201. return mktime ( 3, 0, 0, $month, $day, $year );
  2202. return mktime ( 3, 0, 0, $month, $day - ( $weekday - 1 ), $year );
  2203. }
  2204. /**
  2205. * Returns the week number for specified date.
  2206. *
  2207. * Depends on week numbering settings.
  2208. *
  2209. * @param int $date Date in UNIX timestamp format
  2210. *
  2211. * @return string The week number of the specified date
  2212. */
  2213. function week_number ( $date ) {
  2214. $tmp = getdate($date);
  2215. $iso = gregorianToISO($tmp['mday'], $tmp['mon'], $tmp['year']);
  2216. $parts = explode('-',$iso);
  2217. $week_number = intval($parts[1]);
  2218. return sprintf("%02d",$week_number);
  2219. }
  2220. /**
  2221. * Generates the HTML for an add/edit/delete icon.
  2222. *
  2223. * This function is not yet used. Some of the places that will call it have to
  2224. * be updated to also get the event owner so we know if the current user has
  2225. * access to edit and delete.
  2226. *
  2227. * @param int $id Event ID
  2228. * @param bool $can_edit Can this user edit this event?
  2229. * @param bool $can_delete Can this user delete this event?
  2230. *
  2231. * @return HTML for add/edit/delete icon.
  2232. *
  2233. * @ignore
  2234. */
  2235. function icon_text ( $id, $can_edit, $can_delete ) {
  2236. global $readonly, $is_admin;
  2237. $ret = "<a title=\"" .
  2238. translate("View this entry") . "\" href=\"view_entry.php?id=$id\"><img src=\"view.gif\" alt=\"" .
  2239. translate("View this entry") . "\" style=\"border-width:0px; width:10px; height:10px;\" /></a>";
  2240. if ( $can_edit && $readonly == "N" )
  2241. $ret .= "<a title=\"" .
  2242. translate("Edit entry") . "\" href=\"edit_entry.php?id=$id\"><img src=\"edit.gif\" alt=\"" .
  2243. translate("Edit entry") . "\" style=\"border-width:0px; width:10px; height:10px;\" /></a>";
  2244. if ( $can_delete && ( $readonly == "N" || $is_admin ) )
  2245. $ret .= "<a title=\"" .
  2246. translate("Delete entry") . "\" href=\"del_entry.php?id=$id\" onclick=\"return confirm('" .
  2247. translate("Are you sure you want to delete this entry?") . "\\n\\n" .
  2248. translate("This will delete this entry for all users.") . "');\"><img src=\"delete.gif\" alt=\"" .
  2249. translate("Delete entry") . "\" style=\"border-width:0px; width:10px; height:10px;\" /></a>";
  2250. return $ret;
  2251. }
  2252. /**
  2253. * Prints all the calendar entries for the specified user for the specified date.
  2254. *
  2255. * If we are displaying data from someone other than
  2256. * the logged in user, then check the access permission of the entry.
  2257. *
  2258. * @param string $date Date in YYYYMMDD format
  2259. * @param string $user Username
  2260. * @param bool $ssi Is this being called from week_ssi.php?
  2261. */
  2262. function print_date_entries ( $date, $user, $ssi ) {
  2263. global $events, $readonly, $is_admin, $login,
  2264. $public_access, $public_access_can_add, $cat_id;
  2265. $cnt = 0;
  2266. $get_unapproved = ( $GLOBALS["DISPLAY_UNAPPROVED"] == "Y" );
  2267. // public access events always must be approved before being displayed
  2268. if ( $user == "__public__" )
  2269. $get_unapproved = false;
  2270. $year = substr ( $date, 0, 4 );
  2271. $month = substr ( $date, 4, 2 );
  2272. $day = substr ( $date, 6, 2 );
  2273. $dateu = mktime ( 3, 0, 0, $month, $day, $year );
  2274. $can_add = ( $readonly == "N" || $is_admin );
  2275. if ( $public_access == "Y" && $public_access_can_add != "Y" &&
  2276. $login == "__public__" )
  2277. $can_add = false;
  2278. if ( $readonly == 'Y' )
  2279. $can_add = false;
  2280. if ( ! $ssi && $can_add ) {
  2281. print "<a title=\"" .
  2282. translate("New Entry") . "\" href=\"edit_entry.php?";
  2283. if ( strcmp ( $user, $GLOBALS["login"] ) )
  2284. print "user=$user&amp;";
  2285. if ( ! empty ( $cat_id ) )
  2286. print "cat_id=$cat_id&amp;";
  2287. print "date=$date\"><img src=\"new.gif\" alt=\"" .
  2288. translate("New Entry") . "\" class=\"new\" /></a>";
  2289. $cnt++;
  2290. }
  2291. if ( ! $ssi ) {
  2292. echo "<a class=\"dayofmonth\" href=\"day.php?";
  2293. if ( strcmp ( $user, $GLOBALS["login"] ) )
  2294. echo "user=$user&amp;";
  2295. if ( ! empty ( $cat_id ) )
  2296. echo "cat_id=$cat_id&amp;";
  2297. echo "date=$date\">$day</a>";
  2298. if ( $GLOBALS["DISPLAY_WEEKNUMBER"] == "Y" &&
  2299. date ( "w", $dateu ) == $GLOBALS["WEEK_START"] ) {
  2300. echo "&nbsp;<a title=\"" .
  2301. translate("Week") . "&nbsp;" . week_number ( $dateu ) . "\" href=\"week.php?date=$date";
  2302. if ( strcmp ( $user, $GLOBALS["login"] ) )
  2303. echo "&amp;user=$user";
  2304. if ( ! empty ( $cat_id ) )
  2305. echo "&amp;cat_id=$cat_id";
  2306. echo "\" class=\"weeknumber\">";
  2307. echo "(" .
  2308. translate("Week") . "&nbsp;" . week_number ( $dateu ) . ")</a>";
  2309. }
  2310. print "<br />\n";
  2311. $cnt++;
  2312. }
  2313. // get all the repeating events for this date and store in array $rep
  2314. $rep = get_repeating_entries ( $user, $date, $get_unapproved );
  2315. $cur_rep = 0;
  2316. // get all the non-repeating events for this date and store in $ev
  2317. $ev = get_entries ( $user, $date, $get_unapproved );
  2318. for ( $i = 0; $i < count ( $ev ); $i++ ) {
  2319. // print out any repeating events that are before this one...
  2320. while ( $cur_rep < count ( $rep ) &&
  2321. $rep[$cur_rep]['cal_time'] < $ev[$i]['cal_time'] ) {
  2322. if ( $get_unapproved || $rep[$cur_rep]['cal_status'] == 'A' ) {
  2323. if ( ! empty ( $rep[$cur_rep]['cal_ext_for_id'] ) ) {
  2324. $viewid = $rep[$cur_rep]['cal_ext_for_id'];
  2325. $viewname = $rep[$cur_rep]['cal_name'] . " (" .
  2326. translate("cont.") . ")";
  2327. } else {
  2328. $viewid = $rep[$cur_rep]['cal_id'];
  2329. $viewname = $rep[$cur_rep]['cal_name'];
  2330. }
  2331. print_entry ( $viewid,
  2332. $date, $rep[$cur_rep]['cal_time'], $rep[$cur_rep]['cal_duration'],
  2333. $viewname, $rep[$cur_rep]['cal_description'],
  2334. $rep[$cur_rep]['cal_status'], $rep[$cur_rep]['cal_priority'],
  2335. $rep[$cur_rep]['cal_access'], $rep[$cur_rep]['cal_login'],
  2336. $rep[$cur_rep]['cal_category'] );
  2337. $cnt++;
  2338. }
  2339. $cur_rep++;
  2340. }
  2341. if ( $get_unapproved || $ev[$i]['cal_status'] == 'A' ) {
  2342. if ( ! empty ( $ev[$i]['cal_ext_for_id'] ) ) {
  2343. $viewid = $ev[$i]['cal_ext_for_id'];
  2344. $viewname = $ev[$i]['cal_name'] . " (" .
  2345. translate("cont.") . ")";
  2346. } else {
  2347. $viewid = $ev[$i]['cal_id'];
  2348. $viewname = $ev[$i]['cal_name'];
  2349. }
  2350. print_entry ( $viewid,
  2351. $date, $ev[$i]['cal_time'], $ev[$i]['cal_duration'],
  2352. $viewname, $ev[$i]['cal_description'],
  2353. $ev[$i]['cal_status'], $ev[$i]['cal_priority'],
  2354. $ev[$i]['cal_access'], $ev[$i]['cal_login'],
  2355. $ev[$i]['cal_category'] );
  2356. $cnt++;
  2357. }
  2358. }
  2359. // print out any remaining repeating events
  2360. while ( $cur_rep < count ( $rep ) ) {
  2361. if ( $get_unapproved || $rep[$cur_rep]['cal_status'] == 'A' ) {
  2362. if ( ! empty ( $rep[$cur_rep]['cal_ext_for_id'] ) ) {
  2363. $viewid = $rep[$cur_rep]['cal_ext_for_id'];
  2364. $viewname = $rep[$cur_rep]['cal_name'] . " (" .
  2365. translate("cont.") . ")";
  2366. } else {
  2367. $viewid = $rep[$cur_rep]['cal_id'];
  2368. $viewname = $rep[$cur_rep]['cal_name'];
  2369. }
  2370. print_entry ( $viewid,
  2371. $date, $rep[$cur_rep]['cal_time'], $rep[$cur_rep]['cal_duration'],
  2372. $viewname, $rep[$cur_rep]['cal_description'],
  2373. $rep[$cur_rep]['cal_status'], $rep[$cur_rep]['cal_priority'],
  2374. $rep[$cur_rep]['cal_access'], $rep[$cur_rep]['cal_login'],
  2375. $rep[$cur_rep]['cal_category'] );
  2376. $cnt++;
  2377. }
  2378. $cur_rep++;
  2379. }
  2380. if ( $cnt == 0 )
  2381. echo "&nbsp;"; // so the table cell has at least something
  2382. }
  2383. /**
  2384. * Checks to see if two events overlap.
  2385. *
  2386. * @param string $time1 Time 1 in HHMMSS format
  2387. * @param int $duration1 Duration 1 in minutes
  2388. * @param string $time2 Time 2 in HHMMSS format
  2389. * @param int $duration2 Duration 2 in minutes
  2390. *
  2391. * @return bool True if the two times overlap, false if they do not
  2392. */
  2393. function times_overlap ( $time1, $duration1, $time2, $duration2 ) {
  2394. //echo "times_overlap ( $time1, $duration1, $time2, $duration2 )<br />\n";
  2395. $hour1 = (int) ( $time1 / 10000 );
  2396. $min1 = ( $time1 / 100 ) % 100;
  2397. $hour2 = (int) ( $time2 / 10000 );
  2398. $min2 = ( $time2 / 100 ) % 100;
  2399. // convert to minutes since midnight
  2400. // remove 1 minute from duration so 9AM-10AM will not conflict with 10AM-11AM
  2401. if ( $duration1 > 0 )
  2402. $duration1 -= 1;
  2403. if ( $duration2 > 0 )
  2404. $duration2 -= 1;
  2405. $tmins1start = $hour1 * 60 + $min1;
  2406. $tmins1end = $tmins1start + $duration1;
  2407. $tmins2start = $hour2 * 60 + $min2;
  2408. $tmins2end = $tmins2start + $duration2;
  2409. //echo "tmins1start=$tmins1start, tmins1end=$tmins1end, tmins2start=$tmins2start, tmins2end=$tmins2end<br />\n";
  2410. if ( ( $tmins1start >= $tmins2end ) || ( $tmins2start >= $tmins1end ) )
  2411. return false;
  2412. return true;
  2413. }
  2414. /**
  2415. * Checks for conflicts.
  2416. *
  2417. * Find overlaps between an array of dates and the other dates in the database.
  2418. *
  2419. * Limits on number of appointments: if enabled in System Settings
  2420. * (<var>$limit_appts</var> global variable), too many appointments can also
  2421. * generate a scheduling conflict.
  2422. *
  2423. * @todo Update this to handle exceptions to repeating events
  2424. *
  2425. * @param array $dates Array of dates in YYYYMMDD format that is
  2426. * checked for overlaps.
  2427. * @param int $duration Event duration in minutes
  2428. * @param int $hour Hour of event (0-23)
  2429. * @param int $minute Minute of the event (0-59)
  2430. * @param array $participants Array of users whose calendars are to be checked
  2431. * @param string $login The current user name
  2432. * @param int $id Current event id (this keeps overlaps from
  2433. * wrongly checking an event against itself)
  2434. *
  2435. * @return Empty string for no conflicts or return the HTML of the
  2436. * conflicts when one or more are found.
  2437. */
  2438. function check_for_conflicts ( $dates, $duration, $hour, $minute,
  2439. $participants, $login, $id ) {
  2440. global $single_user_login, $single_user;
  2441. global $repeated_events, $limit_appts, $limit_appts_number;
  2442. if (!count($dates)) return false;
  2443. $evtcnt = array ();
  2444. $sql = "SELECT distinct webcal_entry_user.cal_login, webcal_entry.cal_time," .
  2445. "webcal_entry.cal_duration, webcal_entry.cal_name, " .
  2446. "webcal_entry.cal_id, webcal_entry.cal_ext_for_id, " .
  2447. "webcal_entry.cal_access, " .
  2448. "webcal_entry_user.cal_status, webcal_entry.cal_date " .
  2449. "FROM webcal_entry, webcal_entry_user " .
  2450. "WHERE webcal_entry.cal_id = webcal_entry_user.cal_id " .
  2451. "AND (";
  2452. for ($x = 0; $x < count($dates); $x++) {
  2453. if ($x != 0) $sql .= " OR ";
  2454. $sql.="webcal_entry.cal_date = " . date ( "Ymd", $dates[$x] );
  2455. }
  2456. $sql .= ") AND webcal_entry.cal_time >= 0 " .
  2457. "AND webcal_entry_user.cal_status IN ('A','W') AND ( ";
  2458. if ( $single_user == "Y" ) {
  2459. $participants[0] = $single_user_login;
  2460. } else if ( strlen ( $participants[0] ) == 0 ) {
  2461. // likely called from a form with 1 user
  2462. $participants[0] = $login;
  2463. }
  2464. for ( $i = 0; $i < count ( $participants ); $i++ ) {
  2465. if ( $i > 0 )
  2466. $sql .= " OR ";
  2467. $sql .= " webcal_entry_user.cal_login = '" . $participants[$i] . "'";
  2468. }
  2469. $sql .= " )";
  2470. // make sure we don't get something past the end date of the
  2471. // event we are saving.
  2472. //echo "SQL: $sql<br />\n";
  2473. $conflicts = "";
  2474. $res = dbi_query ( $sql );
  2475. $found = array();
  2476. $count = 0;
  2477. if ( $res ) {
  2478. $time1 = sprintf ( "%d%02d00", $hour, $minute );
  2479. $duration1 = sprintf ( "%d", $duration );
  2480. while ( $row = dbi_fetch_row ( $res ) ) {
  2481. //Add to an array to see if it has been found already for the next part.
  2482. $found[$count++] = $row[4];
  2483. // see if either event overlaps one another
  2484. if ( $row[4] != $id && ( empty ( $row[5] ) || $row[5] != $id ) ) {
  2485. $time2 = $row[1];
  2486. $duration2 = $row[2];
  2487. $cntkey = $row[0] . "-" . $row[8];
  2488. if ( empty ( $evtcnt[$cntkey] ) )
  2489. $evtcnt[$cntkey] = 0;
  2490. else
  2491. $evtcnt[$cntkey]++;
  2492. $over_limit = 0;
  2493. if ( $limit_appts == "Y" && $limit_appts_number > 0
  2494. && $evtcnt[$cntkey] >= $limit_appts_number ) {
  2495. $over_limit = 1;
  2496. }
  2497. if ( $over_limit ||
  2498. times_overlap ( $time1, $duration1, $time2, $duration2 ) ) {
  2499. $conflicts .= "<li>";
  2500. if ( $single_user != "Y" )
  2501. $conflicts .= "$row[0]: ";
  2502. if ( $row[6] == 'R' && $row[0] != $login )
  2503. $conflicts .= "(" . translate("Private") . ")";
  2504. else {
  2505. $conflicts .= "<a href=\"view_entry.php?id=$row[4]";
  2506. if ( $row[0] != $login )
  2507. $conflicts .= "&amp;user=$row[0]";
  2508. $conflicts .= "\">$row[3]</a>";
  2509. }
  2510. if ( $duration2 == ( 24 * 60 ) ) {
  2511. $conflicts .= " (" . translate("All day event") . ")";
  2512. } else {
  2513. $conflicts .= " (" . display_time ( $time2 );
  2514. if ( $duration2 > 0 )
  2515. $conflicts .= "-" .
  2516. display_time ( add_duration ( $time2, $duration2 ) );
  2517. $conflicts .= ")";
  2518. }
  2519. $conflicts .= " on " . date_to_str( $row[8] );
  2520. if ( $over_limit ) {
  2521. $tmp = translate ( "exceeds limit of XXX events per day" );
  2522. $tmp = str_replace ( "XXX", $limit_appts_number, $tmp );
  2523. $conflicts .= " (" . $tmp . ")";
  2524. }
  2525. $conflicts .= "</li>\n";
  2526. }
  2527. }
  2528. }
  2529. dbi_free_result ( $res );
  2530. } else {
  2531. echo translate("Database error") . ": " . dbi_error (); exit;
  2532. }
  2533. //echo "<br />\nhello";
  2534. for ($q=0;$q<count($participants);$q++) {
  2535. $time1 = sprintf ( "%d%02d00", $hour, $minute );
  2536. $duration1 = sprintf ( "%d", $duration );
  2537. //This date filter is not necessary for functional reasons, but it eliminates some of the
  2538. //events that couldn't possibly match. This could be made much more complex to put more
  2539. //of the searching work onto the database server, or it could be dropped all together to put
  2540. //the searching work onto the client.
  2541. $date_filter = "AND (webcal_entry.cal_date <= " . date("Ymd",$dates[count($dates)-1]);
  2542. $date_filter .= " AND (webcal_entry_repeats.cal_end IS NULL OR webcal_entry_repeats.cal_end >= " . date("Ymd",$dates[0]) . "))";
  2543. //Read repeated events for the participants only once for a participant for
  2544. //for performance reasons.
  2545. $repeated_events=query_events($participants[$q],true,$date_filter);
  2546. //for ($dd=0; $dd<count($repeated_events); $dd++) {
  2547. // echo $repeated_events[$dd]['cal_id'] . "<br />";
  2548. //}
  2549. for ($i=0; $i < count($dates); $i++) {
  2550. $dateYmd = date ( "Ymd", $dates[$i] );
  2551. $list = get_repeating_entries($participants[$q],$dateYmd);
  2552. $thisyear = substr($dateYmd, 0, 4);
  2553. $thismonth = substr($dateYmd, 4, 2);
  2554. for ($j=0; $j < count($list);$j++) {
  2555. //okay we've narrowed it down to a day, now I just gotta check the time...
  2556. //I hope this is right...
  2557. $row = $list[$j];
  2558. if ( $row['cal_id'] != $id && ( empty ( $row['cal_ext_for_id'] ) ||
  2559. $row['cal_ext_for_id'] != $id ) ) {
  2560. $time2 = $row['cal_time'];
  2561. $duration2 = $row['cal_duration'];
  2562. if ( times_overlap ( $time1, $duration1, $time2, $duration2 ) ) {
  2563. $conflicts .= "<li>";
  2564. if ( $single_user != "Y" )
  2565. $conflicts .= $row['cal_login'] . ": ";
  2566. if ( $row['cal_access'] == 'R' && $row['cal_login'] != $login )
  2567. $conflicts .= "(" . translate("Private") . ")";
  2568. else {
  2569. $conflicts .= "<a href=\"view_entry.php?id=" . $row['cal_id'];
  2570. if ( ! empty ( $user ) && $user != $login )
  2571. $conflicts .= "&amp;user=$user";
  2572. $conflicts .= "\">" . $row['cal_name'] . "</a>";
  2573. }
  2574. $conflicts .= " (" . display_time ( $time2 );
  2575. if ( $duration2 > 0 )
  2576. $conflicts .= "-" .
  2577. display_time ( add_duration ( $time2, $duration2 ) );
  2578. $conflicts .= ")";
  2579. $conflicts .= " on " . date("l, F j, Y", $dates[$i]);
  2580. $conflicts .= "</li>\n";
  2581. }
  2582. }
  2583. }
  2584. }
  2585. }
  2586. return $conflicts;
  2587. }
  2588. /**
  2589. * Converts a time format HHMMSS (like 130000 for 1PM) into number of minutes past midnight.
  2590. *
  2591. * @param string $time Input time in HHMMSS format
  2592. *
  2593. * @return int The number of minutes since midnight
  2594. */
  2595. function time_to_minutes ( $time ) {
  2596. $h = (int) ( $time / 10000 );
  2597. $m = (int) ( $time / 100 ) % 100;
  2598. $num = $h * 60 + $m;
  2599. return $num;
  2600. }
  2601. /**
  2602. * Calculates which row/slot this time represents.
  2603. *
  2604. * This is used in day and week views where hours of the time are separeted
  2605. * into different cells in a table.
  2606. *
  2607. * <b>Note:</b> the global variable <var>$TIME_SLOTS</var> is used to determine
  2608. * how many time slots there are and how many minutes each is. This variable
  2609. * is defined user preferences (or defaulted to admin system settings).
  2610. *
  2611. * @param string $time Input time in HHMMSS format
  2612. * @param bool $round_down Should we change 1100 to 1059?
  2613. * (This will make sure a 10AM-100AM appointment just
  2614. * shows up in the 10AM slow and not in the 11AM slot
  2615. * also.)
  2616. *
  2617. * @return int The time slot index
  2618. */
  2619. function calc_time_slot ( $time, $round_down = false ) {
  2620. global $TIME_SLOTS, $TZ_OFFSET;
  2621. $interval = ( 24 * 60 ) / $TIME_SLOTS;
  2622. $mins_since_midnight = time_to_minutes ( $time );
  2623. $ret = (int) ( $mins_since_midnight / $interval );
  2624. if ( $round_down ) {
  2625. if ( $ret * $interval == $mins_since_midnight )
  2626. $ret--;
  2627. }
  2628. //echo "$mins_since_midnight / $interval = $ret <br />\n";
  2629. if ( $ret > $TIME_SLOTS )
  2630. $ret = $TIME_SLOTS;
  2631. //echo "<br />\ncalc_time_slot($time) = $ret <br />\nTIME_SLOTS = $TIME_SLOTS<br />\n";
  2632. return $ret;
  2633. }
  2634. /**
  2635. * Generates the HTML for an icon to add a new event.
  2636. *
  2637. * @param string $date Date for new event in YYYYMMDD format
  2638. * @param int $hour Hour of day (0-23)
  2639. * @param int $minute Minute of the hour (0-59)
  2640. * @param string $user Participant to initially select for new event
  2641. *
  2642. * @return string The HTML for the add event icon
  2643. */
  2644. function html_for_add_icon ( $date=0,$hour="", $minute="", $user="" ) {
  2645. global $TZ_OFFSET;
  2646. global $login, $readonly, $cat_id;
  2647. $u_url = '';
  2648. if ( $readonly == 'Y' )
  2649. return '';
  2650. if ( $minute < 0 ) {
  2651. $minute = abs($minute);
  2652. $hour = $hour -1;
  2653. }
  2654. if ( ! empty ( $user ) && $user != $login )
  2655. $u_url = "user=$user&amp;";
  2656. if ( isset ( $hour ) && $hour != NULL )
  2657. $hour += $TZ_OFFSET;
  2658. return "<a title=\"" .
  2659. translate("New Entry") . "\" href=\"edit_entry.php?" . $u_url .
  2660. "date=$date" . ( isset ( $hour ) && $hour != NULL && $hour >= 0 ? "&amp;hour=$hour" : "" ) .
  2661. ( $minute > 0 ? "&amp;minute=$minute" : "" ) .
  2662. ( empty ( $user ) ? "" : "&amp;defusers=$user" ) .
  2663. ( empty ( $cat_id ) ? "" : "&amp;cat_id=$cat_id" ) .
  2664. "\"><img src=\"new.gif\" class=\"new\" alt=\"" .
  2665. translate("New Entry") . "\" /></a>\n";
  2666. }
  2667. /**
  2668. * Generates the HTML for an event to be viewed in the week-at-glance (week.php).
  2669. *
  2670. * The HTML will be stored in an array (global variable $hour_arr)
  2671. * indexed on the event's starting hour.
  2672. *
  2673. * @param int $id Event id
  2674. * @param string $date Date of event in YYYYMMDD format
  2675. * @param string $time Time of event in HHMM format
  2676. * @param string $name Brief description of event
  2677. * @param string $description Full description of event
  2678. * @param string $status Status of event ('A', 'W')
  2679. * @param int $pri Priority of event
  2680. * @param string $access Access to event by others ('P', 'R')
  2681. * @param int $duration Duration of event in minutes
  2682. * @param string $event_owner User who created event
  2683. * @param int $event_category Category id for event
  2684. */
  2685. function html_for_event_week_at_a_glance ( $id, $date, $time,
  2686. $name, $description, $status, $pri, $access, $duration, $event_owner,
  2687. $event_category=-1 ) {
  2688. global $first_slot, $last_slot, $hour_arr, $rowspan_arr, $rowspan,
  2689. $eventinfo, $login, $user;
  2690. static $key = 0;
  2691. global $DISPLAY_ICONS, $PHP_SELF, $TIME_SLOTS;
  2692. global $layers;
  2693. $popupid = "eventinfo-day-$id-$key";
  2694. $key++;
  2695. // Figure out which time slot it goes in.
  2696. if ( $time >= 0 && $duration != ( 24 * 60 ) ) {
  2697. $ind = calc_time_slot ( $time );
  2698. if ( $ind < $first_slot )
  2699. $first_slot = $ind;
  2700. if ( $ind > $last_slot )
  2701. $last_slot = $ind;
  2702. } else
  2703. $ind = 9999;
  2704. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  2705. $class = "layerentry";
  2706. } else {
  2707. $class = "entry";
  2708. if ( $status == "W" ) $class = "unapprovedentry";
  2709. }
  2710. // if we are looking at a view, then always use "entry"
  2711. if ( strstr ( $PHP_SELF, "view_m.php" ) ||
  2712. strstr ( $PHP_SELF, "view_w.php" ) ||
  2713. strstr ( $PHP_SELF, "view_v.php" ) ||
  2714. strstr ( $PHP_SELF, "view_t.php" ) )
  2715. $class = "entry";
  2716. // avoid php warning for undefined array index
  2717. if ( empty ( $hour_arr[$ind] ) )
  2718. $hour_arr[$ind] = "";
  2719. $catIcon = "icons/cat-" . $event_category . ".gif";
  2720. if ( $event_category > 0 && file_exists ( $catIcon ) ) {
  2721. $hour_arr[$ind] .= "<img src=\"$catIcon\" alt=\"$catIcon\" />";
  2722. }
  2723. $hour_arr[$ind] .= "<a title=\"" .
  2724. translate("View this entry") . "\" class=\"$class\" href=\"view_entry.php?id=$id&amp;date=$date";
  2725. if ( strlen ( $GLOBALS["user"] ) > 0 )
  2726. $hour_arr[$ind] .= "&amp;user=" . $GLOBALS["user"];
  2727. $hour_arr[$ind] .= "\" onmouseover=\"window.status='" .
  2728. translate("View this entry") . "'; show(event, '$popupid'); return true;\" onmouseout=\"hide('$popupid'); return true;\">";
  2729. if ( $pri == 3 )
  2730. $hour_arr[$ind] .= "<strong>";
  2731. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  2732. if ($layers) foreach ($layers as $layer) {
  2733. if ( $layer['cal_layeruser'] == $event_owner ) {
  2734. $in_span = true;
  2735. $hour_arr[$ind] .= "<span style=\"color:" . $layer['cal_color'] . ";\">";
  2736. }
  2737. }
  2738. }
  2739. if ( $duration == ( 24 * 60 ) ) {
  2740. $timestr = translate("All day event");
  2741. } else if ( $time >= 0 ) {
  2742. $hour_arr[$ind] .= display_time ( $time ) . "&raquo;&nbsp;";
  2743. $timestr = display_time ( $time );
  2744. if ( $duration > 0 ) {
  2745. // calc end time
  2746. $h = (int) ( $time / 10000 );
  2747. $m = ( $time / 100 ) % 100;
  2748. $m += $duration;
  2749. $d = $duration;
  2750. while ( $m >= 60 ) {
  2751. $h++;
  2752. $m -= 60;
  2753. }
  2754. $end_time = sprintf ( "%02d%02d00", $h, $m );
  2755. $timestr .= "-" . display_time ( $end_time );
  2756. } else {
  2757. $end_time = 0;
  2758. }
  2759. if ( empty ( $rowspan_arr[$ind] ) )
  2760. $rowspan_arr[$ind] = 0; // avoid warning below
  2761. // which slot is end time in? take one off so we don't
  2762. // show 11:00-12:00 as taking up both 11 and 12 slots.
  2763. $endind = calc_time_slot ( $end_time, true );
  2764. if ( $endind == $ind )
  2765. $rowspan = 0;
  2766. else
  2767. $rowspan = $endind - $ind + 1;
  2768. if ( $rowspan > $rowspan_arr[$ind] && $rowspan > 1 )
  2769. $rowspan_arr[$ind] = $rowspan;
  2770. } else {
  2771. $timestr = "";
  2772. }
  2773. // avoid php warning of undefined index when using .= below
  2774. if ( empty ( $hour_arr[$ind] ) )
  2775. $hour_arr[$ind] = "";
  2776. if ( $login != $user && $access == 'R' && strlen ( $user ) ) {
  2777. $hour_arr[$ind] .= "(" . translate("Private") . ")";
  2778. } else if ( $login != $event_owner && $access == 'R' &&
  2779. strlen ( $event_owner ) ) {
  2780. $hour_arr[$ind] .= "(" . translate("Private") . ")";
  2781. } else if ( $login != $event_owner && strlen ( $event_owner ) ) {
  2782. $hour_arr[$ind] .= htmlspecialchars ( $name );
  2783. if ( ! empty ( $in_span ) )
  2784. $hour_arr[$ind] .= "</span>"; //end color span
  2785. } else {
  2786. $hour_arr[$ind] .= htmlspecialchars ( $name );
  2787. }
  2788. if ( $pri == 3 ) $hour_arr[$ind] .= "</strong>"; //end font-weight span
  2789. $hour_arr[$ind] .= "</a>";
  2790. //if ( $DISPLAY_ICONS == "Y" ) {
  2791. // $hour_arr[$ind] .= icon_text ( $id, true, true );
  2792. //}
  2793. $hour_arr[$ind] .= "<br />\n";
  2794. if ( $login != $user && $access == 'R' && strlen ( $user ) ) {
  2795. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  2796. translate("This event is confidential"), "" );
  2797. } else if ( $login != $event_owner && $access == 'R' &&
  2798. strlen ( $event_owner ) ) {
  2799. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  2800. translate("This event is confidential"), "" );
  2801. } else {
  2802. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  2803. $description, $timestr, site_extras_for_popup ( $id ) );
  2804. }
  2805. }
  2806. /**
  2807. * Generates the HTML for an event to be viewed in the day-at-glance (day.php).
  2808. *
  2809. * The HTML will be stored in an array (global variable $hour_arr)
  2810. * indexed on the event's starting hour.
  2811. *
  2812. * @param int $id Event id
  2813. * @param string $date Date of event in YYYYMMDD format
  2814. * @param string $time Time of event in HHMM format
  2815. * @param string $name Brief description of event
  2816. * @param string $description Full description of event
  2817. * @param string $status Status of event ('A', 'W')
  2818. * @param int $pri Priority of event
  2819. * @param string $access Access to event by others ('P', 'R')
  2820. * @param int $duration Duration of event in minutes
  2821. * @param string $event_owner User who created event
  2822. * @param int $event_category Category id for event
  2823. */
  2824. function html_for_event_day_at_a_glance ( $id, $date, $time,
  2825. $name, $description, $status, $pri, $access, $duration, $event_owner,
  2826. $event_category=-1 ) {
  2827. global $first_slot, $last_slot, $hour_arr, $rowspan_arr, $rowspan,
  2828. $eventinfo, $login, $user;
  2829. static $key = 0;
  2830. global $layers, $PHP_SELF, $TIME_SLOTS, $TZ_OFFSET;
  2831. $popupid = "eventinfo-day-$id-$key";
  2832. $key++;
  2833. if ( $login != $user && $access == 'R' && strlen ( $user ) )
  2834. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  2835. translate("This event is confidential"), "" );
  2836. else if ( $login != $event_owner && $access == 'R' &&
  2837. strlen ( $event_owner ) )
  2838. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  2839. translate("This event is confidential"), "" );
  2840. else
  2841. $eventinfo .= build_event_popup ( $popupid, $event_owner, $description,
  2842. "", site_extras_for_popup ( $id ) );
  2843. // calculate slot length in minutes
  2844. $interval = ( 60 * 24 ) / $TIME_SLOTS;
  2845. // If TZ_OFFSET make this event before the start of the day or
  2846. // after the end of the day, adjust the time slot accordingly.
  2847. if ( $time >= 0 && $duration != ( 24 * 60 ) ) {
  2848. if ( $time + ( $TZ_OFFSET * 10000 ) > 240000 )
  2849. $time -= 240000;
  2850. else if ( $time + ( $TZ_OFFSET * 10000 ) < 0 )
  2851. $time += 240000;
  2852. $ind = calc_time_slot ( $time );
  2853. if ( $ind < $first_slot )
  2854. $first_slot = $ind;
  2855. if ( $ind > $last_slot )
  2856. $last_slot = $ind;
  2857. } else
  2858. $ind = 9999;
  2859. //echo "time = $time <br />\nind = $ind <br />\nfirst_slot = $first_slot<br />\n";
  2860. if ( empty ( $hour_arr[$ind] ) )
  2861. $hour_arr[$ind] = "";
  2862. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  2863. $class = "layerentry";
  2864. } else {
  2865. $class = "entry";
  2866. if ( $status == "W" )
  2867. $class = "unapprovedentry";
  2868. }
  2869. // if we are looking at a view, then always use "entry"
  2870. if ( strstr ( $PHP_SELF, "view_m.php" ) ||
  2871. strstr ( $PHP_SELF, "view_w.php" ) ||
  2872. strstr ( $PHP_SELF, "view_v.php" ) ||
  2873. strstr ( $PHP_SELF, "view_t.php" ) )
  2874. $class = "entry";
  2875. $catIcon = "icons/cat-" . $event_category . ".gif";
  2876. if ( $event_category > 0 && file_exists ( $catIcon ) ) {
  2877. $hour_arr[$ind] .= "<img src=\"$catIcon\" alt=\"$catIcon\" />";
  2878. }
  2879. $hour_arr[$ind] .= "<a title=\"" .
  2880. translate("View this entry") . "\" class=\"$class\" href=\"view_entry.php?id=$id&amp;date=$date";
  2881. if ( strlen ( $GLOBALS["user"] ) > 0 )
  2882. $hour_arr[$ind] .= "&amp;user=" . $GLOBALS["user"];
  2883. $hour_arr[$ind] .= "\" onmouseover=\"window.status='" .
  2884. translate("View this entry") . "'; show(event, '$popupid'); return true;\" onmouseout=\"hide('$popupid'); return true;\">";
  2885. if ( $pri == 3 ) $hour_arr[$ind] .= "<strong>";
  2886. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  2887. if ($layers) foreach ($layers as $layer) {
  2888. if ( $layer['cal_layeruser'] == $event_owner) {
  2889. $in_span = true;
  2890. $hour_arr[$ind] .= "<span style=\"color:" . $layer['cal_color'] . ";\">";
  2891. }
  2892. }
  2893. }
  2894. if ( $duration == ( 24 * 60 ) ) {
  2895. $hour_arr[$ind] .= "[" . translate("All day event") . "] ";
  2896. } else if ( $time >= 0 ) {
  2897. $hour_arr[$ind] .= "[" . display_time ( $time );
  2898. if ( $duration > 0 ) {
  2899. // calc end time
  2900. $h = (int) ( $time / 10000 );
  2901. $m = ( $time / 100 ) % 100;
  2902. $m += $duration;
  2903. $d = $duration;
  2904. while ( $m >= 60 ) {
  2905. $h++;
  2906. $m -= 60;
  2907. }
  2908. $end_time = sprintf ( "%02d%02d00", $h, $m );
  2909. $hour_arr[$ind] .= "-" . display_time ( $end_time );
  2910. // which slot is end time in? take one off so we don't
  2911. // show 11:00-12:00 as taking up both 11 and 12 slots.
  2912. $endind = calc_time_slot ( $end_time, true );
  2913. if ( $endind == $ind )
  2914. $rowspan = 0;
  2915. else
  2916. $rowspan = $endind - $ind + 1;
  2917. if ( ! isset ( $rowspan_arr[$ind] ) )
  2918. $rowspan_arr[$ind] = 0;
  2919. if ( $rowspan > $rowspan_arr[$ind] && $rowspan > 1 )
  2920. $rowspan_arr[$ind] = $rowspan;
  2921. }
  2922. $hour_arr[$ind] .= "] ";
  2923. }
  2924. if ( $login != $user && $access == 'R' && strlen ( $user ) )
  2925. $hour_arr[$ind] .= "(" . translate("Private") . ")";
  2926. else
  2927. if ( $login != $event_owner && $access == 'R' && strlen ( $event_owner ) )
  2928. $hour_arr[$ind] .= "(" . translate("Private") . ")";
  2929. else
  2930. if ( $login != $event_owner && strlen ( $event_owner ) )
  2931. {
  2932. $hour_arr[$ind] .= htmlspecialchars ( $name );
  2933. if ( ! empty ( $in_span ) )
  2934. $hour_arr[$ind] .= "</span>"; //end color span
  2935. }
  2936. else
  2937. $hour_arr[$ind] .= htmlspecialchars ( $name );
  2938. if ( $pri == 3 ) $hour_arr[$ind] .= "</strong>"; //end font-weight span
  2939. $hour_arr[$ind] .= "</a>";
  2940. if ( $GLOBALS["DISPLAY_DESC_PRINT_DAY"] == "Y" ) {
  2941. $hour_arr[$ind] .= "\n<dl class=\"desc\">\n";
  2942. $hour_arr[$ind] .= "<dt>" . translate("Description") . ":</dt>\n<dd>";
  2943. if ( ! empty ( $GLOBALS['allow_html_description'] ) &&
  2944. $GLOBALS['allow_html_description'] == 'Y' ) {
  2945. $str = str_replace ( "&", "&amp;", $description );
  2946. $str = str_replace ( "&amp;amp;", "&amp;", $str );
  2947. // If there is no html found, then go ahead and replace
  2948. // the line breaks ("\n") with the html break.
  2949. if ( strstr ( $str, "<" ) && strstr ( $str, ">" ) ) {
  2950. // found some html...
  2951. $hour_arr[$ind] .= $str;
  2952. } else {
  2953. // no html, replace line breaks
  2954. $hour_arr[$ind] .= nl2br ( $str );
  2955. }
  2956. } else {
  2957. // html not allowed in description, escape everything
  2958. $hour_arr[$ind] .= nl2br ( htmlspecialchars ( $description ) );
  2959. }
  2960. $hour_arr[$ind] .= "</dd>\n</dl>\n";
  2961. }
  2962. $hour_arr[$ind] .= "<br />\n";
  2963. }
  2964. /**
  2965. * Prints all the calendar entries for the specified user for the specified date in day-at-a-glance format.
  2966. *
  2967. * If we are displaying data from someone other than
  2968. * the logged in user, then check the access permission of the entry.
  2969. *
  2970. * @param string $date Date in YYYYMMDD format
  2971. * @param string $user Username of calendar
  2972. */
  2973. function print_day_at_a_glance ( $date, $user, $can_add=0 ) {
  2974. global $first_slot, $last_slot, $hour_arr, $rowspan_arr, $rowspan;
  2975. global $TABLEBG, $CELLBG, $TODAYCELLBG, $THFG, $THBG, $TIME_SLOTS, $TZ_OFFSET;
  2976. global $WORK_DAY_START_HOUR, $WORK_DAY_END_HOUR;
  2977. global $repeated_events;
  2978. $get_unapproved = ( $GLOBALS["DISPLAY_UNAPPROVED"] == "Y" );
  2979. if ( $user == "__public__" )
  2980. $get_unapproved = false;
  2981. if ( empty ( $TIME_SLOTS ) ) {
  2982. echo "Error: TIME_SLOTS undefined!<br />\n";
  2983. return;
  2984. }
  2985. // $interval is number of minutes per slot
  2986. $interval = ( 24 * 60 ) / $TIME_SLOTS;
  2987. $rowspan_arr = array ();
  2988. for ( $i = 0; $i < $TIME_SLOTS; $i++ ) {
  2989. $rowspan_arr[$i] = 0;
  2990. }
  2991. // get all the repeating events for this date and store in array $rep
  2992. $rep = get_repeating_entries ( $user, $date );
  2993. $cur_rep = 0;
  2994. // Get static non-repeating events
  2995. $ev = get_entries ( $user, $date, $get_unapproved );
  2996. $hour_arr = array ();
  2997. $interval = ( 24 * 60 ) / $TIME_SLOTS;
  2998. $first_slot = (int) ( ( ( $WORK_DAY_START_HOUR - $TZ_OFFSET ) * 60 ) / $interval );
  2999. $last_slot = (int) ( ( ( $WORK_DAY_END_HOUR - $TZ_OFFSET ) * 60 ) / $interval);
  3000. //echo "first_slot = $first_slot<br />\nlast_slot = $last_slot<br />\ninterval = $interval<br />\nTIME_SLOTS = $TIME_SLOTS<br />\n";
  3001. $rowspan_arr = array ();
  3002. $all_day = 0;
  3003. for ( $i = 0; $i < count ( $ev ); $i++ ) {
  3004. // print out any repeating events that are before this one...
  3005. while ( $cur_rep < count ( $rep ) &&
  3006. $rep[$cur_rep]['cal_time'] < $ev[$i]['cal_time'] ) {
  3007. if ( $get_unapproved || $rep[$cur_rep]['cal_status'] == 'A' ) {
  3008. if ( ! empty ( $rep[$cur_rep]['cal_ext_for_id'] ) ) {
  3009. $viewid = $rep[$cur_rep]['cal_ext_for_id'];
  3010. $viewname = $rep[$cur_rep]['cal_name'] . " (" .
  3011. translate("cont.") . ")";
  3012. } else {
  3013. $viewid = $rep[$cur_rep]['cal_id'];
  3014. $viewname = $rep[$cur_rep]['cal_name'];
  3015. }
  3016. if ( $rep[$cur_rep]['cal_duration'] == ( 24 * 60 ) )
  3017. $all_day = 1;
  3018. html_for_event_day_at_a_glance ( $viewid,
  3019. $date, $rep[$cur_rep]['cal_time'],
  3020. $viewname, $rep[$cur_rep]['cal_description'],
  3021. $rep[$cur_rep]['cal_status'], $rep[$cur_rep]['cal_priority'],
  3022. $rep[$cur_rep]['cal_access'], $rep[$cur_rep]['cal_duration'],
  3023. $rep[$cur_rep]['cal_login'], $rep[$cur_rep]['cal_category'] );
  3024. }
  3025. $cur_rep++;
  3026. }
  3027. if ( $get_unapproved || $ev[$i]['cal_status'] == 'A' ) {
  3028. if ( ! empty ( $ev[$i]['cal_ext_for_id'] ) ) {
  3029. $viewid = $ev[$i]['cal_ext_for_id'];
  3030. $viewname = $ev[$i]['cal_name'] . " (" .
  3031. translate("cont.") . ")";
  3032. } else {
  3033. $viewid = $ev[$i]['cal_id'];
  3034. $viewname = $ev[$i]['cal_name'];
  3035. }
  3036. if ( $ev[$i]['cal_duration'] == ( 24 * 60 ) )
  3037. $all_day = 1;
  3038. html_for_event_day_at_a_glance ( $viewid,
  3039. $date, $ev[$i]['cal_time'],
  3040. $viewname, $ev[$i]['cal_description'],
  3041. $ev[$i]['cal_status'], $ev[$i]['cal_priority'],
  3042. $ev[$i]['cal_access'], $ev[$i]['cal_duration'],
  3043. $ev[$i]['cal_login'], $ev[$i]['cal_category'] );
  3044. }
  3045. }
  3046. // print out any remaining repeating events
  3047. while ( $cur_rep < count ( $rep ) ) {
  3048. if ( $get_unapproved || $rep[$cur_rep]['cal_status'] == 'A' ) {
  3049. if ( ! empty ( $rep[$cur_rep]['cal_ext_for_id'] ) ) {
  3050. $viewid = $rep[$cur_rep]['cal_ext_for_id'];
  3051. $viewname = $rep[$cur_rep]['cal_name'] . " (" .
  3052. translate("cont.") . ")";
  3053. } else {
  3054. $viewid = $rep[$cur_rep]['cal_id'];
  3055. $viewname = $rep[$cur_rep]['cal_name'];
  3056. }
  3057. if ( $rep[$cur_rep]['cal_duration'] == ( 24 * 60 ) )
  3058. $all_day = 1;
  3059. html_for_event_day_at_a_glance ( $viewid,
  3060. $date, $rep[$cur_rep]['cal_time'],
  3061. $viewname, $rep[$cur_rep]['cal_description'],
  3062. $rep[$cur_rep]['cal_status'], $rep[$cur_rep]['cal_priority'],
  3063. $rep[$cur_rep]['cal_access'], $rep[$cur_rep]['cal_duration'],
  3064. $rep[$cur_rep]['cal_login'], $rep[$cur_rep]['cal_category'] );
  3065. }
  3066. $cur_rep++;
  3067. }
  3068. // squish events that use the same cell into the same cell.
  3069. // For example, an event from 8:00-9:15 and another from 9:30-9:45 both
  3070. // want to show up in the 8:00-9:59 cell.
  3071. $rowspan = 0;
  3072. $last_row = -1;
  3073. //echo "First SLot: $first_slot; Last Slot: $last_slot<br />\n";
  3074. $i = 0;
  3075. if ( $first_slot < 0 )
  3076. $i = $first_slot;
  3077. for ( ; $i < $TIME_SLOTS; $i++ ) {
  3078. if ( $rowspan > 1 ) {
  3079. if ( ! empty ( $hour_arr[$i] ) ) {
  3080. $diff_start_time = $i - $last_row;
  3081. if ( $rowspan_arr[$i] > 1 ) {
  3082. if ( $rowspan_arr[$i] + ( $diff_start_time ) > $rowspan_arr[$last_row] ) {
  3083. $rowspan_arr[$last_row] = ( $rowspan_arr[$i] + ( $diff_start_time ) );
  3084. }
  3085. $rowspan += ( $rowspan_arr[$i] - 1 );
  3086. } else {
  3087. $rowspan_arr[$last_row] += $rowspan_arr[$i];
  3088. }
  3089. // this will move entries apart that appear in one field,
  3090. // yet start on different hours
  3091. for ( $u = $diff_start_time ; $u > 0 ; $u-- ) {
  3092. $hour_arr[$last_row] .= "<br />\n";
  3093. }
  3094. $hour_arr[$last_row] .= $hour_arr[$i];
  3095. $hour_arr[$i] = "";
  3096. $rowspan_arr[$i] = 0;
  3097. }
  3098. $rowspan--;
  3099. } else if ( ! empty ( $rowspan_arr[$i] ) && $rowspan_arr[$i] > 1 ) {
  3100. $rowspan = $rowspan_arr[$i];
  3101. $last_row = $i;
  3102. }
  3103. }
  3104. if ( ! empty ( $hour_arr[9999] ) ) {
  3105. echo "<tr><th class=\"empty\">&nbsp;</th>\n" .
  3106. "<td class=\"hasevents\">$hour_arr[9999]</td></tr>\n";
  3107. }
  3108. $rowspan = 0;
  3109. //echo "first_slot = $first_slot<br />\nlast_slot = $last_slot<br />\ninterval = $interval<br />\n";
  3110. for ( $i = $first_slot; $i <= $last_slot; $i++ ) {
  3111. $time_h = (int) ( ( $i * $interval ) / 60 );
  3112. $time_m = ( $i * $interval ) % 60;
  3113. $time = display_time ( ( $time_h * 100 + $time_m ) * 100 );
  3114. echo "<tr>\n<th class=\"row\">" . $time . "</th>\n";
  3115. if ( $rowspan > 1 ) {
  3116. // this might mean there's an overlap, or it could mean one event
  3117. // ends at 11:15 and another starts at 11:30.
  3118. if ( ! empty ( $hour_arr[$i] ) ) {
  3119. echo "<td class=\"hasevents\">";
  3120. if ( $can_add )
  3121. echo html_for_add_icon ( $date, $time_h, $time_m, $user );
  3122. echo "$hour_arr[$i]</td>\n";
  3123. }
  3124. $rowspan--;
  3125. } else {
  3126. if ( empty ( $hour_arr[$i] ) ) {
  3127. echo "<td>";
  3128. if ( $can_add ) {
  3129. echo html_for_add_icon ( $date, $time_h, $time_m, $user ) . "</td>";
  3130. } else {
  3131. echo "&nbsp;</td>";
  3132. }
  3133. echo "</tr>\n";
  3134. } else {
  3135. if ( empty ( $rowspan_arr[$i] ) )
  3136. $rowspan = '';
  3137. else
  3138. $rowspan = $rowspan_arr[$i];
  3139. if ( $rowspan > 1 ) {
  3140. echo "<td rowspan=\"$rowspan\" class=\"hasevents\">";
  3141. if ( $can_add )
  3142. echo html_for_add_icon ( $date, $time_h, $time_m, $user );
  3143. echo "$hour_arr[$i]</td></tr>\n";
  3144. } else {
  3145. echo "<td class=\"hasevents\">";
  3146. if ( $can_add )
  3147. echo html_for_add_icon ( $date, $time_h, $time_m, $user );
  3148. echo "$hour_arr[$i]</td></tr>\n";
  3149. }
  3150. }
  3151. }
  3152. }
  3153. }
  3154. /**
  3155. * Checks for any unnaproved events.
  3156. *
  3157. * If any are found, display a link to the unapproved events (where they can be
  3158. * approved).
  3159. *
  3160. * If the user is an admin user, also count up any public events.
  3161. * If the user is a nonuser admin, count up events on the nonuser calendar.
  3162. *
  3163. * @param string $user Current user login
  3164. */
  3165. function display_unapproved_events ( $user ) {
  3166. global $public_access, $is_admin, $nonuser_enabled, $login;
  3167. // Don't do this for public access login, admin user must approve public
  3168. // events
  3169. if ( $user == "__public__" )
  3170. return;
  3171. $sql = "SELECT COUNT(webcal_entry_user.cal_id) " .
  3172. "FROM webcal_entry_user, webcal_entry " .
  3173. "WHERE webcal_entry_user.cal_id = webcal_entry.cal_id " .
  3174. "AND webcal_entry_user.cal_status = 'W' " .
  3175. "AND ( webcal_entry.cal_ext_for_id IS NULL " .
  3176. "OR webcal_entry.cal_ext_for_id = 0 ) " .
  3177. "AND ( webcal_entry_user.cal_login = '$user'";
  3178. if ( $public_access == "Y" && $is_admin ) {
  3179. $sql .= " OR webcal_entry_user.cal_login = '__public__'";
  3180. }
  3181. if ( $nonuser_enabled == 'Y' ) {
  3182. $admincals = get_nonuser_cals ( $login );
  3183. for ( $i = 0; $i < count ( $admincals ); $i++ ) {
  3184. $sql .= " OR webcal_entry_user.cal_login = '" .
  3185. $admincals[$i]['cal_login'] . "'";
  3186. }
  3187. }
  3188. $sql .= " )";
  3189. //print "SQL: $sql<br />\n";
  3190. $res = dbi_query ( $sql );
  3191. if ( $res ) {
  3192. if ( $row = dbi_fetch_row ( $res ) ) {
  3193. if ( $row[0] > 0 ) {
  3194. $str = translate ("You have XXX unapproved events");
  3195. $str = str_replace ( "XXX", $row[0], $str );
  3196. echo "<a class=\"nav\" href=\"list_unapproved.php";
  3197. if ( $user != $login )
  3198. echo "?user=$user\"";
  3199. echo "\">" . $str . "</a><br />\n";
  3200. }
  3201. }
  3202. dbi_free_result ( $res );
  3203. }
  3204. }
  3205. /**
  3206. * Looks for URLs in the given text, and makes them into links.
  3207. *
  3208. * @param string $text Input text
  3209. *
  3210. * @return string The text altered to have HTML links for any web links
  3211. * (http or https)
  3212. */
  3213. function activate_urls ( $text ) {
  3214. $str = eregi_replace ( "(http://[^[:space:]$]+)",
  3215. "<a href=\"\\1\">\\1</a>", $text );
  3216. $str = eregi_replace ( "(https://[^[:space:]$]+)",
  3217. "<a href=\"\\1\">\\1</a>", $str );
  3218. return $str;
  3219. }
  3220. /**
  3221. * Displays a time in either 12 or 24 hour format.
  3222. *
  3223. * The global variable $TZ_OFFSET is used to adjust the time. Note that this
  3224. * is somewhat of a kludge for timezone support. If an event is set for 11PM
  3225. * server time and the user is 2 hours ahead, it will show up as 1AM, but the
  3226. * date will not be adjusted to the next day.
  3227. *
  3228. * @param string $time Input time in HHMMSS format
  3229. * @param bool $ignore_offset If true, then do not use the timezone offset
  3230. *
  3231. * @return string The time in the user's timezone and preferred format
  3232. *
  3233. * @global int The user's timezone offset from the server
  3234. */
  3235. function display_time ( $time, $ignore_offset=0 ) {
  3236. global $TZ_OFFSET;
  3237. $hour = (int) ( $time / 10000 );
  3238. if ( ! $ignore_offset )
  3239. $hour += $TZ_OFFSET;
  3240. $min = abs( ( $time / 100 ) % 100 );
  3241. //Prevent goofy times like 8:00 9:30 9:00 10:30 10:00
  3242. if ( $time < 0 && $min > 0 ) $hour = $hour - 1;
  3243. while ( $hour < 0 )
  3244. $hour += 24;
  3245. while ( $hour > 23 )
  3246. $hour -= 24;
  3247. if ( $GLOBALS["TIME_FORMAT"] == "12" ) {
  3248. $ampm = ( $hour >= 12 ) ? translate("pm") : translate("am");
  3249. $hour %= 12;
  3250. if ( $hour == 0 )
  3251. $hour = 12;
  3252. $ret = sprintf ( "%d:%02d%s", $hour, $min, $ampm );
  3253. } else {
  3254. $ret = sprintf ( "%d:%02d", $hour, $min );
  3255. }
  3256. return $ret;
  3257. }
  3258. /**
  3259. * Returns the full name of the specified month.
  3260. *
  3261. * Use {@link month_short_name()} to get the abbreviated name of the month.
  3262. *
  3263. * @param int $m Number of the month (0-11)
  3264. *
  3265. * @return string The full name of the specified month
  3266. *
  3267. * @see month_short_name
  3268. */
  3269. function month_name ( $m ) {
  3270. switch ( $m ) {
  3271. case 0: return translate("January");
  3272. case 1: return translate("February");
  3273. case 2: return translate("March");
  3274. case 3: return translate("April");
  3275. case 4: return translate("May_"); // needs to be different than "May"
  3276. case 5: return translate("June");
  3277. case 6: return translate("July");
  3278. case 7: return translate("August");
  3279. case 8: return translate("September");
  3280. case 9: return translate("October");
  3281. case 10: return translate("November");
  3282. case 11: return translate("December");
  3283. }
  3284. return "unknown-month($m)";
  3285. }
  3286. /**
  3287. * Returns the abbreviated name of the specified month (such as "Jan").
  3288. *
  3289. * Use {@link month_name()} to get the full name of the month.
  3290. *
  3291. * @param int $m Number of the month (0-11)
  3292. *
  3293. * @return string The abbreviated name of the specified month (example: "Jan")
  3294. *
  3295. * @see month_name
  3296. */
  3297. function month_short_name ( $m ) {
  3298. switch ( $m ) {
  3299. case 0: return translate("Jan");
  3300. case 1: return translate("Feb");
  3301. case 2: return translate("Mar");
  3302. case 3: return translate("Apr");
  3303. case 4: return translate("May");
  3304. case 5: return translate("Jun");
  3305. case 6: return translate("Jul");
  3306. case 7: return translate("Aug");
  3307. case 8: return translate("Sep");
  3308. case 9: return translate("Oct");
  3309. case 10: return translate("Nov");
  3310. case 11: return translate("Dec");
  3311. }
  3312. return "unknown-month($m)";
  3313. }
  3314. /**
  3315. * Returns the full weekday name.
  3316. *
  3317. * Use {@link weekday_short_name()} to get the abbreviated weekday name.
  3318. *
  3319. * @param int $w Number of the day in the week (0=Sunday,...,6=Saturday)
  3320. *
  3321. * @return string The full weekday name ("Sunday")
  3322. *
  3323. * @see weekday_short_name
  3324. */
  3325. function weekday_name ( $w ) {
  3326. switch ( $w ) {
  3327. case 0: return translate("Sunday");
  3328. case 1: return translate("Monday");
  3329. case 2: return translate("Tuesday");
  3330. case 3: return translate("Wednesday");
  3331. case 4: return translate("Thursday");
  3332. case 5: return translate("Friday");
  3333. case 6: return translate("Saturday");
  3334. }
  3335. return "unknown-weekday($w)";
  3336. }
  3337. /**
  3338. * Returns the abbreviated weekday name.
  3339. *
  3340. * Use {@link weekday_name()} to get the full weekday name.
  3341. *
  3342. * @param int $w Number of the day in the week (0=Sunday,...,6=Saturday)
  3343. *
  3344. * @return string The abbreviated weekday name ("Sun")
  3345. */
  3346. function weekday_short_name ( $w ) {
  3347. switch ( $w ) {
  3348. case 0: return translate("Sun");
  3349. case 1: return translate("Mon");
  3350. case 2: return translate("Tue");
  3351. case 3: return translate("Wed");
  3352. case 4: return translate("Thu");
  3353. case 5: return translate("Fri");
  3354. case 6: return translate("Sat");
  3355. }
  3356. return "unknown-weekday($w)";
  3357. }
  3358. /**
  3359. * Converts a date in YYYYMMDD format into "Friday, December 31, 1999",
  3360. * "Friday, 12-31-1999" or whatever format the user prefers.
  3361. *
  3362. * @param string $indate Date in YYYYMMDD format
  3363. * @param string $format Format to use for date (default is "__month__
  3364. * __dd__, __yyyy__")
  3365. * @param bool $show_weekday Should the day of week also be included?
  3366. * @param bool $short_months Should the abbreviated month names be used
  3367. * instead of the full month names?
  3368. * @param int $server_time ???
  3369. *
  3370. * @return string Date in the specified format
  3371. *
  3372. * @global string Preferred date format
  3373. * @global int User's timezone offset from the server
  3374. */
  3375. function date_to_str ( $indate, $format="", $show_weekday=true, $short_months=false, $server_time="" ) {
  3376. global $DATE_FORMAT, $TZ_OFFSET;
  3377. if ( strlen ( $indate ) == 0 ) {
  3378. $indate = date ( "Ymd" );
  3379. }
  3380. $newdate = $indate;
  3381. if ( $server_time != "" && $server_time >= 0 ) {
  3382. $y = substr ( $indate, 0, 4 );
  3383. $m = substr ( $indate, 4, 2 );
  3384. $d = substr ( $indate, 6, 2 );
  3385. if ( $server_time + $TZ_OFFSET * 10000 > 240000 ) {
  3386. $newdate = date ( "Ymd", mktime ( 3, 0, 0, $m, $d + 1, $y ) );
  3387. } else if ( $server_time + $TZ_OFFSET * 10000 < 0 ) {
  3388. $newdate = date ( "Ymd", mktime ( 3, 0, 0, $m, $d - 1, $y ) );
  3389. }
  3390. }
  3391. // if they have not set a preference yet...
  3392. if ( $DATE_FORMAT == "" )
  3393. $DATE_FORMAT = "__month__ __dd__, __yyyy__";
  3394. if ( empty ( $format ) )
  3395. $format = $DATE_FORMAT;
  3396. $y = (int) ( $newdate / 10000 );
  3397. $m = (int) ( $newdate / 100 ) % 100;
  3398. $d = $newdate % 100;
  3399. $date = mktime ( 3, 0, 0, $m, $d, $y );
  3400. $wday = strftime ( "%w", $date );
  3401. if ( $short_months ) {
  3402. $weekday = weekday_short_name ( $wday );
  3403. $month = month_short_name ( $m - 1 );
  3404. } else {
  3405. $weekday = weekday_name ( $wday );
  3406. $month = month_name ( $m - 1 );
  3407. }
  3408. $yyyy = $y;
  3409. $yy = sprintf ( "%02d", $y %= 100 );
  3410. $ret = $format;
  3411. $ret = str_replace ( "__yyyy__", $yyyy, $ret );
  3412. $ret = str_replace ( "__yy__", $yy, $ret );
  3413. $ret = str_replace ( "__month__", $month, $ret );
  3414. $ret = str_replace ( "__mon__", $month, $ret );
  3415. $ret = str_replace ( "__dd__", $d, $ret );
  3416. $ret = str_replace ( "__mm__", $m, $ret );
  3417. if ( $show_weekday )
  3418. return "$weekday, $ret";
  3419. else
  3420. return $ret;
  3421. }
  3422. /**
  3423. * Converts a hexadecimal digit to an integer.
  3424. *
  3425. * @param string $val Hexadecimal digit
  3426. *
  3427. * @return int Equivalent integer in base-10
  3428. *
  3429. * @ignore
  3430. */
  3431. function hextoint ( $val ) {
  3432. if ( empty ( $val ) )
  3433. return 0;
  3434. switch ( strtoupper ( $val ) ) {
  3435. case "0": return 0;
  3436. case "1": return 1;
  3437. case "2": return 2;
  3438. case "3": return 3;
  3439. case "4": return 4;
  3440. case "5": return 5;
  3441. case "6": return 6;
  3442. case "7": return 7;
  3443. case "8": return 8;
  3444. case "9": return 9;
  3445. case "A": return 10;
  3446. case "B": return 11;
  3447. case "C": return 12;
  3448. case "D": return 13;
  3449. case "E": return 14;
  3450. case "F": return 15;
  3451. }
  3452. return 0;
  3453. }
  3454. /**
  3455. * Extracts a user's name from a session id.
  3456. *
  3457. * This prevents users from begin able to edit their cookies.txt file and set
  3458. * the username in plain text.
  3459. *
  3460. * @param string $instr A hex-encoded string. "Hello" would be "678ea786a5".
  3461. *
  3462. * @return string The decoded string
  3463. *
  3464. * @global array Array of offsets
  3465. *
  3466. * @see encode_string
  3467. */
  3468. function decode_string ( $instr ) {
  3469. global $offsets;
  3470. //echo "<br />\nDECODE<br />\n";
  3471. $orig = "";
  3472. for ( $i = 0; $i < strlen ( $instr ); $i += 2 ) {
  3473. //echo "<br />\n";
  3474. $ch1 = substr ( $instr, $i, 1 );
  3475. $ch2 = substr ( $instr, $i + 1, 1 );
  3476. $val = hextoint ( $ch1 ) * 16 + hextoint ( $ch2 );
  3477. //echo "decoding \"" . $ch1 . $ch2 . "\" = $val<br />\n";
  3478. $j = ( $i / 2 ) % count ( $offsets );
  3479. //echo "Using offsets $j = " . $offsets[$j] . "<br />\n";
  3480. $newval = $val - $offsets[$j] + 256;
  3481. $newval %= 256;
  3482. //echo " neval \"$newval\"<br />\n";
  3483. $dec_ch = chr ( $newval );
  3484. //echo " which is \"$dec_ch\"<br />\n";
  3485. $orig .= $dec_ch;
  3486. }
  3487. //echo "Decode string: '$orig' <br/>\n";
  3488. return $orig;
  3489. }
  3490. /**
  3491. * Takes an input string and encode it into a slightly encoded hexval that we
  3492. * can use as a session cookie.
  3493. *
  3494. * @param string $instr Text to encode
  3495. *
  3496. * @return string The encoded text
  3497. *
  3498. * @global array Array of offsets
  3499. *
  3500. * @see decode_string
  3501. */
  3502. function encode_string ( $instr ) {
  3503. global $offsets;
  3504. //echo "<br />\nENCODE<br />\n";
  3505. $ret = "";
  3506. for ( $i = 0; $i < strlen ( $instr ); $i++ ) {
  3507. //echo "<br />\n";
  3508. $ch1 = substr ( $instr, $i, 1 );
  3509. $val = ord ( $ch1 );
  3510. //echo "val = $val for \"$ch1\"<br />\n";
  3511. $j = $i % count ( $offsets );
  3512. //echo "Using offsets $j = $offsets[$j]<br />\n";
  3513. $newval = $val + $offsets[$j];
  3514. $newval %= 256;
  3515. //echo "newval = $newval for \"$ch1\"<br />\n";
  3516. $ret .= bin2hex ( chr ( $newval ) );
  3517. }
  3518. return $ret;
  3519. }
  3520. /**
  3521. * An implementatin of array_splice() for PHP3.
  3522. *
  3523. * @param array $input Array to be spliced into
  3524. * @param int $offset Where to begin the splice
  3525. * @param int $length How long the splice should be
  3526. * @param array $replacement What to splice in
  3527. *
  3528. * @ignore
  3529. */
  3530. function my_array_splice(&$input,$offset,$length,$replacement) {
  3531. if ( floor(phpversion()) < 4 ) {
  3532. // if offset is negative, then it starts at the end of array
  3533. if ( $offset < 0 )
  3534. $offset = count($input) + $offset;
  3535. for ($i=0;$i<$offset;$i++) {
  3536. $new_array[] = $input[$i];
  3537. }
  3538. // if we have a replacement, insert it
  3539. for ($i=0;$i<count($replacement);$i++) {
  3540. $new_array[] = $replacement[$i];
  3541. }
  3542. // now tack on the rest of the original array
  3543. for ($i=$offset+$length;$i<count($input);$i++) {
  3544. $new_array[] = $input[$i];
  3545. }
  3546. $input = $new_array;
  3547. } else {
  3548. array_splice($input,$offset,$length,$replacement);
  3549. }
  3550. }
  3551. /**
  3552. * Loads current user's category info and stuff it into category global
  3553. * variable.
  3554. *
  3555. * @param string $ex_global Don't include global categories ('' or '1')
  3556. */
  3557. function load_user_categories ($ex_global = '') {
  3558. global $login, $user, $is_assistant;
  3559. global $categories, $category_owners;
  3560. global $categories_enabled, $is_admin;
  3561. $cat_owner = ( ( ! empty ( $user ) && strlen ( $user ) ) && ( $is_assistant ||
  3562. $is_admin ) ) ? $user : $login;
  3563. $categories = array ();
  3564. $category_owners = array ();
  3565. if ( $categories_enabled == "Y" ) {
  3566. $sql = "SELECT cat_id, cat_name, cat_owner FROM webcal_categories WHERE ";
  3567. $sql .= ($ex_global == '') ? " (cat_owner = '$cat_owner') OR (cat_owner IS NULL) ORDER BY cat_owner, cat_name" : " cat_owner = '$cat_owner' ORDER BY cat_name";
  3568. $res = dbi_query ( $sql );
  3569. if ( $res ) {
  3570. while ( $row = dbi_fetch_row ( $res ) ) {
  3571. $cat_id = $row[0];
  3572. $categories[$cat_id] = $row[1];
  3573. $category_owners[$cat_id] = $row[2];
  3574. }
  3575. dbi_free_result ( $res );
  3576. }
  3577. } else {
  3578. //echo "Categories disabled.";
  3579. }
  3580. }
  3581. /**
  3582. * Prints dropdown HTML for categories.
  3583. *
  3584. * @param string $form The page to submit data to (without .php)
  3585. * @param string $date Date in YYYYMMDD format
  3586. * @param int $cat_id Category id that should be pre-selected
  3587. */
  3588. function print_category_menu ( $form, $date = '', $cat_id = '' ) {
  3589. global $categories, $category_owners, $user, $login;
  3590. echo "<form action=\"{$form}.php\" method=\"get\" name=\"SelectCategory\" class=\"categories\">\n";
  3591. if ( ! empty($date) ) echo "<input type=\"hidden\" name=\"date\" value=\"$date\" />\n";
  3592. if ( ! empty ( $user ) && $user != $login )
  3593. echo "<input type=\"hidden\" name=\"user\" value=\"$user\" />\n";
  3594. echo translate ("Category") . ": <select name=\"cat_id\" onchange=\"document.SelectCategory.submit()\">\n";
  3595. echo "<option value=\"\"";
  3596. if ( $cat_id == '' ) echo " selected=\"selected\"";
  3597. echo ">" . translate("All") . "</option>\n";
  3598. $cat_owner = ( ! empty ( $user ) && strlen ( $user ) ) ? $user : $login;
  3599. if ( is_array ( $categories ) ) {
  3600. foreach ( $categories as $K => $V ){
  3601. if ( $cat_owner ||
  3602. empty ( $category_owners[$K] ) ) {
  3603. echo "<option value=\"$K\"";
  3604. if ( $cat_id == $K ) echo " selected=\"selected\"";
  3605. echo ">$V</option>\n";
  3606. }
  3607. }
  3608. }
  3609. echo "</select>\n";
  3610. echo "</form>\n";
  3611. echo "<span id=\"cat\">" . translate ("Category") . ": ";
  3612. echo ( strlen ( $cat_id ) ? $categories[$cat_id] : translate ('All') ) . "</span>\n";
  3613. }
  3614. /**
  3615. * Converts HTML entities in 8bit.
  3616. *
  3617. * <b>Note:</b> Only supported for PHP4 (not PHP3).
  3618. *
  3619. * @param string $html HTML text
  3620. *
  3621. * @return string The converted text
  3622. */
  3623. function html_to_8bits ( $html ) {
  3624. if ( floor(phpversion()) < 4 ) {
  3625. return $html;
  3626. } else {
  3627. return strtr ( $html, array_flip (
  3628. get_html_translation_table (HTML_ENTITIES) ) );
  3629. }
  3630. }
  3631. // ***********************************************************************
  3632. // Functions for getting information about boss and their assistant.
  3633. // ***********************************************************************
  3634. /**
  3635. * Gets a list of an assistant's boss from the webcal_asst table.
  3636. *
  3637. * @param string $assistant Login of assistant
  3638. *
  3639. * @return array Array of bosses, where each boss is an array with the following
  3640. * fields:
  3641. * - <var>cal_login</var>
  3642. * - <var>cal_fullname</var>
  3643. */
  3644. function user_get_boss_list ( $assistant ) {
  3645. global $bosstemp_fullname;
  3646. $res = dbi_query (
  3647. "SELECT cal_boss " .
  3648. "FROM webcal_asst " .
  3649. "WHERE cal_assistant = '$assistant'" );
  3650. $count = 0;
  3651. $ret = array ();
  3652. if ( $res ) {
  3653. while ( $row = dbi_fetch_row ( $res ) ) {
  3654. user_load_variables ( $row[0], "bosstemp_" );
  3655. $ret[$count++] = array (
  3656. "cal_login" => $row[0],
  3657. "cal_fullname" => $bosstemp_fullname
  3658. );
  3659. }
  3660. dbi_free_result ( $res );
  3661. }
  3662. return $ret;
  3663. }
  3664. /**
  3665. * Is this user an assistant of this boss?
  3666. *
  3667. * @param string $assistant Login of potential assistant
  3668. * @param string $boss Login of potential boss
  3669. *
  3670. * @return bool True or false
  3671. */
  3672. function user_is_assistant ( $assistant, $boss ) {
  3673. $ret = false;
  3674. if ( empty ( $boss ) )
  3675. return false;
  3676. $res = dbi_query ( "SELECT * FROM webcal_asst " .
  3677. "WHERE cal_assistant = '$assistant' AND cal_boss = '$boss'" );
  3678. if ( $res ) {
  3679. if ( dbi_fetch_row ( $res ) )
  3680. $ret = true;
  3681. dbi_free_result ( $res );
  3682. }
  3683. return $ret;
  3684. }
  3685. /**
  3686. * Is this user an assistant?
  3687. *
  3688. * @param string $assistant Login for user
  3689. *
  3690. * @return bool true if the user is an assistant to one or more bosses
  3691. */
  3692. function user_has_boss ( $assistant ) {
  3693. $ret = false;
  3694. $res = dbi_query ( "SELECT * FROM webcal_asst " .
  3695. "WHERE cal_assistant = '$assistant'" );
  3696. if ( $res ) {
  3697. if ( dbi_fetch_row ( $res ) )
  3698. $ret = true;
  3699. dbi_free_result ( $res );
  3700. }
  3701. return $ret;
  3702. }
  3703. /**
  3704. * Checks the boss user preferences to see if the boss wants to be notified via
  3705. * email on changes to their calendar.
  3706. *
  3707. * @param string $assistant Assistant login
  3708. * @param string $boss Boss login
  3709. *
  3710. * @return bool True if the boss wants email notifications
  3711. */
  3712. function boss_must_be_notified ( $assistant, $boss ) {
  3713. if (user_is_assistant ( $assistant, $boss ) )
  3714. return ( get_pref_setting ( $boss, "EMAIL_ASSISTANT_EVENTS" )=="Y" ? true : false );
  3715. return true;
  3716. }
  3717. /**
  3718. * Checks the boss user preferences to see if the boss must approve events
  3719. * added to their calendar.
  3720. *
  3721. * @param string $assistant Assistant login
  3722. * @param string $boss Boss login
  3723. *
  3724. * @return bool True if the boss must approve new events
  3725. */
  3726. function boss_must_approve_event ( $assistant, $boss ) {
  3727. if (user_is_assistant ( $assistant, $boss ) )
  3728. return ( get_pref_setting ( $boss, "APPROVE_ASSISTANT_EVENT" )=="Y" ? true : false );
  3729. return true;
  3730. }
  3731. /**
  3732. * Fakes an email for testing purposes.
  3733. *
  3734. * @param string $mailto Email address to send mail to
  3735. * @param string $subj Subject of email
  3736. * @param string $text Email body
  3737. * @param string $hdrs Other email headers
  3738. *
  3739. * @ignore
  3740. */
  3741. function fake_mail ( $mailto, $subj, $text, $hdrs ) {
  3742. echo "To: $mailto <br />\n" .
  3743. "Subject: $subj <br />\n" .
  3744. nl2br ( $hdrs ) . "<br />\n" .
  3745. nl2br ( $text );
  3746. }
  3747. /**
  3748. * Prints all the entries in a time bar format for the specified user for the
  3749. * specified date.
  3750. *
  3751. * If we are displaying data from someone other than the logged in user, then
  3752. * check the access permission of the entry.
  3753. *
  3754. * @param string $date Date in YYYYMMDD format
  3755. * @param string $user Username
  3756. * @param bool $ssi Should we not include links to add new events?
  3757. */
  3758. function print_date_entries_timebar ( $date, $user, $ssi ) {
  3759. global $events, $readonly, $is_admin,
  3760. $public_access, $public_access_can_add;
  3761. $cnt = 0;
  3762. $get_unapproved = ( $GLOBALS["DISPLAY_UNAPPROVED"] == "Y" );
  3763. // public access events always must be approved before being displayed
  3764. if ( $GLOBALS["login"] == "__public__" )
  3765. $get_unapproved = false;
  3766. $year = substr ( $date, 0, 4 );
  3767. $month = substr ( $date, 4, 2 );
  3768. $day = substr ( $date, 6, 2 );
  3769. $dateu = mktime ( 3, 0, 0, $month, $day, $year );
  3770. $can_add = ( $readonly == "N" || $is_admin );
  3771. if ( $public_access == "Y" && $public_access_can_add != "Y" &&
  3772. $GLOBALS["login"] == "__public__" )
  3773. $can_add = false;
  3774. // get all the repeating events for this date and store in array $rep
  3775. $rep = get_repeating_entries ( $user, $date ) ;
  3776. $cur_rep = 0;
  3777. // get all the non-repeating events for this date and store in $ev
  3778. $ev = get_entries ( $user, $date, $get_unapproved );
  3779. for ( $i = 0; $i < count ( $ev ); $i++ ) {
  3780. // print out any repeating events that are before this one...
  3781. while ( $cur_rep < count ( $rep ) &&
  3782. $rep[$cur_rep]['cal_time'] < $ev[$i]['cal_time'] ) {
  3783. if ( $get_unapproved || $rep[$cur_rep]['cal_status'] == 'A' ) {
  3784. print_entry_timebar ( $rep[$cur_rep]['cal_id'],
  3785. $date, $rep[$cur_rep]['cal_time'], $rep[$cur_rep]['cal_duration'],
  3786. $rep[$cur_rep]['cal_name'], $rep[$cur_rep]['cal_description'],
  3787. $rep[$cur_rep]['cal_status'], $rep[$cur_rep]['cal_priority'],
  3788. $rep[$cur_rep]['cal_access'], $rep[$cur_rep]['cal_login'],
  3789. $rep[$cur_rep]['cal_category'] );
  3790. $cnt++;
  3791. }
  3792. $cur_rep++;
  3793. }
  3794. if ( $get_unapproved || $ev[$i]['cal_status'] == 'A' ) {
  3795. print_entry_timebar ( $ev[$i]['cal_id'],
  3796. $date, $ev[$i]['cal_time'], $ev[$i]['cal_duration'],
  3797. $ev[$i]['cal_name'], $ev[$i]['cal_description'],
  3798. $ev[$i]['cal_status'], $ev[$i]['cal_priority'],
  3799. $ev[$i]['cal_access'], $ev[$i]['cal_login'],
  3800. $ev[$i]['cal_category'] );
  3801. $cnt++;
  3802. }
  3803. }
  3804. // print out any remaining repeating events
  3805. while ( $cur_rep < count ( $rep ) ) {
  3806. if ( $get_unapproved || $rep[$cur_rep]['cal_status'] == 'A' ) {
  3807. print_entry_timebar ( $rep[$cur_rep]['cal_id'],
  3808. $date, $rep[$cur_rep]['cal_time'], $rep[$cur_rep]['cal_duration'],
  3809. $rep[$cur_rep]['cal_name'], $rep[$cur_rep]['cal_description'],
  3810. $rep[$cur_rep]['cal_status'], $rep[$cur_rep]['cal_priority'],
  3811. $rep[$cur_rep]['cal_access'], $rep[$cur_rep]['cal_login'],
  3812. $rep[$cur_rep]['cal_category'] );
  3813. $cnt++;
  3814. }
  3815. $cur_rep++;
  3816. }
  3817. if ( $cnt == 0 )
  3818. echo "&nbsp;"; // so the table cell has at least something
  3819. }
  3820. /**
  3821. * Prints the HTML for an events with a timebar.
  3822. *
  3823. * @param int $id Event id
  3824. * @param string $date Date of event in YYYYMMDD format
  3825. * @param string $time Time of event in HHMM format
  3826. * @param int $duration Duration of event in minutes
  3827. * @param string $name Brief description of event
  3828. * @param string $description Full description of event
  3829. * @param string $status Status of event ('A', 'W')
  3830. * @param int $pri Priority of event
  3831. * @param string $access Access to event by others ('P', 'R')
  3832. * @param string $event_owner User who created event
  3833. * @param int $event_category Category id for event
  3834. *
  3835. * @staticvar int Used to ensure all event popups have a unique id
  3836. */
  3837. function print_entry_timebar ( $id, $date, $time, $duration,
  3838. $name, $description, $status,
  3839. $pri, $access, $event_owner, $event_category=-1 ) {
  3840. global $eventinfo, $login, $user, $PHP_SELF, $prefarray;
  3841. static $key = 0;
  3842. $insidespan = false;
  3843. global $layers;
  3844. // compute time offsets in % of total table width
  3845. $day_start=$prefarray["WORK_DAY_START_HOUR"] * 60;
  3846. if ( $day_start == 0 ) $day_start = 9*60;
  3847. $day_end=$prefarray["WORK_DAY_END_HOUR"] * 60;
  3848. if ( $day_end == 0 ) $day_end = 19*60;
  3849. if ( $day_end <= $day_start ) $day_end = $day_start + 60; //avoid exceptions
  3850. if ($time >= 0) {
  3851. $bar_units= 100/(($day_end - $day_start)/60) ; // Percentage each hour occupies
  3852. $ev_start = round((floor(($time/10000) - ($day_start/60)) + (($time/100)%100)/60) * $bar_units);
  3853. }else{
  3854. $ev_start= 0;
  3855. }
  3856. if ($ev_start < 0) $ev_start = 0;
  3857. if ($duration > 0) {
  3858. $ev_duration = round(100 * $duration / ($day_end - $day_start)) ;
  3859. if ($ev_start + $ev_duration > 100 ) {
  3860. $ev_duration = 100 - $ev_start;
  3861. }
  3862. } else {
  3863. if ($time >= 0) {
  3864. $ev_duration = 1;
  3865. } else {
  3866. $ev_duration=100-$ev_start;
  3867. }
  3868. }
  3869. $ev_padding = 100 - $ev_start - $ev_duration;
  3870. // choose where to position the text (pos=0->before,pos=1->on,pos=2->after)
  3871. if ($ev_duration > 20) { $pos = 1; }
  3872. elseif ($ev_padding > 20) { $pos = 2; }
  3873. else { $pos = 0; }
  3874. echo "\n<!-- ENTRY BAR -->\n<table class=\"entrycont\" cellpadding=\"0\" cellspacing=\"0\">\n";
  3875. echo "<tr>\n";
  3876. echo ($ev_start > 0 ? "<td style=\"text-align:right; width:$ev_start%;\">" : "" );
  3877. if ( $pos > 0 ) {
  3878. echo ($ev_start > 0 ? "&nbsp;</td>\n": "" ) ;
  3879. echo "<td style=\"width:$ev_duration%;\">\n<table class=\"entrybar\">\n<tr>\n<td class=\"entry\">";
  3880. if ( $pos > 1 ) {
  3881. echo ($ev_padding > 0 ? "&nbsp;</td>\n": "" ) . "</tr>\n</table></td>\n";
  3882. echo ($ev_padding > 0 ? "<td style=\"text-align:left; width:$ev_padding%;\">" : "");
  3883. }
  3884. };
  3885. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  3886. $class = "layerentry";
  3887. } else {
  3888. $class = "entry";
  3889. if ( $status == "W" ) $class = "unapprovedentry";
  3890. }
  3891. // if we are looking at a view, then always use "entry"
  3892. if ( strstr ( $PHP_SELF, "view_m.php" ) ||
  3893. strstr ( $PHP_SELF, "view_w.php" ) ||
  3894. strstr ( $PHP_SELF, "view_v.php" ) ||
  3895. strstr ( $PHP_SELF, "view_t.php" ) )
  3896. $class = "entry";
  3897. if ( $pri == 3 ) echo "<strong>";
  3898. $popupid = "eventinfo-$id-$key";
  3899. $key++;
  3900. echo "<a class=\"$class\" href=\"view_entry.php?id=$id&amp;date=$date";
  3901. if ( strlen ( $user ) > 0 )
  3902. echo "&amp;user=" . $user;
  3903. echo "\" onmouseover=\"window.status='" .
  3904. translate("View this entry") . "'; show(event, '$popupid'); return true;\" onmouseout=\"hide('$popupid'); return true;\">";
  3905. if ( $login != $event_owner && strlen ( $event_owner ) ) {
  3906. if ($layers) foreach ($layers as $layer) {
  3907. if($layer['cal_layeruser'] == $event_owner) {
  3908. $insidespan = true;
  3909. echo("<span style=\"color:" . $layer['cal_color'] . ";\">");
  3910. }
  3911. }
  3912. }
  3913. echo "[$event_owner]&nbsp;";
  3914. $timestr = "";
  3915. if ( $duration == ( 24 * 60 ) ) {
  3916. $timestr = translate("All day event");
  3917. } else if ( $time >= 0 ) {
  3918. $timestr = display_time ( $time );
  3919. if ( $duration > 0 ) {
  3920. // calc end time
  3921. $h = (int) ( $time / 10000 );
  3922. $m = ( $time / 100 ) % 100;
  3923. $m += $duration;
  3924. $d = $duration;
  3925. while ( $m >= 60 ) {
  3926. $h++;
  3927. $m -= 60;
  3928. }
  3929. $end_time = sprintf ( "%02d%02d00", $h, $m );
  3930. $timestr .= " - " . display_time ( $end_time );
  3931. }
  3932. }
  3933. if ( $login != $user && $access == 'R' && strlen ( $user ) )
  3934. echo "(" . translate("Private") . ")";
  3935. else
  3936. if ( $login != $event_owner && $access == 'R' && strlen ( $event_owner ) )
  3937. echo "(" . translate("Private") . ")";
  3938. else
  3939. if ( $login != $event_owner && strlen ( $event_owner ) )
  3940. {
  3941. echo htmlspecialchars ( $name );
  3942. if ( $insidespan ) { echo ("</span>"); } //end color span
  3943. }
  3944. else
  3945. echo htmlspecialchars ( $name );
  3946. echo "</a>";
  3947. if ( $pri == 3 ) echo "</strong>"; //end font-weight span
  3948. echo "</td>\n";
  3949. if ( $pos < 2 ) {
  3950. if ( $pos < 1 ) {
  3951. echo "<td style=\"width:$ev_duration%;\"><table class=\"entrybar\">\n<tr>\n<td class=\"entry\">&nbsp;</td>\n";
  3952. }
  3953. echo "</tr>\n</table></td>\n";
  3954. echo ($ev_padding > 0 ? "<td style=\"text-align:left; width:$ev_padding%;\">&nbsp;</td>\n" : "" );
  3955. }
  3956. echo "</tr>\n</table>\n";
  3957. if ( $login != $user && $access == 'R' && strlen ( $user ) )
  3958. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  3959. translate("This event is confidential"), "" );
  3960. else
  3961. if ( $login != $event_owner && $access == 'R' && strlen ( $event_owner ) )
  3962. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  3963. translate("This event is confidential"), "" );
  3964. else
  3965. $eventinfo .= build_event_popup ( $popupid, $event_owner,
  3966. $description, $timestr, site_extras_for_popup ( $id ) );
  3967. }
  3968. /**
  3969. * Prints the header for the timebar.
  3970. *
  3971. * @param int $start_hour Start hour
  3972. * @param int $end_hour End hour
  3973. */
  3974. function print_header_timebar($start_hour, $end_hour) {
  3975. // sh+1 ... eh-1
  3976. // +------+----....----+------+
  3977. // | | | |
  3978. // print hours
  3979. if ( ($end_hour - $start_hour) == 0 )
  3980. $offset = 0;
  3981. else
  3982. $offset = round(100/($end_hour - $start_hour));
  3983. echo "\n<!-- TIMEBAR -->\n<table class=\"timebar\">\n<tr><td style=\"width:$offset%;\">&nbsp;</td>\n";
  3984. for ($i = $start_hour+1; $i < $end_hour; $i++) {
  3985. // $prev_offset = $offset;
  3986. // $offset = round(100/($end_hour - $start_hour)*($i - $start_hour + .5));
  3987. $offset = round(100/($end_hour - $start_hour));
  3988. $width = $offset;
  3989. echo "<td style=\"width:$width%;text-align:left;\">$i</td>\n";
  3990. }
  3991. // $width = 100 - $offset;
  3992. // echo "<td style=\"width:$width%;\">&nbsp;</td>\n";
  3993. echo "</tr>\n</table>\n<!-- /TIMEBAR -->\n";
  3994. // print yardstick
  3995. echo "\n<!-- YARDSTICK -->\n<table class=\"yardstick\">\n<tr>\n";
  3996. $width = round(100/($end_hour - $start_hour));
  3997. for ($i = $start_hour; $i < $end_hour; $i++) {
  3998. echo "<td style=\"width:$width%;\">&nbsp;</td>\n";
  3999. }
  4000. echo "</tr>\n</table>\n<!-- /YARDSTICK -->\n";
  4001. }
  4002. /**
  4003. * Gets a list of nonuser calendars and return info in an array.
  4004. *
  4005. * @param string $user Login of admin of the nonuser calendars
  4006. *
  4007. * @return array Array of nonuser cals, where each is an array with the
  4008. * following fields:
  4009. * - <var>cal_login</var>
  4010. * - <var>cal_lastname</var>
  4011. * - <var>cal_firstname</var>
  4012. * - <var>cal_admin</var>
  4013. * - <var>cal_fullname</var>
  4014. */
  4015. function get_nonuser_cals ($user = '') {
  4016. $count = 0;
  4017. $ret = array ();
  4018. $sql = "SELECT cal_login, cal_lastname, cal_firstname, " .
  4019. "cal_admin FROM webcal_nonuser_cals ";
  4020. if ($user != '') $sql .= "WHERE cal_admin = '$user' ";
  4021. $sql .= "ORDER BY cal_lastname, cal_firstname, cal_login";
  4022. $res = dbi_query ( $sql );
  4023. if ( $res ) {
  4024. while ( $row = dbi_fetch_row ( $res ) ) {
  4025. if ( strlen ( $row[1] ) || strlen ( $row[2] ) )
  4026. $fullname = "$row[2] $row[1]";
  4027. else
  4028. $fullname = $row[0];
  4029. $ret[$count++] = array (
  4030. "cal_login" => $row[0],
  4031. "cal_lastname" => $row[1],
  4032. "cal_firstname" => $row[2],
  4033. "cal_admin" => $row[3],
  4034. "cal_fullname" => $fullname
  4035. );
  4036. }
  4037. dbi_free_result ( $res );
  4038. }
  4039. return $ret;
  4040. }
  4041. /**
  4042. * Loads nonuser variables (login, firstname, etc.).
  4043. *
  4044. * The following variables will be set:
  4045. * - <var>login</var>
  4046. * - <var>firstname</var>
  4047. * - <var>lastname</var>
  4048. * - <var>fullname</var>
  4049. * - <var>admin</var>
  4050. * - <var>email</var>
  4051. *
  4052. * @param string $login Login name of nonuser calendar
  4053. * @param string $prefix Prefix to use for variables that will be set.
  4054. * For example, if prefix is "temp", then the login will
  4055. * be stored in the <var>$templogin</var> global variable.
  4056. */
  4057. function nonuser_load_variables ( $login, $prefix ) {
  4058. global $error,$nuloadtmp_email;
  4059. $ret = false;
  4060. $res = dbi_query ( "SELECT cal_login, cal_lastname, cal_firstname, " .
  4061. "cal_admin FROM webcal_nonuser_cals WHERE cal_login = '$login'" );
  4062. if ( $res ) {
  4063. while ( $row = dbi_fetch_row ( $res ) ) {
  4064. if ( strlen ( $row[1] ) || strlen ( $row[2] ) )
  4065. $fullname = "$row[2] $row[1]";
  4066. else
  4067. $fullname = $row[0];
  4068. // We need the email address for the admin
  4069. user_load_variables ( $row[3], 'nuloadtmp_' );
  4070. $GLOBALS[$prefix . "login"] = $row[0];
  4071. $GLOBALS[$prefix . "firstname"] = $row[2];
  4072. $GLOBALS[$prefix . "lastname"] = $row[1];
  4073. $GLOBALS[$prefix . "fullname"] = $fullname;
  4074. $GLOBALS[$prefix . "admin"] = $row[3];
  4075. $GLOBALS[$prefix . "email"] = $nuloadtmp_email;
  4076. $ret = true;
  4077. }
  4078. dbi_free_result ( $res );
  4079. }
  4080. return $ret;
  4081. }
  4082. /**
  4083. * Checks the webcal_nonuser_cals table to determine if the user is the
  4084. * administrator for the nonuser calendar.
  4085. *
  4086. * @param string $login Login of user that is the potential administrator
  4087. * @param string $nonuser Login name for nonuser calendar
  4088. *
  4089. * @return bool True if the user is the administrator for the nonuser calendar
  4090. */
  4091. function user_is_nonuser_admin ( $login, $nonuser ) {
  4092. $ret = false;
  4093. $res = dbi_query ( "SELECT * FROM webcal_nonuser_cals " .
  4094. "WHERE cal_login = '$nonuser' AND cal_admin = '$login'" );
  4095. if ( $res ) {
  4096. if ( dbi_fetch_row ( $res ) )
  4097. $ret = true;
  4098. dbi_free_result ( $res );
  4099. }
  4100. return $ret;
  4101. }
  4102. /**
  4103. * Loads nonuser preferences from the webcal_user_pref table if on a nonuser
  4104. * admin page.
  4105. *
  4106. * @param string $nonuser Login name for nonuser calendar
  4107. */
  4108. function load_nonuser_preferences ($nonuser) {
  4109. global $prefarray;
  4110. $res = dbi_query (
  4111. "SELECT cal_setting, cal_value FROM webcal_user_pref " .
  4112. "WHERE cal_login = '$nonuser'" );
  4113. if ( $res ) {
  4114. while ( $row = dbi_fetch_row ( $res ) ) {
  4115. $setting = $row[0];
  4116. $value = $row[1];
  4117. $sys_setting = "sys_" . $setting;
  4118. // save system defaults
  4119. // ** don't override ones set by load_user_prefs
  4120. if ( ! empty ( $GLOBALS[$setting] ) && empty ( $GLOBALS["sys_" . $setting] ))
  4121. $GLOBALS["sys_" . $setting] = $GLOBALS[$setting];
  4122. $GLOBALS[$setting] = $value;
  4123. $prefarray[$setting] = $value;
  4124. }
  4125. dbi_free_result ( $res );
  4126. }
  4127. }
  4128. /**
  4129. * Determines what the day is after the <var>$TZ_OFFSET</var> and sets it globally.
  4130. *
  4131. * The following global variables will be set:
  4132. * - <var>$thisyear</var>
  4133. * - <var>$thismonth</var>
  4134. * - <var>$thisday</var>
  4135. * - <var>$thisdate</var>
  4136. * - <var>$today</var>
  4137. *
  4138. * @param string $date The date in YYYYMMDD format
  4139. */
  4140. function set_today($date) {
  4141. global $thisyear, $thisday, $thismonth, $thisdate, $today;
  4142. global $TZ_OFFSET, $month, $day, $year, $thisday;
  4143. // Adjust for TimeZone
  4144. $today = time() + ($TZ_OFFSET * 60 * 60);
  4145. if ( ! empty ( $date ) && ! empty ( $date ) ) {
  4146. $thisyear = substr ( $date, 0, 4 );
  4147. $thismonth = substr ( $date, 4, 2 );
  4148. $thisday = substr ( $date, 6, 2 );
  4149. } else {
  4150. if ( empty ( $month ) || $month == 0 )
  4151. $thismonth = date("m", $today);
  4152. else
  4153. $thismonth = $month;
  4154. if ( empty ( $year ) || $year == 0 )
  4155. $thisyear = date("Y", $today);
  4156. else
  4157. $thisyear = $year;
  4158. if ( empty ( $day ) || $day == 0 )
  4159. $thisday = date("d", $today);
  4160. else
  4161. $thisday = $day;
  4162. }
  4163. $thisdate = sprintf ( "%04d%02d%02d", $thisyear, $thismonth, $thisday );
  4164. }
  4165. /**
  4166. * Converts from Gregorian Year-Month-Day to ISO YearNumber-WeekNumber-WeekDay.
  4167. *
  4168. * @internal JGH borrowed gregorianToISO from PEAR Date_Calc Class and added
  4169. * $GLOBALS["WEEK_START"] (change noted)
  4170. *
  4171. * @param int $day Day of month
  4172. * @param int $month Number of month
  4173. * @param int $year Year
  4174. *
  4175. * @return string Date in ISO YearNumber-WeekNumber-WeekDay format
  4176. *
  4177. * @ignore
  4178. */
  4179. function gregorianToISO($day,$month,$year) {
  4180. $mnth = array (0,31,59,90,120,151,181,212,243,273,304,334);
  4181. $y_isleap = isLeapYear($year);
  4182. $y_1_isleap = isLeapYear($year - 1);
  4183. $day_of_year_number = $day + $mnth[$month - 1];
  4184. if ($y_isleap && $month > 2) {
  4185. $day_of_year_number++;
  4186. }
  4187. // find Jan 1 weekday (monday = 1, sunday = 7)
  4188. $yy = ($year - 1) % 100;
  4189. $c = ($year - 1) - $yy;
  4190. $g = $yy + intval($yy/4);
  4191. $jan1_weekday = 1 + intval((((($c / 100) % 4) * 5) + $g) % 7);
  4192. // JGH added next if/else to compensate for week begins on Sunday
  4193. if (! $GLOBALS["WEEK_START"] && $jan1_weekday < 7) {
  4194. $jan1_weekday++;
  4195. } elseif (! $GLOBALS["WEEK_START"] && $jan1_weekday == 7) {
  4196. $jan1_weekday=1;
  4197. }
  4198. // weekday for year-month-day
  4199. $h = $day_of_year_number + ($jan1_weekday - 1);
  4200. $weekday = 1 + intval(($h - 1) % 7);
  4201. // find if Y M D falls in YearNumber Y-1, WeekNumber 52 or
  4202. if ($day_of_year_number <= (8 - $jan1_weekday) && $jan1_weekday > 4){
  4203. $yearnumber = $year - 1;
  4204. if ($jan1_weekday == 5 || ($jan1_weekday == 6 && $y_1_isleap)) {
  4205. $weeknumber = 53;
  4206. } else {
  4207. $weeknumber = 52;
  4208. }
  4209. } else {
  4210. $yearnumber = $year;
  4211. }
  4212. // find if Y M D falls in YearNumber Y+1, WeekNumber 1
  4213. if ($yearnumber == $year) {
  4214. if ($y_isleap) {
  4215. $i = 366;
  4216. } else {
  4217. $i = 365;
  4218. }
  4219. if (($i - $day_of_year_number) < (4 - $weekday)) {
  4220. $yearnumber++;
  4221. $weeknumber = 1;
  4222. }
  4223. }
  4224. // find if Y M D falls in YearNumber Y, WeekNumber 1 through 53
  4225. if ($yearnumber == $year) {
  4226. $j = $day_of_year_number + (7 - $weekday) + ($jan1_weekday - 1);
  4227. $weeknumber = intval($j / 7);
  4228. if ($jan1_weekday > 4) {
  4229. $weeknumber--;
  4230. }
  4231. }
  4232. // put it all together
  4233. if ($weeknumber < 10)
  4234. $weeknumber = '0'.$weeknumber;
  4235. return "{$yearnumber}-{$weeknumber}-{$weekday}";
  4236. }
  4237. /**
  4238. * Is this a leap year?
  4239. *
  4240. * @internal JGH Borrowed isLeapYear from PEAR Date_Calc Class
  4241. *
  4242. * @param int $year Year
  4243. *
  4244. * @return bool True for a leap year, else false
  4245. *
  4246. * @ignore
  4247. */
  4248. function isLeapYear($year='') {
  4249. if (empty($year)) $year = strftime("%Y",time());
  4250. if (strlen($year) != 4) return false;
  4251. if (preg_match('/\D/',$year)) return false;
  4252. return (($year % 4 == 0 && $year % 100 != 0) || $year % 400 == 0);
  4253. }
  4254. /**
  4255. * Replaces unsafe characters with HTML encoded equivalents.
  4256. *
  4257. * @param string $value Input text
  4258. *
  4259. * @return string The cleaned text
  4260. */
  4261. function clean_html($value){
  4262. $value = htmlspecialchars($value, ENT_QUOTES);
  4263. $value = strtr($value, array(
  4264. '(' => '&#40;',
  4265. ')' => '&#41;'
  4266. ));
  4267. return $value;
  4268. }
  4269. /**
  4270. * Removes non-word characters from the specified text.
  4271. *
  4272. * @param string $data Input text
  4273. *
  4274. * @return string The converted text
  4275. */
  4276. function clean_word($data) {
  4277. return preg_replace("/\W/", '', $data);
  4278. }
  4279. /**
  4280. * Removes non-digits from the specified text.
  4281. *
  4282. * @param string $data Input text
  4283. *
  4284. * @return string The converted text
  4285. */
  4286. function clean_int($data) {
  4287. return preg_replace("/\D/", '', $data);
  4288. }
  4289. /**
  4290. * Removes whitespace from the specified text.
  4291. *
  4292. * @param string $data Input text
  4293. *
  4294. * @return string The converted text
  4295. */
  4296. function clean_whitespace($data) {
  4297. return preg_replace("/\s/", '', $data);
  4298. }
  4299. /**
  4300. * Converts language names to their abbreviation.
  4301. *
  4302. * @param string $name Name of the language (such as "French")
  4303. *
  4304. * @return string The abbreviation ("fr" for "French")
  4305. */
  4306. function languageToAbbrev ( $name ) {
  4307. global $browser_languages;
  4308. foreach ( $browser_languages as $abbrev => $langname ) {
  4309. if ( $langname == $name )
  4310. return $abbrev;
  4311. }
  4312. return false;
  4313. }
  4314. /**
  4315. * Creates the CSS for using gradient.php, if the appropriate GD functions are
  4316. * available.
  4317. *
  4318. * A one-pixel wide image will be used for the background image.
  4319. *
  4320. * <b>Note:</b> The gd library module needs to be available to use gradient
  4321. * images. If it is not available, a single background color will be used
  4322. * instead.
  4323. *
  4324. * @param string $color Base color
  4325. * @param int $height Height of gradient image
  4326. * @param int $percent How many percent lighter the top color should be
  4327. * than the base color at the bottom of the image
  4328. *
  4329. * @return string The style sheet text to use
  4330. */
  4331. function background_css ( $color, $height = '', $percent = '' ) {
  4332. $ret = '';
  4333. if ( ( function_exists ( 'imagepng' ) || function_exists ( 'imagegif' ) )
  4334. && ( empty ( $GLOBALS['enable_gradients'] ) ||
  4335. $GLOBALS['enable_gradients'] == 'Y' ) ) {
  4336. $ret = "background: $color url(\"gradient.php?base=" . substr ( $color, 1 );
  4337. if ( $height != '' ) {
  4338. $ret .= "&height=$height";
  4339. }
  4340. if ( $percent != '' ) {
  4341. $ret .= "&percent=$percent";
  4342. }
  4343. $ret .= "\") repeat-x;\n";
  4344. } else {
  4345. $ret = "background-color: $color;\n";
  4346. }
  4347. return $ret;
  4348. }
  4349. /**
  4350. * Draws a daily outlook style availability grid showing events that are
  4351. * approved and awaiting approval.
  4352. *
  4353. * @param string $date Date to show the grid for
  4354. * @param array $participants Which users should be included in the grid
  4355. * @param string $popup Not used
  4356. */
  4357. function daily_matrix ( $date, $participants, $popup = '' ) {
  4358. global $CELLBG, $TODAYCELLBG, $THFG, $THBG, $TABLEBG;
  4359. global $user_fullname, $repeated_events, $events;
  4360. global $WORK_DAY_START_HOUR, $WORK_DAY_END_HOUR, $TZ_OFFSET,$ignore_offset;
  4361. $increment = 15;
  4362. $interval = 4;
  4363. $participant_pct = '20%'; //use percentage
  4364. $first_hour = $WORK_DAY_START_HOUR;
  4365. $last_hour = $WORK_DAY_END_HOUR;
  4366. $hours = $last_hour - $first_hour;
  4367. $cols = (($hours * $interval) + 1);
  4368. $total_pct = '80%';
  4369. $cell_pct = 80 /($hours * $interval);
  4370. $master = array();
  4371. // Build a master array containing all events for $participants
  4372. for ( $i = 0; $i < count ( $participants ); $i++ ) {
  4373. /* Pre-Load the repeated events for quckier access */
  4374. $repeated_events = read_repeated_events ( $participants[$i], "", $date );
  4375. /* Pre-load the non-repeating events for quicker access */
  4376. $events = read_events ( $participants[$i], $date, $date );
  4377. // get all the repeating events for this date and store in array $rep
  4378. $rep = get_repeating_entries ( $participants[$i], $date );
  4379. // get all the non-repeating events for this date and store in $ev
  4380. $ev = get_entries ( $participants[$i], $date );
  4381. // combine into a single array for easy processing
  4382. $ALL = array_merge ( $rep, $ev );
  4383. foreach ( $ALL as $E ) {
  4384. if ($E['cal_time'] == 0) {
  4385. $E['cal_time'] = $first_hour."0000";
  4386. $E['cal_duration'] = 60 * ( $last_hour - $first_hour );
  4387. } else {
  4388. $E['cal_time'] = sprintf ( "%06d", $E['cal_time']);
  4389. }
  4390. $hour = substr($E['cal_time'], 0, 2 );
  4391. $mins = substr($E['cal_time'], 2, 2 );
  4392. // Timezone Offset
  4393. if ( ! $ignore_offset ) $hour += $TZ_OFFSET;
  4394. while ( $hour < 0 ) $hour += 24;
  4395. while ( $hour > 23 ) $hour -= 24;
  4396. // Make sure hour is 2 digits
  4397. $hour = sprintf ( "%02d",$hour);
  4398. // convert cal_time to slot
  4399. if ($mins < 15) {
  4400. $slot = $hour.'';
  4401. } elseif ($mins >= 15 && $mins < 30) {
  4402. $slot = $hour.'.25';
  4403. } elseif ($mins >= 30 && $mins < 45) {
  4404. $slot = $hour.'.5';
  4405. } elseif ($mins >= 45) {
  4406. $slot = $hour.'.75';
  4407. }
  4408. // convert cal_duration to bars
  4409. $bars = $E['cal_duration'] / $increment;
  4410. // never replace 'A' with 'W'
  4411. for ($q = 0; $bars > $q; $q++) {
  4412. $slot = sprintf ("%02.2f",$slot);
  4413. if (strlen($slot) == 4) $slot = '0'.$slot; // add leading zeros
  4414. $slot = $slot.''; // convert to a string
  4415. if ( empty ( $master['_all_'][$slot] ) ||
  4416. $master['_all_'][$slot]['stat'] != 'A') {
  4417. $master['_all_'][$slot]['stat'] = $E['cal_status'];
  4418. }
  4419. if ( empty ( $master[$participants[$i]][$slot] ) ||
  4420. $master[$participants[$i]][$slot]['stat'] != 'A' ) {
  4421. $master[$participants[$i]][$slot]['stat'] = $E['cal_status'];
  4422. $master[$participants[$i]][$slot]['ID'] = $E['cal_id'];
  4423. }
  4424. $slot = $slot + '0.25';
  4425. }
  4426. }
  4427. }
  4428. ?>
  4429. <br />
  4430. <table align="center" class="matrixd" style="width:<?php echo $total_pct;?>;" cellspacing="0" cellpadding="0">
  4431. <tr><td class="matrix" colspan="<?php echo $cols;?>"></td></tr>
  4432. <tr><th style="width:<?php echo $participant_pct;?>;">
  4433. <?php etranslate("Participants");?></th>
  4434. <?php
  4435. $str = '';
  4436. $MouseOut = "onmouseout=\"window.status=''; this.style.backgroundColor='".$THBG."';\"";
  4437. $CC = 1;
  4438. for($i=$first_hour;$i<$last_hour;$i++) {
  4439. $hour = $i;
  4440. if ( $GLOBALS["TIME_FORMAT"] == "12" ) {
  4441. $hour %= 12;
  4442. if ( $hour == 0 ) $hour = 12;
  4443. }
  4444. for($j=0;$j<$interval;$j++) {
  4445. $str .= ' <td id="C'.$CC.'" class="dailymatrix" ';
  4446. $MouseDown = 'onmousedown="schedule_event('.$i.','.sprintf ("%02d",($increment * $j)).');"';
  4447. switch($j) {
  4448. case 1:
  4449. if($interval == 4) { $k = ($hour<=9?'0':substr($hour,0,1)); }
  4450. $str .= 'style="width:'.$cell_pct.'%; text-align:right;" '.$MouseDown." onmouseover=\"window.status='Schedule a ".$hour.':'.($increment * $j<=9?'0':'').($increment * $j)." appointment.'; this.style.backgroundColor='#CCFFCC'; return true;\" ".$MouseOut." title=\"Schedule an appointment for ".$hour.':'.($increment * $j<=9?'0':'').($increment * $j).".\">";
  4451. $str .= $k."</td>\n";
  4452. break;
  4453. case 2:
  4454. if($interval == 4) { $k = ($hour<=9?substr($hour,0,1):substr($hour,1,2)); }
  4455. $str .= 'style="width:'.$cell_pct.'%; text-align:left;" '.$MouseDown." onmouseover=\"window.status='Schedule a ".$hour.':'.($increment * $j)." appointment.'; this.style.backgroundColor='#CCFFCC'; return true;\" ".$MouseOut." title=\"Schedule an appointment for ".$hour.':'.($increment * $j<=9?'0':'').($increment * $j).".\">";
  4456. $str .= $k."</td>\n";
  4457. break;
  4458. default:
  4459. $str .= 'style="width:'.$cell_pct.'%;" '.$MouseDown." onmouseover=\"window.status='Schedule a ".$hour.':'.($increment * $j<=9?'0':'').($increment * $j)." appointment.'; this.style.backgroundColor='#CCFFCC'; return true;\" ".$MouseOut." title=\"Schedule an appointment for ".$hour.':'.($increment * $j<=9?'0':'').($increment * $j).".\">";
  4460. $str .= "&nbsp;&nbsp;</td>\n";
  4461. break;
  4462. }
  4463. $CC++;
  4464. }
  4465. }
  4466. echo $str .
  4467. "</tr>\n<tr><td class=\"matrix\" colspan=\"$cols\"></td></tr>\n";
  4468. // Add user _all_ to beginning of $participants array
  4469. array_unshift($participants, '_all_');
  4470. // Javascript for cells
  4471. $MouseOver = "onmouseover=\"this.style.backgroundColor='#CCFFCC';\"";
  4472. $MouseOut = "onmouseout=\"this.style.backgroundColor='".$CELLBG."';\"";
  4473. // Display each participant
  4474. for ( $i = 0; $i < count ( $participants ); $i++ ) {
  4475. if ($participants[$i] != '_all_') {
  4476. // Load full name of user
  4477. user_load_variables ( $participants[$i], "user_" );
  4478. // exchange space for &nbsp; to keep from breaking
  4479. $user_nospace = preg_replace ( '/\s/', '&nbsp;', $user_fullname );
  4480. } else {
  4481. $user_nospace = translate("All Attendees");
  4482. $user_nospace = preg_replace ( '/\s/', '&nbsp;', $user_nospace );
  4483. }
  4484. echo "<tr>\n<th class=\"row\" style=\"width:{$participant_pct};\">".$user_nospace."</th>\n";
  4485. $col = 1;
  4486. $viewMsg = translate ( "View this entry" );
  4487. // check each timebar
  4488. for ( $j = $first_hour; $j < $last_hour; $j++ ) {
  4489. for ( $k = 0; $k < $interval; $k++ ) {
  4490. $border = ($k == '0') ? ' border-left: 1px solid #000000;' : "";
  4491. $MouseDown = 'onmousedown="schedule_event('.$j.','.sprintf ("%02d",($increment * $k)).');"';
  4492. $RC = $CELLBG;
  4493. //$space = '';
  4494. $space = "&nbsp;";
  4495. $r = sprintf ("%02d",$j) . '.' . sprintf ("%02d", (25 * $k)).'';
  4496. if ( empty ( $master[$participants[$i]][$r] ) ) {
  4497. // ignore this..
  4498. } else if ( empty ( $master[$participants[$i]][$r]['ID'] ) ) {
  4499. // This is the first line for 'all' users. No event here.
  4500. $space = "<span class=\"matrix\"><img src=\"pix.gif\" alt=\"\" style=\"height: 8px\" /></span>";
  4501. } else if ($master[$participants[$i]][$r]['stat'] == "A") {
  4502. $space = "<a class=\"matrix\" href=\"view_entry.php?id={$master[$participants[$i]][$r]['ID']}\"><img src=\"pix.gif\" title=\"$viewMsg\" alt=\"$viewMsg\" /></a>";
  4503. } else if ($master[$participants[$i]][$r]['stat'] == "W") {
  4504. $space = "<a class=\"matrix\" href=\"view_entry.php?id={$master[$participants[$i]][$r]['ID']}\"><img src=\"pixb.gif\" title=\"$viewMsg\" alt=\"$viewMsg\" /></a>";
  4505. }
  4506. echo "<td class=\"matrixappts\" style=\"width:{$cell_pct}%;$border\" ";
  4507. if ($space == "&nbsp;") echo "$MouseDown $MouseOver $MouseOut";
  4508. echo ">$space</td>\n";
  4509. $col++;
  4510. }
  4511. }
  4512. echo "</tr><tr>\n<td class=\"matrix\" colspan=\"$cols\">" .
  4513. "<img src=\"pix.gif\" alt=\"-\" /></td></tr>\n";
  4514. } // End foreach participant
  4515. echo "</table><br />\n";
  4516. $busy = translate ("Busy");
  4517. $tentative = translate ("Tentative");
  4518. echo "<table align=\"center\"><tr><td class=\"matrixlegend\" >\n";
  4519. echo "<img src=\"pix.gif\" title=\"$busy\" alt=\"$busy\" /> $busy &nbsp; &nbsp; &nbsp;\n";
  4520. echo "<img src=\"pixb.gif\" title=\"$tentative\" alt=\"$tentative\" /> $tentative\n";
  4521. echo "</td></tr></table>\n";
  4522. }
  4523. /**
  4524. * Return the time in HHMMSS format of input time + duration
  4525. *
  4526. *
  4527. * <b>Note:</b> The gd library module needs to be available to use gradient
  4528. * images. If it is not available, a single background color will be used
  4529. * instead.
  4530. *
  4531. * @param string $time format "235900"
  4532. * @param int $duration number of minutes
  4533. *
  4534. * @return string The time in HHMMSS format
  4535. */
  4536. function add_duration ( $time, $duration ) {
  4537. $hour = (int) ( $time / 10000 );
  4538. $min = ( $time / 100 ) % 100;
  4539. $minutes = $hour * 60 + $min + $duration;
  4540. $h = $minutes / 60;
  4541. $m = $minutes % 60;
  4542. $ret = sprintf ( "%d%02d00", $h, $m );
  4543. //echo "add_duration ( $time, $duration ) = $ret <br />\n";
  4544. return $ret;
  4545. }
  4546. ?>