Location: PHPKode > projects > ConCentric Event Planning Software > CC/system/application/controllers/concentric/eventparticipants.php
<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * MODULE NAME   : eventparticipants.php
 *
 * DESCRIPTION   : eventparticipants module controller
 *
 * MODIFICATION HISTORY
 *   V1.0   2008-11-13 12:00 PM   - Leane Verhulst     - Created
 *
 * @package			ConCentric
 * @subpackage		eventparticipants component Class
 * @author			Leane Verhulst
 * @copyright		Copyright (c) 2008
 * @license			http://www.gnu.org/licenses/gpl.html
 */

class Eventparticipants extends Concentric_Controller
{
	/**
	* Contructor function
	*
	* Load the instance of CI by invoking the parent constructor
	*
	* @access      public
	* @return      none
	*/
	function Eventparticipants()
	{
		// Call parent constructor
		parent::Concentric_Controller();

		$this->form_name = "EventParticipants";
		$this->load->model('eventparticipants_model');    // Instantiate the model
		// load helper library
		$this->load->helper('concentric');
	}

	// -------------------------------------------------------------------------
	/**
	* "Index" Page
	*
	* Default class action
	*
	* @access      public
	* @return      none
	*/
	function index($sortby = '')
	{
		// The default action is the browse action
		$this->browse($sortby);
	}

	// -------------------------------------------------------------------------
	// Function: browse()
	// Description: Extracts a list of all data records and
	//              displays it.
	function browse($sortby = '')
	{
		// get sort from cookie / save new sort to cookie
		$array = get_eventparticipants_sort($sortby);
		$sortname = $array['name'];
		$sortdirection = $array['direction'];
		$sortby = $array['sortby'];

		// fetch query object from the model
		$template['eventparticipants_list'] = $this->eventparticipants_model->fetchEventParticipants(NULL, $sortby);

		// create urls for use in content view
		$template['base_url']   = 'concentric/eventparticipants/browse/';
		$template['edit_url']   = 'concentric/eventparticipants/edit/';
		$template['delete_url'] = 'concentric/eventparticipants/delete/';
		$template['add_url']    = 'concentric/eventparticipants/add/';
		$template['cancel_url'] = 'concentric/home';
		$template['sort_url']['EventName']  = 'concentric/eventparticipants/browse/eventname';
		$template['sort_url']['ParticipantName']   = 'concentric/eventparticipants/browse/participantname';
		$template['sort_url']['Moderator']   = 'concentric/eventparticipants/browse/moderator';
		$template['sort_url']['Required']   = 'concentric/eventparticipants/browse/required';
		$template['sort_url']['Confirmed']   = 'concentric/eventparticipants/browse/confirmed';
		$template['sort']['name']          = $sortname;
		$template['sort']['direction']     = $sortdirection;

		// Set breadcrumb
		$this->page->set_crumb('Event Participants',$template['base_url']);

		// set values for use in content view
		$template['form_attributes'] = array('name' => $this->form_name, 'id' => $this->form_name);
		$template['header'] = $this->form_name;

		// build content html using grid view and template data
		$data['content'] = $this->load->view('/concentric/eventparticipants/eventparticipants_grid', $template, TRUE);

		// set values for use in header view
		$data['header']  = $this->form_name;

		// pass all data to container view and display to user
		$this->load->view($this->_container,$data);
	}

	// -------------------------------------------------------------------------
	// Function: add()
	// Description: Prompts user for input and adds a new entry
	//              in the database.
	function add()
	{
		$this->_modify('add');
	}

	// -------------------------------------------------------------------------
	// Function: edit()
	// Description: Prompts user for input and updates an entry
	//              in the database.
	function edit()
	{
		$this->_modify('edit');
	}

