Example #1
0
function eme_ical_single_event($event, $title_format, $description_format) {
   global $eme_timezone;
   $title = eme_sanitize_ical (eme_replace_placeholders ( $title_format, $event, "text" ));
   $description = eme_sanitize_ical (eme_replace_placeholders ( $description_format, $event, "text" ));
   $html_description = eme_sanitize_ical (eme_replace_placeholders ( $description_format, $event, "html" ),1);

   $event_link = eme_event_url($event);
   $startstring=new ExpressiveDate($event['event_start_date']." ".$event['event_start_time'],$eme_timezone);
   $dtstartdate=$startstring->format("Ymd");
   $dtstarthour=$startstring->format("His");
   //$dtstart=$dtstartdate."T".$dtstarthour."Z";
   // we'll use localtime, so no "Z"
   $dtstart=$dtstartdate."T".$dtstarthour;
   if ($event['event_end_date'] == "")
      $event['event_end_date'] = $event['event_start_date'];
   if ($event['event_end_time'] == "")
      $event['event_end_time'] = $event['event_start_time'];
   $endstring=$event['event_end_date']." ".$event['event_end_time'];
   $endstring=new ExpressiveDate($event['event_end_date']." ".$event['event_end_time'],$eme_timezone);
   $dtenddate=$endstring->format("Ymd");
   $dtendhour=$endstring->format("His");
   //$dtend=$dtenddate."T".$dtendhour."Z";
   // we'll use localtime, so no "Z"
   $dtend=$dtenddate."T".$dtendhour;
   $tzstring = get_option('timezone_string');

   $res = "";
   $res .= "BEGIN:VEVENT\r\n";
   //DTSTAMP must be in UTC format, so adding "Z" as well
   $res .= "DTSTAMP:" . gmdate('Ymd').'T'. gmdate('His') . "Z\r\n";
   if ($event['event_properties']['all_day']) {
      // ical standard for an all day event: specify only the day, meaning
      // an 'all day' event is flagged as starting at the beginning of one day and lasting until the beginning of the next
      // so it is the same as adding "T000000" as time spec to the start/end datestring
      // But since it "ends" at the beginning of the next day, we should add 24 hours, otherwise the event ends one day too soon
      $dtenddate=$endstring->addOneDay()->format('Ymd');
      $res .= "DTSTART;VALUE=DATE:$dtstartdate\r\n";
      $res .= "DTEND;VALUE=DATE:$dtenddate\r\n";
   } else {
      $res .= "DTSTART;TZID=$tzstring:$dtstart\r\n";
      $res .= "DTEND;TZID=$tzstring:$dtend\r\n";
   }
   $res .= "UID:$dtstart-$dtend-".$event['event_id']."@".$_SERVER['SERVER_NAME']."\r\n";
   $res .= "SUMMARY:$title\r\n";
   $res .= "DESCRIPTION:$description\r\n";
   $res .= "X-ALT-DESC;FMTTYPE=text/html:$html_description\r\n";
   $res .= "URL:$event_link\r\n";
   $res .= "ATTACH:$event_link\r\n";
   if ($event['event_image_id']) {
      $thumb_array = image_downsize( $event['event_image_id'], get_option('eme_thumbnail_size') );
      $thumb_url = $thumb_array[0];
      $res .= "ATTACH:$thumb_url\r\n";
   }
   if (isset($event['location_id']) && $event['location_id']) {
      $location = eme_sanitize_ical (eme_replace_placeholders ( "#_LOCATION, #_ADDRESS, #_TOWN", $event, "text" ));
      $res .= "LOCATION:$location\r\n";
   }
   $res .= "END:VEVENT\r\n";
   return $res;
}
Example #2
0
function eme_printable_booking_report($event_id) {
   global $eme_timezone;
   $event = eme_get_event($event_id);
   $current_userid=get_current_user_id();
   if (!(current_user_can( get_option('eme_cap_edit_events')) || current_user_can( get_option('eme_cap_list_events')) ||
        (current_user_can( get_option('eme_cap_author_event')) && ($event['event_author']==$current_userid || $event['event_contactperson_id']==$current_userid)))) {
        echo "No access";
        die;
   }

   $is_multiprice = eme_is_multi($event['price']);
   $is_multiseat = eme_is_multi($event['event_seats']);
   $bookings = eme_get_bookings_for($event_id);
   $answer_columns = eme_get_answercolumns(eme_get_bookingids_for($event_id));
   $available_seats = eme_get_available_seats($event_id);
   $booked_seats = eme_get_booked_seats($event_id);
   $pending_seats = eme_get_pending_seats($event_id);
   if ($is_multiseat) {
      $available_seats_ms=eme_convert_array2multi(eme_get_available_multiseats($event_id));
      $booked_seats_ms=eme_convert_array2multi(eme_get_booked_multiseats($event_id));
      $pending_seats_ms=eme_convert_array2multi(eme_get_pending_multiseats($event_id));
   }

   $stylesheet = EME_PLUGIN_URL."events_manager.css";
   foreach($answer_columns as $col) {
      $formfield[$col["field_name"]]=eme_get_formfield_id_byname($col["field_name"]);
   }
   ?>
      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
         "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
      <html>
      <head>
         <meta http-equiv="Content-type" content="text/html; charset=utf-8">
         <title>Bookings for <?php echo eme_trans_sanitize_html($event['event_name']);?></title>
          <link rel="stylesheet" href="<?php echo $stylesheet; ?>" type="text/css" media="screen" />
          <?php
            $file_name= get_stylesheet_directory()."/eme.css";
            if (file_exists($file_name))
               echo "<link rel='stylesheet' href='".get_stylesheet_directory_uri()."/eme.css' type='text/css' media='screen' />\n";
            $file_name= get_stylesheet_directory()."/eme_print.css";
            if (file_exists($file_name))
               echo "<link rel='stylesheet' href='".get_stylesheet_directory_uri()."/eme_print.css' type='text/css' media='print' />\n";
          ?>
      </head>
      <body id="eme_printable_body">
         <div id="eme_printable_container">
         <h1>Bookings for <?php echo eme_trans_sanitize_html($event['event_name']);?></h1> 
         <p><?php echo eme_localised_date($event['event_start_date']." ".$event['event_start_time']." ".$eme_timezone); ?></p>
         <p><?php if ($event['location_id']) echo eme_replace_placeholders("#_LOCATIONNAME, #_ADDRESS, #_TOWN", $event); ?></p>
         <?php if ($event['price']) ?>
            <p><?php _e ( 'Price: ','eme' ); echo eme_replace_placeholders("#_CURRENCY #_PRICE", $event)?></p>
         <h1><?php _e('Bookings data', 'eme');?></h1>
         <table id="eme_printable_table">
            <tr>
               <th scope='col' class='eme_print_id'><?php _e('ID', 'eme')?></th>
               <th scope='col' class='eme_print_name'><?php _e('Last Name', 'eme')?></th>
               <th scope='col' class='eme_print_name'><?php _e('First Name', 'eme')?></th>
               <th scope='col' class='eme_print_email'><?php _e('E-mail', 'eme')?></th>
               <th scope='col' class='eme_print_phone'><?php _e('Phone number', 'eme')?></th> 
               <th scope='col' class='eme_print_seats'><?php if ($is_multiprice) _e('Seats (Multiprice)', 'eme'); else _e('Seats', 'eme'); ?></th>
               <th scope='col' class='eme_print_paid'><?php _e('Paid', 'eme')?></th>
               <th scope='col' class='eme_print_booking_date'><?php _e('Booking date', 'eme')?></th>
               <th scope='col' class='eme_print_total_price'><?php _e('Total price', 'eme')?></th>
               <th scope='col' class='eme_print_unique_nbr'><?php _e('Unique nbr', 'eme')?></th>
               <th scope='col' class='eme_print_comment'><?php _e('Comment', 'eme')?></th> 
            <?php
            $nbr_columns=11;
            foreach($answer_columns as $col) {
               $class="eme_print_formfield".$formfield[$col['field_name']];
               print "<th scope='col' class='$class'>".$col['field_name']."</th>";
               $nbr_columns++;
            }
            ?>
            </tr>
            <?php
            foreach($bookings as $booking) {
               $localised_booking_date = eme_localised_date($booking['creation_date']." ".$eme_timezone);
               $localised_booking_time = eme_localised_time($booking['creation_date']." ".$eme_timezone);
               $person = eme_get_person ($booking['person_id']);
               $pending_string="";
               if (eme_event_needs_approval($event_id) && !$booking['booking_approved']) {
                  $pending_string=__('(pending)','eme');
               }
                ?>
            <tr>
               <td class='eme_print_id'><?php echo $booking['booking_id']?></td> 
               <td class='eme_print_name'><?php echo $person['lastname']?></td> 
               <td class='eme_print_name'><?php echo $person['firstname']?></td> 
               <td class='eme_print_email'><?php echo $person['email']?></td>
               <td class='eme_print_phone'><?php echo $person['phone']?></td>
               <td class='eme_print_seats' class='seats-number'><?php 
               if ($is_multiprice) {
                  // in cases where the event switched to multiprice, but somebody already registered while it was still single price: booking_seats_mp is then empty
                  if ($booking['booking_seats_mp'] == "")
                     $booking['booking_seats_mp']=$booking['booking_seats'];
                  echo $booking['booking_seats']." (".$booking['booking_seats_mp'].") ".$pending_string;
               } else {
                  echo $booking['booking_seats']." ".$pending_string;
               }
               ?>
               </td>
               <td class='eme_print_paid'><?php if ($booking['booking_payed']) _e('Yes'); else _e('No'); ?></td>
               <td class='eme_print_booking_date'><?php echo $localised_booking_date." ".$localised_booking_time; ?></td>
               <td class='eme_print_total_price'><?php echo eme_get_total_booking_price($event,$booking); ?></td>
               <td class='eme_print_unique_nbr'><?php echo $booking['transfer_nbr_be97']; ?></td>
               <td class='eme_print_comment'><?=$booking['booking_comment'] ?></td> 
               <?php
                  $answers = eme_get_answers($booking['booking_id']);
                  foreach($answer_columns as $col) {
                     $found=0;
                     foreach ($answers as $answer) {
                        $class="eme_print_formfield".$formfield[$col['field_name']];
                        if ($answer['field_name'] == $col['field_name']) {
                           print "<td class='$class'>".eme_sanitize_html(eme_convert_answer2tag($answer))."</td>";
                           $found=1;
                           break;
                        }
                     }
                     # to make sure the number of columns are correct, we add an empty answer if none was found
                     if (!$found)
                        print "<td class='$class'>&nbsp;</td>";
                  }
               ?>
            </tr>
               <?php } ?>
            <tr id='eme_printable_booked-seats'>
               <td colspan='<?php echo $nbr_columns-4;?>'>&nbsp;</td>
               <td class='total-label'><?php _e('Booked', 'eme')?>:</td>
               <td colspan='3' class='seats-number'><?php
               print $booked_seats;
               if ($is_multiseat) print " ($booked_seats_ms)";
			      if ($pending_seats>0) {
                  if ($is_multiseat)
                     print " ".sprintf( __('(%s pending)','eme'), $pending_seats . " ($pending_seats_ms)");
                  else
                     print " ".sprintf( __('(%s pending)','eme'), $pending_seats);
               }
               ?>
            </td>
            </tr>
            <tr id='eme_printable_available-seats'>
               <td colspan='<?php echo $nbr_columns-4;?>'>&nbsp;</td>
               <td class='total-label'><?php _e('Available', 'eme')?>:</td>
               <td colspan='3' class='seats-number'><?php print $available_seats; if ($is_multiseat) print " ($available_seats_ms)"; ?></td>
            </tr>
         </table>
         </div>
      </body>
      </html>
      <?php
      die();
} 
Example #3
0
function eme_multipayment_form($payment_id, $form_result_message = "")
{
    $ret_string = "<div id='eme-rsvp-message'>";
    if (!empty($form_result_message)) {
        $ret_string .= "<div class='eme-rsvp-message'>{$form_result_message}</div>";
    }
    $ret_string .= "</div>";
    $booking_ids = eme_get_payment_booking_ids($payment_id);
    if (!$booking_ids) {
        return $ret_string;
    }
    $bookings = eme_get_bookings($booking_ids);
    $total_price = eme_bookings_total_booking_price($bookings);
    // we take the currency of the first event in the series
    $event = eme_get_event_by_booking_id($booking_ids[0]);
    $booking = eme_get_booking($booking_ids[0]);
    $cur = $event['currency'];
    $eme_multipayment_form_header_format = get_option('eme_multipayment_form_header_format');
    if (!empty($eme_multipayment_form_header_format)) {
        $result = eme_replace_placeholders($eme_multipayment_form_header_format, $event, "html", 0);
        $result = eme_replace_booking_placeholders($result, $event, $booking);
        $ret_string .= "<div id='eme-payment-formtext' class='eme-payment-formtext'>";
        $ret_string .= $result;
        $ret_string .= "</div>";
    } else {
        $ret_string .= "<div id='eme-payment-handling' class='eme-payment-handling'>" . __('Payment handling', 'eme') . "</div>";
        $ret_string .= "<div id='eme-payment-price-info' class='eme-payment-price-info'>" . sprintf(__("The booking price in %s is: %01.2f", 'eme'), $cur, $total_price) . "</div>";
    }
    $ret_string .= "<div id='eme-payment-form' class='eme-payment-form'>";
    $payment = eme_get_payment($payment_id);
    if ($event['use_paypal']) {
        $ret_string .= eme_paypal_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    if ($event['use_2co']) {
        $ret_string .= eme_2co_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    if ($event['use_webmoney']) {
        $ret_string .= eme_webmoney_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    if ($event['use_fdgg']) {
        $ret_string .= eme_fdgg_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    if ($event['use_mollie']) {
        $ret_string .= eme_mollie_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    if ($event['use_sagepay']) {
        $ret_string .= eme_sagepay_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    if ($event['event_properties']['use_worldpay']) {
        $ret_string .= eme_worldpay_form($event, $payment, $total_price, $booking['lang'], 1);
    }
    $ret_string .= "</div>";
    $eme_multipayment_form_footer_format = get_option('eme_multipayment_form_footer_format');
    if (!empty($eme_multipayment_form_footer_format)) {
        $result = eme_replace_placeholders($eme_multipayment_form_footer_format, $event, "html", 0);
        $result = eme_replace_booking_placeholders($result, $event, $booking);
        $ret_string .= "<div id='eme-payment-formtext' class='eme-payment-formtext'>";
        $ret_string .= $result;
        $ret_string .= "</div>";
    }
    return $ret_string;
}
Example #4
0
function eme_events_in_location_list($location, $scope = "")
{
    $eme_event_list_number_events = get_option('eme_event_list_number_items');
    $events = eme_get_events($eme_event_list_number_events, $scope, "", "", $location['location_id']);
    $list = "";
    if (count($events) > 0) {
        foreach ($events as $event) {
            $list .= eme_replace_placeholders(get_option('eme_location_event_list_item_format'), $event);
        }
    } else {
        $list = get_option('eme_location_no_events_message');
    }
    return $list;
}
Example #5
0
function eme_send_mails_page()
{
    global $wpdb;
    $event_id = isset($_POST['event_id']) ? intval($_POST['event_id']) : 0;
    $action = isset($_POST['eme_admin_action']) ? $_POST['eme_admin_action'] : '';
    $onchange = isset($_POST['onchange']) ? intval($_POST['onchange']) : 0;
    if (isset($_POST['mail_subject']) && !empty($_POST['mail_subject'])) {
        $mail_subject = stripslashes_deep($_POST['mail_subject']);
    } elseif (isset($_POST['subject_template']) && intval($_POST['subject_template']) > 0) {
        $mail_subject = eme_get_template_format(intval($_POST['subject_template']));
    } else {
        $mail_subject = "";
    }
    if (isset($_POST['mail_message']) && !empty($_POST['mail_message'])) {
        $mail_message = stripslashes_deep($_POST['mail_message']);
    } elseif (isset($_POST['message_template']) && intval($_POST['message_template']) > 0) {
        $mail_message = eme_get_template_format(intval($_POST['message_template']));
    } else {
        $mail_message = "";
    }
    if (!$onchange && $event_id > 0 && $action == 'send_mail') {
        $pending_approved = isset($_POST['pending_approved']) ? $_POST['pending_approved'] : 0;
        $only_unpayed = isset($_POST['only_unpayed']) ? $_POST['only_unpayed'] : 0;
        $eme_mail_type = isset($_POST['eme_mail_type']) ? $_POST['eme_mail_type'] : 'attendees';
        if (empty($mail_subject) || empty($mail_message)) {
            print "<div id='message' class='error'><p>" . __('Please enter both subject and message for the mail to be sent.', 'eme') . "</p></div>";
        } else {
            $event = eme_get_event($event_id);
            $current_userid = get_current_user_id();
            if (current_user_can(get_option('eme_cap_send_other_mails')) || current_user_can(get_option('eme_cap_send_mails')) && ($event['event_author'] == $current_userid || $event['event_contactperson_id'] == $current_userid)) {
                $event_name = $event['event_name'];
                $contact = eme_get_contact($event);
                $contact_email = $contact->user_email;
                $contact_name = $contact->display_name;
                $mail_text_html = get_option('eme_rsvp_send_html') ? "html" : "text";
                if ($eme_mail_type == 'attendees') {
                    $attendees = eme_get_attendees_for($event_id, $pending_approved, $only_unpayed);
                    foreach ($attendees as $attendee) {
                        $tmp_subject = eme_replace_placeholders($mail_subject, $event, "text", 0, $attendee['lang']);
                        $tmp_message = eme_replace_placeholders($mail_message, $event, $mail_text_html, 0, $attendee['lang']);
                        $tmp_subject = eme_replace_attendees_placeholders($tmp_subject, $event, $attendee, "text", 0, $attendee['lang']);
                        $tmp_message = eme_replace_attendees_placeholders($tmp_message, $event, $attendee, $mail_text_html, 0, $attendee['lang']);
                        $tmp_subject = eme_translate($tmp_subject, $attendee['lang']);
                        $tmp_message = eme_translate($tmp_message, $attendee['lang']);
                        $person_name = $attendee['lastname'] . ' ' . $attendee['firstname'];
                        eme_send_mail($tmp_subject, $tmp_message, $attendee['email'], $person_name, $contact_email, $contact_name);
                    }
                } elseif ($eme_mail_type == 'bookings') {
                    $bookings = eme_get_bookings_for($event_id, $pending_approved, $only_unpayed);
                    foreach ($bookings as $booking) {
                        // we use the language done in the booking for the mails, not the attendee lang in this case
                        $attendee = eme_get_person($booking['person_id']);
                        if ($attendee && is_array($attendee)) {
                            $tmp_subject = eme_replace_placeholders($mail_subject, $event, "text", 0, $booking['lang']);
                            $tmp_message = eme_replace_placeholders($mail_message, $event, $mail_text_html, 0, $booking['lang']);
                            $tmp_subject = eme_replace_booking_placeholders($tmp_subject, $event, $booking, "text", 0, $booking['lang']);
                            $tmp_message = eme_replace_booking_placeholders($tmp_message, $event, $booking, $mail_text_html, 0, $booking['lang']);
                            $tmp_subject = eme_translate($tmp_subject, $booking['lang']);
                            $tmp_message = eme_translate($tmp_message, $booking['lang']);
                            $person_name = $attendee['lastname'] . ' ' . $attendee['firstname'];
                            eme_send_mail($tmp_subject, $tmp_message, $attendee['email'], $person_name, $contact_email, $contact_name);
                        }
                    }
                } elseif ($eme_mail_type == 'all_wp') {
                    $wp_users = get_users();
                    $tmp_subject = eme_replace_placeholders($mail_subject, $event, "text");
                    $tmp_message = eme_replace_placeholders($mail_message, $event, $mail_text_html);
                    foreach ($wp_users as $wp_user) {
                        eme_send_mail($tmp_subject, $tmp_message, $wp_user->user_email, $wp_user->display_name, $contact_email, $contact_name);
                    }
                } elseif ($eme_mail_type == 'all_wp_not_registered') {
                    $wp_users = get_users();
                    $attendee_wp_ids = eme_get_wp_ids_for($event_id);
                    $tmp_subject = eme_replace_placeholders($mail_subject, $event, "text");
                    $tmp_message = eme_replace_placeholders($mail_message, $event, $mail_text_html);
                    foreach ($wp_users as $wp_user) {
                        if (!in_array($wp_user->ID, $attendee_wp_ids)) {
                            eme_send_mail($tmp_subject, $tmp_message, $wp_user->user_email, $wp_user->display_name, $contact_email, $contact_name);
                        }
                    }
                }
                print "<div id='message' class='updated'><p>" . __('The mail has been sent.', 'eme') . "</p></div>";
            } else {
                print "<div id='message' class='error'><p>" . __('You do not have the permission to send mails for this event.', 'eme') . "</p></div>";
            }
        }
    }
    // now show the form
    eme_send_mail_form($event_id);
}
function eme_replace_formfields_placeholders($event, $booking = "", $format = "", $eme_multibooking = 0)
{
    global $current_user;
    $event_id = $event['event_id'];
    $registration_wp_users_only = $event['registration_wp_users_only'];
    $is_admin = is_admin();
    if ($is_admin && $booking) {
        $editing_booking_from_backend = 1;
    } else {
        $editing_booking_from_backend = 0;
    }
    // if not in the backend and wp membership is required
    // or when editing an existing booking via backend (not a new)
    if ($registration_wp_users_only && !$is_admin || $editing_booking_from_backend) {
        $readonly = "disabled='disabled'";
    } else {
        $readonly = "";
    }
    if (empty($format)) {
        if (!empty($event['event_registration_form_format'])) {
            $format = $event['event_registration_form_format'];
        } elseif ($event['event_properties']['event_registration_form_format_tpl'] > 0) {
            $format = eme_get_template_format($event['event_properties']['event_registration_form_format_tpl']);
        } else {
            $format = get_option('eme_registration_form_format');
        }
    }
    $min_allowed = $event['event_properties']['min_allowed'];
    $max_allowed = $event['event_properties']['max_allowed'];
    if ($event['event_properties']['take_attendance']) {
        $min_allowed = 0;
        $max_allowed = 1;
    }
    if ($editing_booking_from_backend) {
        // in the admin itf, and editing a booking
        // then the avail seats are the total seats
        if (eme_is_multi($event['event_seats'])) {
            $avail_seats = eme_get_multitotal($event['event_seats']);
        } else {
            $avail_seats = $event['event_seats'];
        }
    } else {
        // the next gives the number of available seats, even for multiprice
        $avail_seats = eme_get_available_seats($event_id);
    }
    $booked_places_options = array();
    if (eme_is_multi($max_allowed)) {
        $multi_max_allowed = eme_convert_multi2array($max_allowed);
        $max_allowed_is_multi = 1;
    } else {
        $max_allowed_is_multi = 0;
    }
    if (eme_is_multi($min_allowed)) {
        $multi_min_allowed = eme_convert_multi2array($min_allowed);
        $min_allowed_is_multi = 1;
    } else {
        $min_allowed_is_multi = 0;
    }
    if (eme_is_multi($event['event_seats'])) {
        // in the admin itf, and editing a booking
        // then the avail seats are the total seats
        if ($editing_booking_from_backend) {
            $multi_avail = eme_convert_multi2array($event['event_seats']);
        } else {
            $multi_avail = eme_get_available_multiseats($event_id);
        }
        foreach ($multi_avail as $key => $avail_seats) {
            $booked_places_options[$key] = array();
            if ($max_allowed_is_multi) {
                $real_max_allowed = $multi_max_allowed[$key];
            } else {
                $real_max_allowed = $max_allowed;
            }
            // don't let people choose more seats than available
            if ($real_max_allowed > $avail_seats || $real_max_allowed == 0) {
                $real_max_allowed = $avail_seats;
            }
            if ($min_allowed_is_multi) {
                $real_min_allowed = $multi_min_allowed[$key];
            } else {
                // it's no use to have a non-multi minimum for multiseats
                $real_min_allowed = 0;
            }
            for ($i = $real_min_allowed; $i <= $real_max_allowed; $i++) {
                $booked_places_options[$key][$i] = $i;
            }
        }
    } elseif (eme_is_multi($event['price'])) {
        // we just need to loop through the same amount of seats as there are prices
        foreach (eme_convert_multi2array($event['price']) as $key => $value) {
            $booked_places_options[$key] = array();
            if ($max_allowed_is_multi) {
                $real_max_allowed = $multi_max_allowed[$key];
            } else {
                $real_max_allowed = $max_allowed;
            }
            // don't let people choose more seats than available
            if ($real_max_allowed > $avail_seats || $real_max_allowed == 0) {
                $real_max_allowed = $avail_seats;
            }
            if ($min_allowed_is_multi) {
                $real_min_allowed = $multi_min_allowed[$key];
            } else {
                // it's no use to have a non-multi minimum for multiseats/multiprice
                $real_min_allowed = 0;
            }
            for ($i = $real_min_allowed; $i <= $real_max_allowed; $i++) {
                $booked_places_options[$key][$i] = $i;
            }
        }
    } else {
        if ($max_allowed_is_multi) {
            $real_max_allowed = $multi_max_allowed[0];
        } else {
            $real_max_allowed = $max_allowed;
        }
        // don't let people choose more seats than available
        if ($real_max_allowed > $avail_seats || $real_max_allowed == 0) {
            $real_max_allowed = $avail_seats;
        }
        if ($min_allowed_is_multi) {
            $real_min_allowed = $multi_min_allowed[0];
        } else {
            $real_min_allowed = $min_allowed;
        }
        for ($i = $real_min_allowed; $i <= $real_max_allowed; $i++) {
            $booked_places_options[$i] = $i;
        }
    }
    $required_fields_count = 0;
    $eme_captcha_for_booking = get_option('eme_captcha_for_booking');
    # we need 4 required fields: #_NAME, #_EMAIL, #_SEATS and #_SUBMIT
    # for multiprice: 3 + number of possible prices (we add those later on)
    if (eme_is_multi($event['price'])) {
        $required_fields_min = 3;
    } else {
        $required_fields_min = 4;
    }
    // if we require the captcha: add 1
    if (!$is_admin && $eme_captcha_for_booking) {
        $required_fields_min++;
    }
    // for multi booking forms, the required field count per booking form is 1 (SEATS)
    if (!$is_admin && $eme_multibooking) {
        $required_fields_min = 1;
    }
    $bookerLastName = "";
    $bookerFirstName = "";
    $bookerAddress1 = "";
    $bookerAddress2 = "";
    $bookerCity = "";
    $bookerState = "";
    $bookerZip = "";
    $bookerCountry = "";
    $bookerEmail = "";
    $bookerComment = "";
    $bookerPhone = "";
    $bookedSeats = 0;
    if (is_user_logged_in()) {
        get_currentuserinfo();
        $bookerLastName = $current_user->user_lastname;
        if (empty($bookerLastName)) {
            $bookerLastName = $current_user->display_name;
        }
        $bookerFirstName = $current_user->user_firstname;
        $bookerEmail = $current_user->user_email;
    }
    if ($editing_booking_from_backend) {
        $person = eme_get_person($booking['person_id']);
        // when editing a booking
        $bookerLastName = eme_sanitize_html($person['lastname']);
        $bookerFirstName = eme_sanitize_html($person['firstname']);
        $bookerAddress1 = eme_sanitize_html($person['address1']);
        $bookerAddress2 = eme_sanitize_html($person['address2']);
        $bookerCity = eme_sanitize_html($person['city']);
        $bookerState = eme_sanitize_html($person['state']);
        $bookerZip = eme_sanitize_html($person['zip']);
        $bookerCountry = eme_sanitize_html($person['country']);
        $bookerEmail = eme_sanitize_html($person['email']);
        $bookerPhone = eme_sanitize_html($person['phone']);
        $bookerComment = eme_sanitize_html($booking['booking_comment']);
        $bookedSeats = eme_sanitize_html($booking['booking_seats']);
        if ($booking['booking_seats_mp']) {
            $booking_seats_mp = eme_convert_multi2array($booking['booking_seats_mp']);
            foreach ($booking_seats_mp as $key => $val) {
                $field_index = $key + 1;
                ${"bookedSeats" . $field_index} = eme_sanitize_html($val);
            }
        }
    } else {
        // check for previously filled in data
        // this in case people entered a wrong captcha
        if (isset($_POST['lastname'])) {
            $bookerLastName = eme_sanitize_html(stripslashes_deep($_POST['lastname']));
        }
        if (isset($_POST['firstname'])) {
            $bookerFirstName = eme_sanitize_html(stripslashes_deep($_POST['firstname']));
        }
        if (isset($_POST['address1'])) {
            $bookerAddress1 = eme_sanitize_html(stripslashes_deep($_POST['address1']));
        }
        if (isset($_POST['address2'])) {
            $bookerAddress2 = eme_sanitize_html(stripslashes_deep($_POST['address2']));
        }
        if (isset($_POST['city'])) {
            $bookerCity = eme_sanitize_html(stripslashes_deep($_POST['city']));
        }
        if (isset($_POST['state'])) {
            $bookerState = eme_sanitize_html(stripslashes_deep($_POST['state']));
        }
        if (isset($_POST['zip'])) {
            $bookerZip = eme_sanitize_html(stripslashes_deep($_POST['zip']));
        }
        if (isset($_POST['country'])) {
            $bookerCountry = eme_sanitize_html(stripslashes_deep($_POST['country']));
        }
        if (isset($_POST['email'])) {
            $bookerEmail = eme_sanitize_html(stripslashes_deep($_POST['email']));
        }
        if (isset($_POST['phone'])) {
            $bookerPhone = eme_sanitize_html(stripslashes_deep($_POST['phone']));
        }
        if (isset($_POST['comment'])) {
            $bookerComment = eme_sanitize_html(stripslashes_deep($_POST['comment']));
        }
    }
    // first we do the custom attributes, since these can contain other placeholders
    preg_match_all("/#(ESC|URL)?_ATT\\{.+?\\}(\\{.+?\\})?/", $format, $results);
    foreach ($results[0] as $resultKey => $result) {
        $need_escape = 0;
        $need_urlencode = 0;
        $orig_result = $result;
        if (strstr($result, '#ESC')) {
            $result = str_replace("#ESC", "#", $result);
            $need_escape = 1;
        } elseif (strstr($result, '#URL')) {
            $result = str_replace("#URL", "#", $result);
            $need_urlencode = 1;
        }
        $replacement = "";
        //Strip string of placeholder and just leave the reference
        $attRef = substr(substr($result, 0, strpos($result, '}')), 6);
        if (isset($event['event_attributes'][$attRef])) {
            $replacement = $event['event_attributes'][$attRef];
        }
        if (trim($replacement) == '' && isset($results[2][$resultKey]) && $results[2][$resultKey] != '') {
            //Check to see if we have a second set of braces;
            $replacement = substr($results[2][$resultKey], 1, strlen(trim($results[2][$resultKey])) - 2);
        }
        if ($need_escape) {
            $replacement = eme_sanitize_request(eme_sanitize_html(preg_replace('/\\n|\\r/', '', $replacement)));
        }
        if ($need_urlencode) {
            $replacement = rawurlencode($replacement);
        }
        $format = str_replace($orig_result, $replacement, $format);
    }
    // the 2 placeholders that can contain extra text are treated seperately first
    // the question mark is used for non greedy (minimal) matching
    if (preg_match('/#_CAPTCHAHTML\\{.+\\}/', $format)) {
        // only show the captcha when booking via the frontend, not the admin backend
        if (!$is_admin && $eme_captcha_for_booking) {
            $format = preg_replace('/#_CAPTCHAHTML\\{(.+?)\\}/', '$1', $format);
        } else {
            $format = preg_replace('/#_CAPTCHAHTML\\{(.+?)\\}/', '', $format);
        }
    }
    if (preg_match('/#_SUBMIT\\{.+\\}/', $format)) {
        if ($editing_booking_from_backend) {
            $format = preg_replace('/#_SUBMIT\\{(.+?)\\}/', "<input name='eme_submit_button' class='eme_submit_button' type='submit' value='" . __('Update booking', 'eme') . "' />", $format);
        } else {
            $format = preg_replace('/#_SUBMIT\\{(.+?)\\}/', "<input name='eme_submit_button' class='eme_submit_button' type='submit' value='" . eme_trans_sanitize_html('$1') . "' />", $format);
        }
        if (!$eme_multibooking) {
            $required_fields_count++;
        }
    }
    $deprecated = get_option('eme_deprecated');
    if ($deprecated && preg_match('/#_CAPTCHAHTML\\[.+\\]/', $format)) {
        // only show the captcha when booking via the frontend, not the admin backend
        if (!$is_admin && $eme_captcha_for_booking) {
            $format = preg_replace('/#_CAPTCHAHTML\\[(.+?)\\]/', '$1', $format);
        } else {
            $format = preg_replace('/#_CAPTCHAHTML\\[(.+?)\\]/', '', $format);
        }
    }
    if ($deprecated && preg_match('/#_SUBMIT\\[.+\\]/', $format)) {
        if ($editing_booking_from_backend) {
            $format = preg_replace('/#_SUBMIT\\[(.+?)\\]/', "<input name='eme_submit_button' class='eme_submit_button' type='submit' value='" . __('Update booking', 'eme') . "' />", $format);
        } else {
            $format = preg_replace('/#_SUBMIT\\[(.+?)\\]/', "<input name='eme_submit_button' class='eme_submit_button' type='submit' value='" . eme_trans_sanitize_html('$1') . "' />", $format);
        }
        if (!$eme_multibooking) {
            $required_fields_count++;
        }
    }
    // now the normal placeholders
    preg_match_all("/#(REQ)?_?[A-Z0-9_]+(\\{[A-Z0-9_]+\\})?/", $format, $placeholders);
    // make sure we set the largest matched placeholders first, otherwise if you found e.g.
    // #_LOCATION, part of #_LOCATIONPAGEURL would get replaced as well ...
    usort($placeholders[0], 'sort_stringlenth');
    # we need 3 required fields: #_NAME, #_EMAIL and #_SEATS
    # if these are not present: we don't replace anything and the form is worthless
    foreach ($placeholders[0] as $result) {
        $orig_result = $result;
        $found = 1;
        $required = 0;
        $required_att = "";
        $html5_wanted = 0;
        $replacement = "";
        if (strstr($result, '#REQ')) {
            $result = str_replace("#REQ", "#", $result);
            $required = 1;
            $required_att = "required='required'";
        }
        // also support RESPNAME, RESPEMAIL, ...
        if (strstr($result, '#_RESP')) {
            $result = str_replace("#_RESP", "#_", $result);
        }
        if ($eme_multibooking) {
            $var_prefix = "bookings[{$event_id}][";
            $var_postfix = "]";
        } else {
            $var_prefix = '';
            $var_postfix = '';
        }
        if (preg_match('/#_NAME|#_LASTNAME/', $result)) {
            if (!$eme_multibooking) {
                $replacement = "<input required='required' type='text' name='{$var_prefix}lastname{$var_postfix}' value='{$bookerLastName}' {$readonly} />";
                $required_fields_count++;
                // #_NAME is always required
                $required = 1;
            }
        } elseif (preg_match('/#_FIRSTNAME/', $result)) {
            if (!empty($bookerFirstName)) {
                $replacement = "<input {$required_att} type='text' name='{$var_prefix}firstname{$var_postfix}' value='{$bookerFirstName}' {$readonly} />";
            } else {
                $replacement = "<input {$required_att} type='text' name='{$var_prefix}firstname{$var_postfix}' value='{$bookerFirstName}' />";
            }
        } elseif (preg_match('/#_ADDRESS1/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}address1{$var_postfix}' value='{$bookerAddress1}' />";
        } elseif (preg_match('/#_ADDRESS2/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}address2{$var_postfix}' value='{$bookerAddress2}' />";
        } elseif (preg_match('/#_CITY/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}city{$var_postfix}' value='{$bookerCity}' />";
        } elseif (preg_match('/#_STATE/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}state{$var_postfix}' value='{$bookerState}' />";
        } elseif (preg_match('/#_ZIP/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}zip{$var_postfix}' value='{$bookerZip}' />";
        } elseif (preg_match('/#_COUNTRY/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}country{$var_postfix}' value='{$bookerCountry}' />";
        } elseif (preg_match('/#_HTML5_EMAIL/', $result)) {
            if (!$eme_multibooking) {
                $replacement = "<input required='required' type='email' name='{$var_prefix}email{$var_postfix}' value='{$bookerEmail}' {$readonly} />";
                $required_fields_count++;
                // #_EMAIL is always required
                $required = 1;
            }
        } elseif (preg_match('/#_EMAIL/', $result)) {
            if (!$eme_multibooking) {
                $replacement = "<input required='required' type='text' name='{$var_prefix}email{$var_postfix}' value='{$bookerEmail}' {$readonly} />";
                $required_fields_count++;
                // #_EMAIL is always required
                $required = 1;
            }
        } elseif (preg_match('/#_HTML5_PHONE/', $result)) {
            $replacement = "<input {$required_att} type='tel' name='{$var_prefix}phone{$var_postfix}' value='{$bookerPhone}' />";
        } elseif (preg_match('/#_PHONE/', $result)) {
            $replacement = "<input {$required_att} type='text' name='{$var_prefix}phone{$var_postfix}' value='{$bookerPhone}' />";
        } elseif (preg_match('/#_SEATS$|#_SPACES$/', $result)) {
            $postfield_name = "{$var_prefix}bookedSeats{$var_postfix}";
            if ($editing_booking_from_backend && isset($bookedSeats)) {
                $entered_val = $bookedSeats;
            } elseif ($eme_multibooking && isset($_POST['bookings'][$event_id]) && isset($_POST['bookings'][$event_id]['bookedSeats'])) {
                $entered_val = intval($_POST['bookings'][$event_id]['bookedSeats']);
            } elseif (isset($_POST['bookedSeats'])) {
                $entered_val = intval($_POST['bookedSeats']);
            } else {
                $entered_val = 0;
            }
            if ($event['event_properties']['take_attendance']) {
                $replacement = eme_ui_select_binary($entered_val, $postfield_name);
            } else {
                $replacement = eme_ui_select($entered_val, $postfield_name, $booked_places_options);
            }
            $required_fields_count++;
        } elseif ($deprecated && preg_match('/#_(SEATS|SPACES)(\\d+)/', $result, $matches) || preg_match('/#_(SEATS|SPACES)\\{(\\d+)\\}/', $result, $matches)) {
            $field_id = intval($matches[2]);
            $postfield_name = "{$var_prefix}bookedSeats" . $field_id . $var_postfix;
            if ($editing_booking_from_backend && isset(${"bookedSeats" . $field_id})) {
                $entered_val = ${"bookedSeats" . $field_id};
            } elseif ($eme_multibooking && isset($_POST['bookings'][$event_id]) && isset($_POST['bookings'][$event_id]['bookedSeats' . $field_id])) {
                $entered_val = intval($_POST['bookings'][$event_id]['bookedSeats' . $field_id]);
            } elseif (isset($_POST['bookedSeats' . $field_id])) {
                $entered_val = intval($_POST['bookedSeats' . $field_id]);
            } else {
                $entered_val = 0;
            }
            if (eme_is_multi($event['event_seats']) || eme_is_multi($event['price'])) {
                if ($event['event_properties']['take_attendance']) {
                    $replacement = eme_ui_select_binary($entered_val, $postfield_name);
                } else {
                    $replacement = eme_ui_select($entered_val, $postfield_name, $booked_places_options[$field_id - 1]);
                }
            } else {
                if ($event['event_properties']['take_attendance']) {
                    $replacement = eme_ui_select_binary($entered_val, $postfield_name);
                } else {
                    $replacement = eme_ui_select($entered_val, $postfield_name, $booked_places_options);
                }
            }
            $required_fields_count++;
        } elseif (preg_match('/#_COMMENT/', $result)) {
            if (!$eme_multibooking) {
                $replacement = "<textarea {$required_att} name='{$var_prefix}comment{$var_postfix}'>{$bookerComment}</textarea>";
            }
        } elseif (preg_match('/#_CAPTCHA/', $result) && $eme_captcha_for_booking) {
            if (!$eme_multibooking) {
                $replacement = "<img src='" . EME_PLUGIN_URL . "captcha.php?sessionvar=eme_add_booking'><br /><input required='required' type='text' name='captcha_check' autocomplete='off' />";
                $required_fields_count++;
            }
        } elseif ($deprecated && preg_match('/#_FIELDNAME(\\d+)/', $result, $matches) || preg_match('/#_FIELDNAME\\{(\\d+)\\}/', $result, $matches)) {
            $field_id = intval($matches[1]);
            $formfield = eme_get_formfield_byid($field_id);
            $replacement = eme_trans_sanitize_html($formfield['field_name']);
        } elseif ($deprecated && preg_match('/#_FIELD(\\d+)/', $result, $matches) || preg_match('/#_FIELD\\{(\\d+)\\}/', $result, $matches)) {
            $field_id = intval($matches[1]);
            $postfield_name = "{$var_prefix}FIELD" . $field_id . $var_postfix;
            $entered_val = "";
            if ($booking) {
                $answers = eme_get_answers($booking['booking_id']);
                $formfield = eme_get_formfield_byid($field_id);
                foreach ($answers as $answer) {
                    if ($answer['field_name'] == $formfield['field_name']) {
                        // the entered value for the function eme_get_formfield_html needs to be an array for multiple values
                        // since we store them with "||", we can use the good old eme_is_multi function and split in an array then
                        $entered_val = $answer['answer'];
                        if (eme_is_multi($entered_val)) {
                            $entered_val = eme_convert_multi2array($entered_val);
                        }
                    }
                }
            } elseif (isset($_POST[$postfield_name])) {
                $entered_val = stripslashes_deep($_POST[$postfield_name]);
            }
            $replacement = eme_get_formfield_html($field_id, $entered_val, $required);
        } elseif (preg_match('/#_SUBMIT/', $result, $matches)) {
            if (!$eme_multibooking) {
                if ($editing_booking_from_backend) {
                    $replacement = "<input name='eme_submit_button' type='submit' value='" . __('Update booking', 'eme') . "' />";
                } else {
                    $replacement = "<input name='eme_submit_button' type='submit' value='" . eme_trans_sanitize_html(get_option('eme_rsvp_addbooking_submit_string')) . "' />";
                }
                $required_fields_count++;
            }
        } else {
            $found = 0;
        }
        if ($required) {
            $replacement .= "<div class='eme-required-field'>&nbsp;" . __('(Required field)', 'eme') . "</div>";
        }
        if ($found) {
            $format = str_replace($orig_result, $replacement, $format);
        }
    }
    // now any leftover event placeholders
    $format = eme_replace_placeholders($format, $event);
    // now, replace any language tags found in the format itself
    $format = eme_translate($format);
    # we need 4 required fields: #_NAME, #_EMAIL, #_SEATS and #_SUBMIT
    # for multiprice: 3 + number of possible prices
    # if these are not present: we don't replace anything and the form is worthless
    if (eme_is_multi($event['price'])) {
        $matches = preg_split('/\\|\\|/', $event['price']);
        $count = count($matches);
        // the count can be >3+$count if conditional tags are used to combine a form for single and multiple prices
        if ($required_fields_count >= $required_fields_min + $count) {
            return $format;
        } else {
            $res = __('Not all required fields are present in the booking form.', 'eme');
            $res .= '<br />' . __("Since this is a multiprice event, make sure you changed the setting 'Registration Form Format' for the event to include #_SEATxx placeholders for each price.", 'eme');
            $res .= '<br />' . __("See the documentation about multiprice events.", 'eme');
            return "<div id='message' class='eme-rsvp-message'>{$res}</div>";
        }
    } elseif ($required_fields_count >= $required_fields_min) {
        // the count can be > 4 if conditional tags are used to combine a form for single and multiple prices
        return $format;
    } else {
        return __('Not all required fields are present in the booking form.', 'eme');
    }
}
Example #7
0
function eme_general_head()
{
    $extra_html_header = get_option('eme_html_header');
    $extra_html_header = trim(preg_replace('/\\r\\n/', "\n", $extra_html_header));
    if (!empty($extra_html_header)) {
        echo $extra_html_header . "\n";
    }
    if (eme_is_single_event_page()) {
        $event = eme_get_event(get_query_var('event_id'));
        // I don't know if the canonical rel-link is needed, but since WP adds it by default ...
        $canon_url = eme_event_url($event);
        echo "<link rel=\"canonical\" href=\"{$canon_url}\" />\n";
        $extra_headers_format = get_option('eme_event_html_headers_format');
        if (!empty($extra_headers_format)) {
            $extra_headers_lines = explode("\n", $extra_headers_format);
            foreach ($extra_headers_lines as $extra_header_format) {
                # the text format already removes most of html code, so let's use that
                $extra_header = strip_shortcodes(eme_replace_placeholders($extra_header_format, $event, "text", 0));
                # the text format converts \n to \r\n but we want one line only
                $extra_header = trim(preg_replace('/\\r\\n/', "", $extra_header));
                if ($extra_header != "") {
                    echo $extra_header . "\n";
                }
            }
        }
    } elseif (eme_is_single_location_page()) {
        $location = eme_get_location(get_query_var('location_id'));
        $canon_url = eme_location_url($location);
        echo "<link rel=\"canonical\" href=\"{$canon_url}\" />\n";
        $extra_headers_format = get_option('eme_location_html_headers_format');
        if (!empty($extra_headers_format)) {
            $extra_headers_lines = explode("\n", $extra_headers_format);
            foreach ($extra_headers_lines as $extra_header_format) {
                # the text format already removes most of html code, so let's use that
                $extra_header = strip_shortcodes(eme_replace_locations_placeholders($extra_header_format, $location, "text", 0));
                # the text format converts \n to \r\n but we want one line only
                $extra_header = trim(preg_replace('/\\r\\n/', "", $extra_header));
                if (!empty($extra_header)) {
                    echo $extra_header . "\n";
                }
            }
        }
    }
    $gmap_is_active = get_option('eme_gmap_is_active');
    $load_js_in_header = get_option('eme_load_js_in_header');
    if ($gmap_is_active && $load_js_in_header) {
        echo "<script type='text/javascript' src='//maps.google.com/maps/api/js?v=3.16&amp;sensor=false'></script>\n";
        echo "<script type='text/javascript' src='" . EME_PLUGIN_URL . "js/eme_location_map.js'></script>\n";
    }
}
Example #8
0
function eme_get_calendar($args = "")
{
    global $wp_locale;
    global $wpdb, $eme_timezone;
    // the calendar is being used, so we need the jquery for the calendar
    global $eme_need_calendar_js;
    $eme_need_calendar_js = 1;
    $defaults = array('category' => 0, 'notcategory' => 0, 'full' => 0, 'month' => '', 'year' => '', 'echo' => 1, 'long_events' => 0, 'author' => '', 'contact_person' => '', 'location_id' => '', 'template_id' => 0);
    $r = wp_parse_args($args, $defaults);
    extract($r);
    $echo = $echo === "true" || $echo === "1" ? true : $echo;
    $full = $full === "true" || $full === "1" ? true : $full;
    $long_events = $long_events === "true" || $long_events === "1" ? true : $long_events;
    $echo = $echo === "false" || $echo === "0" ? false : $echo;
    $full = $full === "false" || $full === "0" ? false : $full;
    $long_events = $long_events === "false" || $long_events === "0" ? false : $long_events;
    // this comes from global wordpress preferences
    $start_of_week = get_option('start_of_week');
    $eme_date_obj = new ExpressiveDate(null, $eme_timezone);
    if (get_option('eme_use_client_clock') && isset($_SESSION['eme_client_mday']) && isset($_SESSION['eme_client_month']) && isset($_SESSION['eme_client_fullyear'])) {
        // these come from client unless their clock is wrong
        $iNowDay = sprintf("%02d", $_SESSION['eme_client_mday']);
        $iNowMonth = sprintf("%02d", $_SESSION['eme_client_month']);
        $iNowYear = sprintf("%04d", $_SESSION['eme_client_fullyear']);
    } else {
        // Get current year, month and day
        list($iNowYear, $iNowMonth, $iNowDay) = explode('-', $eme_date_obj->getDate());
    }
    $iSelectedYear = $year;
    $iSelectedMonth = $month;
    if ($iSelectedMonth == '') {
        $iSelectedMonth = $iNowMonth;
    }
    if ($iSelectedYear == '') {
        $iSelectedYear = $iNowYear;
    }
    $iSelectedMonth = sprintf("%02d", $iSelectedMonth);
    // Get name and number of days of specified month
    $eme_date_obj->setDay(1);
    $eme_date_obj->setMonth($iSelectedMonth);
    $eme_date_obj->setYear($iSelectedYear);
    // Get friendly month name, but since DateTime::format doesn't respect the locale, we need eme_localised_date
    if ($full) {
        list($sMonthName, $iDaysInMonth) = explode('-', eme_localised_date($eme_date_obj->getDate(), 'F-t'));
    } else {
        list($sMonthName, $iDaysInMonth) = explode('-', eme_localised_date($eme_date_obj->getDate(), 'M-t'));
    }
    // take into account some locale info: some always best show full month name, some show month after year, some have a year suffix
    $locale_code = substr(get_locale(), 0, 2);
    $showMonthAfterYear = 0;
    $yearSuffix = "";
    switch ($locale_code) {
        case "hu":
            $showMonthAfterYear = 1;
            break;
        case "ja":
            $showMonthAfterYear = 1;
            $sMonthName = eme_localised_date($eme_date_obj->getDate(), 'F');
            $yearSuffix = "年";
            break;
        case "ko":
            $showMonthAfterYear = 1;
            $sMonthName = eme_localised_date($eme_date_obj->getDate(), 'F');
            $yearSuffix = "년";
            break;
        case "zh":
            $showMonthAfterYear = 1;
            $sMonthName = eme_localised_date($eme_date_obj->getDate(), 'F');
            $yearSuffix = "年";
            break;
    }
    if ($showMonthAfterYear) {
        $cal_datestring = "{$iSelectedYear}{$yearSuffix} {$sMonthName}";
    } else {
        $cal_datestring = "{$sMonthName} {$iSelectedYear}{$yearSuffix}";
    }
    // Get previous year and month
    $iPrevYear = $iSelectedYear;
    $iPrevMonth = $iSelectedMonth - 1;
    if ($iPrevMonth <= 0) {
        $iPrevYear--;
        $iPrevMonth = 12;
        // set to December
    }
    $iPrevMonth = sprintf("%02d", $iPrevMonth);
    // Get next year and month
    $iNextYear = $iSelectedYear;
    $iNextMonth = $iSelectedMonth + 1;
    if ($iNextMonth > 12) {
        $iNextYear++;
        $iNextMonth = 1;
    }
    $iNextMonth = sprintf("%02d", $iNextMonth);
    // Get number of days of previous month
    $eme_date_obj2 = new ExpressiveDate(null, $eme_timezone);
    $eme_date_obj2->setDay(1);
    $eme_date_obj2->setMonth($iPrevMonth);
    $eme_date_obj2->setYear($iPrevYear);
    $iPrevDaysInMonth = (int) $eme_date_obj2->getDaysInMonth();
    // Get numeric representation of the day of the week of the first day of specified (current) month
    // remember: first day of week is a Sunday
    // if you want the day of the week to begin on Monday: start_of_week=1, Tuesday: start_of_week=2, etc ...
    // So, if e.g. the month starts on a Sunday and start_of_week=1 (Monday), then $iFirstDayDow is 6
    $iFirstDayDow = (int) $eme_date_obj->getDayOfWeekAsNumeric() - $start_of_week;
    if ($iFirstDayDow < 0) {
        $iFirstDayDow += 7;
    }
    // On what day the previous month begins
    $iPrevShowFrom = $iPrevDaysInMonth - $iFirstDayDow + 1;
    // we'll look for events in the requested month and 7 days before and after
    $calbegin = "{$iPrevYear}-{$iPrevMonth}-{$iPrevShowFrom}";
    $calend = "{$iNextYear}-{$iNextMonth}-07";
    $events = eme_get_events(0, "{$calbegin}--{$calend}", "ASC", 0, $location_id, $category, $author, $contact_person, 1, $notcategory);
    $eventful_days = array();
    if ($events) {
        //Go through the events and slot them into the right d-m index
        foreach ($events as $event) {
            if ($event['event_status'] == STATUS_PRIVATE && !is_user_logged_in()) {
                continue;
            }
            $eme_date_obj_end = new ExpressiveDate($event['event_end_date'] . " " . $event['event_end_time'], $eme_timezone);
            $eme_date_obj_now = new ExpressiveDate(null, $eme_timezone);
            if (get_option('eme_cal_hide_past_events') && $eme_date_obj_end->lessThan($eme_date_obj_now)) {
                continue;
            }
            if ($long_events) {
                //If $long_events is set then show a date as eventful if there is an multi-day event which runs during that day
                $eme_date_obj_tmp = new ExpressiveDate($event['event_start_date'] . " " . $event['event_start_time'], $eme_timezone);
                if ($eme_date_obj_end->lessThan($eme_date_obj_tmp)) {
                    $eme_date_obj_end = $eme_date_obj_tmp->copy();
                }
                $day_count = 0;
                while ($eme_date_obj_tmp->lessOrEqualTo($eme_date_obj_end)) {
                    $event_eventful_date = $eme_date_obj_tmp->getDate();
                    //Only show events on the day that they start
                    if (isset($eventful_days[$event_eventful_date]) && is_array($eventful_days[$event_eventful_date])) {
                        $eventful_days[$event_eventful_date][] = $event;
                    } else {
                        $eventful_days[$event_eventful_date] = array($event);
                    }
                    $eme_date_obj_tmp->addOneDay();
                }
            } else {
                //Only show events on the day that they start
                if (isset($eventful_days[$event['event_start_date']]) && is_array($eventful_days[$event['event_start_date']])) {
                    $eventful_days[$event['event_start_date']][] = $event;
                } else {
                    $eventful_days[$event['event_start_date']] = array($event);
                }
            }
        }
    }
    // we found all the events for the wanted days, now get them in the correct format with a good link
    if ($template_id) {
        $event_format = eme_get_template_format($template_id);
    } else {
        $event_format = get_option('eme_full_calendar_event_format');
    }
    $event_title_format = get_option('eme_small_calendar_event_title_format');
    $event_title_separator_format = get_option('eme_small_calendar_event_title_separator');
    $cells = array();
    foreach ($eventful_days as $day_key => $events) {
        // Set the date into the key
        $events_titles = array();
        foreach ($events as $event) {
            $events_titles[] = eme_replace_placeholders($event_title_format, $event, "text");
        }
        $link_title = implode($event_title_separator_format, $events_titles);
        $cal_day_link = eme_calendar_day_url($day_key);
        // Let's add the possible options
        // template_id is not being used per event
        if (!empty($location_id)) {
            $cal_day_link = add_query_arg(array('location_id' => $location_id), $cal_day_link);
        }
        if (!empty($category)) {
            $cal_day_link = add_query_arg(array('category' => $category), $cal_day_link);
        }
        if (!empty($notcategory)) {
            $cal_day_link = add_query_arg(array('notcategory' => $scope), $cal_day_link);
        }
        if (!empty($author)) {
            $cal_day_link = add_query_arg(array('author' => $author), $cal_day_link);
        }
        if (!empty($contact_person)) {
            $cal_day_link = add_query_arg(array('contact_person' => $contact_person), $cal_day_link);
        }
        $event_date = explode('-', $day_key);
        $event_day = ltrim($event_date[2], '0');
        $cells[$day_key] = "<a title='{$link_title}' href='{$cal_day_link}'>{$event_day}</a>";
        if ($full) {
            $cells[$day_key] .= "<ul class='eme-calendar-day-event'>";
            foreach ($events as $event) {
                $cells[$day_key] .= eme_replace_placeholders($event_format, $event);
            }
            $cells[$day_key] .= "</ul>";
        }
    }
    // If previous month
    $isPreviousMonth = $iFirstDayDow > 0;
    // Initial day on the calendar
    $iCalendarDay = $isPreviousMonth ? $iPrevShowFrom : 1;
    $isNextMonth = false;
    $sCalTblRows = '';
    // Generate rows for the calendar
    for ($i = 0; $i < 6; $i++) {
        // 6-weeks range
        if ($isNextMonth) {
            continue;
        }
        $sCalTblRows .= "<tr>";
        for ($j = 0; $j < 7; $j++) {
            // 7 days a week
            // we need the calendar day with 2 digits for the planned events
            $iCalendarDay_padded = sprintf("%02d", $iCalendarDay);
            if ($isPreviousMonth) {
                $calstring = "{$iPrevYear}-{$iPrevMonth}-{$iCalendarDay_padded}";
            } elseif ($isNextMonth) {
                $calstring = "{$iNextYear}-{$iNextMonth}-{$iCalendarDay_padded}";
            } else {
                $calstring = "{$iSelectedYear}-{$iSelectedMonth}-{$iCalendarDay_padded}";
            }
            // each day in the calendar has the name of the day as a class by default
            $eme_date_obj = new ExpressiveDate($calstring, $eme_timezone);
            $sClass = $eme_date_obj->format('D');
            if (isset($cells[$calstring])) {
                if ($isPreviousMonth) {
                    $sClass .= " eventful-pre event-day-{$iCalendarDay}";
                } elseif ($isNextMonth) {
                    $sClass .= " eventful-post event-day-{$iCalendarDay}";
                } elseif ($calstring == "{$iNowYear}-{$iNowMonth}-{$iNowDay}") {
                    $sClass .= " eventful-today event-day-{$iCalendarDay}";
                } else {
                    $sClass .= " eventful event-day-{$iCalendarDay}";
                }
                $sCalTblRows .= '<td class="' . $sClass . '">' . $cells[$calstring] . "</td>\n";
            } else {
                if ($isPreviousMonth) {
                    $sClass .= " eventless-pre";
                } elseif ($isNextMonth) {
                    $sClass .= " eventless-post";
                } elseif ($calstring == "{$iNowYear}-{$iNowMonth}-{$iNowDay}") {
                    $sClass .= " eventless-today";
                } else {
                    $sClass .= " eventless";
                }
                $sCalTblRows .= '<td class="' . $sClass . '">' . $iCalendarDay . "</td>\n";
            }
            // Next day
            $iCalendarDay++;
            if ($isPreviousMonth && $iCalendarDay > $iPrevDaysInMonth) {
                $isPreviousMonth = false;
                $iCalendarDay = 1;
            }
            if (!$isPreviousMonth && !$isNextMonth && $iCalendarDay > $iDaysInMonth) {
                $isNextMonth = true;
                $iCalendarDay = 1;
            }
        }
        $sCalTblRows .= "</tr>\n";
    }
    $weekdays = array(__('Sunday'), __('Monday'), __('Tuesday'), __('Wednesday'), __('Thursday'), __('Friday'), __('Saturday'));
    $sCalDayNames = "";
    // respect the beginning of the week offset
    for ($i = $start_of_week; $i < $start_of_week + 7; $i++) {
        $j = $i;
        if ($j == 7) {
            $j -= 7;
        }
        if ($full) {
            $sCalDayNames .= "<td>" . $wp_locale->get_weekday_abbrev($weekdays[$j]) . "</td>";
        } else {
            $sCalDayNames .= "<td>" . $wp_locale->get_weekday_initial($weekdays[$j]) . "</td>";
        }
    }
    // the real links are created via jquery when clicking on the prev-month or next-month class-links
    $previous_link = "<a class='prev-month' href=\"#\">&lt;&lt;</a>";
    $next_link = "<a class='next-month' href=\"#\">&gt;&gt;</a>";
    $random = rand(100, 200);
    $full ? $class = 'eme-calendar-full' : ($class = 'eme-calendar');
    $calendar = "<div class='{$class}' id='eme-calendar-{$random}'>";
    if ($full) {
        $fullclass = 'fullcalendar';
        $head = "<td class='month_name' colspan='7'>{$previous_link} {$next_link} {$cal_datestring}</td>\n";
    } else {
        $fullclass = '';
        $head = "<td>{$previous_link}</td><td class='month_name' colspan='5'>{$cal_datestring}</td><td>{$next_link}</td>\n";
    }
    // Build the heading portion of the calendar table
    $calendar .= "<table class='eme-calendar-table {$fullclass}'>\n" . "<thead>\n<tr>\n" . $head . "</tr>\n</thead>\n" . "<tr class='days-names'>\n" . $sCalDayNames . "</tr>\n";
    $calendar .= $sCalTblRows;
    $calendar .= "</table>\n</div>";
    // we generate the onclick javascript per calendar div
    // this is important if more than one calendar exists on the page
    $calendar .= "<script type='text/javascript'>\n         jQuery('#eme-calendar-" . $random . " a.prev-month').click(function(e){\n            e.preventDefault();\n            tableDiv = jQuery('#eme-calendar-" . $random . "');\n            loadCalendar(tableDiv, '{$full}', '{$long_events}','{$iPrevMonth}','{$iPrevYear}','{$category}','{$author}','{$contact_person}','{$location_id}','{$notcategory}','{$template_id}');\n         } );\n         jQuery('#eme-calendar-" . $random . " a.next-month').click(function(e){\n            e.preventDefault();\n            tableDiv = jQuery('#eme-calendar-" . $random . "');\n            loadCalendar(tableDiv, '{$full}', '{$long_events}','{$iNextMonth}','{$iNextYear}','{$category}','{$author}','{$contact_person}','{$location_id}','{$notcategory}','{$template_id}');\n         } );\n         </script>";
    $output = $calendar;
    if ($echo) {
        echo $output;
    } else {
        return $output;
    }
}