web/wp-content/plugins/calendar/calendar.php
branchwordpress
changeset 112 fb7cd02b9848
parent 111 6b96085291d7
child 123 561aa6d282f6
equal deleted inserted replaced
111:6b96085291d7 112:fb7cd02b9848
     1 <?php
       
     2 /*
       
     3 Plugin Name: Calendar
       
     4 Plugin URI: http://www.kieranoshea.com
       
     5 Description: This plugin allows you to display a calendar of all your events and appointments as a page on your site.
       
     6 Author: Kieran O'Shea
       
     7 Author URI: http://www.kieranoshea.com
       
     8 Version: 1.2.2
       
     9 */
       
    10 
       
    11 /*  Copyright 2008  Kieran O'Shea  (email : kieran@kieranoshea.com)
       
    12 
       
    13     This program is free software; you can redistribute it and/or modify
       
    14     it under the terms of the GNU General Public License as published by
       
    15     the Free Software Foundation; either version 2 of the License, or
       
    16     (at your option) any later version.
       
    17 
       
    18     This program is distributed in the hope that it will be useful,
       
    19     but WITHOUT ANY WARRANTY; without even the implied warranty of
       
    20     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    21     GNU General Public License for more details.
       
    22 
       
    23     You should have received a copy of the GNU General Public License
       
    24     along with this program; if not, write to the Free Software
       
    25     Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
       
    26 */
       
    27 
       
    28 // Enable internationalisation
       
    29 $plugin_dir = basename(dirname(__FILE__));
       
    30 load_plugin_textdomain( 'calendar','wp-content/plugins/'.$plugin_dir, $plugin_dir);
       
    31 
       
    32 // Define the tables used in Calendar
       
    33 define('WP_CALENDAR_TABLE', $table_prefix . 'calendar');
       
    34 define('WP_CALENDAR_CONFIG_TABLE', $table_prefix . 'calendar_config');
       
    35 define('WP_CALENDAR_CATEGORIES_TABLE', $table_prefix . 'calendar_categories');
       
    36 
       
    37 // Create a master category for Calendar and its sub-pages
       
    38 add_action('admin_menu', 'calendar_menu');
       
    39 
       
    40 // Enable the ability for the calendar to be loaded from pages
       
    41 add_filter('the_content','calendar_insert');
       
    42 
       
    43 // Add the function that puts style information in the header
       
    44 add_action('wp_head', 'calendar_wp_head');
       
    45 
       
    46 // Add the function that deals with deleted users
       
    47 add_action('delete_user', 'deal_with_deleted_user');
       
    48 
       
    49 // Add the widgets if we are using version 2.8
       
    50 add_action('widgets_init', 'widget_init_calendar_today');
       
    51 add_action('widgets_init', 'widget_init_calendar_upcoming');
       
    52 
       
    53 // Before we get on with the functions, we need to define the initial style used for Calendar
       
    54 
       
    55 // Function to deal with events posted by a user when that user is deleted
       
    56 function deal_with_deleted_user($id)
       
    57 {
       
    58   global $wpdb;
       
    59 
       
    60   // This wouldn't work unless the database was up to date. Lets check.
       
    61   check_calendar();
       
    62 
       
    63   // Do the query
       
    64   $wpdb->get_results("UPDATE ".WP_CALENDAR_TABLE." SET event_author=".$wpdb->get_var("SELECT MIN(ID) FROM ".$wpdb->prefix."users",0,0)." WHERE event_author=".$id);
       
    65 }
       
    66 
       
    67 // Function to add the calendar style into the header
       
    68 function calendar_wp_head()
       
    69 {
       
    70   global $wpdb;
       
    71 
       
    72   // If the calendar isn't installed or upgraded this won't work
       
    73   check_calendar();
       
    74 
       
    75   $styles = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='calendar_style'");
       
    76   if (!empty($styles))
       
    77     {
       
    78       foreach ($styles as $style)
       
    79         {
       
    80 	  echo '<style type="text/css">
       
    81 <!--
       
    82 ';
       
    83           echo $style->config_value.'
       
    84 ';
       
    85 	  echo '//-->
       
    86 </style>
       
    87 ';
       
    88         }
       
    89     }
       
    90 }
       
    91 
       
    92 // Function to deal with adding the calendar menus
       
    93 function calendar_menu() 
       
    94 {
       
    95   global $wpdb;
       
    96 
       
    97   // We make use of the Calendar tables so we must have installed Calendar
       
    98   check_calendar();
       
    99 
       
   100   // Set admin as the only one who can use Calendar for security
       
   101   $allowed_group = 'manage_options';
       
   102 
       
   103   // Use the database to *potentially* override the above if allowed
       
   104   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='can_manage_events'");
       
   105   if (!empty($configs))
       
   106     {
       
   107       foreach ($configs as $config)
       
   108 	{
       
   109 	  $allowed_group = $config->config_value;
       
   110 	}
       
   111     }
       
   112 
       
   113   // Add the admin panel pages for Calendar. Use permissions pulled from above
       
   114    if (function_exists('add_menu_page')) 
       
   115      {
       
   116        add_menu_page(__('Calendar','calendar'), __('Calendar','calendar'), $allowed_group, 'calendar', 'edit_calendar');
       
   117      }
       
   118    if (function_exists('add_submenu_page')) 
       
   119      {
       
   120        add_submenu_page('calendar', __('Manage Calendar','calendar'), __('Manage Calendar','calendar'), $allowed_group, 'calendar', 'edit_calendar');
       
   121        add_action( "admin_head", 'calendar_add_javascript' );
       
   122        // Note only admin can change calendar options
       
   123        add_submenu_page('calendar', __('Manage Categories','calendar'), __('Manage Categories','calendar'), 'manage_options', 'calendar-categories', 'manage_categories');
       
   124        add_submenu_page('calendar', __('Calendar Config','calendar'), __('Calendar Options','calendar'), 'manage_options', 'calendar-config', 'edit_calendar_config');
       
   125      }
       
   126 }
       
   127 
       
   128 // Function to add the javascript to the admin header
       
   129 function calendar_add_javascript()
       
   130 { 
       
   131   echo '<script type="text/javascript" src="';
       
   132   bloginfo('wpurl');
       
   133   echo '/wp-content/plugins/calendar/javascript.js"></script>
       
   134 <script type="text/javascript">document.write(getCalendarStyles());</script>
       
   135 ';
       
   136 }
       
   137 
       
   138 // Function to deal with loading the calendar into pages
       
   139 function calendar_insert($content)
       
   140 {
       
   141   if (preg_match('{CALENDAR}',$content))
       
   142     {
       
   143       $cal_output = calendar();
       
   144       $content = str_replace('{CALENDAR}',$cal_output,$content);
       
   145     }
       
   146   return $content;
       
   147 }
       
   148 
       
   149 // Function to check what version of Calendar is installed and install if needed
       
   150 function check_calendar()
       
   151 {
       
   152   // Checks to make sure Calendar is installed, if not it adds the default
       
   153   // database tables and populates them with test data. If it is, then the 
       
   154   // version is checked through various means and if it is not up to date 
       
   155   // then it is upgraded.
       
   156 
       
   157   // Lets see if this is first run and create us a table if it is!
       
   158   global $wpdb, $initial_style;
       
   159 
       
   160   // All this style info will go into the database on a new install
       
   161   // This looks nice in the Kubrick theme
       
   162   $initial_style = "    .calnk a:hover {
       
   163          background-position:0 0;
       
   164          text-decoration:none;  
       
   165          color:#000000;
       
   166          border-bottom:1px dotted #000000;
       
   167          }
       
   168     .calnk a:visited {
       
   169          text-decoration:none;
       
   170          color:#000000;
       
   171          border-bottom:1px dotted #000000;
       
   172         }
       
   173     .calnk a {
       
   174         text-decoration:none; 
       
   175         color:#000000; 
       
   176         border-bottom:1px dotted #000000;
       
   177         }
       
   178     .calnk a span { 
       
   179         display:none; 
       
   180         }
       
   181     .calnk a:hover span {
       
   182         color:#333333; 
       
   183         background:#F6F79B; 
       
   184         display:block;
       
   185         position:absolute; 
       
   186         margin-top:1px; 
       
   187         padding:5px; 
       
   188         width:150px; 
       
   189         z-index:100;
       
   190         }
       
   191      .calendar-table {
       
   192         border:none;
       
   193         width:100%;
       
   194      }
       
   195      .calendar-heading {
       
   196         height:25px;
       
   197         text-align:center;
       
   198         border:1px solid #D6DED5;
       
   199         background-color:#E4EBE3;
       
   200      }
       
   201      .calendar-next {
       
   202         width:25%;
       
   203         text-align:center;
       
   204      }
       
   205      .calendar-prev {
       
   206         width:25%;
       
   207         text-align:center;
       
   208      }
       
   209      .calendar-month {
       
   210         width:50%;
       
   211         text-align:center;
       
   212         font-weight:bold;
       
   213      }
       
   214      .normal-day-heading {
       
   215         text-align:center;
       
   216         width:25px;
       
   217         height:25px;
       
   218         font-size:0.8em;
       
   219         border:1px solid #DFE6DE;
       
   220         background-color:#EBF2EA;
       
   221      }
       
   222      .weekend-heading {
       
   223         text-align:center;
       
   224         width:25px;
       
   225         height:25px;
       
   226         font-size:0.8em;
       
   227         border:1px solid #DFE6DE;
       
   228         background-color:#EBF2EA;
       
   229         color:#FF0000;
       
   230      }
       
   231      .day-with-date {
       
   232         vertical-align:text-top;
       
   233         text-align:left;
       
   234         width:60px;
       
   235         height:60px;
       
   236         border:1px solid #DFE6DE;
       
   237      }
       
   238      .no-events {
       
   239 
       
   240      }
       
   241      .day-without-date {
       
   242         width:60px;
       
   243         height:60px;
       
   244         border:1px solid #E9F0E8;
       
   245      }
       
   246      span.weekend {
       
   247         color:#FF0000;
       
   248      }
       
   249      .current-day {
       
   250         vertical-align:text-top;
       
   251         text-align:left;
       
   252         width:60px;
       
   253         height:60px;
       
   254         border:1px solid #BFBFBF;
       
   255         background-color:#E4EBE3;
       
   256      }
       
   257      span.event {
       
   258         font-size:0.75em;
       
   259      }
       
   260      .kjo-link {
       
   261         font-size:0.75em;
       
   262         text-align:center;
       
   263      }
       
   264      .event-title {
       
   265         text-align:center;
       
   266         font-weight:bold;
       
   267         font-size:1.2em;
       
   268      }
       
   269      .event-title-break {
       
   270         width:96%;
       
   271         margin-left:2%;
       
   272         margin-right:2%;
       
   273         margin-top:5px;
       
   274         margin-bottom:5px;
       
   275         text-align:center;
       
   276         height:1px;
       
   277         background-color:#000000;
       
   278      }
       
   279      .event-content-break {
       
   280         width:96%;
       
   281         margin-left:2%;
       
   282         margin-right:2%;
       
   283         margin-top:5px;
       
   284         margin-bottom:5px;
       
   285         text-align:center;
       
   286         height:1px;
       
   287         background-color:#000000;
       
   288      }
       
   289      .calendar-date-switcher {
       
   290         height:25px;
       
   291         text-align:center;
       
   292         border:1px solid #D6DED5;
       
   293         background-color:#E4EBE3;
       
   294      }
       
   295      .calendar-date-switcher form {
       
   296         margin:0;
       
   297         padding:0;
       
   298      }
       
   299      .calendar-date-switcher input {
       
   300         border:1px #D6DED5 solid;
       
   301      }
       
   302      .calendar-date-switcher select {
       
   303         border:1px #D6DED5 solid;
       
   304      }
       
   305      .cat-key {
       
   306         width:100%;
       
   307         margin-top:10px;
       
   308         padding:5px;
       
   309         border:1px solid #D6DED5;
       
   310      }";
       
   311      
       
   312 
       
   313   // Assume this is not a new install until we prove otherwise
       
   314   $new_install = false;
       
   315   $vone_point_one_upgrade = false;
       
   316   $vone_point_two_beta_upgrade = false;
       
   317 
       
   318   $wp_calendar_exists = false;
       
   319   $wp_calendar_config_exists = false;
       
   320   $wp_calendar_config_version_number_exists = false;
       
   321 
       
   322   // Determine the calendar version
       
   323   $tables = $wpdb->get_results("show tables;");
       
   324   foreach ( $tables as $table )
       
   325     {
       
   326       foreach ( $table as $value )
       
   327         {
       
   328 	  if ( $value == WP_CALENDAR_TABLE )
       
   329 	    {
       
   330 	      $wp_calendar_exists = true;
       
   331 	    }
       
   332 	  if ( $value == WP_CALENDAR_CONFIG_TABLE )
       
   333             {
       
   334               $wp_calendar_config_exists = true;
       
   335               
       
   336 	      // We now try and find the calendar version number
       
   337               // This will be a lot easier than finding other stuff 
       
   338               // in the future.
       
   339 	      $version_number = $wpdb->get_var("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='calendar_version'"); 
       
   340 	      if ($version_number == "1.2")
       
   341 		{
       
   342 		  $wp_calendar_config_version_number_exists = true;
       
   343 		}
       
   344             }
       
   345         }
       
   346     }
       
   347 
       
   348   if ($wp_calendar_exists == false && $wp_calendar_config_exists == false)
       
   349     {
       
   350       $new_install = true;
       
   351     }
       
   352   else if ($wp_calendar_exists == true && $wp_calendar_config_exists == false)
       
   353     {
       
   354       $vone_point_one_upgrade = true;
       
   355     }
       
   356   else if ($wp_calendar_exists == true && $wp_calendar_config_exists == true && $wp_calendar_config_version_number_exists == false)
       
   357     {
       
   358       $vone_point_two_beta_upgrade = true;
       
   359     }
       
   360 
       
   361   // Now we've determined what the current install is or isn't 
       
   362   // we perform operations according to the findings
       
   363   if ( $new_install == true )
       
   364     {
       
   365       $sql = "CREATE TABLE " . WP_CALENDAR_TABLE . " (
       
   366                                 event_id INT(11) NOT NULL AUTO_INCREMENT ,
       
   367                                 event_begin DATE NOT NULL ,
       
   368                                 event_end DATE NOT NULL ,
       
   369                                 event_title VARCHAR(30) NOT NULL ,
       
   370                                 event_desc TEXT NOT NULL ,
       
   371                                 event_time TIME ,
       
   372                                 event_recur CHAR(1) ,
       
   373                                 event_repeats INT(3) ,
       
   374                                 event_author BIGINT(20) UNSIGNED,
       
   375                                 PRIMARY KEY (event_id)
       
   376                         )";
       
   377       $wpdb->get_results($sql);
       
   378       $sql = "CREATE TABLE " . WP_CALENDAR_CONFIG_TABLE . " (
       
   379                                 config_item VARCHAR(30) NOT NULL ,
       
   380                                 config_value TEXT NOT NULL ,
       
   381                                 PRIMARY KEY (config_item)
       
   382                         )";
       
   383       $wpdb->get_results($sql);
       
   384       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='can_manage_events', config_value='edit_posts'";
       
   385       $wpdb->get_results($sql);
       
   386       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='calendar_style', config_value='".$initial_style."'";
       
   387       $wpdb->get_results($sql);
       
   388       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_author', config_value='false'";
       
   389       $wpdb->get_results($sql);
       
   390       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_jump', config_value='false'";
       
   391       $wpdb->get_results($sql);
       
   392       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_todays', config_value='true'";
       
   393       $wpdb->get_results($sql);
       
   394       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_upcoming', config_value='true'";
       
   395       $wpdb->get_results($sql);
       
   396       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_upcoming_days', config_value=7";
       
   397       $wpdb->get_results($sql);
       
   398 
       
   399       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='calendar_version', config_value='1.2'";
       
   400       $wpdb->get_results($sql);
       
   401       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='enable_categories', config_value='false'";
       
   402       $wpdb->get_results($sql);
       
   403       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_category BIGINT(20) UNSIGNED";
       
   404       $wpdb->get_results($sql);
       
   405       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_category=1";
       
   406       $wpdb->get_results($sql);
       
   407       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_link TEXT";
       
   408       $wpdb->get_results($sql);
       
   409       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_link=''";
       
   410       $wpdb->get_results($sql);
       
   411       $sql = "CREATE TABLE " . WP_CALENDAR_CATEGORIES_TABLE . " ( 
       
   412                                 category_id INT(11) NOT NULL AUTO_INCREMENT, 
       
   413                                 category_name VARCHAR(30) NOT NULL , 
       
   414                                 category_colour VARCHAR(30) NOT NULL , 
       
   415                                 PRIMARY KEY (category_id) 
       
   416                              )";
       
   417       $wpdb->get_results($sql);
       
   418       $sql = "INSERT INTO " . WP_CALENDAR_CATEGORIES_TABLE . " SET category_id=1, category_name='General', category_colour='#F6F79B'";
       
   419       $wpdb->get_results($sql);
       
   420     }
       
   421   else if ($vone_point_one_upgrade == true)
       
   422     {
       
   423       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_author BIGINT(20) UNSIGNED";
       
   424       $wpdb->get_results($sql);
       
   425       $sql = "UPDATE ".WP_CALENDAR_TABLE." SET event_author=".$wpdb->get_var("SELECT MIN(ID) FROM ".$wpdb->prefix."users",0,0);
       
   426       $wpdb->get_results($sql);
       
   427       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." MODIFY event_desc TEXT NOT NULL";
       
   428       $wpdb->get_results($sql);
       
   429       $sql = "CREATE TABLE " . WP_CALENDAR_CONFIG_TABLE . " (
       
   430                                 config_item VARCHAR(30) NOT NULL ,
       
   431                                 config_value TEXT NOT NULL ,
       
   432                                 PRIMARY KEY (config_item)
       
   433                         )";
       
   434       $wpdb->get_results($sql);
       
   435       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='can_manage_events', config_value='edit_posts'";
       
   436       $wpdb->get_results($sql);
       
   437       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='calendar_style', config_value='".$initial_style."'";
       
   438       $wpdb->get_results($sql);
       
   439       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_author', config_value='false'";
       
   440       $wpdb->get_results($sql);
       
   441       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_jump', config_value='false'";
       
   442       $wpdb->get_results($sql);
       
   443       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_todays', config_value='true'";
       
   444       $wpdb->get_results($sql);
       
   445       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_upcoming', config_value='true'";
       
   446       $wpdb->get_results($sql);
       
   447       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='display_upcoming_days', config_value=7";
       
   448       $wpdb->get_results($sql);
       
   449 
       
   450       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='calendar_version', config_value='1.2'";
       
   451       $wpdb->get_results($sql);
       
   452       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='enable_categories', config_value='false'";
       
   453       $wpdb->get_results($sql);
       
   454       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_category BIGINT(20) UNSIGNED";
       
   455       $wpdb->get_results($sql);
       
   456       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_category=1";
       
   457       $wpdb->get_results($sql);
       
   458       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_link TEXT";
       
   459       $wpdb->get_results($sql);
       
   460       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_link=''";
       
   461       $wpdb->get_results($sql);
       
   462       $sql = "CREATE TABLE " . WP_CALENDAR_CATEGORIES_TABLE . " ( 
       
   463                                 category_id INT(11) NOT NULL AUTO_INCREMENT, 
       
   464                                 category_name VARCHAR(30) NOT NULL , 
       
   465                                 category_colour VARCHAR(30) NOT NULL , 
       
   466                                 PRIMARY KEY (category_id) 
       
   467                               )";
       
   468       $wpdb->get_results($sql);
       
   469       $sql = "INSERT INTO " . WP_CALENDAR_CATEGORIES_TABLE . " SET category_id=1, category_name='General', category_colour='#F6F79B'";
       
   470       $wpdb->get_results($sql);
       
   471     }
       
   472   else if ($vone_point_two_beta_upgrade == true)
       
   473     {
       
   474       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='calendar_version', config_value='1.2'";
       
   475       $wpdb->get_results($sql);
       
   476       $sql = "INSERT INTO ".WP_CALENDAR_CONFIG_TABLE." SET config_item='enable_categories', config_value='false'";
       
   477       $wpdb->get_results($sql);
       
   478       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_category BIGINT(20) UNSIGNED";
       
   479       $wpdb->get_results($sql);
       
   480       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_category=1";
       
   481       $wpdb->get_results($sql);
       
   482       $sql = "ALTER TABLE ".WP_CALENDAR_TABLE." ADD COLUMN event_link TEXT";
       
   483       $wpdb->get_results($sql);
       
   484       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_link=''";
       
   485       $wpdb->get_results($sql);
       
   486       $sql = "CREATE TABLE " . WP_CALENDAR_CATEGORIES_TABLE . " (
       
   487                                 category_id INT(11) NOT NULL AUTO_INCREMENT, 
       
   488                                 category_name VARCHAR(30) NOT NULL , 
       
   489                                 category_colour VARCHAR(30) NOT NULL , 
       
   490                                 PRIMARY KEY (category_id) 
       
   491                              )";
       
   492       $wpdb->get_results($sql);
       
   493       $sql = "INSERT INTO " . WP_CALENDAR_CATEGORIES_TABLE . " SET category_id=1, category_name='General', category_colour='#F6F79B'";
       
   494       $wpdb->get_results($sql);
       
   495       $sql = "UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value='".$initial_style."' WHERE config_item='calendar_style'";
       
   496       $wpdb->get_results($sql);
       
   497     }
       
   498 }
       
   499 
       
   500 // Used on the manage events admin page to display a list of events
       
   501 function wp_events_display_list()
       
   502 {
       
   503 	global $wpdb;
       
   504 	
       
   505 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " ORDER BY event_begin DESC");
       
   506 	
       
   507 	if ( !empty($events) )
       
   508 	{
       
   509 		?>
       
   510 		<table class="widefat page fixed" width="100%" cellpadding="3" cellspacing="3">
       
   511 		        <thead>
       
   512 			    <tr>
       
   513 				<th class="manage-column" scope="col"><?php _e('ID','calendar') ?></th>
       
   514 				<th class="manage-column" scope="col"><?php _e('Title','calendar') ?></th>
       
   515 				<th class="manage-column" scope="col"><?php _e('Description','calendar') ?></th>
       
   516 				<th class="manage-column" scope="col"><?php _e('Start Date','calendar') ?></th>
       
   517 				<th class="manage-column" scope="col"><?php _e('End Date','calendar') ?></th>
       
   518 				<th class="manage-column" scope="col"><?php _e('Recurs','calendar') ?></th>
       
   519 				<th class="manage-column" scope="col"><?php _e('Repeats','calendar') ?></th>
       
   520 		                <th class="manage-column" scope="col"><?php _e('Author','calendar') ?></th>
       
   521 		                <th class="manage-column" scope="col"><?php _e('Category','calendar') ?></th>
       
   522 				<th class="manage-column" scope="col"><?php _e('Edit','calendar') ?></th>
       
   523 				<th class="manage-column" scope="col"><?php _e('Delete','calendar') ?></th>
       
   524 			    </tr>
       
   525 		        </thead>
       
   526 		<?php
       
   527 		$class = '';
       
   528 		foreach ( $events as $event )
       
   529 		{
       
   530 			$class = ($class == 'alternate') ? '' : 'alternate';
       
   531 			?>
       
   532 			<tr class="<?php echo $class; ?>">
       
   533 				<th scope="row"><?php echo $event->event_id; ?></th>
       
   534 				<td><?php echo $event->event_title; ?></td>
       
   535 				<td><?php echo $event->event_desc; ?></td>
       
   536 				<td><?php echo $event->event_begin; ?></td>
       
   537 				<td><?php echo $event->event_end; ?></td>
       
   538 				<td>
       
   539 				<?php 
       
   540 					// Interpret the DB values into something human readable
       
   541 					if ($event->event_recur == 'S') { echo __('Never','calendar'); } 
       
   542 					else if ($event->event_recur == 'W') { echo __('Weekly','calendar'); }
       
   543 					else if ($event->event_recur == 'M') { echo __('Monthly','calendar'); }
       
   544 					else if ($event->event_recur == 'Y') { echo __('Yearly','calendar'); }
       
   545 				?>
       
   546 				</td>
       
   547 				<td>
       
   548 				<?php
       
   549 				        // Interpret the DB values into something human readable
       
   550 					if ($event->event_recur == 'S') { echo __('N/A','calendar'); }
       
   551 					else if ($event->event_repeats == 0) { echo __('Forever','calendar'); }
       
   552 					else if ($event->event_repeats > 0) { echo $event->event_repeats.' '.__('Times','calendar'); }					
       
   553 				?>
       
   554 				</td>
       
   555 				<td><?php $e = get_userdata($event->event_author); echo $e->display_name; ?></td>
       
   556                                 <?php
       
   557 				$sql = "SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE . " WHERE category_id=".$event->event_category;
       
   558                                 $this_cat = $wpdb->get_row($sql);
       
   559                                 ?>
       
   560 				<td style="background-color:<?php echo $this_cat->category_colour;?>;"><?php echo $this_cat->category_name; ?></td>
       
   561 				<?php unset($this_cat); ?>
       
   562 				<td><a href="<?php echo $_SERVER['PHP_SELF'] ?>?page=calendar&amp;action=edit&amp;event_id=<?php echo $event->event_id;?>" class='edit'><?php echo __('Edit','calendar'); ?></a></td>
       
   563 				<td><a href="<?php echo $_SERVER['PHP_SELF'] ?>?page=calendar&amp;action=delete&amp;event_id=<?php echo $event->event_id;?>" class="delete" onclick="return confirm('<?php _e('Are you sure you want to delete this event?','calendar'); ?>')"><?php echo __('Delete','calendar'); ?></a></td>
       
   564 			</tr>
       
   565 			<?php
       
   566 		}
       
   567 		?>
       
   568 		</table>
       
   569 		<?php
       
   570 	}
       
   571 	else
       
   572 	{
       
   573 		?>
       
   574 		<p><?php _e("There are no events in the database!",'calendar')	?></p>
       
   575 		<?php	
       
   576 	}
       
   577 }
       
   578 
       
   579 
       
   580 // The event edit form for the manage events admin page
       
   581 function wp_events_edit_form($mode='add', $event_id=false)
       
   582 {
       
   583 	global $wpdb,$users_entries;
       
   584 	$data = false;
       
   585 	
       
   586 	if ( $event_id !== false )
       
   587 	{
       
   588 		if ( intval($event_id) != $event_id )
       
   589 		{
       
   590 			echo "<div class=\"error\"><p>".__('Bad Monkey! No banana!','calendar')."</p></div>";
       
   591 			return;
       
   592 		}
       
   593 		else
       
   594 		{
       
   595 			$data = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_id='" . mysql_escape_string($event_id) . "' LIMIT 1");
       
   596 			if ( empty($data) )
       
   597 			{
       
   598 				echo "<div class=\"error\"><p>".__("An event with that ID couldn't be found",'calendar')."</p></div>";
       
   599 				return;
       
   600 			}
       
   601 			$data = $data[0];
       
   602 		}
       
   603 		// Recover users entries if they exist; in other words if editing an event went wrong
       
   604 		if (!empty($users_entries))
       
   605 		  {
       
   606 		    $data = $users_entries;
       
   607 		  }
       
   608 	}
       
   609 	// Deal with possibility that form was submitted but not saved due to error - recover user's entries here
       
   610 	else
       
   611 	  {
       
   612 	    $data = $users_entries;
       
   613 	  }
       
   614 	
       
   615 	?>
       
   616         <div id="pop_up_cal" style="position:absolute;margin-left:150px;visibility:hidden;background-color:white;layer-background-color:white;z-index:1;"></div>
       
   617 	<form name="quoteform" id="quoteform" class="wrap" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?page=calendar">
       
   618 		<input type="hidden" name="action" value="<?php echo $mode; ?>">
       
   619 		<input type="hidden" name="event_id" value="<?php echo $event_id; ?>">
       
   620 	
       
   621 		<div id="linkadvanceddiv" class="postbox">
       
   622 			<div style="float: left; width: 98%; clear: both;" class="inside">
       
   623                                 <table cellpadding="5" cellspacing="5">
       
   624                                 <tr>				
       
   625 				<td><legend><?php _e('Event Title','calendar'); ?></legend></td>
       
   626 				<td><input type="text" name="event_title" class="input" size="40" maxlength="30"
       
   627 					value="<?php if ( !empty($data) ) echo htmlspecialchars($data->event_title); ?>" /></td>
       
   628                                 </tr>
       
   629                                 <tr>
       
   630 				<td style="vertical-align:top;"><legend><?php _e('Event Description','calendar'); ?></legend></td>
       
   631 				<td><textarea name="event_desc" class="input" rows="5" cols="50"><?php if ( !empty($data) ) echo htmlspecialchars($data->event_desc); ?></textarea></td>
       
   632                                 </tr>
       
   633                                 <tr>
       
   634 				<td><legend><?php _e('Event Category','calendar'); ?></legend></td>
       
   635 				<td>	 <select name="event_category">
       
   636 					     <?php
       
   637 					         // Grab all the categories and list them
       
   638 						 $sql = "SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE;
       
   639 	                                         $cats = $wpdb->get_results($sql);
       
   640                                                  foreach($cats as $cat)
       
   641 						   {
       
   642 						     echo '<option value="'.$cat->category_id.'"';
       
   643                                                      if (!empty($data))
       
   644 						       {
       
   645 							 if ($data->event_category == $cat->category_id)
       
   646 							   {
       
   647 							     echo 'selected="selected"';
       
   648 							   }
       
   649 						       }
       
   650                                                      echo '>'.$cat->category_name.'</option>
       
   651 ';
       
   652 						   }
       
   653                                              ?>
       
   654                                          </select>
       
   655                                 </td>
       
   656                                 </tr>
       
   657                                 <tr>
       
   658 				<td><legend><?php _e('Event Link (Optional)','calendar'); ?></legend></td>
       
   659                                 <td><input type="text" name="event_link" class="input" size="40" value="<?php if ( !empty($data) ) echo htmlspecialchars($data->event_link); ?>" /></td>
       
   660                                 </tr>
       
   661                                 <tr>
       
   662 				<td><legend><?php _e('Start Date','calendar'); ?></legend></td>
       
   663                                 <td>        <script type="text/javascript">
       
   664 					var cal_begin = new CalendarPopup('pop_up_cal');
       
   665 					function unifydates() {
       
   666 					  document.forms['quoteform'].event_end.value = document.forms['quoteform'].event_begin.value;
       
   667 					}
       
   668 					</script>
       
   669 					<input type="text" name="event_begin" class="input" size="12"
       
   670 					value="<?php 
       
   671 					if ( !empty($data) ) 
       
   672 					{
       
   673 						echo htmlspecialchars($data->event_begin);
       
   674 					}
       
   675 					else
       
   676 					{
       
   677 						echo date("Y-m-d");
       
   678 					} 
       
   679 					?>" /> <a href="#" onClick="cal_begin.select(document.forms['quoteform'].event_begin,'event_begin_anchor','yyyy-MM-dd'); return false;" name="event_begin_anchor" id="event_begin_anchor"><?php _e('Select Date','calendar'); ?></a>
       
   680 				</td>
       
   681                                 </tr>
       
   682                                 <tr>
       
   683 				<td><legend><?php _e('End Date','calendar'); ?></legend></td>
       
   684                                 <td>    <script type="text/javascript">
       
   685 					function check_and_print() {
       
   686 					unifydates();
       
   687 					var cal_end = new CalendarPopup('pop_up_cal');
       
   688 					var newDate = new Date();
       
   689 					newDate.setFullYear(document.forms['quoteform'].event_begin.value.split('-')[0],document.forms['quoteform'].event_begin.value.split('-')[1]-1,document.forms['quoteform'].event_begin.value.split('-')[2]);
       
   690 					newDate.setDate(newDate.getDate()-1);
       
   691                                         cal_end.addDisabledDates(null, formatDate(newDate, "yyyy-MM-dd"));
       
   692                                         cal_end.select(document.forms['quoteform'].event_end,'event_end_anchor','yyyy-MM-dd');
       
   693 					}
       
   694                                         </script>
       
   695 					<input type="text" name="event_end" class="input" size="12"
       
   696 					value="<?php 
       
   697 					if ( !empty($data) ) 
       
   698 					{
       
   699 						echo htmlspecialchars($data->event_end);
       
   700 					}
       
   701 					else
       
   702 					{
       
   703 						echo date("Y-m-d");
       
   704 					}
       
   705 					?>" />  <a href="#" onClick="check_and_print(); return false;" name="event_end_anchor" id="event_end_anchor"><?php _e('Select Date','calendar'); ?></a>
       
   706 				</td>
       
   707                                 </tr>
       
   708                                 <tr>
       
   709 				<td><legend><?php _e('Time (hh:mm)','calendar'); ?></legend></td>
       
   710 				<td>	<input type="text" name="event_time" class="input" size=12
       
   711 					value="<?php 
       
   712 					if ( !empty($data) ) 
       
   713 					{
       
   714 						if ($data->event_time == "00:00:00")
       
   715 						{
       
   716 							echo '';
       
   717 						}
       
   718 						else
       
   719 						{
       
   720 							echo date("H:i",strtotime(htmlspecialchars($data->event_time)));
       
   721 						}
       
   722 					}
       
   723 					else
       
   724 					{
       
   725 						echo date("H:i");
       
   726 					}
       
   727 					?>" /> <?php _e('Optional, set blank if not required.','calendar'); ?> <?php _e('Current time difference from GMT is ','calendar'); echo get_option('gmt_offset'); _e(' hour(s)'); ?>
       
   728 				</td>
       
   729                                 </tr>
       
   730                                 <tr>
       
   731 				<td><legend><?php _e('Recurring Events','calendar'); ?></legend></td>
       
   732 				<td>	<?php
       
   733 					if ($data->event_repeats != NULL)
       
   734 					{
       
   735 						$repeats = $data->event_repeats;
       
   736 					}
       
   737 					else
       
   738 					{
       
   739 						$repeats = 0;
       
   740 					}
       
   741 
       
   742 					if ($data->event_recur == "S")
       
   743 					{
       
   744 						$selected_s = 'selected="selected"';
       
   745 					}
       
   746 					else if ($data->event_recur == "W")
       
   747 					{
       
   748 						$selected_w = 'selected="selected"';
       
   749 					}
       
   750 					else if ($data->event_recur == "M")
       
   751 					{
       
   752 						$selected_m = 'selected="selected"';
       
   753 					}
       
   754 					else if ($data->event_recur == "Y")
       
   755 					{
       
   756 						$selected_y = 'selected="selected"';
       
   757 					}
       
   758 					?>
       
   759 					  <?php _e('Repeats for','calendar'); ?> 
       
   760 					<input type="text" name="event_repeats" class="input" size="1" value="<?php echo $repeats; ?>" /> 
       
   761 					<select name="event_recur" class="input">
       
   762 						<option class="input" <?php echo $selected_s; ?> value="S">None</option>
       
   763 						<option class="input" <?php echo $selected_w; ?> value="W">Weeks</option>
       
   764 						<option class="input" <?php echo $selected_m; ?> value="M">Months</option>
       
   765 						<option class="input" <?php echo $selected_y; ?> value="Y">Years</option>
       
   766 					</select><br />
       
   767 					<?php _e('Entering 0 means forever. Where the recurrance interval is left at none, the event will not reoccur.','calendar'); ?>
       
   768 				</td>
       
   769                                 </tr>
       
   770                                 </table>
       
   771 			</div>
       
   772 			<div style="clear:both; height:1px;">&nbsp;</div>
       
   773 		</div>
       
   774                 <input type="submit" name="save" class="button bold" value="<?php _e('Save','calendar'); ?> &raquo;" />
       
   775 	</form>
       
   776 	<?php
       
   777 }
       
   778 
       
   779 // The actual function called to render the manage events page and 
       
   780 // to deal with posts
       
   781 function edit_calendar()
       
   782 {
       
   783     global $current_user, $wpdb, $users_entries;
       
   784   ?>
       
   785   <style type="text/css">
       
   786 <!--
       
   787 	.error {
       
   788 	  background: lightcoral;
       
   789 	  border: 1px solid #e64f69;
       
   790 	  margin: 1em 5% 10px;
       
   791 	  padding: 0 1em 0 1em;
       
   792 	}
       
   793 
       
   794 	.center { 
       
   795 	  text-align: center;	
       
   796 	}
       
   797 	.right { text-align: right;	
       
   798 	}
       
   799         .left { 
       
   800 	  text-align: left;		
       
   801 	}
       
   802 	.top { 
       
   803 	  vertical-align: top;	
       
   804 	}
       
   805 	.bold { 
       
   806 	  font-weight: bold; 
       
   807 	}
       
   808 	.private { 
       
   809 	  color: #e64f69;		
       
   810 	}
       
   811 //-->
       
   812 </style>
       
   813 
       
   814 <?php
       
   815 
       
   816 // First some quick cleaning up 
       
   817 $edit = $create = $save = $delete = false;
       
   818 
       
   819 // Make sure we are collecting the variables we need to select years and months
       
   820 $action = !empty($_REQUEST['action']) ? $_REQUEST['action'] : '';
       
   821 $event_id = !empty($_REQUEST['event_id']) ? $_REQUEST['event_id'] : '';
       
   822 
       
   823 
       
   824 // Lets see if this is first run and create us a table if it is!
       
   825 check_calendar();
       
   826 
       
   827 // Deal with adding an event to the database
       
   828 if ( $action == 'add' )
       
   829 {
       
   830 	$title = !empty($_REQUEST['event_title']) ? $_REQUEST['event_title'] : '';
       
   831 	$desc = !empty($_REQUEST['event_desc']) ? $_REQUEST['event_desc'] : '';
       
   832 	$begin = !empty($_REQUEST['event_begin']) ? $_REQUEST['event_begin'] : '';
       
   833 	$end = !empty($_REQUEST['event_end']) ? $_REQUEST['event_end'] : '';
       
   834 	$time = !empty($_REQUEST['event_time']) ? $_REQUEST['event_time'] : '';
       
   835 	$recur = !empty($_REQUEST['event_recur']) ? $_REQUEST['event_recur'] : '';
       
   836 	$repeats = !empty($_REQUEST['event_repeats']) ? $_REQUEST['event_repeats'] : '';
       
   837 	$category = !empty($_REQUEST['event_category']) ? $_REQUEST['event_category'] : '';
       
   838         $linky = !empty($_REQUEST['event_link']) ? $_REQUEST['event_link'] : '';
       
   839 
       
   840 	// Deal with the fools who have left magic quotes turned on
       
   841 	if ( ini_get('magic_quotes_gpc') )
       
   842 	{
       
   843 		$title = stripslashes($title);
       
   844 		$desc = stripslashes($desc);
       
   845 		$begin = stripslashes($begin);
       
   846 		$end = stripslashes($end);
       
   847 		$time = stripslashes($time);
       
   848 		$recur = stripslashes($recur);
       
   849 		$repeats = stripslashes($repeats);
       
   850                 $category = stripslashes($category);
       
   851                 $linky = stripslashes($linky);	
       
   852 	}	
       
   853 
       
   854 	// Perform some validation on the submitted dates - this checks for valid years and months
       
   855 	$date_format_one = '/^([0-9]{4})-([0][1-9])-([0-3][0-9])$/';
       
   856         $date_format_two = '/^([0-9]{4})-([1][0-2])-([0-3][0-9])$/';
       
   857 	if ((preg_match($date_format_one,$begin) || preg_match($date_format_two,$begin)) && (preg_match($date_format_one,$end) || preg_match($date_format_two,$end)))
       
   858 	  {
       
   859             // We know we have a valid year and month and valid integers for days so now we do a final check on the date
       
   860             $begin_split = split('-',$begin);
       
   861 	    $begin_y = $begin_split[0]; 
       
   862 	    $begin_m = $begin_split[1];
       
   863 	    $begin_d = $begin_split[2];
       
   864             $end_split = split('-',$end);
       
   865 	    $end_y = $end_split[0];
       
   866 	    $end_m = $end_split[1];
       
   867 	    $end_d = $end_split[2];
       
   868             if (checkdate($begin_m,$begin_d,$begin_y) && checkdate($end_m,$end_d,$end_y))
       
   869 	     {
       
   870 	       // Ok, now we know we have valid dates, we want to make sure that they are either equal or that the end date is later than the start date
       
   871 	       if (strtotime($end) >= strtotime($begin))
       
   872 		 {
       
   873 		   $start_date_ok = 1;
       
   874 		   $end_date_ok = 1;
       
   875 		 }
       
   876 	       else
       
   877 		 {
       
   878 		   ?>
       
   879 		   <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Your event end date must be either after or the same as your event begin date','calendar'); ?></p></div>
       
   880 		   <?php
       
   881 		 }
       
   882 	     } 
       
   883 	    else
       
   884 	      {
       
   885 		?>
       
   886                 <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Your date formatting is correct but one or more of your dates is invalid. Check for number of days in month and leap year related errors.','calendar'); ?></p></div>
       
   887                 <?php
       
   888 	      }
       
   889 	  }
       
   890 	else
       
   891 	  {
       
   892 	    ?>
       
   893             <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Both start and end dates must be entered and be in the format YYYY-MM-DD','calendar'); ?></p></div>
       
   894             <?php
       
   895 	  }
       
   896         // We check for a valid time, or an empty one
       
   897         $time_format_one = '/^([0-1][0-9]):([0-5][0-9])$/';
       
   898 	$time_format_two = '/^([2][0-3]):([0-5][0-9])$/';
       
   899         if (preg_match($time_format_one,$time) || preg_match($time_format_two,$time) || $time == '')
       
   900           {
       
   901             $time_ok = 1;
       
   902           }
       
   903         else
       
   904           {
       
   905             ?>
       
   906             <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The time field must either be blank or be entered in the format hh:mm','calendar'); ?></p></div>
       
   907             <?php
       
   908 	  }
       
   909 	// We check to make sure the URL is alright                                                        
       
   910 	if (preg_match('/^(http)(s?)(:)\/\//',$linky) || $linky == '')
       
   911 	  {
       
   912 	    $url_ok = 1;
       
   913 	  }
       
   914 	else
       
   915 	  {
       
   916               ?>
       
   917               <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The URL entered must either be prefixed with http:// or be completely blank','calendar'); ?></p></div>
       
   918               <?php
       
   919 	  }
       
   920 	// The title must be at least one character in length and no more than 30 - no non-standard characters allowed
       
   921 	if (preg_match('/^[a-zA-Z0-9]{1}[a-zA-Z0-9[:space:]]{0,29}$/',$title))
       
   922 	  {
       
   923 	    $title_ok =1;
       
   924 	  }
       
   925 	else
       
   926 	  {
       
   927               ?>
       
   928               <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The event title must be between 1 and 30 characters in length and contain no punctuation. Spaces are allowed but the title must not start with one.','calendar'); ?></p></div>
       
   929               <?php
       
   930 	  }
       
   931 	// We run some checks on recurrance                                                                        
       
   932 	if (($repeats == 0 && $recur == 'S') || (($repeats >= 0) && ($recur == 'W' || $recur == 'M' || $recur == 'Y')))
       
   933 	  {
       
   934 	    $recurring_ok = 1;
       
   935 	  }
       
   936 	else
       
   937 	  {
       
   938               ?>
       
   939               <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The repetition value must be 0 unless a type of recurrance is selected in which case the repetition value must be 0 or higher','calendar'); ?></p></div>
       
   940               <?php
       
   941 	  }
       
   942 	if ($start_date_ok == 1 && $end_date_ok == 1 && $time_ok == 1 && $url_ok == 1 && $title_ok == 1 && $recurring_ok == 1)
       
   943 	  {
       
   944 	    $sql = "INSERT INTO " . WP_CALENDAR_TABLE . " SET event_title='" . mysql_escape_string($title)
       
   945 	     . "', event_desc='" . mysql_escape_string($desc) . "', event_begin='" . mysql_escape_string($begin) 
       
   946              . "', event_end='" . mysql_escape_string($end) . "', event_time='" . mysql_escape_string($time) . "', event_recur='" . mysql_escape_string($recur) . "', event_repeats='" . mysql_escape_string($repeats) . "', event_author=".$current_user->ID.", event_category=".mysql_escape_string($category).", event_link='".mysql_escape_string($linky)."'";
       
   947 	     
       
   948 	    $wpdb->get_results($sql);
       
   949 	
       
   950 	    $sql = "SELECT event_id FROM " . WP_CALENDAR_TABLE . " WHERE event_title='" . mysql_escape_string($title) . "'"
       
   951 		. " AND event_desc='" . mysql_escape_string($desc) . "' AND event_begin='" . mysql_escape_string($begin) . "' AND event_end='" . mysql_escape_string($end) . "' AND event_recur='" . mysql_escape_string($recur) . "' AND event_repeats='" . mysql_escape_string($repeats) . "' LIMIT 1";
       
   952 	    $result = $wpdb->get_results($sql);
       
   953 	
       
   954 	    if ( empty($result) || empty($result[0]->event_id) )
       
   955 	      {
       
   956                 ?>
       
   957 		<div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('An event with the details you submitted could not be found in the database. This may indicate a problem with your database or the way in which it is configured.','calendar'); ?></p></div>
       
   958 		<?php
       
   959 	      }
       
   960 	    else
       
   961 	      {
       
   962 		?>
       
   963 		<div class="updated"><p><?php _e('Event added. It will now show in your calendar.','calendar'); ?></p></div>
       
   964 		<?php
       
   965 	      }
       
   966 	  }
       
   967 	else
       
   968 	  {
       
   969 	    // The form is going to be rejected due to field validation issues, so we preserve the users entries here
       
   970 	    $users_entries->event_title = $title;
       
   971 	    $users_entries->event_desc = $desc;
       
   972 	    $users_entries->event_begin = $begin;
       
   973 	    $users_entries->event_end = $end;
       
   974 	    $users_entries->event_time = $time;
       
   975 	    $users_entries->event_recur = $recur;
       
   976 	    $users_entries->event_repeats = $repeats;
       
   977 	    $users_entries->event_category = $category;
       
   978 	    $users_entries->event_link = $linky;
       
   979 	  }
       
   980 }
       
   981 // Permit saving of events that have been edited
       
   982 elseif ( $action == 'edit_save' )
       
   983 {
       
   984 	$title = !empty($_REQUEST['event_title']) ? $_REQUEST['event_title'] : '';
       
   985 	$desc = !empty($_REQUEST['event_desc']) ? $_REQUEST['event_desc'] : '';
       
   986 	$begin = !empty($_REQUEST['event_begin']) ? $_REQUEST['event_begin'] : '';
       
   987 	$end = !empty($_REQUEST['event_end']) ? $_REQUEST['event_end'] : '';
       
   988 	$time = !empty($_REQUEST['event_time']) ? $_REQUEST['event_time'] : '';
       
   989 	$recur = !empty($_REQUEST['event_recur']) ? $_REQUEST['event_recur'] : '';
       
   990 	$repeats = !empty($_REQUEST['event_repeats']) ? $_REQUEST['event_repeats'] : '';
       
   991 	$category = !empty($_REQUEST['event_category']) ? $_REQUEST['event_category'] : '';
       
   992         $linky = !empty($_REQUEST['event_link']) ? $_REQUEST['event_link'] : '';
       
   993 
       
   994 	// Deal with the fools who have left magic quotes turned on
       
   995 	if ( ini_get('magic_quotes_gpc') )
       
   996 	{
       
   997 		$title = stripslashes($title);
       
   998 		$desc = stripslashes($desc);
       
   999 		$begin = stripslashes($begin);
       
  1000 		$end = stripslashes($end);
       
  1001 		$time = stripslashes($time);
       
  1002 		$recur = stripslashes($recur);
       
  1003 		$repeats = stripslashes($repeats);
       
  1004                 $category = stripslashes($category);
       
  1005                 $linky = stripslashes($linky);	
       
  1006 	}
       
  1007 	
       
  1008 	if ( empty($event_id) )
       
  1009 	{
       
  1010 		?>
       
  1011 		<div class="error"><p><strong><?php _e('Failure','calendar'); ?>:</strong> <?php _e("You can't update an event if you haven't submitted an event id",'calendar'); ?></p></div>
       
  1012 		<?php		
       
  1013 	}
       
  1014 	else
       
  1015 	{
       
  1016 	  // Perform some validation on the submitted dates - this checks for valid years and months
       
  1017           $date_format_one = '/^([0-9]{4})-([0][1-9])-([0-3][0-9])$/';
       
  1018 	  $date_format_two = '/^([0-9]{4})-([1][0-2])-([0-3][0-9])$/';
       
  1019 	  if ((preg_match($date_format_one,$begin) || preg_match($date_format_two,$begin)) && (preg_match($date_format_one,$end) || preg_match($date_format_two,$end)))
       
  1020 	    {
       
  1021 	      // We know we have a valid year and month and valid integers for days so now we do a final check on the date
       
  1022               $begin_split = split('-',$begin);
       
  1023 	      $begin_y = $begin_split[0];
       
  1024 	      $begin_m = $begin_split[1];
       
  1025 	      $begin_d = $begin_split[2];
       
  1026 	      $end_split = split('-',$end);
       
  1027 	      $end_y = $end_split[0];
       
  1028 	      $end_m = $end_split[1];
       
  1029 	      $end_d = $end_split[2];
       
  1030 	      if (checkdate($begin_m,$begin_d,$begin_y) && checkdate($end_m,$end_d,$end_y))
       
  1031 		{
       
  1032 		  // Ok, now we know we have valid dates, we want to make sure that they are either equal or that the end date is later than the start date
       
  1033                   if (strtotime($end) >= strtotime($begin))
       
  1034 		    {
       
  1035 		      $start_date_ok = 1;
       
  1036 		      $end_date_ok = 1;
       
  1037 		    }
       
  1038 		  else
       
  1039 		    {
       
  1040                       ?>
       
  1041                       <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Your event end date must be either after or the same as your event begin date','calendar'); ?></p></div>
       
  1042                       <?php
       
  1043                     }
       
  1044 		}
       
  1045 	      else
       
  1046 		{
       
  1047                 ?>
       
  1048                 <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Your date formatting is correct but one or more of your dates is invalid. Check for number of days in month and leap year related errors.','calendar'); ?></p></div>
       
  1049                 <?php
       
  1050                 }
       
  1051 	    }
       
  1052 	  else
       
  1053 	    {
       
  1054             ?>
       
  1055             <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Both start and end dates must be entered and be in the format YYYY-MM-DD','calendar'); ?></p></div>
       
  1056             <?php
       
  1057 	    }
       
  1058 	  // We check for a valid time, or an empty one
       
  1059 	  $time_format_one = '/^([0-1][0-9]):([0-5][0-9])$/';
       
  1060 	  $time_format_two = '/^([2][0-3]):([0-5][0-9])$/';
       
  1061 	  if (preg_match($time_format_one,$time) || preg_match($time_format_two,$time) || $time == '')
       
  1062 	    {
       
  1063 	      $time_ok = 1;
       
  1064 	    }
       
  1065 	  else
       
  1066 	    {
       
  1067             ?>
       
  1068             <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The time field must either be blank or be entered in the format hh:mm','calendar'); ?></p></div>
       
  1069             <?php
       
  1070 	    }
       
  1071           // We check to make sure the URL is alright
       
  1072 	  if (preg_match('/^(http)(s?)(:)\/\//',$linky) || $linky == '')
       
  1073 	    {
       
  1074 	      $url_ok = 1;
       
  1075 	    }
       
  1076 	  else
       
  1077 	    {
       
  1078 	      ?>
       
  1079 	      <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The URL entered must either be prefixed with http:// or be completely blank','calendar'); ?></p></div>
       
  1080 	      <?php
       
  1081 	    }
       
  1082 	  // The title must be at least one character in length and no more than 30 - no non-standard characters allowed
       
  1083 	  if (preg_match('/^[a-zA-Z0-9]{1}[a-zA-Z0-9[:space:]]{0,29}$/',$title))
       
  1084             {
       
  1085 	      $title_ok =1;
       
  1086 	    }
       
  1087           else
       
  1088             {
       
  1089 	      ?>
       
  1090               <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The event title must be between 1 and 30 characters in length and contain no punctuation. Spaces are allowed but the title must not start with one.','calendar'); ?></p></div>
       
  1091               <?php
       
  1092 	    }
       
  1093 	  // We run some checks on recurrance              
       
  1094           if (($repeats == 0 && $recur == 'S') || (($repeats >= 0) && ($recur == 'W' || $recur == 'M' || $recur == 'Y')))
       
  1095             {
       
  1096               $recurring_ok = 1;
       
  1097             }
       
  1098           else
       
  1099             {
       
  1100               ?>
       
  1101               <div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('The repetition value must be 0 unless a type of recurrance is selected in which case the repetition value must be 0 or higher','calendar'); ?></p></div>
       
  1102               <?php
       
  1103 	    }
       
  1104 	  if ($start_date_ok == 1 && $end_date_ok == 1 && $time_ok == 1 && $url_ok == 1 && $title_ok && $recurring_ok == 1)
       
  1105 	    {
       
  1106 		$sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_title='" . mysql_escape_string($title)
       
  1107 		     . "', event_desc='" . mysql_escape_string($desc) . "', event_begin='" . mysql_escape_string($begin) 
       
  1108                      . "', event_end='" . mysql_escape_string($end) . "', event_time='" . mysql_escape_string($time) . "', event_recur='" . mysql_escape_string($recur) . "', event_repeats='" . mysql_escape_string($repeats) . "', event_author=".$current_user->ID . ", event_category=".mysql_escape_string($category).", event_link='".mysql_escape_string($linky)."' WHERE event_id='" . mysql_escape_string($event_id) . "'";
       
  1109 		     
       
  1110 		$wpdb->get_results($sql);
       
  1111 		
       
  1112 		$sql = "SELECT event_id FROM " . WP_CALENDAR_TABLE . " WHERE event_title='" . mysql_escape_string($title) . "'"
       
  1113 		     . " AND event_desc='" . mysql_escape_string($desc) . "' AND event_begin='" . mysql_escape_string($begin) . "' AND event_end='" . mysql_escape_string($end) . "' AND event_recur='" . mysql_escape_string($recur) . "' AND event_repeats='" . mysql_escape_string($repeats) . "' LIMIT 1";
       
  1114 		$result = $wpdb->get_results($sql);
       
  1115 		
       
  1116 		if ( empty($result) || empty($result[0]->event_id) )
       
  1117 		{
       
  1118 			?>
       
  1119 			<div class="error"><p><strong><?php _e('Failure','calendar'); ?>:</strong> <?php _e('The database failed to return data to indicate the event has been updated sucessfully. This may indicate a problem with your database or the way in which it is configured.','calendar'); ?></p></div>
       
  1120 			<?php
       
  1121 		}
       
  1122 		else
       
  1123 		{
       
  1124 			?>
       
  1125 			<div class="updated"><p><?php _e('Event updated successfully','calendar'); ?></p></div>
       
  1126 			<?php
       
  1127 		}
       
  1128 	    }
       
  1129           else
       
  1130 	    {
       
  1131 	      // The form is going to be rejected due to field validation issues, so we preserve the users entries here
       
  1132               $users_entries->event_title = $title;
       
  1133 	      $users_entries->event_desc = $desc;
       
  1134 	      $users_entries->event_begin = $begin;
       
  1135 	      $users_entries->event_end = $end;
       
  1136 	      $users_entries->event_time = $time;
       
  1137 	      $users_entries->event_recur = $recur;
       
  1138 	      $users_entries->event_repeats = $repeats;
       
  1139 	      $users_entries->event_category = $category;
       
  1140 	      $users_entries->event_link = $linky;
       
  1141 	      $error_with_saving = 1;
       
  1142 	    }		
       
  1143 	}
       
  1144 }
       
  1145 // Deal with deleting an event from the database
       
  1146 elseif ( $action == 'delete' )
       
  1147 {
       
  1148 	if ( empty($event_id) )
       
  1149 	{
       
  1150 		?>
       
  1151 		<div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e("You can't delete an event if you haven't submitted an event id",'calendar'); ?></p></div>
       
  1152 		<?php			
       
  1153 	}
       
  1154 	else
       
  1155 	{
       
  1156 		$sql = "DELETE FROM " . WP_CALENDAR_TABLE . " WHERE event_id='" . mysql_escape_string($event_id) . "'";
       
  1157 		$wpdb->get_results($sql);
       
  1158 		
       
  1159 		$sql = "SELECT event_id FROM " . WP_CALENDAR_TABLE . " WHERE event_id='" . mysql_escape_string($event_id) . "'";
       
  1160 		$result = $wpdb->get_results($sql);
       
  1161 		
       
  1162 		if ( empty($result) || empty($result[0]->event_id) )
       
  1163 		{
       
  1164 			?>
       
  1165 			<div class="updated"><p><?php _e('Event deleted successfully','calendar'); ?></p></div>
       
  1166 			<?php
       
  1167 		}
       
  1168 		else
       
  1169 		{
       
  1170 			?>
       
  1171 			<div class="error"><p><strong><?php _e('Error','calendar'); ?>:</strong> <?php _e('Despite issuing a request to delete, the event still remains in the database. Please investigate.','calendar'); ?></p></div>
       
  1172 			<?php
       
  1173 
       
  1174 		}		
       
  1175 	}
       
  1176 }
       
  1177 
       
  1178 // Now follows a little bit of code that pulls in the main 
       
  1179 // components of this page; the edit form and the list of events
       
  1180 ?>
       
  1181 
       
  1182 <div class="wrap">
       
  1183 	<?php
       
  1184 	if ( $action == 'edit' || ($action == 'edit_save' && $error_with_saving == 1))
       
  1185 	{
       
  1186 		?>
       
  1187 		<h2><?php _e('Edit Event','calendar'); ?></h2>
       
  1188 		<?php
       
  1189 		if ( empty($event_id) )
       
  1190 		{
       
  1191 			echo "<div class=\"error\"><p>".__("You must provide an event id in order to edit it",'calendar')."</p></div>";
       
  1192 		}
       
  1193 		else
       
  1194 		{
       
  1195 			wp_events_edit_form('edit_save', $event_id);
       
  1196 		}	
       
  1197 	}
       
  1198 	else
       
  1199 	{
       
  1200 		?>
       
  1201 		<h2><?php _e('Add Event','calendar'); ?></h2>
       
  1202 		<?php wp_events_edit_form(); ?>
       
  1203 	
       
  1204 		<h2><?php _e('Manage Events','calendar'); ?></h2>
       
  1205 		<?php
       
  1206 			wp_events_display_list();
       
  1207 	}
       
  1208 	?>
       
  1209 </div>
       
  1210 
       
  1211 <?php
       
  1212  
       
  1213 }
       
  1214 
       
  1215 // Display the admin configuration page
       
  1216 function edit_calendar_config()
       
  1217 {
       
  1218   global $wpdb, $initial_style;
       
  1219 
       
  1220   // We can't use this page unless Calendar is installed/upgraded
       
  1221   check_calendar();
       
  1222 
       
  1223   if (isset($_POST['permissions']) && isset($_POST['style']))
       
  1224     {
       
  1225       if ($_POST['permissions'] == 'subscriber') { $new_perms = 'read'; }
       
  1226       else if ($_POST['permissions'] == 'contributor') { $new_perms = 'edit_posts'; }
       
  1227       else if ($_POST['permissions'] == 'author') { $new_perms = 'publish_posts'; }
       
  1228       else if ($_POST['permissions'] == 'editor') { $new_perms = 'moderate_comments'; }
       
  1229       else if ($_POST['permissions'] == 'admin') { $new_perms = 'manage_options'; }
       
  1230       else { $new_perms = 'manage_options'; }
       
  1231 
       
  1232       $calendar_style = mysql_escape_string($_POST['style']);
       
  1233       $display_upcoming_days = mysql_escape_string($_POST['display_upcoming_days']);
       
  1234 
       
  1235       if (mysql_escape_string($_POST['display_author']) == 'on')
       
  1236 	{
       
  1237 	  $disp_author = 'true';
       
  1238 	}
       
  1239       else
       
  1240 	{
       
  1241 	  $disp_author = 'false';
       
  1242 	}
       
  1243 
       
  1244       if (mysql_escape_string($_POST['display_jump']) == 'on')
       
  1245         {
       
  1246           $disp_jump = 'true';
       
  1247         }
       
  1248       else
       
  1249         {
       
  1250           $disp_jump = 'false';
       
  1251         }
       
  1252 
       
  1253       if (mysql_escape_string($_POST['display_todays']) == 'on')
       
  1254         {
       
  1255           $disp_todays = 'true';
       
  1256         }
       
  1257       else
       
  1258         {
       
  1259           $disp_todays = 'false';
       
  1260         }
       
  1261 
       
  1262       if (mysql_escape_string($_POST['display_upcoming']) == 'on')
       
  1263         {
       
  1264           $disp_upcoming = 'true';
       
  1265         }
       
  1266       else
       
  1267         {
       
  1268           $disp_upcoming = 'false';
       
  1269         }
       
  1270 
       
  1271       if (mysql_escape_string($_POST['enable_categories']) == 'on')
       
  1272         {
       
  1273           $enable_categories = 'true';
       
  1274         }
       
  1275       else
       
  1276         {
       
  1277 	  $enable_categories = 'false';
       
  1278         }
       
  1279 
       
  1280       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$new_perms."' WHERE config_item='can_manage_events'");
       
  1281       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$calendar_style."' WHERE config_item='calendar_style'");
       
  1282       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$disp_author."' WHERE config_item='display_author'");
       
  1283       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$disp_jump."' WHERE config_item='display_jump'");
       
  1284       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$disp_todays."' WHERE config_item='display_todays'");
       
  1285       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$disp_upcoming."' WHERE config_item='display_upcoming'");
       
  1286       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$display_upcoming_days."' WHERE config_item='display_upcoming_days'");
       
  1287       $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$enable_categories."' WHERE config_item='enable_categories'");
       
  1288 
       
  1289       // Check to see if we are replacing the original style
       
  1290       if (mysql_escape_string($_POST['reset_styles']) == 'on')
       
  1291         {
       
  1292           $wpdb->get_results("UPDATE " . WP_CALENDAR_CONFIG_TABLE . " SET config_value = '".$initial_style."' WHERE config_item='calendar_style'");
       
  1293         }
       
  1294 
       
  1295       echo "<div class=\"updated\"><p><strong>".__('Settings saved','calendar').".</strong></p></div>";
       
  1296     }
       
  1297 
       
  1298   // Pull the values out of the database that we need for the form
       
  1299   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='can_manage_events'");
       
  1300   if (!empty($configs))
       
  1301     {
       
  1302       foreach ($configs as $config)
       
  1303         {
       
  1304           $allowed_group = $config->config_value;
       
  1305         }
       
  1306     }
       
  1307 
       
  1308   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='calendar_style'");
       
  1309   if (!empty($configs))
       
  1310     {
       
  1311       foreach ($configs as $config)
       
  1312         {
       
  1313           $calendar_style = $config->config_value;
       
  1314         }
       
  1315     }
       
  1316   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='display_author'");
       
  1317   if (!empty($configs))
       
  1318     {
       
  1319       foreach ($configs as $config)
       
  1320         {
       
  1321 	  if ($config->config_value == 'true')
       
  1322 	    {
       
  1323 	      $yes_disp_author = 'selected="selected"';
       
  1324 	    }
       
  1325 	  else
       
  1326 	    {
       
  1327 	      $no_disp_author = 'selected="selected"';
       
  1328 	    }
       
  1329         }
       
  1330     }
       
  1331   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='display_jump'");
       
  1332   if (!empty($configs))
       
  1333     {
       
  1334       foreach ($configs as $config)
       
  1335         {
       
  1336           if ($config->config_value == 'true')
       
  1337             {
       
  1338               $yes_disp_jump = 'selected="selected"';
       
  1339             }
       
  1340           else
       
  1341             {
       
  1342               $no_disp_jump = 'selected="selected"';
       
  1343             }
       
  1344         }
       
  1345     }
       
  1346   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='display_todays'");
       
  1347   if (!empty($configs))
       
  1348     {
       
  1349       foreach ($configs as $config)
       
  1350         {
       
  1351           if ($config->config_value == 'true')
       
  1352             {
       
  1353               $yes_disp_todays = 'selected="selected"';
       
  1354             }
       
  1355           else
       
  1356             {
       
  1357               $no_disp_todays = 'selected="selected"';
       
  1358             }
       
  1359         }
       
  1360     }
       
  1361   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='display_upcoming'");
       
  1362   if (!empty($configs))
       
  1363     {
       
  1364       foreach ($configs as $config)
       
  1365         {
       
  1366           if ($config->config_value == 'true')
       
  1367             {
       
  1368               $yes_disp_upcoming = 'selected="selected"';
       
  1369             }
       
  1370           else
       
  1371             {
       
  1372               $no_disp_upcoming = 'selected="selected"';
       
  1373             }
       
  1374         }
       
  1375     }
       
  1376   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='display_upcoming_days'");
       
  1377   if (!empty($configs))
       
  1378     {
       
  1379       foreach ($configs as $config)
       
  1380         {
       
  1381           $upcoming_days = $config->config_value;
       
  1382         }
       
  1383     }
       
  1384   $configs = $wpdb->get_results("SELECT config_value FROM " . WP_CALENDAR_CONFIG_TABLE . " WHERE config_item='enable_categories'");
       
  1385   if (!empty($configs))
       
  1386     {
       
  1387       foreach ($configs as $config)
       
  1388         {
       
  1389           if ($config->config_value == 'true')
       
  1390             {
       
  1391               $yes_enable_categories = 'selected="selected"';
       
  1392             }
       
  1393           else
       
  1394             {
       
  1395               $no_enable_categories = 'selected="selected"';
       
  1396             }
       
  1397         }
       
  1398     }
       
  1399   if ($allowed_group == 'read') { $subscriber_selected='selected="selected"';}
       
  1400   else if ($allowed_group == 'edit_posts') { $contributor_selected='selected="selected"';}
       
  1401   else if ($allowed_group == 'publish_posts') { $author_selected='selected="selected"';}
       
  1402   else if ($allowed_group == 'moderate_comments') { $editor_selected='selected="selected"';}
       
  1403   else if ($allowed_group == 'manage_options') { $admin_selected='selected="selected"';}
       
  1404 
       
  1405   // Now we render the form
       
  1406   ?>
       
  1407   <style type="text/css">
       
  1408   <!--
       
  1409         .error {
       
  1410 	  background: lightcoral;
       
  1411 	  border: 1px solid #e64f69;
       
  1412 	  margin: 1em 5% 10px;
       
  1413 	  padding: 0 1em 0 1em;
       
  1414 	}
       
  1415 
       
  1416         .center { 
       
  1417 	  text-align: center; 
       
  1418 	}
       
  1419         .right { 
       
  1420 	  text-align: right; 
       
  1421 	}
       
  1422         .left { 
       
  1423 	  text-align: left; 
       
  1424 	}
       
  1425         .top { 
       
  1426 	  vertical-align: top; 
       
  1427 	}
       
  1428         .bold { 
       
  1429 	  font-weight: bold; 
       
  1430 	}
       
  1431         .private { 
       
  1432 	  color: #e64f69; 
       
  1433 	}
       
  1434   //-->                                                                                                                                                        
       
  1435   </style>
       
  1436 
       
  1437   <div class="wrap">
       
  1438   <h2><?php _e('Calendar Options','calendar'); ?></h2>
       
  1439   <form name="quoteform" id="quoteform" class="wrap" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?page=calendar-config">
       
  1440                 <div id="linkadvanceddiv" class="postbox">
       
  1441                         <div style="float: left; width: 98%; clear: both;" class="inside">
       
  1442                                 <table cellpadding="5" cellspacing="5">
       
  1443 				<tr>
       
  1444                                 <td><legend><?php _e('Choose the lowest user group that may manage events','calendar'); ?></legend></td>
       
  1445 				<td>        <select name="permissions">
       
  1446 				            <option value="subscriber"<?php echo $subscriber_selected ?>><?php _e('Subscriber','calendar')?></option>
       
  1447 				            <option value="contributor" <?php echo $contributor_selected ?>><?php _e('Contributor','calendar')?></option>
       
  1448 				            <option value="author" <?php echo $author_selected ?>><?php _e('Author','calendar')?></option>
       
  1449 				            <option value="editor" <?php echo $editor_selected ?>><?php _e('Editor','calendar')?></option>
       
  1450 				            <option value="admin" <?php echo $admin_selected ?>><?php _e('Administrator','calendar')?></option>
       
  1451 				        </select>
       
  1452                                 </td>
       
  1453                                 </tr>
       
  1454                                 <tr>
       
  1455 				<td><legend><?php _e('Do you want to display the author name on events?','calendar'); ?></legend></td>
       
  1456                                 <td>    <select name="display_author">
       
  1457                                         <option value="on" <?php echo $yes_disp_author ?>><?php _e('Yes','calendar') ?></option>
       
  1458                                         <option value="off" <?php echo $no_disp_author ?>><?php _e('No','calendar') ?></option>
       
  1459                                     </select>
       
  1460                                 </td>
       
  1461                                 </tr>
       
  1462                                 <tr>
       
  1463 				<td><legend><?php _e('Display a jumpbox for changing month and year quickly?','calendar'); ?></legend></td>
       
  1464                                 <td>    <select name="display_jump">
       
  1465                                          <option value="on" <?php echo $yes_disp_jump ?>><?php _e('Yes','calendar') ?></option>
       
  1466                                          <option value="off" <?php echo $no_disp_jump ?>><?php _e('No','calendar') ?></option>
       
  1467                                     </select>
       
  1468                                 </td>
       
  1469                                 </tr>
       
  1470                                 <tr>
       
  1471 				<td><legend><?php _e('Display todays events?','calendar'); ?></legend></td>
       
  1472                                 <td>    <select name="display_todays">
       
  1473 						<option value="on" <?php echo $yes_disp_todays ?>><?php _e('Yes','calendar') ?></option>
       
  1474 						<option value="off" <?php echo $no_disp_todays ?>><?php _e('No','calendar') ?></option>
       
  1475                                     </select>
       
  1476                                 </td>
       
  1477                                 </tr>
       
  1478                                 <tr>
       
  1479 				<td><legend><?php _e('Display upcoming events?','calendar'); ?></legend></td>
       
  1480                                 <td>    <select name="display_upcoming">
       
  1481 						<option value="on" <?php echo $yes_disp_upcoming ?>><?php _e('Yes','calendar') ?></option>
       
  1482 						<option value="off" <?php echo $no_disp_upcoming ?>><?php _e('No','calendar') ?></option>
       
  1483                                     </select>
       
  1484 				    <?php _e('for','calendar'); ?> <input type="text" name="display_upcoming_days" value="<?php echo $upcoming_days ?>" size="1" maxlength="2" /> <?php _e('days into the future','calendar'); ?>
       
  1485                                 </td>
       
  1486                                 </tr>
       
  1487                                 <tr>
       
  1488 				<td><legend><?php _e('Enable event categories?','calendar'); ?></legend></td>
       
  1489                                 <td>    <select name="enable_categories">
       
  1490 				                <option value="on" <?php echo $yes_enable_categories ?>><?php _e('Yes','calendar') ?></option>
       
  1491 						<option value="off" <?php echo $no_enable_categories ?>><?php _e('No','calendar') ?></option>
       
  1492                                     </select>
       
  1493                                 </td>
       
  1494                                 </tr>
       
  1495                                 <tr>
       
  1496 				<td style="vertical-align:top;"><legend><?php _e('Configure the stylesheet for Calendar','calendar'); ?></legend></td>
       
  1497 				<td><textarea name="style" rows="10" cols="60" tabindex="2"><?php echo $calendar_style; ?></textarea><br />
       
  1498                                 <input type="checkbox" name="reset_styles" /> <?php _e('Tick this box if you wish to reset the Calendar style to default','calendar'); ?></td>
       
  1499                                 </tr>
       
  1500                                 </table>
       
  1501 			</div>
       
  1502                         <div style="clear:both; height:1px;">&nbsp;</div>
       
  1503 	        </div>
       
  1504                 <input type="submit" name="save" class="button bold" value="<?php _e('Save','calendar'); ?> &raquo;" />
       
  1505   </form>
       
  1506   </div>
       
  1507   <?php
       
  1508 
       
  1509 
       
  1510 }
       
  1511 
       
  1512 // Function to handle the management of categories
       
  1513 function manage_categories()
       
  1514 {
       
  1515   global $wpdb;
       
  1516 
       
  1517   // Calendar must be installed and upgraded before this will work
       
  1518   check_calendar();
       
  1519 
       
  1520 ?>
       
  1521 <style type="text/css">
       
  1522   <!--
       
  1523    .error {
       
  1524      background: lightcoral;
       
  1525      border: 1px solid #e64f69;
       
  1526      margin: 1em 5% 10px;
       
  1527      padding: 0 1em 0 1em;
       
  1528    }
       
  1529 
       
  1530   .center {
       
  1531     text-align: center;
       
  1532   }
       
  1533   .right {
       
  1534     text-align: right;
       
  1535   }
       
  1536   .left {
       
  1537     text-align: left;
       
  1538   }
       
  1539   .top {
       
  1540     vertical-align: top;
       
  1541   }
       
  1542   .bold {
       
  1543     font-weight: bold;
       
  1544   }
       
  1545   .private {
       
  1546   color: #e64f69;
       
  1547   }
       
  1548   //-->                                                                                                                                                                               
       
  1549 </style>
       
  1550 <?php
       
  1551   // We do some checking to see what we're doing
       
  1552   if (isset($_POST['mode']) && $_POST['mode'] == 'add')
       
  1553     {
       
  1554       $sql = "INSERT INTO " . WP_CALENDAR_CATEGORIES_TABLE . " SET category_name='".mysql_escape_string($_POST['category_name'])."', category_colour='".mysql_escape_string($_POST['category_colour'])."'";
       
  1555       $wpdb->get_results($sql);
       
  1556       echo "<div class=\"updated\"><p><strong>".__('Category added successfully','calendar')."</strong></p></div>";
       
  1557     }
       
  1558   else if (isset($_GET['mode']) && isset($_GET['category_id']) && $_GET['mode'] == 'delete')
       
  1559     {
       
  1560       $sql = "DELETE FROM " . WP_CALENDAR_CATEGORIES_TABLE . " WHERE category_id=".mysql_escape_string($_GET['category_id']);
       
  1561       $wpdb->get_results($sql);
       
  1562       $sql = "UPDATE " . WP_CALENDAR_TABLE . " SET event_category=1 WHERE event_category=".mysql_escape_string($_GET['category_id']);
       
  1563       $wpdb->get_results($sql);
       
  1564       echo "<div class=\"updated\"><p><strong>".__('Category deleted successfully','calendar')."</strong></p></div>";
       
  1565     }
       
  1566   else if (isset($_GET['mode']) && isset($_GET['category_id']) && $_GET['mode'] == 'edit' && !isset($_POST['mode']))
       
  1567     {
       
  1568       $sql = "SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE . " WHERE category_id=".mysql_escape_string($_GET['category_id']);
       
  1569       $cur_cat = $wpdb->get_row($sql);
       
  1570       ?>
       
  1571 <div class="wrap">
       
  1572    <h2><?php _e('Edit Category','calendar'); ?></h2>
       
  1573     <form name="catform" id="catform" class="wrap" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?page=calendar-categories">
       
  1574                 <input type="hidden" name="mode" value="edit" />
       
  1575                 <input type="hidden" name="category_id" value="<?php echo $cur_cat->category_id ?>" />
       
  1576                 <div id="linkadvanceddiv" class="postbox">
       
  1577                         <div style="float: left; width: 98%; clear: both;" class="inside">
       
  1578 				<table cellpadding="5" cellspacing="5">
       
  1579                                 <tr>
       
  1580 				<td><legend><?php _e('Category Name','calendar'); ?>:</legend></td>
       
  1581                                 <td><input type="text" name="category_name" class="input" size="30" maxlength="30" value="<?php echo $cur_cat->category_name ?>" /></td>
       
  1582 				</tr>
       
  1583                                 <tr>
       
  1584 				<td><legend><?php _e('Category Colour (Hex format)','calendar'); ?>:</legend></td>
       
  1585                                 <td><input type="text" name="category_colour" class="input" size="10" maxlength="7" value="<?php echo $cur_cat->category_colour ?>" /></td>
       
  1586                                 </tr>
       
  1587                                 </table>
       
  1588                         </div>
       
  1589                         <div style="clear:both; height:1px;">&nbsp;</div>
       
  1590                 </div>
       
  1591                 <input type="submit" name="save" class="button bold" value="<?php _e('Save','calendar'); ?> &raquo;" />
       
  1592     </form>
       
  1593 </div>
       
  1594       <?php
       
  1595     }
       
  1596   else if (isset($_POST['mode']) && isset($_POST['category_id']) && isset($_POST['category_name']) && isset($_POST['category_colour']) && $_POST['mode'] == 'edit')
       
  1597     {
       
  1598       $sql = "UPDATE " . WP_CALENDAR_CATEGORIES_TABLE . " SET category_name='".mysql_escape_string($_POST['category_name'])."', category_colour='".mysql_escape_string($_POST['category_colour'])."' WHERE category_id=".mysql_escape_string($_POST['category_id']);
       
  1599       $wpdb->get_results($sql);
       
  1600       echo "<div class=\"updated\"><p><strong>".__('Category edited successfully','calendar')."</strong></p></div>";
       
  1601     }
       
  1602 
       
  1603   if ($_GET['mode'] != 'edit' || $_POST['mode'] == 'edit')
       
  1604     {
       
  1605 ?>
       
  1606 
       
  1607   <div class="wrap">
       
  1608     <h2><?php _e('Add Category','calendar'); ?></h2>
       
  1609     <form name="catform" id="catform" class="wrap" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>?page=calendar-categories">
       
  1610                 <input type="hidden" name="mode" value="add" />
       
  1611                 <input type="hidden" name="category_id" value="">
       
  1612                 <div id="linkadvanceddiv" class="postbox">
       
  1613                         <div style="float: left; width: 98%; clear: both;" class="inside">
       
  1614        				<table cellspacing="5" cellpadding="5">
       
  1615                                 <tr>
       
  1616                                 <td><legend><?php _e('Category Name','calendar'); ?>:</legend></td>
       
  1617                                 <td><input type="text" name="category_name" class="input" size="30" maxlength="30" value="" /></td>
       
  1618                                 </tr>
       
  1619                                 <tr>
       
  1620                                 <td><legend><?php _e('Category Colour (Hex format)','calendar'); ?>:</legend></td>
       
  1621                                 <td><input type="text" name="category_colour" class="input" size="10" maxlength="7" value="" /></td>
       
  1622                                 </tr>
       
  1623                                 </table>
       
  1624                         </div>
       
  1625 		        <div style="clear:both; height:1px;">&nbsp;</div>
       
  1626                 </div>
       
  1627                 <input type="submit" name="save" class="button bold" value="<?php _e('Save','calendar'); ?> &raquo;" />
       
  1628     </form>
       
  1629     <h2><?php _e('Manage Categories','calendar'); ?></h2>
       
  1630 <?php
       
  1631     
       
  1632     // We pull the categories from the database	
       
  1633     $categories = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE . " ORDER BY category_id ASC");
       
  1634 
       
  1635  if ( !empty($categories) )
       
  1636    {
       
  1637      ?>
       
  1638      <table class="widefat page fixed" width="50%" cellpadding="3" cellspacing="3">
       
  1639        <thead> 
       
  1640        <tr>
       
  1641          <th class="manage-column" scope="col"><?php _e('ID','calendar') ?></th>
       
  1642 	 <th class="manage-column" scope="col"><?php _e('Category Name','calendar') ?></th>
       
  1643 	 <th class="manage-column" scope="col"><?php _e('Category Colour','calendar') ?></th>
       
  1644 	 <th class="manage-column" scope="col"><?php _e('Edit','calendar') ?></th>
       
  1645 	 <th class="manage-column" scope="col"><?php _e('Delete','calendar') ?></th>
       
  1646        </tr>
       
  1647        </thead>
       
  1648        <?php
       
  1649        $class = '';
       
  1650        foreach ( $categories as $category )
       
  1651          {
       
  1652 	   $class = ($class == 'alternate') ? '' : 'alternate';
       
  1653            ?>
       
  1654            <tr class="<?php echo $class; ?>">
       
  1655 	     <th scope="row"><?php echo $category->category_id; ?></th>
       
  1656 	     <td><?php echo $category->category_name; ?></td>
       
  1657 	     <td style="background-color:<?php echo $category->category_colour; ?>;">&nbsp;</td>
       
  1658 	     <td><a href="<?php echo $_SERVER['PHP_SELF']  ?>?page=calendar-categories&amp;mode=edit&amp;category_id=<?php echo $category->category_id;?>" class='edit'><?php echo __('Edit','calendar'); ?></a></td>
       
  1659 	     <?php
       
  1660 	     if ($category->category_id == 1)
       
  1661 	       {
       
  1662 		 echo '<td>'.__('N/A','calendar').'</td>';
       
  1663 	       }
       
  1664              else
       
  1665 	       {
       
  1666                ?>
       
  1667                <td><a href="<?php echo $_SERVER['PHP_SELF'] ?>?page=calendar-categories&amp;mode=delete&amp;category_id=<?php echo $category->category_id;?>" class="delete" onclick="return confirm('<?php echo __('Are you sure you want to delete this category?','calendar'); ?>')"><?php echo __('Delete','calendar'); ?></a></td>
       
  1668                <?php
       
  1669 	       }
       
  1670                 ?>
       
  1671               </tr>
       
  1672                 <?php
       
  1673           }
       
  1674       ?>
       
  1675       </table>
       
  1676       <?php
       
  1677    }
       
  1678  else
       
  1679    {
       
  1680      echo '<p>'.__('There are no categories in the database - something has gone wrong!','calendar').'</p>';
       
  1681    }
       
  1682 
       
  1683 ?>
       
  1684   </div>
       
  1685 
       
  1686 <?php
       
  1687       } 
       
  1688 }
       
  1689 
       
  1690 // Function to return a prefix which will allow the correct 
       
  1691 // placement of arguments into the query string.
       
  1692 function permalink_prefix()
       
  1693 {
       
  1694   // Get the permalink structure from WordPress
       
  1695   $p_link = get_permalink();
       
  1696 
       
  1697   // Work out what the real URL we are viewing is
       
  1698   $s = empty($_SERVER["HTTPS"]) ? '' : ($_SERVER["HTTPS"] == "on") ? "s" : ""; 
       
  1699   $protocol = substr(strtolower($_SERVER["SERVER_PROTOCOL"]), 0, strpos(strtolower($_SERVER["SERVER_PROTOCOL"]), "/")).$s;
       
  1700   $port = ($_SERVER["SERVER_PORT"] == "80") ? "" : (":".$_SERVER["SERVER_PORT"]);
       
  1701   $real_link = $protocol.'://'.$_SERVER['SERVER_NAME'].$port.$_SERVER['REQUEST_URI'];
       
  1702 
       
  1703   // Now use all of that to get the correctly craft the Calendar link prefix
       
  1704   if (strstr($p_link, '?') && $p_link == $real_link)
       
  1705     {
       
  1706       $link_part = $p_link.'&';
       
  1707     }
       
  1708   else if ($p_link == $real_link)
       
  1709     {
       
  1710       $link_part = $p_link.'?';
       
  1711     }
       
  1712   else if (strstr($real_link, '?'))  
       
  1713     {
       
  1714       if (isset($_GET['month']) && isset($_GET['yr']))
       
  1715 	{
       
  1716 	  $new_tail = split("&", $real_link);
       
  1717 	  foreach ($new_tail as $item)
       
  1718 	    {
       
  1719 	      if (!strstr($item, 'month') && !strstr($item, 'yr'))
       
  1720 		{
       
  1721 		  $link_part .= $item.'&';
       
  1722 		}
       
  1723 	    }
       
  1724 	  if (!strstr($link_part, '?'))
       
  1725 	    {
       
  1726 	      $new_tail = split("month", $link_part);
       
  1727 	      $link_part = $new_tail[0].'?'.$new_tail[1];
       
  1728 	    }
       
  1729 	}
       
  1730       else
       
  1731 	{
       
  1732 	  $link_part = $real_link.'&';
       
  1733 	}
       
  1734     }
       
  1735   else
       
  1736     {
       
  1737       $link_part = $real_link.'?';
       
  1738     }
       
  1739 
       
  1740   return $link_part;
       
  1741 }
       
  1742 
       
  1743 // Configure the "Next" link in the calendar
       
  1744 function next_link($cur_year,$cur_month)
       
  1745 {
       
  1746   $mod_rewrite_months = array(1=>'jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec');
       
  1747   $next_year = $cur_year + 1;
       
  1748 
       
  1749   if ($cur_month == 12)
       
  1750     {
       
  1751       return '<a href="' . permalink_prefix() . 'month=jan&yr=' . $next_year . '">'.__('Next','calendar').' &raquo;</a>';
       
  1752     }
       
  1753   else
       
  1754     {
       
  1755       $next_month = $cur_month + 1;
       
  1756       $month = $mod_rewrite_months[$next_month];
       
  1757       return '<a href="' . permalink_prefix() . 'month='.$month.'&yr=' . $cur_year . '">'.__('Next','calendar').' &raquo;</a>';
       
  1758     }
       
  1759 }
       
  1760 
       
  1761 // Configure the "Previous" link in the calendar
       
  1762 function prev_link($cur_year,$cur_month)
       
  1763 {
       
  1764   $mod_rewrite_months = array(1=>'jan','feb','mar','apr','may','jun','jul','aug','sept','oct','nov','dec');
       
  1765   $last_year = $cur_year - 1;
       
  1766 
       
  1767   if ($cur_month == 1)
       
  1768     {
       
  1769       return '<a href="' . permalink_prefix() . 'month=dec&yr='. $last_year .'">&laquo; '.__('Prev','calendar').'</a>';
       
  1770     }
       
  1771   else
       
  1772     {
       
  1773       $next_month = $cur_month - 1;
       
  1774       $month = $mod_rewrite_months[$next_month];
       
  1775       return '<a href="' . permalink_prefix() . 'month='.$month.'&yr=' . $cur_year . '">&laquo; '.__('Prev','calendar').'</a>';
       
  1776     }
       
  1777 }
       
  1778 
       
  1779 // Print upcoming events
       
  1780 function upcoming_events()
       
  1781 {
       
  1782   global $wpdb;
       
  1783 
       
  1784   // This function cannot be called unless calendar is up to date
       
  1785   check_calendar();
       
  1786  
       
  1787   // Find out if we should be displaying upcoming events
       
  1788   $display = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_upcoming'",0,0);
       
  1789 
       
  1790   if ($display == 'true')
       
  1791     {
       
  1792       // Get number of days we should go into the future 
       
  1793       $future_days = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_upcoming_days'",0,0);
       
  1794       $day_count = 1;
       
  1795 
       
  1796       while ($day_count < $future_days+1)
       
  1797 	{
       
  1798 	  list($y,$m,$d) = split("-",date("Y-m-d",mktime($day_count*24,0,0,date("m"),date("d"),date("Y"))));
       
  1799 	  $events = grab_events($y,$m,$d);
       
  1800 	  usort($events, "time_cmp");
       
  1801 	  if (count($events) != 0) {
       
  1802 	    $output .= '<li>'.date(get_option('date_format'),mktime($day_count*24,0,0,date("m"),date("d"),date("Y"))).'<ul>';
       
  1803 	  }
       
  1804 	  foreach($events as $event)
       
  1805 	    {
       
  1806 	      if ($event->event_time == '00:00:00') {
       
  1807 		$time_string = ' '.__('all day','calendar');
       
  1808 	      }
       
  1809 	      else {
       
  1810 		$time_string = ' '.__('at','calendar').' '.date(get_option('time_format'), strtotime($event->event_time));
       
  1811 	      }
       
  1812               $output .= '<li>'.draw_widget_event($event).$time_string.'</li>';
       
  1813 	    }
       
  1814 	  if (count($events) != 0) {
       
  1815 	    $output .= '</ul></li>';
       
  1816 	  }
       
  1817 	  $day_count = $day_count+1;
       
  1818 	}
       
  1819 
       
  1820       if ($output != '')
       
  1821 	{
       
  1822 	  $visual = '<li class="upcoming-events"><h2>'.__('Upcoming Events','calendar').'</h2><ul>';
       
  1823 	  $visual .= $output;
       
  1824 	  $visual .= '</ul></li>';
       
  1825 	  return $visual;
       
  1826 	}
       
  1827     }
       
  1828 }
       
  1829 
       
  1830 // Print todays events
       
  1831 function todays_events()
       
  1832 {
       
  1833   global $wpdb;
       
  1834 
       
  1835   // This function cannot be called unless calendar is up to date
       
  1836   check_calendar();
       
  1837 
       
  1838   // Find out if we should be displaying todays events
       
  1839   $display = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_todays'",0,0);
       
  1840 
       
  1841   if ($display == 'true')
       
  1842     {
       
  1843       $output = '<li class="todays-events"><h2>'.__('Today\'s Events','calendar').'</h2><ul>';
       
  1844       $events = grab_events(date("Y"),date("m"),date("d"));
       
  1845       usort($events, "time_cmp");
       
  1846       foreach($events as $event)
       
  1847 	{
       
  1848 	  if ($event->event_time == '00:00:00') {
       
  1849 	    $time_string = ' '.__('all day','calendar');
       
  1850 	  }
       
  1851 	  else {
       
  1852 	    $time_string = ' '.__('at','calendar').' '.date(get_option('time_format'), strtotime($event->event_time));
       
  1853 	  }
       
  1854 	  $output .= '<li>'.draw_widget_event($event).$time_string.'</li>';
       
  1855 	}
       
  1856       $output .= '</ul></li>';
       
  1857       if (count($events) != 0)
       
  1858 	{
       
  1859 	  return $output;
       
  1860 	}
       
  1861     }
       
  1862 }
       
  1863 
       
  1864 // Function to compare time in event objects
       
  1865 function time_cmp($a, $b)
       
  1866 {
       
  1867   if ($a->event_time == $b->event_time) {
       
  1868     return 0;
       
  1869   }
       
  1870   return ($a->event_time < $b->event_time) ? -1 : 1;
       
  1871 }
       
  1872 
       
  1873 // Used to draw multiple events
       
  1874 function draw_events($events)
       
  1875 {
       
  1876   // We need to sort arrays of objects by time
       
  1877   usort($events, "time_cmp");
       
  1878 
       
  1879   // Now process the events
       
  1880   foreach($events as $event)
       
  1881     {
       
  1882       $output .= draw_event($event);
       
  1883     }
       
  1884   return $output;
       
  1885 }
       
  1886 
       
  1887 // Widget todays events
       
  1888 function todays_events_widget() {
       
  1889   global $wpdb;
       
  1890 
       
  1891   // This function cannot be called unless calendar is up to date
       
  1892   check_calendar();
       
  1893 
       
  1894   // Find out if we should be displaying todays events
       
  1895   $display = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_todays'",0,0);
       
  1896 
       
  1897   if ($display == 'true')
       
  1898     {
       
  1899       $output = '<ul>';
       
  1900       $events = grab_events(date("Y"),date("m"),date("d"));
       
  1901       usort($events, "time_cmp");
       
  1902       foreach($events as $event)
       
  1903         {
       
  1904           if ($event->event_time == '00:00:00') {
       
  1905             $time_string = ' '.__('all day','calendar');
       
  1906           }
       
  1907           else {
       
  1908             $time_string = ' '.__('at','calendar').' '.date(get_option('time_format'), strtotime($event->event_time));
       
  1909           }
       
  1910           $output .= '<li>'.draw_widget_event($event).$time_string.'</li>';
       
  1911         }
       
  1912       $output .= '</ul>';
       
  1913       if (count($events) != 0)
       
  1914         {
       
  1915           return $output;
       
  1916         }
       
  1917     }
       
  1918 }
       
  1919 
       
  1920 // Widget upcoming events
       
  1921 function upcoming_events_widget() {
       
  1922   global $wpdb;
       
  1923 
       
  1924   // This function cannot be called unless calendar is up to date
       
  1925   check_calendar();
       
  1926 
       
  1927   // Find out if we should be displaying upcoming events
       
  1928   $display = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_upcoming'",0,0);
       
  1929 
       
  1930   if ($display == 'true')
       
  1931     {
       
  1932       // Get number of days we should go into the future
       
  1933       $future_days = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_upcoming_days'",0,0);
       
  1934       $day_count = 1;
       
  1935 
       
  1936       while ($day_count < $future_days+1)
       
  1937         {
       
  1938           list($y,$m,$d) = split("-",date("Y-m-d",mktime($day_count*24,0,0,date("m"),date("d"),date("Y"))));
       
  1939           $events = grab_events($y,$m,$d);
       
  1940           usort($events, "time_cmp");
       
  1941           if (count($events) != 0) {
       
  1942             $output .= '<li>'.date(get_option('date_format'),mktime($day_count*24,0,0,date("m"),date("d"),date("Y"))).'<ul>';
       
  1943           }
       
  1944           foreach($events as $event)
       
  1945             {
       
  1946               if ($event->event_time == '00:00:00') {
       
  1947                 $time_string = ' '.__('all day','calendar');
       
  1948               }
       
  1949               else {
       
  1950                 $time_string = ' '.__('at','calendar').' '.date(get_option('time_format'), strtotime($event->event_time));
       
  1951               }
       
  1952               $output .= '<li>'.draw_widget_event($event).$time_string.'</li>';
       
  1953             }
       
  1954           if (count($events) != 0) {
       
  1955             $output .= '</ul></li>';
       
  1956           }
       
  1957           $day_count = $day_count+1;
       
  1958         }
       
  1959 
       
  1960       if ($output != '')
       
  1961         {
       
  1962           $visual = '<ul>';
       
  1963           $visual .= $output;
       
  1964           $visual .= '</ul>';
       
  1965           return $visual;
       
  1966         }
       
  1967     }
       
  1968 }
       
  1969 
       
  1970 // The widget to show todays events in the sidebar
       
  1971 function widget_init_calendar_today() {
       
  1972   // Check for required functions
       
  1973   if (!function_exists('register_sidebar_widget'))
       
  1974     return;
       
  1975 
       
  1976   function widget_calendar_today($args) {
       
  1977     extract($args);
       
  1978     $the_title = get_option('calendar_today_widget_title');
       
  1979     $widget_title = empty($the_title) ? __('Today\'s Events','calendar') : $the_title;
       
  1980     $the_events = todays_events_widget();
       
  1981     if ($the_events != '') {
       
  1982       echo $before_widget;
       
  1983       echo $before_title . $widget_title . $after_title;
       
  1984       echo $the_events;
       
  1985       echo $after_widget;
       
  1986     }
       
  1987   }
       
  1988 
       
  1989   function widget_calendar_today_control() {
       
  1990     $widget_title = get_option('calendar_today_widget_title');
       
  1991     if (isset($_POST['calendar_today_widget_title'])) {
       
  1992       update_option('calendar_today_widget_title',strip_tags($_POST['calendar_today_widget_title']));
       
  1993     }
       
  1994     ?>
       
  1995     <p>
       
  1996        <label for="calendar_today_widget_title"><?php _e('Title','calendar'); ?>:<br />
       
  1997        <input class="widefat" type="text" id="calendar_today_widget_title" name="calendar_today_widget_title" value="<?php echo $widget_title; ?>"/></label>
       
  1998     </p>
       
  1999     <?php
       
  2000   }
       
  2001 
       
  2002   register_sidebar_widget(__('Today\'s Events','calendar'),'widget_calendar_today');
       
  2003   register_widget_control(__('Today\'s Events','calendar'),'widget_calendar_today_control');
       
  2004   }
       
  2005 
       
  2006 // The widget to show todays events in the sidebar                                              
       
  2007 function widget_init_calendar_upcoming() {
       
  2008   // Check for required functions                                                               
       
  2009   if (!function_exists('register_sidebar_widget'))
       
  2010     return;
       
  2011 
       
  2012   function widget_calendar_upcoming($args) {
       
  2013     extract($args);
       
  2014     $the_title = get_option('calendar_upcoming_widget_title');
       
  2015     $widget_title = empty($the_title) ? __('Upcoming Events','calendar') : $the_title;
       
  2016     $the_events = upcoming_events_widget();
       
  2017     if ($the_events != '') {
       
  2018       echo $before_widget;
       
  2019       echo $before_title . $widget_title . $after_title;
       
  2020       echo $the_events;
       
  2021       echo $after_widget;
       
  2022     }
       
  2023   }
       
  2024 
       
  2025   function widget_calendar_upcoming_control() {
       
  2026     $widget_title = get_option('calendar_upcoming_widget_title');
       
  2027     if (isset($_POST['calendar_upcoming_widget_title'])) {
       
  2028       update_option('calendar_upcoming_widget_title',strip_tags($_POST['calendar_upcoming_widget_title']));
       
  2029     }
       
  2030     ?>
       
  2031     <p>
       
  2032        <label for="calendar_upcoming_widget_title"><?php _e('Title','calendar'); ?>:<br />
       
  2033        <input class="widefat" type="text" id="calendar_upcoming_widget_title" name="calendar_upcoming_widget_title" value="<?php echo $widget_title; ?>"/></label>
       
  2034     </p>
       
  2035     <?php
       
  2036   }
       
  2037 
       
  2038   register_sidebar_widget(__('Upcoming Events','calendar'),'widget_calendar_upcoming');
       
  2039   register_widget_control(__('Upcoming Events','calendar'),'widget_calendar_upcoming_control');
       
  2040 }
       
  2041 
       
  2042 
       
  2043 // Used to draw an event to the screen
       
  2044 function draw_event($event)
       
  2045 {
       
  2046   global $wpdb;
       
  2047 
       
  2048   // Calendar must be updated to run this function
       
  2049   check_calendar();
       
  2050 
       
  2051   // Before we do anything we want to know if we                                             
       
  2052   // should display the author and/or show categories. 
       
  2053   // We check for this later                                      
       
  2054   $display_author = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_author'",0,0);
       
  2055   $show_cat = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='enable_categories'",0,0);
       
  2056 
       
  2057   if ($show_cat == 'true')
       
  2058     {
       
  2059       $sql = "SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE . " WHERE category_id=".$event->event_category;
       
  2060       $cat_details = $wpdb->get_row($sql);
       
  2061       $style = "background-color:".$cat_details->category_colour.";";
       
  2062     }
       
  2063 
       
  2064   $header_details .=  '<div class="event-title">'.$event->event_title.'</div><div class="event-title-break"></div>';
       
  2065   if ($event->event_time != "00:00:00")
       
  2066     {
       
  2067       $header_details .= '<strong>'.__('Time','calendar').':</strong> ' . date(get_option('time_format'), strtotime($event->event_time)) . '<br />';
       
  2068     }
       
  2069   if ($display_author == 'true')
       
  2070     {
       
  2071       $e = get_userdata($event->event_author);
       
  2072       $header_details .= '<strong>'.__('Posted by', 'calendar').':</strong> '.$e->display_name.'<br />';
       
  2073     }
       
  2074   if ($display_author == 'true' || $event->event_time != "00:00:00")
       
  2075     {
       
  2076       $header_details .= '<div class="event-content-break"></div>';
       
  2077     }
       
  2078   if ($event->event_link != '') { $linky = $event->event_link; }
       
  2079   else { $linky = '#'; }
       
  2080 
       
  2081   $details = '<br />
       
  2082 * <span class="calnk" nowrap="nowrap"><a href="'.$linky.'" style="'.$style.'">' . $event->event_title . '<span style="'.$style.'">' . $header_details . '' . $event->event_desc . '</span></a></span>';
       
  2083 
       
  2084   return $details;
       
  2085 }
       
  2086 
       
  2087 // Draw an event but customise the HTML for use in the widget
       
  2088 function draw_widget_event($event)
       
  2089 {
       
  2090   global $wpdb;
       
  2091 
       
  2092   // Calendar must be updated to run this function
       
  2093   check_calendar();
       
  2094 
       
  2095   // Before we do anything we want to know if we
       
  2096   // should display the author and/or show categories.
       
  2097   // We check for this later
       
  2098   $display_author = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_author'",0,0);
       
  2099   $show_cat = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='enable_categories'",0,0);
       
  2100 
       
  2101   if ($show_cat == 'true')
       
  2102     {
       
  2103       $sql = "SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE . " WHERE category_id=".$event->event_category;
       
  2104       $cat_details = $wpdb->get_row($sql);
       
  2105       $style = "background-color:".$cat_details->category_colour.";";
       
  2106     }
       
  2107 
       
  2108   $header_details .=  '<div class="event-title">'.$event->event_title.'</div><div class="event-title-break"></div>';
       
  2109   if ($event->event_time != "00:00:00")
       
  2110     {
       
  2111       $header_details .= '<strong>'.__('Time','calendar').':</strong> ' . date(get_option('time_format'), strtotime($event->event_time)) . '<br />';
       
  2112     }
       
  2113   if ($display_author == 'true')
       
  2114     {
       
  2115       $e = get_userdata($event->event_author);
       
  2116       $header_details .= '<strong>'.__('Posted by','calendar').':</strong> '.$e->display_name.'<br />';
       
  2117     }
       
  2118   if ($display_author == 'true' || $event->event_time != "00:00:00")
       
  2119     {
       
  2120       $header_details .= '<div class="event-content-break"></div>';
       
  2121     }
       
  2122   if ($event->event_link != '') { $linky = $event->event_link; }
       
  2123   else { $linky = '#'; }
       
  2124 
       
  2125   $details = '<span class="calnk" nowrap="nowrap"><a href="'.$linky.'">' . $event->event_title . '<span style="'.$style.'">' . $header_details . '' . $event->event_desc . '</span></a></span>';
       
  2126 
       
  2127   return $details;
       
  2128 }
       
  2129 
       
  2130 // Grab all events for the requested date from calendar
       
  2131 function grab_events($y,$m,$d)
       
  2132 {
       
  2133      global $wpdb;
       
  2134 
       
  2135      $arr_events = array();
       
  2136 
       
  2137      // Get the date format right
       
  2138      $date = $y . '-' . $m . '-' . $d;
       
  2139      
       
  2140      // Firstly we check for conventional events. These will form the first instance of a recurring event
       
  2141      // or the only instance of a one-off event
       
  2142      $events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_begin <= '$date' AND event_end >= '$date' AND event_recur = 'S' ORDER BY event_id");
       
  2143      if (!empty($events))
       
  2144      {
       
  2145          foreach($events as $event)
       
  2146          {
       
  2147 	   array_push($arr_events, $event);
       
  2148          }
       
  2149      }
       
  2150 
       
  2151 	// Even if there were results for that query, we may still have events recurring 
       
  2152 	// from the past on this day. We now methodically check the for these events
       
  2153 
       
  2154 	/* 
       
  2155 	 The yearly code - easy because the day and month will be the same, so we return all yearly
       
  2156 	 events that match the date part. Out of these we show those with a repeat of 0, and fast-foward
       
  2157 	 a number of years for those with a value more than 0. Those that land in the future are displayed.
       
  2158 	*/
       
  2159 
       
  2160 	
       
  2161 	// Deal with forever recurring year events
       
  2162 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_recur = 'Y' AND EXTRACT(YEAR FROM '$date') >= EXTRACT(YEAR FROM event_begin) AND event_repeats = 0 ORDER BY event_id");
       
  2163 
       
  2164 	if (!empty($events))
       
  2165      	{
       
  2166        	  foreach($events as $event)
       
  2167           {
       
  2168 	    // This is going to get complex so lets setup what we would place in for 
       
  2169 	    // an event so we can drop it in with ease
       
  2170 
       
  2171 	    // Technically we don't care about the years, but we need to find out if the 
       
  2172 	    // event spans the turn of a year so we can deal with it appropriately.
       
  2173 	    $year_begin = date('Y',strtotime($event->event_begin));
       
  2174 	    $year_end = date('Y',strtotime($event->event_end));
       
  2175 
       
  2176 	    if ($year_begin == $year_end)
       
  2177 	    {
       
  2178 		if (date('m-d',strtotime($event->event_begin)) <= date('m-d',strtotime($date)) && 
       
  2179 			date('m-d',strtotime($event->event_end)) >= date('m-d',strtotime($date)))
       
  2180 		{
       
  2181 	      		array_push($arr_events, $event);
       
  2182 		}
       
  2183 	    }
       
  2184 	    else if ($year_begin < $year_end)
       
  2185 	    {
       
  2186 		if (date('m-d',strtotime($event->event_begin)) <= date('m-d',strtotime($date)) || 
       
  2187 			date('m-d',strtotime($event->event_end)) >= date('m-d',strtotime($date)))
       
  2188 		{
       
  2189 	      		array_push($arr_events, $event);
       
  2190 		}
       
  2191 	    }
       
  2192           }
       
  2193      	}
       
  2194 	
       
  2195 	// Now the ones that happen a finite number of times
       
  2196 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_recur = 'Y' AND EXTRACT(YEAR FROM '$date') >= EXTRACT(YEAR FROM event_begin) AND event_repeats != 0 AND (EXTRACT(YEAR FROM '$date')-EXTRACT(YEAR FROM event_begin)) <= event_repeats ORDER BY event_id");
       
  2197 	if (!empty($events))
       
  2198      	{
       
  2199        	  foreach($events as $event)
       
  2200           {
       
  2201 	    // This is going to get complex so lets setup what we would place in for 
       
  2202 	    // an event so we can drop it in with ease
       
  2203 
       
  2204 	    // Technically we don't care about the years, but we need to find out if the 
       
  2205 	    // event spans the turn of a year so we can deal with it appropriately.
       
  2206 	    $year_begin = date('Y',strtotime($event->event_begin));
       
  2207 	    $year_end = date('Y',strtotime($event->event_end));
       
  2208 
       
  2209 	    if ($year_begin == $year_end)
       
  2210 	    {
       
  2211 		if (date('m-d',strtotime($event->event_begin)) <= date('m-d',strtotime($date)) && 
       
  2212 			date('m-d',strtotime($event->event_end)) >= date('m-d',strtotime($date)))
       
  2213 		{
       
  2214 	      		array_push($arr_events, $event);
       
  2215 		}
       
  2216 	    }
       
  2217 	    else if ($year_begin < $year_end)
       
  2218 	    {
       
  2219 		if (date('m-d',strtotime($event->event_begin)) <= date('m-d',strtotime($date)) || 
       
  2220 			date('m-d',strtotime($event->event_end)) >= date('m-d',strtotime($date)))
       
  2221 		{
       
  2222 	      		array_push($arr_events, $event);
       
  2223 		}
       
  2224 	    }
       
  2225           }
       
  2226      	}	
       
  2227 
       
  2228 	/* 
       
  2229 	  The monthly code - just as easy because as long as the day of the month is correct, then we 
       
  2230 	  show the event
       
  2231 	*/
       
  2232 
       
  2233 	// The monthly events that never stop recurring
       
  2234 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_recur = 'M' AND EXTRACT(YEAR FROM '$date') >= EXTRACT(YEAR FROM event_begin) AND event_repeats = 0 ORDER BY event_id");
       
  2235 	if (!empty($events))
       
  2236      	{
       
  2237        	  foreach($events as $event)
       
  2238           {
       
  2239 	    // This is going to get complex so lets setup what we would place in for 
       
  2240 	    // an event so we can drop it in with ease
       
  2241 
       
  2242 	    // Technically we don't care about the years or months, but we need to find out if the 
       
  2243 	    // event spans the turn of a year or month so we can deal with it appropriately.
       
  2244 	    $month_begin = date('m',strtotime($event->event_begin));
       
  2245 	    $month_end = date('m',strtotime($event->event_end));
       
  2246 
       
  2247 	    if ($month_begin == $month_end)
       
  2248 	    {
       
  2249 		if (date('d',strtotime($event->event_begin)) <= date('d',strtotime($date)) && 
       
  2250 			date('d',strtotime($event->event_end)) >= date('d',strtotime($date)))
       
  2251 		{
       
  2252 	      		array_push($arr_events, $event);
       
  2253 		}
       
  2254 	    }
       
  2255 	    else if ($month_begin < $month_end)
       
  2256 	    {
       
  2257 		if ( ($event->event_begin <= date('Y-m-d',strtotime($date))) && (date('d',strtotime($event->event_begin)) <= date('d',strtotime($date)) || 
       
  2258 			date('d',strtotime($event->event_end)) >= date('d',strtotime($date))) )
       
  2259 		{
       
  2260 	      		array_push($arr_events, $event);
       
  2261 		}
       
  2262 	    }
       
  2263           }
       
  2264      	}
       
  2265 
       
  2266 
       
  2267 	// Now the ones that happen a finite number of times
       
  2268 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_recur = 'M' AND EXTRACT(YEAR FROM '$date') >= EXTRACT(YEAR FROM event_begin) AND event_repeats != 0 AND (PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM '$date'),EXTRACT(YEAR_MONTH FROM event_begin))) <= event_repeats ORDER BY event_id");
       
  2269 	if (!empty($events))
       
  2270      	{
       
  2271        	  foreach($events as $event)
       
  2272           {
       
  2273 	    // This is going to get complex so lets setup what we would place in for 
       
  2274 	    // an event so we can drop it in with ease
       
  2275 
       
  2276 	    // Technically we don't care about the years or months, but we need to find out if the 
       
  2277 	    // event spans the turn of a year or month so we can deal with it appropriately.
       
  2278 	    $month_begin = date('m',strtotime($event->event_begin));
       
  2279 	    $month_end = date('m',strtotime($event->event_end));
       
  2280 
       
  2281 	    if ($month_begin == $month_end)
       
  2282 	    {
       
  2283 		if (date('d',strtotime($event->event_begin)) <= date('d',strtotime($date)) && 
       
  2284 			date('d',strtotime($event->event_end)) >= date('d',strtotime($date)))
       
  2285 		{
       
  2286 		        array_push($arr_events, $event);
       
  2287 		}
       
  2288 	    }
       
  2289 	    else if ($month_begin < $month_end)
       
  2290 	    {
       
  2291 		if ( ($event->event_begin <= date('Y-m-d',strtotime($date))) && (date('d',strtotime($event->event_begin)) <= date('d',strtotime($date)) || 
       
  2292 			date('d',strtotime($event->event_end)) >= date('d',strtotime($date))) )
       
  2293 		{
       
  2294 	      		array_push($arr_events, $event);
       
  2295 		}
       
  2296 	    }
       
  2297           }
       
  2298      	}
       
  2299 
       
  2300 
       
  2301 	/* 
       
  2302 	  Weekly - well isn't this fun! We need to scan all weekly events, find what day they fell on
       
  2303 	  and see if that matches the current day. If it does, we check to see if the repeats are 0. 
       
  2304 	  If they are, display the event, if not, we fast forward from the original day in week blocks 
       
  2305 	  until the number is exhausted. If the date we arrive at is in the future, display the event.
       
  2306 	*/
       
  2307 
       
  2308 	// The weekly events that never stop recurring
       
  2309 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_recur = 'W' AND '$date' >= event_begin AND event_repeats = 0 ORDER BY event_id");
       
  2310 	if (!empty($events))
       
  2311      	{
       
  2312        	  foreach($events as $event)
       
  2313           {
       
  2314 	    // This is going to get complex so lets setup what we would place in for 
       
  2315 	    // an event so we can drop it in with ease
       
  2316 
       
  2317 	    // Now we are going to check to see what day the original event
       
  2318 	    // fell on and see if the current date is both after it and on 
       
  2319 	    // the correct day. If it is, display the event!
       
  2320 	    $day_start_event = date('D',strtotime($event->event_begin));
       
  2321 	    $day_end_event = date('D',strtotime($event->event_end));
       
  2322 	    $current_day = date('D',strtotime($date));
       
  2323 
       
  2324 	    $plan = array();
       
  2325 	    $plan['Mon'] = 1;
       
  2326 	    $plan['Tue'] = 2;
       
  2327 	    $plan['Wed'] = 3;
       
  2328 	    $plan['Thu'] = 4;
       
  2329 	    $plan['Fri'] = 5;
       
  2330 	    $plan['Sat'] = 6;
       
  2331 	    $plan['Sun'] = 7;
       
  2332 
       
  2333 	    if ($plan[$day_start_event] > $plan[$day_end_event])
       
  2334 	    {
       
  2335 		if (($plan[$day_start_event] <= $plan[$current_day]) || ($plan[$current_day] <= $plan[$day_end_event]))
       
  2336 	    	{
       
  2337 			array_push($arr_events, $event);
       
  2338 	    	}
       
  2339 	    }
       
  2340 	    else if (($plan[$day_start_event] < $plan[$day_end_event]) || ($plan[$day_start_event]== $plan[$day_end_event]))
       
  2341 	    {
       
  2342 		if (($plan[$day_start_event] <= $plan[$current_day]) && ($plan[$current_day] <= $plan[$day_end_event]))
       
  2343 	    	{
       
  2344 			array_push($arr_events, $event);
       
  2345 	    	}		
       
  2346 	    }
       
  2347 	    
       
  2348           }
       
  2349      	}
       
  2350 
       
  2351 	// The weekly events that have a limit on how many times they occur
       
  2352 	$events = $wpdb->get_results("SELECT * FROM " . WP_CALENDAR_TABLE . " WHERE event_recur = 'W' AND '$date' >= event_begin AND event_repeats != 0 AND (event_repeats*7) >= (TO_DAYS('$date') - TO_DAYS(event_end)) ORDER BY event_id");
       
  2353 	if (!empty($events))
       
  2354      	{
       
  2355        	  foreach($events as $event)
       
  2356           {
       
  2357 	    // This is going to get complex so lets setup what we would place in for 
       
  2358 	    // an event so we can drop it in with ease
       
  2359 
       
  2360 	    // Now we are going to check to see what day the original event
       
  2361 	    // fell on and see if the current date is both after it and on 
       
  2362 	    // the correct day. If it is, display the event!
       
  2363 	    $day_start_event = date('D',strtotime($event->event_begin));
       
  2364 	    $day_end_event = date('D',strtotime($event->event_end));
       
  2365 	    $current_day = date('D',strtotime($date));
       
  2366 
       
  2367 	    $plan = array();
       
  2368 	    $plan['Mon'] = 1;
       
  2369 	    $plan['Tue'] = 2;
       
  2370 	    $plan['Wed'] = 3;
       
  2371 	    $plan['Thu'] = 4;
       
  2372 	    $plan['Fri'] = 5;
       
  2373 	    $plan['Sat'] = 6;
       
  2374 	    $plan['Sun'] = 7;
       
  2375 
       
  2376 	    if ($plan[$day_start_event] > $plan[$day_end_event])
       
  2377 	    {
       
  2378 		if (($plan[$day_start_event] <= $plan[$current_day]) || ($plan[$current_day] <= $plan[$day_end_event]))
       
  2379 	    	{
       
  2380 			array_push($arr_events, $event);
       
  2381 	    	}
       
  2382 	    }
       
  2383 	    else if (($plan[$day_start_event] < $plan[$day_end_event]) || ($plan[$day_start_event]== $plan[$day_end_event]))
       
  2384 	    {
       
  2385 		if (($plan[$day_start_event] <= $plan[$current_day]) && ($plan[$current_day] <= $plan[$day_end_event]))
       
  2386 	    	{
       
  2387 			array_push($arr_events, $event);
       
  2388 	    	}		
       
  2389 	    }
       
  2390 
       
  2391           }
       
  2392      	}
       
  2393  
       
  2394      return $arr_events;
       
  2395 }
       
  2396 
       
  2397 
       
  2398 // Actually do the printing of the calendar
       
  2399 // Compared to searching for and displaying events
       
  2400 // this bit is really rather easy!
       
  2401 function calendar()
       
  2402 {
       
  2403     global $wpdb;
       
  2404 
       
  2405     // First things first, make sure calendar is up to date
       
  2406     check_calendar();
       
  2407 
       
  2408     // Deal with the week not starting on a monday
       
  2409     if (get_option('start_of_week') == 0)
       
  2410       {
       
  2411 	$name_days = array(1=>__('Sunday','calendar'),__('Monday','calendar'),__('Tuesday','calendar'),__('Wednesday','calendar'),__('Thursday','calendar'),__('Friday','calendar'),__('Saturday','calendar'));
       
  2412       }
       
  2413     // Choose Monday if anything other than Sunday is set
       
  2414     else
       
  2415       {
       
  2416 	$name_days = array(1=>__('Monday','calendar'),__('Tuesday','calendar'),__('Wednesday','calendar'),__('Thursday','calendar'),__('Friday','calendar'),__('Saturday','calendar'),__('Sunday','calendar'));
       
  2417       }
       
  2418 
       
  2419     // Carry on with the script
       
  2420     $name_months = array(1=>__('January','calendar'),__('February','calendar'),__('March','calendar'),__('April','calendar'),__('May','calendar'),__('June','calendar'),__('July','calendar'),__('August','calendar'),__('September','calendar'),__('October','calendar'),__('November','calendar'),__('December','calendar'));
       
  2421 
       
  2422     // If we don't pass arguments we want a calendar that is relevant to today
       
  2423     if (empty($_GET['month']) || empty($_GET['yr']))
       
  2424     {
       
  2425         $c_year = date("Y");
       
  2426         $c_month = date("m");
       
  2427         $c_day = date("d");
       
  2428     }
       
  2429 
       
  2430     // Years get funny if we exceed 3000, so we use this check
       
  2431     if ($_GET['yr'] <= 3000 && $_GET['yr'] >= 0)
       
  2432     {
       
  2433         // This is just plain nasty and all because of permalinks
       
  2434         // which are no longer used, this will be cleaned up soon
       
  2435         if ($_GET['month'] == 'jan' || $_GET['month'] == 'feb' || $_GET['month'] == 'mar' || $_GET['month'] == 'apr' || $_GET['month'] == 'may' || $_GET['month'] == 'jun' || $_GET['month'] == 'jul' || $_GET['month'] == 'aug' || $_GET['month'] == 'sept' || $_GET['month'] == 'oct' || $_GET['month'] == 'nov' || $_GET['month'] == 'dec')
       
  2436 	  {
       
  2437 
       
  2438 	       // Again nasty code to map permalinks into something
       
  2439 	       // databases can understand. This will be cleaned up
       
  2440                $c_year = mysql_escape_string($_GET['yr']);
       
  2441                if ($_GET['month'] == 'jan') { $t_month = 1; }
       
  2442                else if ($_GET['month'] == 'feb') { $t_month = 2; }
       
  2443                else if ($_GET['month'] == 'mar') { $t_month = 3; }
       
  2444                else if ($_GET['month'] == 'apr') { $t_month = 4; }
       
  2445                else if ($_GET['month'] == 'may') { $t_month = 5; }
       
  2446                else if ($_GET['month'] == 'jun') { $t_month = 6; }
       
  2447                else if ($_GET['month'] == 'jul') { $t_month = 7; }
       
  2448                else if ($_GET['month'] == 'aug') { $t_month = 8; }
       
  2449                else if ($_GET['month'] == 'sept') { $t_month = 9; }
       
  2450                else if ($_GET['month'] == 'oct') { $t_month = 10; }
       
  2451                else if ($_GET['month'] == 'nov') { $t_month = 11; }
       
  2452                else if ($_GET['month'] == 'dec') { $t_month = 12; }
       
  2453                $c_month = $t_month;
       
  2454                $c_day = date("d");
       
  2455         }
       
  2456 	// No valid month causes the calendar to default to today
       
  2457         else
       
  2458         {
       
  2459                $c_year = date("Y");
       
  2460                $c_month = date("m");
       
  2461                $c_day = date("d");
       
  2462         }
       
  2463     }
       
  2464     // No valid year causes the calendar to default to today
       
  2465     else
       
  2466     {
       
  2467         $c_year = date("Y");
       
  2468         $c_month = date("m");
       
  2469         $c_day = date("d");
       
  2470     }
       
  2471 
       
  2472     // Fix the days of the week if week start is not on a monday
       
  2473     if (get_option('start_of_week') == 0)
       
  2474       {
       
  2475 	$first_weekday = date("w",mktime(0,0,0,$c_month,1,$c_year));
       
  2476         $first_weekday = ($first_weekday==0?1:$first_weekday+1);
       
  2477       }
       
  2478     // Otherwise assume the week starts on a Monday. Anything other 
       
  2479     // than Sunday or Monday is just plain odd
       
  2480     else
       
  2481       {
       
  2482 	$first_weekday = date("w",mktime(0,0,0,$c_month,1,$c_year));
       
  2483 	$first_weekday = ($first_weekday==0?7:$first_weekday);
       
  2484       }
       
  2485 
       
  2486     $days_in_month = date("t", mktime (0,0,0,$c_month,1,$c_year));
       
  2487 
       
  2488     // Start the table and add the header and naviagtion
       
  2489     $calendar_body .= '
       
  2490 <table cellspacing="1" cellpadding="0" class="calendar-table">
       
  2491 ';
       
  2492 
       
  2493     // We want to know if we should display the date switcher
       
  2494     $date_switcher = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='display_jump'",0,0);
       
  2495 
       
  2496     if ($date_switcher == 'true')
       
  2497       {
       
  2498 	$calendar_body .= '<tr>
       
  2499         <td colspan="7" class="calendar-date-switcher">
       
  2500             <form method="GET" action="'.$_SERVER['REQUEST_URI'].'">
       
  2501 ';
       
  2502 	$qsa = array();
       
  2503 	parse_str($_SERVER['QUERY_STRING'],$qsa);
       
  2504 	foreach ($qsa as $name => $argument)
       
  2505 	  {
       
  2506 	    if ($name != 'month' && $name != 'yr')
       
  2507 	      {
       
  2508 		$calendar_body .= '<input type="hidden" name="'.$name.'" value="'.$argument.'" />
       
  2509 ';
       
  2510 	      }
       
  2511 	  }
       
  2512 	function month_comparison($month)
       
  2513 	  {
       
  2514 	    $current_month = strtolower(date("M", time()));
       
  2515 	    if (isset($_GET['yr']) && isset($_GET['month']))
       
  2516 	      {
       
  2517 		if ($month == $_GET['month'])
       
  2518 		  {
       
  2519 		    return ' selected="selected"';
       
  2520 		  }
       
  2521 	      }
       
  2522 	    elseif ($month == $current_month) 
       
  2523 	      { 
       
  2524 		return ' selected="selected"'; 
       
  2525 	      }
       
  2526 	  }
       
  2527 	// We build the months in the switcher
       
  2528 	$calendar_body .= '
       
  2529             '.__('Month','calendar').': <select name="month" style="width:100px;">
       
  2530             <option value="jan"'.month_comparison('jan').'>'.__('January','calendar').'</option>
       
  2531             <option value="feb"'.month_comparison('feb').'>'.__('February','calendar').'</option>
       
  2532             <option value="mar"'.month_comparison('mar').'>'.__('March','calendar').'</option>
       
  2533             <option value="apr"'.month_comparison('apr').'>'.__('April','calendar').'</option>
       
  2534             <option value="may"'.month_comparison('may').'>'.__('May','calendar').'</option>
       
  2535             <option value="jun"'.month_comparison('jun').'>'.__('June','calendar').'</option>
       
  2536             <option value="jul"'.month_comparison('jul').'>'.__('July','calendar').'</option> 
       
  2537             <option value="aug"'.month_comparison('aug').'>'.__('August','calendar').'</option> 
       
  2538             <option value="sept"'.month_comparison('sept').'>'.__('September','calendar').'</option> 
       
  2539             <option value="oct"'.month_comparison('oct').'>'.__('October','calendar').'</option> 
       
  2540             <option value="nov"'.month_comparison('nov').'>'.__('November','calendar').'</option> 
       
  2541             <option value="dec"'.month_comparison('dec').'>'.__('December','calendar').'</option> 
       
  2542             </select>
       
  2543             '.__('Year','calendar').': <select name="yr" style="width:60px;">
       
  2544 ';
       
  2545 
       
  2546 	// The year builder is string mania. If you can make sense of this, 
       
  2547         // you know your PHP!
       
  2548 	function year_comparison($year)
       
  2549           {
       
  2550             $current_year = strtolower(date("Y", time()));
       
  2551             if (isset($_GET['yr']) && isset($_GET['month']))
       
  2552               {
       
  2553                 if ($year == $_GET['yr'])
       
  2554                   {
       
  2555                     return ' selected="selected"';
       
  2556                   }
       
  2557               }
       
  2558             else if ($year == $current_year)
       
  2559               {
       
  2560                 return ' selected="selected"';
       
  2561               }
       
  2562           }
       
  2563 
       
  2564 	$past = 30;
       
  2565 	$future = 30;
       
  2566 	$fut = 1;
       
  2567 	while ($past > 0)
       
  2568 	  {
       
  2569 	    $p .= '            <option value="';
       
  2570 	    $p .= date("Y",time())-$past;
       
  2571 	    $p .= '"'.year_comparison(date("Y",time())-$past).'>';
       
  2572 	    $p .= date("Y",time())-$past.'</option>
       
  2573 ';
       
  2574 	    $past = $past - 1;
       
  2575 	  }
       
  2576 	while ($fut < $future) 
       
  2577 	  {
       
  2578 	    $f .= '            <option value="';
       
  2579 	    $f .= date("Y",time())+$fut;
       
  2580 	    $f .= '"'.year_comparison(date("Y",time())+$fut).'>';
       
  2581 	    $f .= date("Y",time())+$fut.'</option>
       
  2582 ';
       
  2583 	    $fut = $fut + 1;
       
  2584 	  } 
       
  2585 	$calendar_body .= $p;
       
  2586 	$calendar_body .= '            <option value="'.date("Y",time()).'"'.year_comparison(date("Y",time())).'>'.date("Y",time()).'</option>
       
  2587 ';
       
  2588 	$calendar_body .= $f;
       
  2589         $calendar_body .= '</select>
       
  2590             <input type="submit" value="Go" />
       
  2591             </form>
       
  2592         </td>
       
  2593 </tr>
       
  2594 ';
       
  2595       }
       
  2596 
       
  2597     // The header of the calendar table and the links. Note calls to link functions
       
  2598     $calendar_body .= '<tr>
       
  2599                 <td colspan="7" class="calendar-heading">
       
  2600                     <table border="0" cellpadding="0" cellspacing="0" width="100%">
       
  2601                     <tr>
       
  2602                     <td class="calendar-prev">' . prev_link($c_year,$c_month) . '</td>
       
  2603                     <td class="calendar-month">'.$name_months[(int)$c_month].' '.$c_year.'</td>
       
  2604                     <td class="calendar-next">' . next_link($c_year,$c_month) . '</td>
       
  2605                     </tr>
       
  2606                     </table>
       
  2607                 </td>
       
  2608 </tr>
       
  2609 ';
       
  2610 
       
  2611     // Print the headings of the days of the week
       
  2612     $calendar_body .= '<tr>
       
  2613 ';
       
  2614     for ($i=1; $i<=7; $i++) 
       
  2615       {
       
  2616 	// Colours need to be different if the starting day of the week is different
       
  2617 	if (get_option('start_of_week') == 0)
       
  2618 	  {
       
  2619 	    $calendar_body .= '        <td class="'.($i<7&&$i>1?'normal-day-heading':'weekend-heading').'">'.$name_days[$i].'</td>
       
  2620 ';
       
  2621 	  }
       
  2622 	else
       
  2623 	  {
       
  2624 	    $calendar_body .= '        <td class="'.($i<6?'normal-day-heading':'weekend-heading').'">'.$name_days[$i].'</td>
       
  2625 ';
       
  2626 	  }
       
  2627       }
       
  2628     $calendar_body .= '</tr>
       
  2629 ';
       
  2630 
       
  2631     for ($i=1; $i<=$days_in_month;)
       
  2632       {
       
  2633         $calendar_body .= '<tr>
       
  2634 ';
       
  2635         for ($ii=1; $ii<=7; $ii++)
       
  2636 	  {
       
  2637             if ($ii==$first_weekday && $i==1)
       
  2638 	      {
       
  2639 		$go = TRUE;
       
  2640 	      }
       
  2641             elseif ($i > $days_in_month ) 
       
  2642 	      {
       
  2643 		$go = FALSE;
       
  2644 	      }
       
  2645 
       
  2646             if ($go) 
       
  2647 	      {
       
  2648 		// Colours again, this time for the day numbers
       
  2649 		if (get_option('start_of_week') == 0)
       
  2650 		  {
       
  2651 		    // This bit of code is for styles believe it or not.
       
  2652 		    $grabbed_events = grab_events($c_year,$c_month,$i);
       
  2653 		    $no_events_class = '';
       
  2654 		    if (!count($grabbed_events))
       
  2655 		      {
       
  2656 			$no_events_class = ' no-events';
       
  2657 		      }
       
  2658 		    $calendar_body .= '        <td class="'.(date("Ymd", mktime (0,0,0,$c_month,$i,$c_year))==date("Ymd")?'current-day':'day-with-date').$no_events_class.'"><span '.($ii<7&&$ii>1?'':'class="weekend"').'>'.$i++.'</span><span class="event">' . draw_events($grabbed_events) . '</span></td>
       
  2659 ';
       
  2660 		  }
       
  2661 		else
       
  2662 		  {
       
  2663 		    $grabbed_events = grab_events($c_year,$c_month,$i);
       
  2664 		    $no_events_class = '';
       
  2665 	            if (!count($grabbed_events))
       
  2666 		      {
       
  2667 			$no_events_class = ' no-events';
       
  2668 		      }
       
  2669 		    $calendar_body .= '        <td class="'.(date("Ymd", mktime (0,0,0,$c_month,$i,$c_year))==date("Ymd")?'current-day':'day-with-date').$no_events_class.'"><span '.($ii<6?'':'class="weekend"').'>'.$i++.'</span><span class="event">' . draw_events($grabbed_events) . '</span></td>
       
  2670 ';
       
  2671 		  }
       
  2672 	      }
       
  2673             else 
       
  2674 	      {
       
  2675 		$calendar_body .= '        <td class="day-without-date">&nbsp;</td>
       
  2676 ';
       
  2677 	      }
       
  2678         }
       
  2679         $calendar_body .= '</tr>
       
  2680 ';
       
  2681     }
       
  2682     $show_cat = $wpdb->get_var("SELECT config_value FROM ".WP_CALENDAR_CONFIG_TABLE." WHERE config_item='enable_categories'",0,0);
       
  2683 
       
  2684     if ($show_cat == 'true')
       
  2685       {
       
  2686 	$sql = "SELECT * FROM " . WP_CALENDAR_CATEGORIES_TABLE . " ORDER BY category_name ASC";
       
  2687 	$cat_details = $wpdb->get_results($sql);
       
  2688         $calendar_body .= '<tr><td colspan="7">
       
  2689 <table class="cat-key">
       
  2690 <tr><td colspan="2"><strong>'.__('Category Key','calendar').'</strong></td></tr>
       
  2691 ';
       
  2692         foreach($cat_details as $cat_detail)
       
  2693 	  {
       
  2694 	    $calendar_body .= '<tr><td style="background-color:'.$cat_detail->category_colour.'; width:20px; height:20px;"></td><td>'.$cat_detail->category_name.'</td></tr>';
       
  2695 	  }
       
  2696         $calendar_body .= '</table>
       
  2697 </td></tr>
       
  2698 ';
       
  2699       }
       
  2700     $calendar_body .= '</table>
       
  2701 ';
       
  2702 
       
  2703     // A little link to yours truely. See the README if you wish to remove this
       
  2704     $calendar_body .= '<div class="kjo-link" style="visibility:visible;display:block;"><p>'.__('Calendar developed and supported by ', 'calendar').'<a href="http://www.kieranoshea.com">Kieran O\'Shea</a></p></div>
       
  2705 ';
       
  2706 
       
  2707     // Phew! After that bit of string building, spit it all out.
       
  2708     // The actual printing is done by the calling function.
       
  2709     return $calendar_body;
       
  2710 }
       
  2711 
       
  2712 ?>