	// -------------------------------------------------------------------------
	// Function: modify()
	// Description: Prompts user for input and adds/edits an entry
	//              in the database. Default to add mode.
	function _modify($mode = 'add')
	{
		// Initialize variable
		$other_scripts_data = '';

		// load validation library to help validate data
		$this->load->library('validation');

		// load grid helper
		$this->load->helper('grid');

		// create urls and values for use in content view
		$template['form_url'] = 'concentric/eventparticipants/' . $mode . '/';
		$template['cancel_url'] = 'concentric/eventparticipants/browse';
		$template['form_attributes'] = array( 'method' => 'post', 'id' => $this->form_name, 'name' => $this->form_name );
		$template['header']  = $this->form_name;

		// Set breadcrumb
		$this->page->set_crumb('Event Participants',$template['cancel_url']);
		$this->page->set_crumb($mode,$template['form_url']);


		$this->_initialize();   // Setup the fields
		$this->_validation();   // Load the validation rules and fields


		// if validation has not run or if it failed
		if ( $this->validation->run() == FALSE )
		{
			// Save validation errors to flashmsg
			// Will be output in content view by status->display
			$this->validation->output_errors();

			// Get values for form fields and build the form fields
			$status = $this->_get_form_values($mode);

			// If the returned values got an error
			if ($status === FALSE)
			{
				// Show error message
				flashMsg('error','There was a problem editing that record.');
				// redirect to main location
				redirect('/concentric/eventparticipants/', 'location');
			}

			// Save field data to array to be passed to content view
			$template['fields'] = $this->fields;

			// build content html using details view and template data
			$data['content'] = $this->load->view('/concentric/details', $template, TRUE);
			// pass other scripts data to container
			$data['other_scripts'] = $other_scripts_data;

			// pass all data to container view and display to user
			$this->load->view($this->_container, $data);
		}
		else  // User is submitting valid data
		{
			// Store the values from the form into the db
			// XXS Filtering enforced for user input
			$data['field']['id']			= $this->input->post('id', TRUE);
			$data['field']['eventID']		= $this->input->post('eventID', TRUE);
			$data['field']['participantID']	= $this->input->post('participantID', TRUE);
			$data['field']['moderatorQ']	= $this->input->post('moderatorQ', TRUE);
			$data['field']['requiredQ']		= $this->input->post('requiredQ', TRUE);
			$data['field']['confirmedQ']	= $this->input->post('confirmedQ', TRUE);

			if ($mode == 'add')
			{
				// add the data to the table and return id
				$idField = $this->eventparticipants_model->addRow('eventParticipants',$data['field']);
				$status = ($idField) ? TRUE : FALSE;
			}
			else
			{
				$idField = $data['field']['id'];
				// update the data in the table
				$obj = $this->eventparticipants_model->update('eventParticipants', $data['field'], 'id = ' . $idField);
				$status = ($obj) ? TRUE : FALSE;
			}

			// if there was no error in add or edit
			if ($status)
			{
				// Show success message
				flashMsg('success','Record ' . $idField . ' has been saved.');
			}
			else  // there was an error
			{
				// Show error message
				flashMsg('error','The record has not been saved.');
			}

			// redirect to main location
			redirect('/concentric/eventparticipants/', 'location');
			// ?redirect to add/edit?
			// redirect('/concentric/eventparticipants/' . $mode . '/', 'location');
		}
	}

	// -------------------------------------------------------------------------
	// Function: delete()
	// Description: Controller function to process user delete requests
	function delete()
	{
		$idField = $this->uri->segment(4);

		//$confirm = $this->_delete_confirm($idField);  //add later
		$confirm = TRUE;

		if ($confirm)
		{
			if ( $this->eventparticipants_model->delete('eventParticipants', 'id =' . $idField) )
			{
				flashMsg('success', 'The record has been deleted.');
			}
			else
			{
				flashMsg('error', 'There was a problem deleting the record');
			}
		}

		redirect('/concentric/eventparticipants/', 'location');
	}

	// -------------------------------------------------------------------------
	function _delete_confirm($id)
	{
		//add later
	}

