PageRenderTime 2133ms CodeModel.GetById 250ms app.highlight 1222ms RepoModel.GetById 350ms app.codeStats 1ms

/halogy/application/libraries/Core.php

https://bitbucket.org/haloweb/halogy-1.0/
PHP | 1376 lines | 1028 code | 190 blank | 158 comment | 153 complexity | 45b6911b2581e9f032b644d48a3bdce3 MD5 | raw file
   1<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
   2/**
   3 * Halogy
   4 *
   5 * A user friendly, modular content management system for PHP 5.0
   6 * Built on CodeIgniter - http://codeigniter.com
   7 *
   8 * @package		Halogy
   9 * @author		Haloweb Ltd.
  10 * @copyright	Copyright (c) 2008-2011, Haloweb Ltd.
  11 * @license		http://halogy.com/license
  12 * @link		http://halogy.com/
  13 * @since		Version 1.0
  14 * @filesource
  15 */
  16
  17// ------------------------------------------------------------------------
  18
  19class Core {
  20	
  21	var $CI;						// CI instance
  22	var $table ;					// default table
  23	var $siteID;					// id of the site
  24	var $uri_assoc_segment = 4; 	// segment where the magic happens
  25	var $adminOverRide = FALSE;		// allows for override of siteID
  26	var $currentPage;
  27	var $where = array();
  28	var $set = array();
  29	var $required = array();
  30	
  31	function Core()
  32	{	
  33		// init vars
  34		$this->CI =& get_instance();
  35		
  36		// get siteID, if available
  37		if (defined('SITEID'))
  38		{
  39			$this->siteID = SITEID;
  40		}
  41		
  42		// set groupID from session (if set)
  43		$this->groupID = ($this->CI->session->userdata('groupID')) ? $this->CI->session->userdata('groupID') : 0;	
  44	}	
  45
  46	function get_page($pageID = FALSE, $uri = FALSE)
  47	{
  48		// get page data
  49		$this->CI->db->where('siteID', $this->siteID);
  50
  51		// if getting by uri check its not deleted
  52		if ($uri)
  53		{
  54			$this->CI->db->where('deleted', 0);
  55		}
  56		
  57		if (intval($pageID))
  58		{
  59			$this->CI->db->where('pageID', $pageID);
  60		}
  61		elseif ($uri !== FALSE && $pageID === FALSE)
  62		{
  63			$this->CI->db->where('uri', $uri);
  64		}
  65		else
  66		{
  67			return FALSE;
  68		}
  69
  70		// get the latest one, not a deleted one from the past
  71		$this->CI->db->order_by('dateCreated', 'desc');
  72		
  73		$query = $this->CI->db->get('pages', 1);
  74		
  75		if ($query->num_rows() == 1)
  76		{
  77			return $query->row_array();
  78		}
  79		else
  80		{
  81			return FALSE;
  82		}
  83	}
  84
  85	function get_active_page($uri = '')
  86	{
  87		// get published page
  88		if (!$uri)
  89		{
  90			return FALSE;
  91		}
  92		
  93		$this->CI->db->where('siteID', $this->siteID);
  94		
  95		$this->CI->db->where('active', 1);
  96		$this->CI->db->where('deleted', 0);
  97
  98		$this->CI->db->where('uri', $uri);
  99		
 100		$query = $this->CI->db->get('pages', 1);
 101		
 102		if ($query->num_rows() == 1)
 103		{
 104			return $query->row_array();
 105		}
 106		else
 107		{
 108			return FALSE;
 109		}
 110	}
 111
 112	function generate_page($pageID, $admin = FALSE, $templateID = '')
 113	{
 114		// get page data
 115		$pagedata = $this->get_page($pageID);
 116
 117		// load template, either from override or from page data
 118		if ($templateID)
 119		{
 120			$page = $this->CI->template->generate_template(array('templateID' => $templateID));
 121		}
 122		else
 123		{
 124			$page = $this->CI->template->generate_template($pagedata);
 125		}
 126		
 127		// set default parse variable to nothing
 128		$page['error'] = '';
 129		$page['message'] = '';
 130
 131		// tell the parser some important info like versionID
 132		$page['pageID'] = $pagedata['pageID'];
 133		$page['templateID'] = $pagedata['templateID'];
 134		$page['versionID'] = $pagedata['versionID'];
 135
 136		// if logged in as admin, then get the blocks from draft, otherwise get them from the published version
 137		$versionID = ($admin === TRUE) ? $pagedata['draftID'] : $pagedata['versionID'];
 138
 139		// populate blocks from db (if they exist)		
 140		if ($blocksResult = $this->get_blocks($versionID))
 141		{
 142			foreach($blocksResult as $blockRow)
 143			{
 144				// set bodies and get images for mkdn view
 145				$body[$blockRow['blockRef']] = form_prep($blockRow['body']);
 146
 147				$mkdnBody[$blockRow['blockRef']] = $this->CI->template->parse_body($blockRow['body']);
 148			}
 149		}
 150
 151		// parse for blocks
 152		preg_match_all('/block([a-z0-9\-_]+)/i', $page['body'], $blocks);
 153		if ($blocks)
 154		{
 155			foreach($blocks[1] as $block => $value)
 156			{
 157				$blockRef = 'block'.$value;
 158				if ($admin)
 159				{
 160					$page[$blockRef] = '
 161						<div class="halogycms_container">
 162							<div id="'.$blockRef.'" class="halogycms_edit">
 163								<div class="halogycms_buttons">
 164									<a href="#" class="halogycms_boldbutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_bold.png" alt="Bold" title="Bold" class="halogycms_helper" /></a>
 165									<a href="#" class="halogycms_italicbutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_italic.png" alt="Italic" title="Italic" class="halogycms_helper" /></a>
 166									<a href="#" class="halogycms_h1button"><img src="'.$this->CI->config->item('staticPath').'/images/btn_h1.png" alt="Heading 1" title="Heading 1" class="halogycms_helper" /></a>
 167									<a href="#" class="halogycms_h2button"><img src="'.$this->CI->config->item('staticPath').'/images/btn_h2.png" alt="Heading 2" title="Heading 2" class="halogycms_helper" /></a>
 168									<a href="#" class="halogycms_h3button"><img src="'.$this->CI->config->item('staticPath').'/images/btn_h3.png" alt="Heading 3" title="Heading 3" class="halogycms_helper" /></a>
 169									<a href="#" class="halogycms_urlbutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_url.png" alt="Insert Link" title="Insert Link" class="halogycms_helper" /></a>
 170									<a href="#" class="halogycms_imagebutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_image.png" alt="Insert Image" title="Insert Image" class="halogycms_helper" /></a>
 171									<a href="#" class="halogycms_filebutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_file.png" alt="Insert File" title="Insert File" class="halogycms_helper" /></a>									
 172									<a href="#" class="halogycms_cancelbutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_cancel.png" alt="Cancel" title="Cancel Changes" class="halogycms_helper" /></a>
 173									<a href="/admin/pages/add_block/'.$versionID.'/'.$blockRef.'" class="halogycms_savebutton"><img src="'.$this->CI->config->item('staticPath').'/images/btn_save.png" alt="Save" title="Save Changes" class="halogycms_helper" /></a>
 174									<a href="#" class="halogycms_editbutton">Edit</a>									
 175								</div>
 176								<div class="halogycms_blockelement">'.@$mkdnBody[$blockRef].'</div>
 177								<div class="halogycms_editblock"><textarea rows="8" cols="10" class="code">'.@$body[$blockRef].'</textarea></div>
 178							</div>
 179						</div>
 180					';
 181				}
 182				else
 183				{
 184					$page[$blockRef] = @$mkdnBody[$blockRef];
 185				}				
 186			}
 187		}
 188		
 189		return $page;
 190	}
 191
 192	function get_versions($pageID)
 193	{
 194		$this->CI->db->where('pageID', $pageID);
 195		$this->CI->db->where('published', 1);
 196
 197		$this->CI->db->order_by('dateCreated', 'desc');
 198	
 199		$query = $this->CI->db->get('page_versions', 30);
 200		
 201		// get data
 202		if ($query->num_rows())
 203		{
 204			return $query->result_array();
 205		}
 206		else
 207		{
 208			return false;
 209		}		
 210	}
 211
 212	function get_drafts($pageID)
 213	{
 214		$this->CI->db->where('pageID', $pageID);
 215		$this->CI->db->where('published', 0);
 216
 217		$this->CI->db->order_by('dateCreated', 'desc');
 218	
 219		$query = $this->CI->db->get('page_versions');
 220		
 221		// get data
 222		if ($query->num_rows())
 223		{
 224			return $query->result_array();
 225		}
 226		else
 227		{
 228			return false;
 229		}		
 230	}
 231
 232	function get_blocks($versionID)
 233	{
 234		$this->CI->db->where('siteID', $this->siteID);		
 235		$this->CI->db->select('MAX(blockID) as blockID');
 236		$this->CI->db->where('versionID', $versionID);
 237		$this->CI->db->group_by('blockRef');
 238		$this->CI->db->order_by('dateCreated','DESC');
 239		$query = $this->CI->db->get('page_blocks');
 240		$result = $query->result_array();
 241		$numBlocks = $query->num_rows();
 242		
 243		// get data
 244		if ($numBlocks > 0)
 245		{
 246			foreach($result as $row)
 247			{
 248				$blockIDs[] = $row['blockID'];
 249			}
 250
 251			$this->CI->db->where('siteID', $this->siteID);
 252			$this->CI->db->where_in('blockID', $blockIDs);
 253			$this->CI->db->where('versionID', $versionID);
 254			$this->CI->db->order_by('blockID');
 255			$query = $this->CI->db->get('page_blocks', $numBlocks);
 256			
 257			return $query->result_array();
 258		}
 259		else
 260		{
 261			return false;
 262		}		
 263	}
 264
 265	function get_template($templateID = '')
 266	{
 267		// default where
 268		$this->CI->db->where('t1.siteID', $this->siteID, FALSE);
 269		$this->CI->db->where('t1.deleted', 0, FALSE);
 270		$this->CI->db->where('templateID', $templateID);
 271
 272		// select
 273		$this->CI->db->select('t1.*, t2.body, t2.dateCreated, t2.userID');
 274
 275		// join revisions
 276		$this->CI->db->join('template_versions t2', 't2.versionID = t1 . versionID', 'left');
 277		
 278		// get em
 279		$query = $this->CI->db->get('templates t1', 1);
 280		
 281		if ($query->num_rows())
 282		{
 283			return $query->row_array();
 284		}
 285		else
 286		{
 287			return FALSE;
 288		}
 289	}
 290
 291	function get_module_template($modulePath = '')
 292	{
 293		// default where
 294		$this->CI->db->where('t1.siteID', $this->siteID, FALSE);
 295		$this->CI->db->where('t1.deleted', 0, FALSE);
 296		$this->CI->db->where('modulePath', $modulePath);
 297
 298		// select
 299		$this->CI->db->select('t1.*, t2.body, t2.dateCreated, t2.userID');
 300
 301		// join revisions
 302		$this->CI->db->join('template_versions t2', 't2.versionID = t1 . versionID', 'left');
 303		
 304		// get em
 305		$query = $this->CI->db->get('templates t1', 1);
 306		
 307		if ($query->num_rows())
 308		{
 309			return $query->row_array();
 310		}
 311		else
 312		{
 313			return FALSE;
 314		}
 315	}
 316
 317	function get_include($includeRef = '', $includeID = '')
 318	{
 319		// default where
 320		$this->CI->db->where('t1.siteID', $this->siteID, FALSE);
 321		$this->CI->db->where('t1.deleted', 0, FALSE);
 322
 323		// get by reference
 324		if ($includeRef)
 325		{
 326			$this->CI->db->where('includeRef', $includeRef);
 327		}
 328
 329		// get by ID
 330		elseif ($includeID)
 331		{
 332			$this->CI->db->where('includeID', $includeID);
 333		}
 334
 335		// or fail
 336		else
 337		{
 338			return FALSE;
 339		}
 340
 341		// select
 342		$this->CI->db->select('t1.*, t2.body, t2.dateCreated, t2.userID');
 343
 344		// join revisions
 345		$this->CI->db->join('include_versions t2', 't2.versionID = t1 . versionID', 'left');
 346		
 347		// get em
 348		$query = $this->CI->db->get('includes t1', 1);
 349		
 350		if ($query->num_rows())
 351		{
 352			return $query->row_array();
 353		}
 354		else
 355		{
 356			return FALSE;
 357		}		
 358	}
 359
 360	function lookup_user($userID, $display = FALSE)
 361	{
 362		// default wheres
 363		$this->CI->db->where('userID', $userID);
 364
 365		// grab
 366		$query = $this->CI->db->get('users', 1);
 367
 368		if ($query->num_rows())
 369		{
 370			$row = $query->row_array();
 371			
 372			if ($display !== FALSE)
 373			{
 374				return ($row['displayName']) ? $row['displayName'] : $row['firstName'].' '.$row['lastName'];
 375			}
 376			else
 377			{
 378				return $row;
 379			}
 380		}
 381		else
 382		{
 383			return FALSE;
 384		}		
 385	}
 386
 387	function add_draft($pageID)
 388	{
 389		if ($pagedata = $this->get_page($pageID))
 390		{	
 391			// add new version
 392			$this->CI->db->set('pageID', $pageID);
 393			$this->CI->db->set('dateCreated', date("Y-m-d H:i:s"));
 394			$this->CI->db->set('userID', $this->CI->session->userdata('userID'));
 395			$this->CI->db->set('siteID', $this->siteID);
 396			$this->CI->db->insert('page_versions');
 397	
 398			// get version ID
 399			$draftID = $this->CI->db->insert_id();
 400
 401			// update page draft
 402			$this->CI->db->set('draftID', $draftID);
 403			$this->CI->db->where('siteID', $this->siteID);
 404			$this->CI->db->where('pageID', $pageID);
 405			$this->CI->db->update('pages');
 406
 407			// add the old blocks in to this new version
 408			if ($blocks = $this->get_blocks($pagedata['draftID']))
 409			{
 410				foreach($blocks as $block)
 411				{
 412					$body = $block['body'];
 413					$this->add_block($body, $draftID, $block['blockRef']);
 414				}
 415			}				
 416		
 417			return $draftID;
 418		}
 419		else
 420		{
 421			return FALSE;
 422		}
 423	}
 424
 425	function get_latest_block($versionID)
 426	{
 427		$this->CI->db->where('versionID', $versionID);
 428		$this->CI->db->where('siteID', $this->siteID);
 429		
 430		$this->CI->db->order_by('dateCreated', 'desc');
 431
 432		// grab
 433		$query = $this->CI->db->get('page_blocks', 1);
 434
 435		if ($query->num_rows())
 436		{
 437			$row = $query->row_array();
 438			return $row;
 439		}
 440		else
 441		{
 442			return FALSE;
 443		}
 444	}
 445	
 446	function publish_page($pageID, $draftID)
 447	{
 448		$this->CI->db->set('dateModified', date("Y-m-d H:i:s"));
 449		$this->CI->db->set('datePublished', date("Y-m-d H:i:s"));
 450		$this->CI->db->set('versionID', $draftID);
 451		$this->CI->db->set('active', 1);
 452		$this->CI->db->where('pageID', $pageID);
 453		$this->CI->db->where('siteID', $this->siteID);
 454		$this->CI->db->update('pages');
 455
 456		return TRUE;
 457	}
 458
 459	function publish_draft($draftID)
 460	{
 461		// publish version
 462		$this->CI->db->set('published', 1);
 463		$this->CI->db->where('siteID', $this->siteID);
 464		$this->CI->db->where('versionID', $draftID);
 465		$this->CI->db->update('page_versions');
 466
 467		return TRUE;
 468	}
 469
 470	function revert_version($pageID, $versionID)
 471	{
 472		// update the template with version
 473		$this->CI->db->set('versionID', $versionID);
 474		$this->CI->db->where('pageID', $pageID);
 475		$this->CI->db->where('siteID', $this->siteID);
 476		$this->CI->db->update('pages');
 477
 478		return TRUE;
 479	}
 480
 481	function revert_draft($pageID, $draftID)
 482	{
 483		// update the template with version
 484		$this->CI->db->set('draftID', $draftID);
 485		$this->CI->db->where('pageID', $pageID);
 486		$this->CI->db->where('siteID', $this->siteID);		
 487		$this->CI->db->update('pages');
 488
 489		return TRUE;
 490	}
 491
 492	function add_block($body, $versionID, $blockRef = 'block')
 493	{
 494		// delete blocks for this version
 495		$this->CI->db->where('page_blocks.siteID', $this->siteID);
 496		$this->CI->db->where('page_blocks.versionID', $versionID);
 497		$this->CI->db->where('page_blocks.blockRef', $blockRef);
 498		$this->CI->db->delete('page_blocks');
 499
 500		// add block
 501		$this->CI->db->query("SET NAMES 'utf8'");
 502		$this->CI->db->set('versionID', $versionID);
 503		$this->CI->db->set('dateCreated', date("Y-m-d H:i:s"));
 504		$this->CI->db->set('siteID', $this->siteID);
 505		$this->CI->db->set('blockRef', $blockRef);
 506		$this->CI->db->set('body', $body);
 507		$this->CI->db->insert('page_blocks');
 508
 509		return TRUE;
 510	}
 511
 512	function add_view($pageID)
 513	{
 514		$this->CI->db->set('views', 'views+1', false);
 515		$this->CI->db->where('pageID', $pageID);
 516		$this->CI->db->where('siteID', $this->siteID);		
 517		$this->CI->db->update('pages');
 518	}
 519
 520	function get_web_form_by_ref($formRef)
 521	{
 522		$this->CI->db->where('formRef', $formRef);
 523		
 524		$this->CI->db->where('deleted', 0);
 525		$this->CI->db->where('siteID', $this->siteID);
 526		
 527		$query = $this->CI->db->get('web_forms', 1);
 528
 529		if ($query->num_rows())
 530		{
 531			return $query->row_array();
 532		}
 533		else
 534		{
 535			return FALSE;
 536		}
 537	}
 538		
 539	function web_form()
 540	{
 541		// get web form
 542		if (!$webform = $this->CI->core->get_web_form_by_ref($this->CI->core->decode($this->CI->input->post('formID'))))
 543		{
 544			return FALSE;
 545		}
 546		
 547		// set main required field
 548		$this->CI->form_validation->set_rules('email', 'Email', 'required|valid_email');
 549		
 550		// find out if a user account needs to be created
 551		$account = ($webform['account']) ? TRUE : FALSE;
 552
 553		// get required fields
 554		$required = $this->CI->input->post('required', TRUE);
 555
 556		// get optional required fields
 557		if ($required)
 558		{
 559			$requiredArray = explode('|', $required);
 560			foreach($requiredArray as $field)
 561			{
 562				$this->CI->form_validation->set_rules($field, ucfirst($field), 'required');
 563			}
 564		}
 565
 566		// get first and last name
 567		if ($this->CI->input->post('firstName', TRUE))
 568		{
 569			$firstName = $this->CI->input->post('firstName', TRUE);
 570			$lastName = $this->CI->input->post('lastName', TRUE);
 571		}		
 572		elseif ($fullName = $this->CI->input->post('fullName', TRUE))
 573		{
 574			$fullNameArray = @explode(' ', $fullName);
 575			$lastName = (sizeof($fullNameArray) > 0) ? ucfirst(trim(end($fullNameArray))) : '';
 576			$firstName = (sizeof($fullNameArray) > 0) ? ucfirst(trim($fullNameArray[0])) : $fullName;
 577		}
 578		else
 579		{
 580			$firstName = '';
 581			$lastName = '';
 582		}
 583
 584		// at least set the name and email in to a session
 585		if (!$this->CI->session->userdata('session_user'))
 586		{
 587			$this->CI->session->set_userdata('email', $this->CI->input->post('email', TRUE));
 588			$this->CI->session->set_userdata('firstName', $firstName);
 589			$this->CI->session->set_userdata('lastName', $lastName);
 590		}
 591		
 592		// if capturing check user is unique and a password matches
 593		if ($account)
 594		{
 595			// email and message are always required
 596			$this->CI->form_validation->set_rules('email', 'Email', 'required|valid_email|unique[users.email]|trim');
 597	
 598			// check if password was submitted, make it required if so
 599			if (array_key_exists('password', $_POST))
 600			{
 601				// require password confirm?
 602				if (isset($_POST['confirmPassword']))
 603				{
 604					$this->form_validation->set_rules('password', 'Password', 'required|matches[confirmPassword]');
 605				}
 606				else
 607				{
 608					$this->form_validation->set_rules('password', 'Password', 'required');
 609				}
 610			}
 611		}
 612		
 613		// look for files
 614		$files = FALSE;
 615		if ($webform['fileTypes'] && count($_FILES))
 616		{
 617			foreach($_FILES as $name => $file)
 618			{
 619				$this->CI->uploads->maxSize = '2000';
 620				$this->CI->uploads->allowedTypes = $webform['fileTypes'];
 621				
 622				// check a file has actually been uploaded
 623				if ($file['name'] != '')
 624				{
 625					if ($fileData = $this->CI->uploads->upload_file($name))
 626					{
 627						$files[$name] = $fileData;
 628					}
 629					else
 630					{
 631						$this->CI->form_validation->set_error($this->CI->uploads->errors);
 632					}
 633				}
 634			}
 635		}
 636		
 637		// captcha
 638		if (isset($_POST['captcha']) && !$this->_captcha_check())
 639		{
 640			$this->CI->form_validation->set_error('Sorry you didn\'t pass the spam check. Please make sure Javascript is enabled.');
 641		}
 642		
 643		// add ticket
 644		if ($this->CI->form_validation->run())
 645		{
 646			if ($account)
 647			{
 648				// create user
 649				$this->create_user();
 650				
 651				// set admin session name, if given
 652				if (!$this->CI->site->config['activation'])
 653				{
 654					$this->CI->load->library('auth');
 655					$username = array('field' => 'email', 'label' => 'Email address', 'value' => $this->CI->input->post('email'));
 656					$password = ($this->CI->input->post('password')) ? $this->CI->input->post('password', TRUE) : substr(md5(time()),0,6);
 657
 658					// login or get error message
 659					if (!$this->CI->auth->login($username, $password, 'session_user', FALSE))
 660					{
 661						$this->CI->form_validation->set_error($this->CI->auth->error);
 662					}
 663				}
 664			}
 665
 666			// add ticket
 667			$this->add_ticket($webform, $files);
 668
 669			// redirect if set
 670			if ($redirect = $webform['outcomeRedirect'])
 671			{
 672				redirect($redirect);
 673			}
 674
 675			// get message if set
 676			if ($message = $webform['outcomeMessage'])
 677			{
 678				return $message;
 679			}
 680			else
 681			{
 682				return 'Thank you, your message was sent successfully.';
 683			}				
 684		}
 685		else
 686		{
 687			return FALSE;
 688		}
 689	}
 690
 691	function add_ticket($webform, $files = '')
 692	{
 693		// get web form
 694		if (!$webform)
 695		{
 696			return FALSE;
 697		}
 698			
 699		if ($this->CI->input->post('email'))
 700		{
 701			// set system fields
 702			$fields = array('required', 'formID', 'fieldSet', 'fileTypes', 'account', 'formName', 'outcomeEmails', 'outcomeRedirect', 'outcomeMessage', 'fullName', 'email', 'subject', 'message', 'toEmail', 'captcha', 'firstName', 'lastName', 'password', 'confirmPassword', 'groupID');
 703			
 704			// set default message
 705			$message = '';
 706			$filepaths = '';
 707
 708			// get extra posted info and prepend to message
 709			if (count($_POST))
 710			{
 711				foreach($_POST as $post => $value)
 712				{
 713					if (!in_array($post, $fields) && !preg_match('/^submit$|^submit\_x$|^submit\_y|^x|^y/i', $post))
 714					{
 715						$postValue = $this->CI->input->post($post, TRUE);
 716						$message .= "\t".ucfirst($post) . ": ".$value."\n\n";
 717					}
 718				}
 719			}
 720			
 721			// get files and prepend to message
 722			if ($files)
 723			{
 724				$message .= "\tFiles: ".count($files).((count($files) != 1) ? ' files' : ' file')." uploaded\n\n";
 725				$filepaths .= '<br />';
 726				foreach($files as $name => $fileData)
 727				{
 728					$filepaths .= '<br /><a href="'.site_url($this->CI->uploads->uploadsPath.'/'.$fileData['file_name']).'">'.$fileData['client_name'].'</a>';
 729				}
 730			}
 731			
 732			// get posted message
 733			$message .= (strlen($message) > 1) ? "\n" : '';			
 734			$message .= $this->CI->input->post('message', TRUE);
 735
 736			// set defaults 
 737			$fullName = ($this->CI->input->post('fullName')) ? $this->CI->input->post('fullName', TRUE) : 'N/A';
 738			$subject = ($this->CI->input->post('subject')) ? $this->CI->input->post('subject', TRUE) : (($webform['formName']) ? $webform['formName'] : 'No Subject');
 739			
 740			// set outcome emails
 741			if ($this->CI->input->post('outcomeEmails'))
 742			{
 743				$outcomeEmails = explode(',', $this->CI->input->post('outcomeEmails'));
 744			}
 745			else
 746			{
 747				$outcomeEmails = ($webform['outcomeEmails']) ? explode(',', $webform['outcomeEmails']) : $this->CI->site->config['siteEmail'];
 748			}
 749			
 750			// get first name and last name
 751			$names = explode(' ', $fullName);
 752			$firstName = (sizeof($names) > 1 && $names[0]) ? ucfirst(trim($names[0])) : $name;
 753			$lastName = (sizeof($names) > 1) ? ucfirst(end($names)) : '';
 754					
 755			// add ticket
 756			$this->CI->db->set('siteID', $this->siteID);
 757			$this->CI->db->set('dateCreated', date("Y-m-d H:i:s"));
 758			($webform['formName']) ? $this->CI->db->set('formName', $webform['formName']) : ''; 
 759			$this->CI->db->set('fullName', $fullName);
 760			$this->CI->db->set('email', $this->CI->input->post('email', TRUE));
 761			$this->CI->db->set('subject', $subject);
 762			$this->CI->db->set('body', $message.$filepaths);
 763			$this->CI->db->insert('tickets');
 764			$ticketID = $this->CI->db->insert_id();			
 765
 766			// set header and footer
 767			$emailHeader = str_replace('{name}', $fullName, $this->CI->site->config['emailHeader']);
 768			$emailHeader = str_replace('{first-name}', $firstName, $emailHeader);
 769			$emailHeader = str_replace('{last-name}', $lastName, $emailHeader);
 770			$emailHeader = str_replace('{email}', $this->CI->input->post('email', TRUE), $emailHeader);
 771			$emailFooter = str_replace('{name}', $fullName, $this->CI->site->config['emailFooter']);
 772			$emailFooter = str_replace('{first-name}', $firstName, $emailFooter);
 773			$emailFooter = str_replace('{last-name}', $lastName, $emailFooter);
 774			$emailFooter = str_replace('{email}', $this->CI->input->post('email', TRUE), $emailFooter);
 775			$emailTicket = str_replace('{name}', $fullName, $this->CI->site->config['emailTicket']);
 776			$emailTicket = str_replace('{first-name}', $firstName, $emailTicket);
 777			$emailTicket = str_replace('{last-name}', $lastName, $emailTicket);
 778			$emailTicket = str_replace('{email}', $this->CI->input->post('email', TRUE), $emailTicket);
 779			
 780			// send despatch email to customer
 781			$body = $emailHeader."\n\n";
 782			$body .= $emailTicket."\n\n";
 783			$body .= "\tTicket ID: ".$ticketID."\n";
 784			$body .= "\tSubject: ".$subject."\n";
 785			$body .= "\tName: ".$fullName."\n";
 786			$body .= "\tEmail: ".$this->CI->input->post('email')."\n\n";
 787
 788			// attach message
 789			if ($message)
 790			{
 791				$body .= "Message:\n";
 792				$body .= "---------------------------------------------\n\n";
 793				$body .= $message."\n\n";			
 794				$body .= "---------------------------------------------\n\n";
 795			}
 796
 797			// send username and password
 798			if ($webform['account'])
 799			{
 800				$body .= "Your login details are below:\n";
 801				$body .= "---------------------------------------------\n\n";
 802				$body .= "Your email: \t".$this->CI->input->post('email')."\n";
 803				$body .= "Your password: \t".(($this->CI->input->post('password', TRUE)) ? $this->CI->input->post('password', TRUE) : substr(md5(time()),0,6))."\n\n";
 804				$body .= "---------------------------------------------\n\n";
 805			}
 806			
 807			$footerBody = $emailFooter;
 808	
 809			// load email lib and email user and admin
 810			$this->CI->load->library('email');
 811
 812			// attach files
 813			if ($files)
 814			{
 815				foreach ($files as $file)
 816				{	
 817					$this->CI->email->attach($file['full_path']);
 818				}
 819			}
 820
 821			// send to recipient
 822			$this->CI->email->to($this->CI->input->post('email', TRUE));
 823			$this->CI->email->from($this->CI->site->config['siteEmail'], $this->CI->site->config['siteName']);
 824			$this->CI->email->subject('[#'.$ticketID.']: ' . $subject);
 825			$this->CI->email->message($body.$footerBody);
 826			$this->CI->email->send();
 827
 828			$this->CI->email->clear();
 829
 830			// send to CC or admin
 831			$this->CI->email->to($outcomeEmails);
 832			$this->CI->email->from($this->CI->input->post('email', TRUE));
 833			$this->CI->email->subject('FW: [#'.$ticketID.']: ' . $this->CI->input->post('subject', TRUE));
 834			$this->CI->email->message("A web form was submitted on ".$this->CI->site->config['siteName'].".\n\n---------------------------------------------\n\n".$body.$footerBody);
 835			$this->CI->email->send();
 836
 837			return $ticketID;
 838		}
 839		else
 840		{
 841			return FALSE;
 842		}
 843	}
 844
 845	function create_user()
 846	{
 847		// get values
 848		$this->CI->core->get_values('users');	
 849
 850		// security check
 851		if ($this->CI->input->post('username')) $this->CI->core->set['username'] = '';
 852		if ($this->CI->input->post('subscribed')) $this->CI->core->set['subscribed'] = '';
 853		if ($this->CI->input->post('plan')) $this->CI->core->set['plan'] = '';
 854		if ($this->CI->input->post('siteID')) $this->CI->core->set['siteID'] = $this->siteID;
 855		if ($this->CI->input->post('userID')) $this->CI->core->set['userID'] = '';
 856		if ($this->CI->input->post('kudos')) $this->CI->core->set['kudos'] = '';
 857		if ($this->CI->input->post('posts')) $this->CI->core->set['posts'] = '';
 858
 859		// set folder (making sure it's not an admin folder)
 860		$permissionGroupsArray = $this->CI->permission->get_groups('admin');
 861		foreach((array)$permissionGroupsArray as $group)
 862		{
 863			$permissionGroups[$group['groupID']] = $group['groupName'];
 864		}				
 865		if ($this->CI->input->post('groupID') > 0 && !@in_array($this->CI->input->post('groupID'), $permissionGroups))
 866		{
 867			$this->CI->core->set['groupID'] = $this->CI->input->post('groupID');
 868		}
 869
 870		// set date
 871		$this->CI->core->set['dateCreated'] = date("Y-m-d H:i:s");
 872
 873		// init null name
 874		$firstName = '';
 875		$lastName = '';
 876		
 877		// set name if only fullName is posted
 878		if ($this->CI->input->post('fullName') && (!$this->CI->input->post('firstName') && !$this->CI->input->post('lastName')))
 879		{
 880			$fullName = $this->CI->input->post('fullName', TRUE);
 881			$fullNameArray = @explode(' ', $fullName);
 882			$lastName = (sizeof($fullNameArray) > 0) ? ucfirst(trim(end($fullNameArray))) : '';
 883			$firstName = (sizeof($fullNameArray) > 0) ? ucfirst(trim($fullNameArray[0])) : $fullName;
 884			
 885			$this->CI->core->set['firstName'] = $firstName;
 886			$this->CI->core->set['lastName'] = $lastName;			
 887		}
 888		
 889		// set first name
 890		if ($this->CI->input->post('firstName'))
 891		{
 892			$firstName = ucfirst($this->CI->input->post('firstName', TRUE));
 893			$this->CI->core->set['firstName'] = $firstName;
 894		}
 895		
 896		// set last name
 897		if ($this->CI->input->post('lastName'))
 898		{
 899			$lastName = ucfirst($this->CI->input->post('lastName', TRUE));
 900			$this->CI->core->set['lastName'] = $lastName;
 901		}		
 902
 903		// generate password
 904		if (!$this->CI->input->post('password'))
 905		{
 906			$password = md5(substr(md5(time()),0,6));
 907			$this->CI->core->set['password'] = $password;
 908		}
 909
 910		// set manual activation
 911		if ($this->CI->site->config['activation'])
 912		{
 913			$this->CI->core->set['active'] = 0;
 914		}
 915
 916		// set email on flash data
 917		$flashEmail = $this->CI->session->flashdata('email');
 918
 919		// update table
 920		if ($this->CI->input->post('email') && ($this->CI->input->post('password') || $password))
 921		{
 922			if ($this->CI->core->update('users'))
 923			{
 924				$result = array(
 925					'userID' => $this->CI->db->insert_id(),
 926					'email' => $this->CI->input->post('email', TRUE),
 927					'password' => ($this->CI->input->post('password')) ? $this->CI->input->post('password', TRUE) : $password,
 928					'firstName' => $firstName,
 929					'lastName' => $lastName
 930				);	
 931				
 932				return $result;
 933			}
 934			else
 935			{
 936				return FALSE;
 937			}
 938		}
 939		else
 940		{
 941			return FALSE;
 942		}
 943	}
 944
 945	function _captcha_check()
 946	{
 947		// if captcha is posted, check its not a bot (requires js)
 948		if ($this->CI->input->post('captcha') == 'notabot')
 949		{
 950			return TRUE;
 951		}
 952		elseif ($this->CI->input->post('captcha') != 'notabot')
 953		{
 954			$this->CI->form_validation->set_message('captcha_check', 'You didn\'t pass the spam check, please contact us to post a comment.');
 955			return FALSE;
 956		}
 957	}
 958	
 959	
 960	/* utilities */
 961	
 962	
 963	// gets posted values
 964	function get_post()
 965	{
 966		if (count($_POST))
 967		{
 968			$post = array();
 969			foreach($_POST as $key => $value)
 970			{
 971				$post[$key] = $this->CI->input->post($key);
 972			}
 973			
 974			return $post;
 975		}
 976		else
 977		{
 978			return FALSE;
 979		}
 980	}
 981
 982	// gets values from post and/or the row
 983	function get_values($data = '', $id = '')
 984	{
 985		// init array
 986		$values = array();
 987
 988		// populate by row if set
 989		if (@is_array($data))
 990		{
 991			$row = $data;
 992			$values = $data;
 993		}
 994
 995		// get data from database		
 996		else
 997		{
 998			$table = $data;
 999			
1000			if ($id)
1001			{
1002				$query = $this->CI->db->get_where($table, $id);
1003	
1004				if ($query->num_rows())
1005				{
1006					$row = $query->row_array();	
1007					$values = $row;
1008				}
1009			}
1010		}
1011
1012		// get post if there is any
1013		if ($post = $this->get_post())
1014		{
1015			// check posted data is in fields
1016			foreach ($post as $field => $value)
1017			{
1018				// make sure the value is just a normal value and not an array
1019				if (!is_array($value))
1020				{
1021					if (isset($row) && isset($row[$field]) && $value == $row[$field])
1022					{
1023						unset($this->required[$field]);
1024					}
1025					else
1026					{
1027						// prep password
1028						if ($field == 'password')
1029						{
1030							if ($value != '')
1031							{
1032								$values[$field] = md5($value);
1033							}
1034						}
1035		
1036						// overwrite value with posted value
1037						else
1038						{
1039							$values[$field] = $value;
1040						}
1041					}
1042			
1043					if (array_key_exists($field, $this->set))
1044					{
1045						unset($values[$field]);
1046					}	
1047				}
1048			}
1049		}
1050
1051		return $values;
1052	}
1053
1054	// is ajax?
1055    function is_ajax() 
1056    {
1057        return (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'));
1058    }
1059
1060	// check for errors
1061	function check_errors()
1062	{	
1063		// set rules for validation
1064		if (isset($this->required))
1065		{
1066			$config = array();
1067			
1068			foreach ($this->required as $field => $name)
1069			{
1070				if (is_array($name))
1071				{
1072					$config[$field] = array('field' => $field, 'label' => $name['label'], 'rules' => $name['rules']);
1073				}
1074				else
1075				{
1076					if ($field == 'email')
1077					{
1078						$config[$field] = array('field' => $field, 'label' => $name, 'rules' => 'required|valid_email');
1079					}
1080					elseif ($field == 'password')
1081					{
1082						$config[$field] = array('field' => $field, 'label' => $name, 'rules' => 'required|matches[confirmPassword]');
1083					}
1084					else
1085					{
1086						$config[$field] = array('field' => $field, 'label' => $name, 'rules' => 'required');
1087					}
1088				}
1089			}
1090
1091			// set rules and fields for validation
1092			$this->CI->form_validation->set_rules($config);
1093
1094			if (!$this->CI->form_validation->run() && isset($this->required) && count($this->required))
1095			{
1096				return FALSE;
1097			}
1098			else
1099			{
1100				return TRUE;
1101			}
1102		}
1103		else
1104		{
1105			return TRUE;
1106		}
1107	}
1108	
1109	// get all rows from a table
1110	function viewall($table, $where = '', $order = '', $limit = '')
1111	{
1112		// get table fields
1113		$fields = $this->CI->db->list_fields($table);
1114		
1115		// set limit from uri if set
1116		$limit = (!$limit) ? $this->CI->site->config['paging'] : $limit;
1117
1118		// get uri array for ordering
1119		$uriArray = $this->CI->uri->uri_to_assoc($this->uri_assoc_segment);
1120
1121		// set order on order array
1122		if (count($uriArray))
1123		{
1124			foreach($uriArray as $key => $value)
1125			{
1126				if ($key)
1127				{
1128					if ($key == 'orderasc')
1129					{
1130						$this->CI->db->order_by($value,'asc');
1131					}
1132					elseif ($key == 'orderdesc')
1133					{
1134						$this->CI->db->order_by($value,'desc');
1135					}
1136				}
1137			}
1138		}
1139		
1140		// order override
1141		elseif ($order && !is_array($order))
1142		{
1143			$this->CI->db->order_by($order, 'asc');
1144		}
1145		elseif ($order && is_array($order))
1146		{
1147			$this->CI->db->order_by($order[0], $order[1]);
1148		}
1149
1150		if (!(isset($uriArray['orderasc']) || isset($uriArray['orderdesc'])) && in_array('dateCreated', $fields))
1151		{
1152			$this->CI->db->order_by('dateCreated', 'desc');
1153		}
1154		
1155		// wheres
1156		if ($where)
1157		{
1158			$this->CI->db->where($where);
1159		}
1160		if (!$this->adminOverRide && $this->siteID)
1161		{
1162			$this->CI->db->where('siteID', $this->siteID);
1163		}
1164		if (in_array('deleted', $fields))
1165		{
1166			$this->CI->db->where('deleted', 0);
1167		}
1168
1169		// get and return results
1170		$query = $this->CI->db->get($table, $limit, $this->CI->pagination->offset);
1171		$output[$table] = $query->result_array();
1172
1173		// do same thing again but get count
1174		if ($where)
1175		{
1176			$this->CI->db->where($where);
1177		}
1178		if (!$this->adminOverRide && $this->siteID)
1179		{
1180			$this->CI->db->where('siteID', $this->siteID);
1181		}
1182		if (in_array('deleted', $fields))
1183		{
1184			$this->CI->db->where('deleted', 0);
1185		}		
1186		$query_total = $this->CI->db->get($table); 
1187		$totalRows = $query_total->num_rows();	
1188
1189		// set pagination config
1190		$this->set_paging($totalRows, $limit);
1191
1192		return $output;			
1193	}
1194
1195	// update table	
1196	function update($table, $id = '')
1197	{	
1198		if (count($_POST) || count($_FILES))
1199		{
1200			// get fields of this table
1201			$fields = $this->CI->db->list_fields($table);
1202
1203			// get data from database
1204			if ($id)
1205			{
1206				$query = $this->CI->db->get_where($table, $id);
1207	
1208				if ($query->num_rows())
1209				{
1210					$row = $query->row_array();	
1211				}
1212			}
1213
1214			// get values
1215			$values = @$this->get_values($row);
1216
1217			// check posted data is in fields
1218			foreach ($values as $field => $value)
1219			{
1220				if (@!in_array($field, $fields))
1221				{
1222					unset($values[$field]);
1223				}
1224				if (array_key_exists($field, $this->set))
1225				{
1226					unset($values[$field]);
1227				}
1228			}
1229
1230			//  if validate is unsuccessful show errors (return false) else insert and redirect
1231			if ($this->check_errors())
1232			{
1233				// set siteID
1234				if (!$this->adminOverRide && $this->siteID)
1235				{
1236					$this->set['siteID'] = SITEID;
1237				}			
1238				
1239				// set fields
1240				if ($this->set && sizeof($this->set) > 0)
1241				{				
1242					$this->CI->db->set($this->set);
1243					unset($this->set);
1244				}
1245	
1246				// add row
1247				if (@!$row && !$id)
1248				{
1249					$this->CI->db->insert($table, $values);
1250				}
1251				// edit row
1252				else
1253				{
1254					if ($this->where && sizeof($this->where) > 0)
1255					{
1256						$this->CI->db->where($this->where);
1257					}
1258					$this->CI->db->where($id);
1259					$this->CI->db->update($table, $values);
1260				}
1261
1262				unset($this->required);
1263
1264				return TRUE;
1265			}
1266			else
1267			{
1268				return FALSE;
1269			}			
1270		}
1271		else
1272		{
1273			return FALSE;
1274		}
1275	}
1276
1277	// set paging
1278	function set_paging($totalRows, $limit = '')
1279	{
1280		// get default limit
1281		$limit = ($limit) ? $limit : $this->CI->site->config['paging'];
1282		
1283		// set pagination config
1284		$config['total_rows'] = $totalRows;		
1285		$config['per_page'] = $limit;
1286		$config['full_tag_open'] = '<div class="pagination"><p>';
1287		$config['full_tag_close'] = '</p></div>';
1288		$config['num_links'] = 6;
1289		$this->CI->pagination->initialize($config);
1290	}	
1291
1292	// delete permanently
1293	function delete($table, $id)
1294	{	
1295		// delete item from db
1296		if (!$this->adminOverRide && $this->siteID)
1297		{
1298			$this->CI->db->where('siteID', $this->siteID);
1299		}		
1300		if ($this->where && sizeof($this->where) > 0)
1301		{
1302			$this->CI->db->where($this->where);
1303		}
1304		$this->CI->db->delete($table, $id);
1305
1306		if ($this->CI->db->affected_rows())
1307		{
1308			return true;
1309		}
1310		else
1311		{
1312			return false;
1313		}
1314	}
1315
1316	// delete from site but keep in database
1317	function soft_delete($table, $id)
1318	{
1319		// soft delete item from db
1320		if (!$this->adminOverRide && $this->siteID)
1321		{
1322			$this->CI->db->where('siteID', $this->siteID);
1323		}		
1324		$this->CI->db->set('deleted', 1);
1325		if ($this->where && sizeof($this->where) > 0)
1326		{
1327			$this->CI->db->where($this->where);
1328		}
1329		$this->CI->db->where($id);
1330		$this->CI->db->update($table);
1331
1332		if ($this->CI->db->affected_rows())
1333		{
1334			return true;
1335		}
1336		else
1337		{
1338			return false;
1339		}
1340	}
1341	
1342	// order rows
1343	function order($table = '', $field = '')
1344	{
1345		// for each posted item, order it with new row id
1346		if ($table && $field)
1347		{
1348			foreach ($_POST[$table] as $key => $value)
1349			{
1350				if ($this->siteID)
1351				{	
1352					$this->CI->db->where('siteID', $this->siteID);
1353				}
1354				$this->CI->db->where($field.'ID', $value);
1355				$this->CI->db->update($table, array($field.'Order' => ($key + 1)));
1356			}
1357		}
1358		else
1359		{
1360			return false;
1361		}
1362	}	
1363
1364	// encode url
1365	function encode($data)
1366	{
1367		return strtr(rtrim(base64_encode($data), '='), '+/', '-_');
1368	}
1369
1370	// decode url
1371	function decode($base64)
1372	{
1373		return base64_decode(strtr($base64, '-_', '+/'));
1374	}
1375	
1376}