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

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

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

		$this->form_name = "Locations";
		$this->load->model('locations_model');    // Instantiate the model
	}

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

	// -------------------------------------------------------------------------
	// Function: browse()
	// Description: Extracts a list of all data records and
	//              displays it.
	function browse()
	{
		// fetch query object from the model
		$template['locations_list'] = $this->locations_model->fetchLocations();

		// create urls for use in content view
		$template['base_url']   = 'concentric/locations/browse/';
		$template['edit_url'] = 'concentric/locations/edit/';
		$template['delete_url'] = 'concentric/locations/delete/';
		$template['add_url']    = 'concentric/locations/add/';
		$template['cancel_url'] = 'concentric/home';

		// 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/locations/locations_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');

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


		$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/locations/', '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']['name']				= $this->input->post('name', TRUE);
			$data['field']['sortOrder']			= $this->input->post('sortOrder', TRUE);
			$data['field']['alternateName']		= $this->input->post('alternateName', TRUE);
			$data['field']['capacity']			= $this->input->post('capacity', TRUE);
			$data['field']['colorID']			= $this->input->post('colorID', TRUE);
			$data['field']['publicQ']			= $this->input->post('publicQ', TRUE);

			if ($mode == 'add')
			{
				// add the data to the table and return id
				$idField = $this->locations_model->addRow('locations',$data['field']);
				$status = ($idField) ? TRUE : FALSE;
			}
			else
			{
				$idField = $data['field']['id'];
				// update the data in the table
				$obj = $this->locations_model->update('locations', $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 . ' (' . $data['field']['name'] . ') has been saved.');
			}
			else  // there was an error
			{
				// Show error message
				flashMsg('error','The record for (' . $data['field']['name'] . ') has not been saved.');
			}

			// redirect to main location
			redirect('/concentric/locations/', 'location');
			// ?redirect to add/edit?
			// redirect('/concentric/locations/' . $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->locations_model->delete('locations', 'id =' . $idField) )
			{
				flashMsg('success', 'The record has been deleted.');
			}
			else
			{
				flashMsg('error', 'There was a problem deleting the record');
			}
		}

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

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

	// -------------------------------------------------------------------------
	// id, name, sortOrder, alternateName, colorID, publicQ
	function _get_form_values($mode = 'add')
	{
		if ($mode == 'add')
		{
			// Set empty values / default values
			$this->fields['id']['value'] = '';
			$this->fields['name']['value'] = '';
			$this->fields['sortOrder']['value'] = '';
			$this->fields['alternateName']['value'] = '';
			$this->fields['capacity']['value'] = '';
			$this->fields['colorID']['value'] = '';
			$this->fields['publicQ']['value'] = 1;
			$this->fields['publicQ']['checked'] = TRUE;
		}
		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->locations_model->fetch('locations','id, name, sortOrder, alternateName, capacity, colorID, publicQ','','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['name']['value'] = $row['name'];
			$this->fields['sortOrder']['value'] = $row['sortOrder'];
			$this->fields['alternateName']['value'] = $row['alternateName'];
			$this->fields['capacity']['value'] = $row['capacity'];
			$this->fields['colorID']['value'] = $row['colorID'];
			$this->fields['colorID']['selected'] = $row['colorID'];
			$this->fields['publicQ']['value'] = 1;
			$this->fields['publicQ']['checked'] = ($row['publicQ']) ? 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['name']  = $this->fields['name']['rules'];
		$form_rules['sortOrder']  = $this->fields['sortOrder']['rules'];
		$form_rules['alternateName']  = $this->fields['alternateName']['rules'];
		$form_rules['capacity']  = $this->fields['capacity']['rules'];
		$form_rules['colorID']  = $this->fields['colorID']['rules'];
		$form_rules['publicQ']  = $this->fields['publicQ']['rules'];
		$this->validation->set_rules($form_rules);

		// load the field labels
		$form_fields['id']   = $this->fields['id']['label'];
		$form_fields['name'] = $this->fields['name']['label'];
		$form_fields['sortOrder']   = $this->fields['sortOrder']['label'];
		$form_fields['alternateName']   = $this->fields['alternateName']['label'];
		$form_fields['capacity']   = $this->fields['capacity']['label'];
		$form_fields['colorID']   = $this->fields['colorID']['label'];
		$form_fields['publicQ']   = $this->fields['publicQ']['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)

		$this->fields['id'] = array('label' => 'Location ID',
							'name' => 'id',
							'type' => 'hidden');
		$this->fields['name'] = array('rules' => 'trim|required|max_length[50]|callback__unique_field[locations.name]|xss_clean',
							'label' => 'Location Name',
							'name' => 'name',
							'desc' => 'Enter the name of the location as it should be displayed on reports.',
							'type' => 'text');
		$this->fields['sortOrder'] = array('rules' => 'trim|required|max_length[5]|integer|xss_clean',
							'label' => 'Sort Order',
							'name' => 'sortOrder',
							'desc' => 'Enter the sort order for the location. Locations that can joined to make a larger location should be next to each other in sort order. Sort order also determines the location order on certain reports.',
							'type' => 'text');
		$this->fields['alternateName'] = array('rules' => 'trim|max_length[50]|alpha_dash_space|xss_clean',
							'label' => 'Alternate Location Name',
							'name' => 'alternateName',
							'desc' => 'Enter an alternate name for the location, i.e. ConSuite or Film Room.',
							'type' => 'text');
		$this->fields['capacity'] = array('rules' => 'trim|max_length[50]|alpha_dash_space|xss_clean',
							'label' => 'Capacity',
							'name' => 'capacity',
							'desc' => 'Enter the capacity for the location assuming theater style seating.',
							'type' => 'text');
		$this->fields['colorID'] = array('rules' => 'trim|xss_clean',
							'label' => 'Color',
							'name' => 'colorID',
							'desc' => 'Enter the color that should be used on the grid report for this location.',
							'type' => 'dropdown',
							'options' => $this->_get_color_array(),
							'selected' => '');
		$this->fields['publicQ'] = array('rules' => 'trim|xss_clean',
							'label' => 'Public?',
							'name' => 'publicQ',
							'desc' => 'Is this location public? Locations that are not public are not printed on most reports.',
							'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->locations_model->count_condition($table, $where);
		return ($count > 0) ? FALSE : TRUE;
	}

	/**
	 * Get color array
	 *
	 * @access    private
	 * @return    array
	 */
	 function _get_color_array()
	{
		// Load the color model
		$this->load->model('colors_model');

		// fetch query object from the model with fields id, name
		$query = $this->colors_model->fetch('colors','id, name','','','name ASC');

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

		return $data;
	}


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

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

		// Set breadcrumb
		$this->page->set_crumb('Location Reports','concentric/locations/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/locations/locations_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
	*
	* @access      public
	* @return      none
	*/
	function rep_all()
	{
		// fetch query object from the model
		$template['locations_list'] = $this->locations_model->fetchLocations();

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

		// Set breadcrumbs
		$this->page->set_crumb('Location Reports','concentric/locations/reports/');
		$this->page->set_crumb('List All','concentric/locations/rep_all/');

		// 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/locations/locations_list_all', $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->locations_model->fetchLocations();

		// Initialize values
		$data = '';
		$eor = ($eor == '') ? '' : (',' . $eor);
		// Loop through the data and build the data
		foreach ($query->result_array() as $row)
		{
			$data .= '"' . $row['id'] . '","' . $row['name'] . '","' . $row['alternateName'] . '","' . $row['capacity'] . '","' . $row['sortOrder'] . '","' . $row['color_name'] . '","' . $row['publicQ'] . '"' . $eor . "\n";
		}

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

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

	// -------------------------------------------------------------------------
	/**
	* Report to show location schedules
	*
	* @access      public
	* @return      none
	*/
	function rep_schedule()
	{
		// create urls for use in content view
		$template['base_url']   = 'concentric/locations/reports/';
		$template['cancel_url'] = 'concentric/home';

		// Set breadcrumbs
		$this->page->set_crumb('Location Reports','concentric/locations/reports/');
		$this->page->set_crumb('Location Schedules','concentric/locations/rep_schedule/');

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


		$this->load->helper('grid');    // load helper library
		$this->load->model('events_model');    // Instantiate the model
		$this->load->model('eventlocations_model');    // Instantiate the model

		// fetch query object from the model - returns event ids and location ids
		$query = $this->eventlocations_model->fetchScheduledLocations();

		$template['content'] = '';  //initialize

		// loop thru events and get details
		if ($query->num_rows() > 0)
		{
			foreach ($query->result_array() as $locationrow)
			{
				// output location details
				$template['content'] .= '<b><big>' . $locationrow['name'];
				if ($locationrow['alternateName'])
					$template['content'] .= ' - ' . $locationrow['alternateName'];
				$template['content'] .= '</big></b>' . '<br />' . "\n";
				$template['content'] .= '<b>' . $locationrow['eventday'] . '</b>' . '<br />' . "\n";
				//$template['content'] .= $locationrow['id'] . ' - ' . $locationrow['sortOrder'] . '<br />' . "\n";
				$template['content'] .= '<br />' . "\n";

				// now get list of event ids for locations
				$query2 = $this->eventlocations_model->fetchScheduledLocations2('DATE(event.startDateTime) = "'.$locationrow['eventdate'].'" AND location.id = '.$locationrow['id']);
				//flashMsg('info','Count is '.$query2->num_rows());
				// loop thru events and get details
				foreach ($query2->result_array() as $eventrow)
				{
					// output event details
					$sdttm = strtotime($eventrow['startDateTime']);  //start dttm
					$edttm = strtotime("+".($eventrow['eventLength']*3600).' seconds', $sdttm);  //end dttm
					$eventrow['endDateTime'] = date('Y-m-d H:i:s',$edttm);  //change back to sql
					$sdt = date('m-d-Y',$sdttm);
					$stm = $this->_gettime($eventrow['startDateTime']);
					$etm = $this->_gettime($eventrow['endDateTime']);
					$day = date("l",strtotime($eventrow['startDateTime']));
					$template['content'] .= $stm . ' to ' . $etm . ' - ' . $eventrow['name'] . '<br />' . "\n";
				}
				$query2->free_result();


				$template['content'] .= '<hr>' . "\n";
			}
		}


		// build content html using view and template data
		$data['content'] = $this->load->view('/concentric/locations/locations_generic', $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);
	}

	/**
	 * gettime
	 * Converts a SQL format date time to just time converted to hh:mi am/pm format.
	 *
	 * @access    private
	 * @param     string  The string that is a SQL datetime.
	 * @return    string Time in hh:mi am/pm format.
	 */
	function _gettime($dttm)
	{
		list($dt, $tm) = explode(' ', $dttm);  //separate into parts
		$tm1 = explode(':', $tm);  //separate time parts
		$tm = $tm1[0] . ':' . $tm1[1];  //remove seconds from time
		$tm = cnv_tm_from_military($tm);  //convert
		return $tm;
	}




}


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