	// -------------------------------------------------------------------------
	// @access private
	function _get_form_values($mode = 'add')
	{
		if ($mode == 'add')
		{
			// Set empty values / default values
			$this->fields['id']['value'] = '';
			$this->fields['eventID']['value'] = '';
			$this->fields['eventID']['selected'] = 0;
			$this->fields['participantID']['value'] = '';
			$this->fields['participantID']['selected'] = 0;
			$this->fields['moderatorQ']['value'] = 1;
			$this->fields['moderatorQ']['checked'] = FALSE;
			$this->fields['requiredQ']['value'] = 1;
			$this->fields['requiredQ']['checked'] = FALSE;
			$this->fields['confirmedQ']['value'] = 1;
			$this->fields['confirmedQ']['checked'] = FALSE;
		}
		else
		{
			//get the id from either the hidden field or the url
			$idField = ($this->input->post('id', TRUE) != '') ? $this->input->post('id', TRUE) : $this->uri->segment(4);

			// fetch query object from the model with all fields
			$qry = $this->eventparticipants_model->fetch('eventParticipants','id, eventID, participantID, moderatorQ, requiredQ, confirmedQ','','id = ' . $idField);

			// There should only be 1 row. If not, return FALSE
			if ($qry->num_rows() != 1)
			{
				return FALSE;
			}

			// Get the single result as an array and save values
			$row = $qry->row_array();
			$this->fields['id']['value'] = $row['id'];
			$this->fields['eventID']['value'] = $row['eventID'];
			$this->fields['eventID']['selected'] = $row['eventID'];
			$this->fields['participantID']['value'] = $row['participantID'];
			$this->fields['participantID']['selected'] = $row['participantID'];
			$this->fields['moderatorQ']['value'] = 1;
			$this->fields['moderatorQ']['checked'] = ($row['moderatorQ']) ? TRUE : FALSE;
			$this->fields['requiredQ']['value'] = 1;
			$this->fields['requiredQ']['checked'] = ($row['requiredQ']) ? TRUE : FALSE;
			$this->fields['confirmedQ']['value'] = 1;
			$this->fields['confirmedQ']['checked'] = ($row['confirmedQ']) ? TRUE : FALSE;
		}

		// Now build the form fields
		foreach ($this->fields as $field)
		{
			$this->fields[$field['name']]['form'] = build_form_field($field);
		}

		return TRUE;
	}


	// -------------------------------------------------------------------------
	function _validation()
	{
		// load the rules
		$form_rules['eventID']  = $this->fields['eventID']['rules'];
		$form_rules['participantID']  = $this->fields['participantID']['rules'];
		$form_rules['moderatorQ']  = $this->fields['moderatorQ']['rules'];
		$form_rules['requiredQ']  = $this->fields['requiredQ']['rules'];
		$form_rules['confirmedQ']  = $this->fields['confirmedQ']['rules'];
		$this->validation->set_rules($form_rules);

		// load the field labels
		$form_fields['id']   = $this->fields['id']['label'];
		$form_fields['eventID']   = $this->fields['eventID']['label'];
		$form_fields['participantID']   = $this->fields['participantID']['label'];
		$form_fields['moderatorQ']   = $this->fields['moderatorQ']['label'];
		$form_fields['requiredQ']   = $this->fields['requiredQ']['label'];
		$form_fields['confirmedQ']   = $this->fields['confirmedQ']['label'];
		$this->validation->set_fields($form_fields);

		// set error delimiters
		$this->validation->set_error_delimiters('<span class="error">', '</span>');

	}


	// -------------------------------------------------------------------------
	/**
	 * Initalize Values
	 * 
	 * @access private
	 * @return void;
	 */
	function _initialize()
	{
		// Setup custom field options - list fields in the order they should
		// appear in the details view
		//   rules - validation rules (optional)
		//   label - descriptive name of the field (optional)
		//   name - database field name ** MUST BE SAME AS KEY ** (required)
		//   desc - long description to show to user on form (optional)
		//   type - set of values (required)
		//            text - basic input box
		//            hidden - keep this field hidden
		//            textarea
		//            checkbox
		//            dropdown
		//            password
		//   class - class name (optional)
		//   script - html script code to insert on the field
		//   after_form_script - html script code to insert after the form has been displayed

		$this->fields['id'] = array('label' => 'Event ID',
							'name' => 'id',
							'type' => 'hidden');
		$this->fields['eventID'] = array('rules' => 'trim|required|callback__not_zero|xss_clean',
							'label' => 'Event Name',
							'name' => 'eventID',
							'desc' => 'Enter the event name.',
							'type' => 'dropdown',
							'options' => $this->_get_event_array(),
							'selected' => '');
		$this->fields['participantID'] = array('rules' => 'trim|required|callback__not_zero|callback__check_part_conflict|callback__duplicate|xss_clean',
							'label' => 'Participant Name',
							'name' => 'participantID',
							'desc' => 'Enter the participant to add to this event.',
							'type' => 'dropdown',
							'options' => $this->_get_participant_array(),
							'selected' => '');
		$this->fields['moderatorQ'] = array('rules' => 'trim|xss_clean',
							'label' => 'Moderator?',
							'name' => 'moderatorQ',
							'desc' => 'Is this participant a moderator for this event?',
							'type' => 'checkbox');
		$this->fields['requiredQ'] = array('rules' => 'trim|xss_clean',
							'label' => 'Required?',
							'name' => 'requiredQ',
							'desc' => 'Is this participant required for this event? If so, then do not remove this participant from this event.',
							'type' => 'checkbox');
		$this->fields['confirmedQ'] = array('rules' => 'trim|xss_clean',
							'label' => 'Confirmed?',
							'name' => 'confirmedQ',
							'desc' => 'Has this participant been confirmed for this event? If so, then this participant should not be removed without notifying them.',
							'type' => 'checkbox');

		return;
	}

	/**
	 * Unique_field
	 * ** Assumes that the db model has already been loaded. **
	 *
	 * @access    private
	 * @param     string  The string to check for in the db.
	 * @param     field   The table and column of the field to check in table.column format
	 * @return    bool
	 */
	function _unique_field($str, $field)
	{
		list($table, $column) = split("\.", $field, 2);

		// Set the error message to use
		$this->validation->set_message('_unique_field','The %s field must have a unique value in the database.');

		$where= isset($_POST['id']) ? array('id !='=> $_POST['id'], $column=>$str) : array($column=>$str);
		$count = $this->eventparticipants_model->count_condition($table, $where);
		return ($count > 0) ? FALSE : TRUE;
	}

	/**
	 * Get participant array
	 *
	 * @access    private
	 * @return    array
	 */
	 function _get_participant_array()
	{
		// Load the model
		$this->load->model('participants_model');

		// fetch query object from the model with fields id, name
		$query = $this->participants_model->fetch('participants','id, sortedName','','activeQ = 1','sortedName ASC');

		// Loop through to build array
		$data = array();
		$data[0] = '';
		foreach ($query->result_array() as $row)
		{
			$data[$row['id']] = $row['sortedName'];
		}

		return $data;
	}

	/**
	 * Get event array
	 *
	 * @access    private
	 * @return    array
	 */
	 function _get_event_array()
	{
		// Load the model
		$this->load->model('events_model');

		// fetch query object from the model with fields id, name
		$query = $this->events_model->fetch('events','id, name','','activeQ = 1','name ASC');

		// Loop through to build array
		$data = array();
		$data[0] = '';
		foreach ($query->result_array() as $row)
		{
			$data[$row['id']] = $row['name'];
		}

		return $data;
	}

	// -------------------------------------------------------------------------
	/**
	 * Check that item selected is not the zero (empty) choice
	 *
	 * @access    private
	 * @param     string  The string to check.
	 * @return    bool
	 */
	function _not_zero($str)
	{
		// Set the error message to use
		$this->validation->set_message('_not_zero','The %s field is required.');

		if ($str == 0)
			return FALSE;

		return TRUE;
	}

	// -------------------------------------------------------------------------
	/**
	 * Check that event does not have a conflict before scheduling
	 *
	 * @access    private
	 * @param     string  The string to check.
	 * @return    bool
	 */
	function _check_part_conflict($str)
	{
		// Set the error message to use
		$this->validation->set_message('_check_part_conflict','The %s field cannot be scheduled due to a conflict.');

		// if no event id, there can be no conflicts
		$eventid = $this->input->post('eventID', TRUE);
		if ($eventid == '')
			return TRUE;  //good, no conflicts

		// if no participant id, there can be no conflicts
		$partid = $this->input->post('participantID', TRUE);
		if ($partid == '')
			return TRUE;  //good, no conflicts

		// get current participant info
		$query = $this->participants_model->fetch('participants','sortedName','','id = '.$partid);
		if ($query->num_rows() == 0)
			return TRUE;  //should never happen
		$partrow = $query->row_array();
		$query->free_result();

		// get event info
		$this->load->model('events_model');
		$query = $this->events_model->fetch('events','startDateTime,eventLength,setupTime,teardownTime','','id = '.$eventid);
		if ($query->num_rows() == 0)
			return TRUE;  //good, no conflicts
		$eventrow = $query->row_array();
		$query->free_result();
		$str = $eventrow['startDateTime'];  //get date string
		// if date is blank, there can be no conflicts
		if ($str == '0000-00-00 00:00:00' OR $str == '')
			return TRUE;  //good, no conflicts

		// get current participants for this event
		$this->load->model('eventparticipants_model');
		$query = $this->eventparticipants_model->fetchEventParticipants('event.id = '.$eventid);
		if ($query->num_rows() > 0)
		{
			// convert participants query to array
			foreach ($query->result_array() as $row)
			{
				$partsort[$row['participant_sortedname']] = $row['participant_id'];
			}
		}
		$query->free_result();
		// add cuurent participant to this list
		$partsort[$partrow['sortedName']] = $partid;

		$partGrid = $this->events_model->build_part_grid($partsort);  // Build the participant grid for conflict checking
		//print_r($partGrid);


		// get event data
		$sdttm = strtotime($str);
		$edttm = strtotime("+".($eventrow['eventLength']*3600).' seconds', $sdttm);
		$setup = strtotime("-".($eventrow['setupTime']*3600).' seconds', $sdttm);
		$teardown = strtotime("+".($eventrow['teardownTime']*3600).' seconds', $sdttm);
		$eventInfo = array('id' => $eventid,
							'sdttm' => date('Y-m-d H:i:s',$sdttm),
							'edttm' => date('Y-m-d H:i:s',$edttm),
							'setupdttm' => date('Y-m-d H:i:s',$setup),
							'teardowndttm' => date('Y-m-d H:i:s',$teardown),
							'setup' => $eventrow['setupTime'],
							'teardown' => $eventrow['teardownTime'],
							'eventlength' => $eventrow['eventLength']
							);

		// check that an event can fit on grid and return status
		$status = check_event_on_partgrid($partGrid, $partsort, $eventInfo, $this->ccsettings->item('interval_length'));

		// if status is not blank, there was a problem
		if ($status != '')
		{
			flashMsg('warning',$status);
			return FALSE;  //bad, conflicts
		}

		return TRUE;  //good, no conflicts
	}

	// -------------------------------------------------------------------------
	/**
	 * Check whether participant is already on panel
	 *
	 * @access    private
	 * @param     string  The string to check.
	 * @return    bool
	 */
	function _duplicate($str)
	{
		// **There is a bug with dup checking. Updating an existing record causes dup msg.
		return TRUE;

		// Set the error message to use
		$this->validation->set_message('_duplicate','This participant has already been added to the panel.');

		// if no participant id, quit
		$partid = $this->input->post('participantID', TRUE);
		if ($partid == '')
			return TRUE;

		// if no event id, quit
		$eventid = $this->input->post('eventID', TRUE);
		if ($eventid == '')
			return TRUE;

		// get participant info
		$query = $this->eventparticipants_model->fetch('eventParticipants','id','','participantID = '.$partid.' && eventID = '.$eventid);
		if ($query->num_rows() == 0)
			return TRUE;  //good, no entries

		return FALSE;  //bad, already on panel
	}




	// --------------------------------------------------------------------------------------------
	// Reports
	// --------------------------------------------------------------------------------------------

	// -------------------------------------------------------------------------
	/**
	* Reports Page
	*
	* @access      public
	* @return      none
	*/
	function reports()
	{
		// create urls for use in content view
		$template['base_url']   = 'concentric/eventparticipants/reports/';
		$template['cancel_url'] = 'concentric/home';

		// Set breadcrumb
		$this->page->set_crumb('Event Participants Reports','concentric/eventparticipants/reports/');

		// set values for use in content view
		$template['form_attributes'] = array('name' => $this->form_name, 'id' => $this->form_name);
		$template['header'] = $this->form_name;

		// build content html
		$data['content'] = $this->load->view('/concentric/eventparticipants/eventparticipants_reports_menu', $template, TRUE);

		// set values for use in header view
		$data['header']  = $this->form_name;

		// pass all data to container view and display to user
		$this->load->view($this->_container,$data);
	}

	// -------------------------------------------------------------------------
	/**
	* Report all data by event
	*
	* @access      public
	* @return      none
	*/
	function rep_all_event()
	{
		// fetch query object from the model
		$template['eventparticipants_list'] = $this->eventparticipants_model->fetchEventParticipants('participant.activeQ = 1');
		$template['events_list'] = $this->eventparticipants_model->fetchScheduledEvents('','participant.sortedName ASC');

		// create urls for use in content view
		$template['base_url']   = 'concentric/eventparticipants/reports/';
		$template['cancel_url'] = 'concentric/home';

		// Set breadcrumbs
		$this->page->set_crumb('Event Participant Reports','concentric/eventparticipants/reports/');
		$this->page->set_crumb('List All by Event','concentric/eventparticipants/rep_all_event/');

		// set values for use in content view
		$template['form_attributes'] = array('name' => $this->form_name, 'id' => $this->form_name);
		$template['header'] = $this->form_name;
		$template['mode'] = 'internal';

		// build content html using grid view and template data
		$data['content'] = $this->load->view('/concentric/eventparticipants/eventparticipants_eventlist', $template, TRUE);

		// set values for use in header view
		$data['header']  = $this->form_name;

		// pass all data to container view and display to user
		$this->load->view($this->_container,$data);
	}

	// -------------------------------------------------------------------------
	/**
	* Download all data
	*
	* @access      public
	* @return      none
	*/
	function rep_download_all($eor = '')
	{
		// Load the helper
		$this->load->helper('download');

		// fetch query object from the model
		$query = $this->eventparticipants_model->fetchEventParticipants();

		// Initialize values
		$data = '';
		$eor = ($eor == '') ? '' : (',' . $eor);
		// Create header row
		$data .= 'id,event_name,participant_name,moderatorQ,requiredQ,confirmedQ' . $eor . "\n";
		// Loop through the data and build the data
		foreach ($query->result_array() as $row)
		{
			$data .= '"' . $row['id'] . '","' . $row['event_name'] . '","' . $row['participant_name'] . '","' . $row['moderatorQ'] . '","' . $row['requiredQ'] . '","' . $row['confirmedQ'] . '"' . $eor . "\n";
		}

		// Download the file
		force_download('eventparticipants.csv', $data);

		redirect('/concentric/eventparticipants/reports', 'location');
	}


}


/* End of file eventparticipants.php */
/* Location: ./system/application/controllers/concentric/eventparticipants.php */
Return current item: ConCentric Event Planning Software