PageRenderTime 716ms CodeModel.GetById 242ms app.highlight 260ms RepoModel.GetById 202ms app.codeStats 1ms

/halogy/application/libraries/Template.php

https://bitbucket.org/haloweb/halogy-1.0/
PHP | 1094 lines | 818 code | 144 blank | 132 comment | 124 complexity | dc09db849d48da51f56e14aed10666af 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 Template {
  20
  21	// set defaults
  22	var $CI;								// CI instance
  23	var $base_path = '';					// default base path
  24	var $moduleTemplates = array();
  25	var $template = array();
  26	
  27	function Template()
  28	{
  29		$this->CI =& get_instance();
  30		
  31		// get siteID, if available
  32		if (defined('SITEID'))
  33		{
  34			$this->siteID = SITEID;
  35		}
  36
  37		$this->uploadsPath = $this->CI->config->item('uploadsPath');
  38
  39		// populate module templates array
  40		$this->moduleTemplates = array(
  41			'blog',		
  42			'blog_single',
  43			'blog_search',
  44			'community_account',
  45			'community_create_account',
  46			'community_forgotten',
  47			'community_home',
  48			'community_login',
  49			'community_members',
  50			'community_messages',
  51			'community_messages_form',
  52			'community_messages_popup',
  53			'community_messages_read',
  54			'community_reset',
  55			'community_view_profile',
  56			'community_view_profile_private',
  57			'events',		
  58			'events_single',
  59			'events_search',
  60			'forums',
  61			'forums_delete',
  62			'forums_edit_post',
  63			'forums_edit_topic',						
  64			'forums_forum',
  65			'forums_post_reply',
  66			'forums_post_topic',
  67			'forums_search',
  68			'forums_topic',
  69			'shop_account',
  70			'shop_browse',
  71			'shop_cancel',
  72			'shop_cart',
  73			'shop_checkout',
  74			'shop_create_account',
  75			'shop_donation',
  76			'shop_featured',
  77			'shop_forgotten',
  78			'shop_login',
  79			'shop_orders',
  80			'shop_prelogin',
  81			'shop_product',
  82			'shop_recommend',
  83			'shop_recommend_popup',			
  84			'shop_reset',
  85			'shop_review',
  86			'shop_review_popup',
  87			'shop_subscriptions',
  88			'shop_success',
  89			'shop_view_order',
  90			'wiki',
  91			'wiki_form',
  92			'wiki_page',
  93			'wiki_search'
  94		);		
  95	}
  96
  97	function generate_template($pagedata, $file = false)
  98	{	
  99		// page data
 100		@$this->template['page:title'] = (isset($pagedata['title'])) ? htmlentities($pagedata['title']) : htmlentities($this->CI->site->config['siteName']);
 101		@$this->template['page:keywords'] = (isset($pagedata['keywords'])) ? $pagedata['keywords'] : '';
 102		@$this->template['page:description'] = (isset($pagedata['description'])) ? $pagedata['description'] : '';
 103		@$this->template['page:date'] = (isset($pagedata['dateCreated'])) ? dateFmt($pagedata['dateCreated']) : '';
 104		@$this->template['page:date-modified'] = (isset($pagedata['dateModified'])) ? dateFmt($pagedata['dateModified']) : '';
 105		@$this->template['page:uri'] = $this->CI->uri->uri_string();
 106		@$this->template['page:uri-encoded'] = $this->CI->core->encode($this->CI->uri->uri_string());
 107		@$this->template['page:uri:segment(1)'] = $this->CI->uri->segment(1);
 108		@$this->template['page:uri:segment(2)'] = $this->CI->uri->segment(2);
 109		@$this->template['page:uri:segment(3)'] = $this->CI->uri->segment(3);
 110		@$this->template['page:template'] = ($this->template['page:template']) ? $this->template['page:template'] : '';
 111
 112		// find out if logged in
 113		$this->template['logged-in'] = ($this->CI->session->userdata('session_user')) ? TRUE : FALSE;
 114		
 115		// find out if subscribed
 116		$this->template['subscribed'] = ($this->CI->session->userdata('subscribed')) ? TRUE : FALSE;		
 117
 118		// find out if admin
 119		$this->template['admin'] = ($this->CI->session->userdata('session_admin')) ? TRUE : FALSE;		
 120
 121		// find out if this is ajax
 122		$this->template['ajax'] = ((isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest'))) ? TRUE : FALSE;
 123
 124		// find out if browser is iphone
 125		$this->template['mobile'] = (strpos($_SERVER['HTTP_USER_AGENT'], 'iPhone') || strpos($_SERVER['HTTP_USER_AGENT'], 'Android')) ? TRUE : FALSE;
 126
 127		// permissions
 128		if ($this->CI->session->userdata('session_admin'))
 129		{
 130			if ($permissions = $this->CI->permission->get_group_permissions($this->CI->session->userdata('groupID')))
 131			{
 132				foreach($permissions as $permission)
 133				{
 134					@$this->template['permission:'.$permission] = TRUE;
 135				}
 136			}
 137		}
 138
 139		// feed (if it exists for the module)
 140		@$this->template['page:feed'] = (isset($pagedata['feed'])) ? $pagedata['feed'] : '';
 141
 142		// either build template from a file or from db
 143		if ($file)
 144		{
 145			$templateBody = $this->parse_template($file, FALSE, NULL, FALSE);
 146		}
 147		else
 148		{
 149			$templateData = $this->CI->core->get_template($pagedata['templateID']);
 150			$templateBody = $templateData['body'];
 151		}
 152
 153		// parse it for everything else
 154		$this->template['body'] = $this->parse_template($templateBody, FALSE, NULL, FALSE);
 155
 156		// get navigation and build menu
 157		if (preg_match_all('/{navigation(\:([a-z0-9\.-]+))?}/i', $this->template['body'], $matches))
 158		{
 159			$this->template = $this->parse_navigation('navigation', $this->template);			
 160		}
 161
 162		return $this->template;
 163	}
 164
 165	function parse_includes($body)
 166	{
 167		// get includes
 168		preg_match_all('/include\:([a-z0-9\.-]+)/i', $body, $includes);
 169
 170		if ($includes)
 171		{
 172			$includeBody = '';
 173			foreach($includes[1] as $include => $value)
 174			{
 175				$includeRow = $this->CI->core->get_include($value);
 176
 177				$includeBody = $this->parse_body($includeRow['body'], FALSE, NULL, FALSE);
 178
 179				$includeBody = $this->CI->parser->conditionals($includeBody, $this->template, TRUE);
 180
 181				$body = str_replace('{include:'.$value.'}', $includeBody, $body);
 182			}
 183		}
 184
 185		return $body;
 186	}
 187
 188	function parse_navigation($navTag, $template, $group = '')
 189	{
 190		$template[$navTag] = '';
 191		$template[$navTag.':parents'] = '';	
 192				
 193		if ($navigation = $this->get_nav_parents($group))
 194		{			
 195			$i = 1;
 196			foreach($navigation as $nav)
 197			{
 198				// get subnav
 199				$children = $this->get_nav_children($nav['navID']);
 200
 201				// set last state on menu
 202				$class = '';
 203				if ($i == 1)
 204				{
 205					$class .= 'first ';
 206				}
 207
 208				// set last state on menu
 209				if (sizeof($navigation) == $i)
 210				{
 211					$class .= 'last ';
 212				}
 213				
 214				// parse the nav item for the link
 215				$template[$navTag] .= $this->parse_nav_item($nav['uri'], $nav['navName'], $children, $class);
 216				$template[$navTag.':parents'] .= $this->parse_nav_item($nav['uri'], $nav['navName'], $children, $class);
 217
 218				// output subnav
 219				if ($children)
 220				{
 221					$template[$navTag] .= '<ul class="subnav">';
 222					foreach($children as $child)
 223					{
 224						$navItem = $this->parse_nav_item($child['uri'], $child['navName']).'</li>';
 225						$template[$navTag] .= $navItem;
 226					}
 227					$template[$navTag] .= '</ul>';
 228				}
 229
 230				$template[$navTag] .= '</li>';
 231				$template[$navTag.':parents'] .= '</li>';
 232				
 233				$i++;
 234			}
 235		}
 236		
 237		// get children for this segment
 238		$template[$navTag.':children'] = $this->parse_navigation_children();
 239
 240		return $template;
 241	}
 242	
 243	function parse_navigation_children()
 244	{
 245		$output = '';
 246		
 247		// get children for this uri
 248		if ($navigation = $this->get_nav())
 249		{
 250			foreach($navigation as $nav)
 251			{
 252				// get subnav
 253				if ($children = $this->get_nav_children($nav['navID']))
 254				{
 255					foreach($children as $child)
 256					{
 257						$navItem = $this->parse_nav_item($child['uri'], $child['navName']).'</li>';
 258						if ($this->CI->uri->segment(1) == $nav['uri'] || 
 259							(
 260								($this->CI->uri->uri_string() == '' || $this->CI->uri->segment(1) == 'home') &&
 261								($nav['uri'] == '/' || $nav['uri'] == 'home')
 262							)
 263						)
 264						{
 265							$output .= $navItem;
 266						}
 267					}
 268				}
 269			}
 270		}
 271		
 272		return $output;
 273	}
 274
 275	function parse_nav_item($uri, $name, $children = FALSE, $class = '')
 276	{
 277		// init stuff
 278		$output = '';
 279		$childs = array();
 280
 281		// tidy children array
 282		if ($children)
 283		{
 284			foreach($children as $child)
 285			{
 286				$childs[] = $child['uri'];
 287			}
 288		}
 289		
 290		// set active state on menu
 291		$currentNav = $uri;
 292		$output .= '<li class="';
 293		if (($currentNav != '/' && preg_match('/^'.str_replace('/','\/',$currentNav).'/i', substr($this->CI->uri->uri_string(), 1))) || 
 294			$currentNav == $this->CI->uri->segment(1) ||  
 295			(($currentNav == '' || $currentNav == 'home' || $currentNav == '/') && 
 296			($this->CI->uri->uri_string() == '' || $this->CI->uri->uri_string() == '/home' || $this->CI->uri->uri_string() == '/')) ||
 297			@in_array(substr($this->CI->uri->uri_string(),1), $childs)
 298		)
 299		{
 300			$class .= 'active selected ';
 301		}
 302		if ($children)
 303		{
 304			$class .= 'expanded ';
 305		}
 306		
 307		// filter uri to make sure it's cool
 308		if (substr($uri,0,1) == '/')
 309		{
 310			$href = $uri;
 311		}
 312		elseif (stristr($uri,'http://'))
 313		{
 314			$href = $uri;
 315		}
 316		elseif (stristr($uri,'www.'))
 317		{
 318			$href = 'http://'.$uri;
 319		}
 320		elseif (stristr($uri,'mailto:'))
 321		{
 322			$href = $uri;
 323		}
 324		elseif ($uri == 'home')
 325		{
 326			$href = '/';
 327		}			
 328		else
 329		{
 330			$href = '/'.$uri;
 331		}
 332
 333		$output .= trim($class).'"><a href="'.$href.'" class="'.trim($class).'"><span>'.htmlentities($name).'</span></a>';
 334
 335		return $output;
 336	}
 337
 338	function get_nav($navID = '')
 339	{
 340		// default where
 341		$this->CI->db->where(array('siteID' => $this->siteID, 'deleted' => 0));
 342
 343		// where parent is set
 344		$this->CI->db->where('parentID', 0); 
 345
 346		// get navigation from pages
 347		$this->CI->db->select('uri, pageID as navID, pageName as navName');
 348				
 349		$this->CI->db->order_by('pageOrder', 'asc');
 350		
 351		$query = $this->CI->db->get('pages');
 352		
 353		if ($query->num_rows())
 354		{
 355			return $query->result_array();
 356		}
 357		else
 358		{
 359			return false;
 360		}		
 361	}
 362
 363	function get_nav_parents()
 364	{
 365		// default where
 366		$this->CI->db->where(array('siteID' => $this->siteID, 'deleted' => 0));
 367
 368		// where parent is set
 369		$this->CI->db->where('parentID', 0); 
 370
 371		// get navigation from pages
 372		$this->CI->db->select('uri, pageID as navID, pageName as navName');
 373		
 374		// nav has to be active because its parents
 375		$this->CI->db->where('navigation', 1);
 376		
 377		$this->CI->db->order_by('pageOrder', 'asc');
 378		
 379		$query = $this->CI->db->get('pages');
 380		
 381		if ($query->num_rows())
 382		{
 383			return $query->result_array();
 384		}
 385		else
 386		{
 387			return false;
 388		}		
 389	}
 390
 391	function get_nav_children($navID = '', $group = '')
 392	{
 393		// default where
 394		$this->CI->db->where(array('siteID' => $this->siteID, 'deleted' => 0));
 395
 396		// get nav by ID
 397		$this->CI->db->where('parentID', $navID);
 398
 399		// get navigation from navigation table
 400		if ($group)
 401		{
 402			// nav has to be active
 403			$this->CI->db->where('active', 1);
 404			
 405			$this->CI->db->order_by('navOrder', 'asc');
 406			
 407			$query = $this->CI->db->get('navigation');
 408		}
 409
 410		// just select from pages
 411		else
 412		{
 413			// nav has to be active
 414			$this->CI->db->select('uri, pageID as navID, pageName as navName');
 415			
 416			$this->CI->db->where('navigation', 1);
 417			
 418			$this->CI->db->order_by('pageOrder', 'asc');
 419			
 420			$query = $this->CI->db->get('pages');
 421		}
 422				
 423		if ($query->num_rows())
 424		{
 425			return $query->result_array();
 426		}
 427		else
 428		{
 429			return FALSE;
 430		}		
 431	}
 432
 433	function parse_template($body, $condense = FALSE, $link = '', $mkdn = TRUE)
 434	{		
 435		$body = $this->parse_body($body, $condense, $link, $mkdn);
 436		
 437		return $body;
 438	}
 439
 440	function parse_body($body, $condense = FALSE, $link = '', $mkdn = TRUE)
 441	{		
 442		// parse for images		
 443		$body = $this->parse_images($body);
 444
 445		// parse for files
 446		$body = $this->parse_files($body);
 447
 448		// parse for files
 449		$body = $this->parse_includes($body);
 450
 451		// parse for modules
 452		$this->template = $this->parse_modules($body, $this->template);	
 453		
 454		// site globals
 455		$body = str_replace('{site:name}', $this->CI->site->config['siteName'], $body);
 456		$body = str_replace('{site:domain}', $this->CI->site->config['siteDomain'], $body);
 457		$body = str_replace('{site:url}', $this->CI->site->config['siteURL'], $body);
 458		$body = str_replace('{site:email}', $this->CI->site->config['siteEmail'], $body);
 459		$body = str_replace('{site:tel}', $this->CI->site->config['siteTel'], $body);		
 460		$body = str_replace('{site:currency}', $this->CI->site->config['currency'], $body);
 461		$body = str_replace('{site:currency-symbol}', currency_symbol(), $body);
 462
 463		// logged in userdata
 464		$body = str_replace('{userdata:id}', ($this->CI->session->userdata('userID')) ? $this->CI->session->userdata('userID') : '', $body);
 465		$body = str_replace('{userdata:email}', ($this->CI->session->userdata('email')) ? $this->CI->session->userdata('email') : '', $body);
 466		$body = str_replace('{userdata:username}', ($this->CI->session->userdata('username')) ? $this->CI->session->userdata('username') : '', $body);
 467		$body = str_replace('{userdata:name}', ($this->CI->session->userdata('firstName') && $this->CI->session->userdata('lastName')) ? $this->CI->session->userdata('firstName').' '.$this->CI->session->userdata('lastName') : '', $body);		
 468		$body = str_replace('{userdata:first-name}', ($this->CI->session->userdata('firstName')) ? $this->CI->session->userdata('firstName') : '', $body);
 469		$body = str_replace('{userdata:last-name}', ($this->CI->session->userdata('lastName')) ? $this->CI->session->userdata('lastName') : '', $body);
 470
 471		// other useful stuff
 472		$body = str_replace('{date}', dateFmt(date("Y-m-d H:i:s"), ($this->CI->site->config['dateOrder'] == 'MD') ? 'M jS Y' : 'jS M Y'), $body);
 473		$body = str_replace('{date:unixtime}', time(), $body);
 474		
 475		// condense
 476		if ($condense)
 477		{
 478			if ($endchr = strpos($body, '{more}'))
 479			{
 480				$body = substr($body, 0, ($endchr + 6));
 481				$body = str_replace('{more}', '<p class="more"><a href="'.$link.'" class="button more">Read more</a></p>', $body);				
 482			}
 483		}
 484		else
 485		{
 486			$body = str_replace('{more}', '', $body);
 487		}
 488
 489		// parse for clears
 490		$body = str_replace('{clear}', '<div style="clear:both;"/></div>', $body);
 491
 492		// parse for pads
 493		$body = str_replace('{pad}', '<div style="padding-bottom:10px;width:10px;clear:both;"/></div>', $body);
 494		
 495		// parse body for markdown and images
 496		if ($mkdn === TRUE)
 497		{
 498			// parse for mkdn
 499			$body = mkdn($body);
 500		}
 501		
 502		return $body;
 503	}
 504
 505	function parse_modules($body, $template)
 506	{
 507		// get web forms
 508		if (preg_match_all('/{webform:([A-Za-z0-9_\-]+)}/i', $body, $matches))
 509		{
 510			// filter matches
 511			$webformID = preg_replace('/{|}/', '', $matches[0][0]);
 512			$webform = $this->CI->core->get_web_form_by_ref($matches[1][0]);
 513			$template[$webformID] = '';
 514			$required = array();
 515	
 516			// get web form
 517			if ($webform)
 518			{
 519				// set fields
 520				if ($webform['fieldSet'] == 1)
 521				{
 522					$required[] = 'fullName';
 523					$required[] = 'subject';
 524					$required[] = 'message';					
 525
 526					// populate template
 527					$template[$webformID] .= '
 528						<div class="formrow field-fullName">
 529							<label for="fullName">Full Name</label>
 530							<input type="text" id="fullName" name="fullName" value="'.$this->CI->input->post('fullName').'" class="formelement" />
 531						</div>
 532			
 533						<div class="formrow field-email">
 534							<label for="email">Email</label>
 535							<input type="text" id="email" name="email" value="'.$this->CI->input->post('email').'" class="formelement" />
 536						</div>
 537	
 538						<div class="formrow field-subject">
 539							<label for="subject">Subject</label>
 540							<input type="text" id="subject" name="subject" value="'.$this->CI->input->post('subject').'" class="formelement" />
 541						</div>
 542	
 543						<div class="formrow field-message">		
 544							<label for="message">Message</label>
 545							<textarea id="message" name="message" class="formelement small">'.$this->CI->input->post('message').'</textarea>
 546						</div>
 547					';
 548				}
 549				
 550				// set fields
 551				if ($webform['fieldSet'] == 2)
 552				{
 553					$required[] = 'fullName';
 554
 555					// populate template
 556					$template[$webformID] .= '
 557						<div class="formrow field-fullName">
 558							<label for="fullName">Full Name</label>
 559							<input type="text" id="fullName" name="fullName" value="'.$this->CI->input->post('fullName').'" class="formelement" />
 560						</div>
 561			
 562						<div class="formrow field-email">
 563							<label for="email">Email</label>
 564							<input type="text" id="email" name="email" value="'.$this->CI->input->post('email').'" class="formelement" />
 565						</div>
 566
 567						<input type="hidden" name="subject" value="'.$webform['formName'].'" />
 568					';
 569				}
 570
 571				// set fields
 572				if ($webform['fieldSet'] == 0)
 573				{
 574					// populate template
 575					$template[$webformID] .= '
 576						<input type="hidden" name="subject" value="'.$webform['formName'].'" />
 577					';
 578				}
 579
 580				// set account
 581				if ($webform['account'] == 1)
 582				{
 583					// populate template
 584					$template[$webformID] .= '
 585						<input type="hidden" name="subject" value="'.$webform['formName'].'" />					
 586						<input type="hidden" name="message" value="'.$webform['outcomeMessage'].'" />
 587						<input type="hidden" name="groupID" value="'.$webform['groupID'].'" />						
 588					';
 589				}
 590
 591				// set required
 592				if ($required)
 593				{
 594					$template[$webformID] .= '
 595						<input type="hidden" name="required" value="'.implode('|', $required).'" />
 596					';
 597				}
 598
 599				// output encoded webform ID
 600				$template[$webformID] .= '
 601					<input type="hidden" name="formID" value="'.$this->CI->core->encode($matches[1][0]).'" />
 602				';	
 603			}
 604			else
 605			{
 606				$template[$webformID] = '';
 607			}
 608		}
 609
 610		// get blog headlines
 611		if (preg_match_all('/{headlines:blog(:category(\(([A-Za-z0-9_-]+)\))?)?(:limit(\(([0-9]+)\))?)?}/i', $body, $matches))
 612		{
 613			// load blog model
 614			$this->CI->load->model('blog/blog_model', 'blog');
 615
 616			// filter through matches
 617			for ($x = 0; $x < sizeof($matches[0]); $x++)
 618			{
 619				// filter matches
 620				$headlineID = preg_replace('/{|}/', '', $matches[0][$x]);
 621				$limit = ($matches[6][$x]) ? $matches[6][$x] : $this->CI->site->config['headlines'];			
 622				$headlines = ($matches[3][$x]) ? $this->CI->blog->get_posts_by_category($matches[3][$x], $limit) : $this->CI->blog->get_posts($limit);
 623			
 624				// get latest posts
 625				if ($headlines)
 626				{	
 627					// fill up template array
 628					$i = 0;
 629					foreach ($headlines as $headline)
 630					{
 631						// get rid of any template tags
 632						$headlineBody = $this->parse_body($headline['body'], TRUE, site_url('blog/'.dateFmt($headline['dateCreated'], 'Y/m').'/'.$headline['uri']));
 633						$headlineExcerpt = $this->parse_body($headline['excerpt'], TRUE, site_url('blog/'.dateFmt($headline['dateCreated'], 'Y/m').'/'.$headline['uri']));
 634	
 635						// populate loop
 636						$template[$headlineID][$i] = array(
 637							'headline:link' => site_url('blog/'.dateFmt($headline['dateCreated'], 'Y/m').'/'.$headline['uri']),
 638							'headline:title' => $headline['postTitle'],
 639							'headline:date' => dateFmt($headline['dateCreated'], ($this->CI->site->config['dateOrder'] == 'MD') ? 'M jS Y' : 'jS M Y'),
 640							'headline:day' => dateFmt($headline['dateCreated'], 'd'),
 641							'headline:month' => dateFmt($headline['dateCreated'], 'M'),
 642							'headline:year' => dateFmt($headline['dateCreated'], 'y'),						
 643							'headline:body' => $headlineBody,
 644							'headline:excerpt' => $headlineExcerpt,						
 645							'headline:comments-count' => $headline['numComments'],
 646							'headline:author' => $this->CI->blog->lookup_user($headline['userID'], TRUE),
 647							'headline:author-id' => $headline['userID'],
 648							'headline:class' => ($i % 2) ? ' alt ' : ''						
 649						);
 650	
 651						$i++;
 652					}
 653				}
 654				else
 655				{
 656					$template[$headlineID] = array();
 657				}
 658			}
 659		}
 660
 661		// get events headlines
 662		if (preg_match_all('/{headlines:events(:limit(\(([0-9]+)\))?)?}/i', $body, $matches))
 663		{
 664			// load events model
 665			$this->CI->load->model('events/events_model', 'events');
 666
 667			// filter matches
 668			$headlineID = preg_replace('/{|}/', '', $matches[0][0]);
 669			$limit = ($matches[3][0]) ? $matches[3][0] : $this->CI->site->config['headlines'];			
 670
 671			// get latest posts
 672			if ($headlines = $this->CI->events->get_events($limit))
 673			{	
 674				// fill up template array
 675				$i = 0;
 676				foreach ($headlines as $headline)
 677				{
 678					$headlineBody = $this->parse_body($headline['description'], TRUE, site_url('events/viewevent/'.$headline['eventID']));
 679					$headlineExcerpt = $this->parse_body($headline['excerpt'], TRUE, site_url('events/viewevent/'.$headline['eventID']));
 680					
 681					$template[$headlineID][$i] = array(
 682						'headline:link' => site_url('events/viewevent/'.$headline['eventID']),
 683						'headline:title' => $headline['eventTitle'],
 684						'headline:date' => dateFmt($headline['eventDate'], ($this->CI->site->config['dateOrder'] == 'MD') ? 'M jS Y' : 'jS M Y'),
 685						'headline:day' => dateFmt($headline['eventDate'], 'd'),
 686						'headline:month' => dateFmt($headline['eventDate'], 'M'),
 687						'headline:year' => dateFmt($headline['eventDate'], 'y'),	
 688						'headline:body' => $headlineBody,
 689						'headline:excerpt' => $headlineExcerpt,
 690						'headline:author' => $this->CI->events->lookup_user($headline['userID'], TRUE),
 691						'headline:author-id' => $headline['userID'],						
 692						'headline:class' => ($i % 2) ? ' alt ' : ''
 693					);
 694
 695					$i++;
 696				}
 697			}
 698			else
 699			{
 700				$template[$headlineID] = array();
 701			}
 702		}
 703		
 704		// get gallery
 705		if (preg_match_all('/{gallery:([A-Za-z0-9_-]+)(:limit\(([0-9]+)\))?}/i', $body, $matches))
 706		{
 707			// load libs etc
 708			$this->CI->load->model('images/images_model', 'images');
 709
 710			// filter through matches
 711			for ($x = 0; $x < sizeof($matches[0]); $x++)
 712			{	
 713				// filter matches
 714				$headlineID = preg_replace('/{|}/', '', $matches[0][0]);
 715				$limit = ($matches[3][$x]) ? $matches[3][$x] : 9;
 716
 717				// get latest posts
 718				if ($gallery = $this->CI->images->get_images_by_folder_ref($matches[1][$x], $limit))
 719				{	
 720					// fill up template array
 721					$i = 0;
 722					foreach ($gallery as $galleryimage)
 723					{
 724						if ($imageData = $this->get_image($galleryimage['imageRef']))
 725						{
 726							$imageHTML = display_image($imageData['src'], $imageData['imageName']);
 727							$imageHTML = preg_replace('/src=("[^"]*")/i', 'src="/images/'.$imageData['imageRef'].strtolower($imageData['ext']).'"', $imageHTML);
 728							
 729							$thumbTML = display_image($imageData['src'], $imageData['imageName']);
 730							$thumbHTML = preg_replace('/src=("[^"]*")/i', 'src="/thumbs/'.$imageData['imageRef'].strtolower($imageData['ext']).'"', $imageHTML);									
 731							
 732							$template[$headlineID][$i] = array(
 733								'galleryimage:link' => site_url('images/'.$imageData['imageRef'].$imageData['ext']),
 734								'galleryimage:title' => $imageData['imageName'],
 735								'galleryimage:image' => $imageHTML,
 736								'galleryimage:thumb' => $thumbHTML,
 737								'galleryimage:filename' => $imageData['imageRef'].'.'.$imageData['ext'],
 738								'galleryimage:date' => dateFmt($imageData['dateCreated'], ($this->CI->site->config['dateOrder'] == 'MD') ? 'M jS Y' : 'jS M Y'),
 739								'galleryimage:author' => $this->CI->images->lookup_user($imageData['userID'], TRUE),
 740								'galleryimage:author-id' => $imageData['userID'],					
 741								'galleryimage:class' => $imageData['class']
 742							);
 743							
 744							$i++;
 745						}
 746					}
 747				}
 748				else
 749				{
 750					$template[$headlineID] = array();
 751				}
 752			}
 753		}
 754
 755		// get shop gateway
 756		if (preg_match('/{shop:(.+)}|{headlines:shop/i', $body))
 757		{
 758			// load messages model
 759			$this->CI->load->model('shop/shop_model', 'shop');
 760			
 761			// shop globals
 762			$template['shop:email'] = $this->CI->site->config['shopEmail'];
 763			$template['shop:paypal'] = $this->CI->shop->paypal_url;
 764			$template['shop:gateway'] = ($this->CI->site->config['shopGateway'] == 'sagepay' || $this->CI->site->config['shopGateway'] == 'authorize') ? site_url('/shop/checkout') : $this->CI->shop->gateway_url;
 765			
 766			// get shop headlines
 767			if (preg_match_all('/{headlines:shop(:category\(([A-Za-z0-9_-]+)\))?(:limit\(([0-9]+)\))?}/i', $body, $matches))
 768			{
 769				// filter matches
 770				$headlineID = preg_replace('/{|}/', '', $matches[0][0]);
 771				$limit = ($matches[4][0]) ? $matches[4][0] : $this->CI->site->config['headlines'];
 772				$catSafe = $matches[2][0];
 773					
 774				// get latest posts
 775				if ($headlines = $this->CI->shop->get_latest_products($catSafe, $limit))
 776				{	
 777					// fill up template array
 778					$i = 0;
 779					foreach ($headlines as $headline)
 780					{
 781						// get body and excerpt
 782						$headlineBody = (strlen($headline['description']) > 100) ? substr($headline['description'], 0, 100).'...' : $headline['description'];
 783						$headlineExcerpt = nl2br($headline['excerpt']);
 784	
 785						// get images
 786						if (!$headlineImage = $this->CI->uploads->load_image($headline['productID'], false, true))
 787						{
 788							$headlineImage['src'] = $this->CI->config->item('staticPath').'/images/nopicture.jpg';
 789						}	
 790
 791						// get images
 792						if (!$headlineThumb = $this->CI->uploads->load_image($headline['productID'], true, true))
 793						{
 794							$headlineThumb['src'] = $this->CI->config->item('staticPath').'/images/nopicture.jpg';
 795						}
 796						
 797						// populate template
 798						$template[$headlineID][$i] = array(
 799							'headline:id' => $headline['productID'],
 800							'headline:link' => site_url('shop/'.$headline['productID'].'/'.strtolower(url_title($headline['productName']))),
 801							'headline:title' => $headline['productName'],
 802							'headline:subtitle' => $headline['subtitle'],
 803							'headline:date' => dateFmt($headline['dateCreated'], ($this->CI->site->config['dateOrder'] == 'MD') ? 'M jS Y' : 'jS M Y'),
 804							'headline:body' => $headlineBody,
 805							'headline:excerpt' => $headlineExcerpt,
 806							'headline:price' => currency_symbol().number_format($headline['price'],2),
 807							'headline:image-path' => $headlineImage['src'],
 808							'headline:thumb-path' => $headlineThumb['src'],
 809							'headline:cell-width' => floor(( 1 / $limit) * 100),
 810							'headline:price' => currency_symbol().number_format($headline['price'],2),
 811							'headline:stock' => $headline['stock'],
 812							'headline:class' => ($i % 2) ? ' alt ' : ''
 813						);
 814	
 815						$i++;
 816					}
 817				}
 818				else
 819				{
 820					$template[$headlineID] = array();
 821				}
 822			}
 823
 824			// get shop headlines
 825			if (preg_match_all('/{headlines:shop:featured(:limit(\(([0-9]+)\))?)?}/i', $body, $matches))
 826			{
 827				// filter matches
 828				$headlineID = preg_replace('/{|}/', '', $matches[0][0]);
 829				$limit = ($matches[3][0]) ? $matches[3][0] : $this->CI->site->config['headlines'];				
 830	
 831				// get latest posts
 832				if ($headlines = $this->CI->shop->get_latest_featured_products($limit))
 833				{	
 834					// fill up template array
 835					$i = 0;
 836					foreach ($headlines as $headline)
 837					{
 838						// get body and excerpt
 839						$headlineBody = (strlen($headline['description']) > 100) ? substr($headline['description'], 0, 100).'...' : $headline['description'];
 840						$headlineExcerpt = nl2br($headline['excerpt']);
 841												
 842						// get images
 843						if (!$headlineImage = $this->CI->uploads->load_image($headline['productID'], false, true))
 844						{
 845							$headlineImage['src'] = $this->CI->config->item('staticPath').'/images/nopicture.jpg';
 846						}
 847	
 848						// get thumb
 849						if (!$headlineThumb = $this->CI->uploads->load_image($headline['productID'], true, true))
 850						{
 851							$headlineThumb['src'] = $this->CI->config->item('staticPath').'/images/nopicture.jpg';
 852						}
 853							
 854						$template[$headlineID][$i] = array(
 855							'headline:id' => $headline['productID'],
 856							'headline:link' => site_url('shop/'.$headline['productID'].'/'.strtolower(url_title($headline['productName']))),
 857							'headline:title' => $headline['productName'],
 858							'headline:subtitle' => $headline['subtitle'],
 859							'headline:date' => dateFmt($headline['dateCreated'], ($this->CI->site->config['dateOrder'] == 'MD') ? 'M jS Y' : 'jS M Y'),
 860							'headline:body' => $headlineBody,
 861							'headline:excerpt' => $headlineExcerpt,
 862							'headline:price' => currency_symbol().number_format($headline['price'],2),
 863							'headline:image-path' => $headlineImage['src'],
 864							'headline:thumb-path' => $headlineThumb['src'],
 865							'headline:cell-width' => floor(( 1 / $limit) * 100),
 866							'headline:price' => currency_symbol().number_format($headline['price'],2),
 867							'headline:stock' => $headline['stock'],
 868							'headline:class' => ($i % 2) ? ' alt ' : ''
 869						);
 870	
 871						$i++;
 872					}
 873				}
 874				else
 875				{
 876					$template[$headlineID] = array();
 877				}
 878			}
 879
 880			// get shop cart headlines
 881			if (preg_match('/({((.+)?)shop:cartitems((.+)?)})+|{shop:subtotal}/i', $body))
 882			{
 883				// get shopping cart
 884				$cart = $this->CI->shop->load_cart();
 885	
 886				// get latest posts
 887				if ($headlines = $cart['cart'])
 888				{	
 889					// fill up template array
 890					$i = 0;
 891					foreach ($headlines as $headline)
 892					{					
 893						$template['shop:cartitems'][$i] = array(
 894							'cartitem:link' => site_url('shop/'.$headline['productID'].'/'.strtolower(url_title($headline['productName']))),
 895							'cartitem:title' => $headline['productName'],
 896							'cartitem:quantity' => $headline['quantity'],
 897							'cartitem:price' => currency_symbol().(number_format($headline['price'] * $headline['quantity'], 2)),
 898							'cartitem:class' => ($i % 2) ? ' alt ' : ''
 899						);
 900	
 901						$i++;
 902					}
 903					$template['shop:numitems'] = count($headlines);
 904					$template['shop:subtotal'] = currency_symbol().number_format($cart['subtotal'], 2);
 905				}
 906				else
 907				{
 908					$template['shop:numitems'] = 0;
 909					$template['shop:subtotal'] = currency_symbol().number_format(0, 2);
 910					$template['shop:cartitems'] = array();
 911				}
 912			}
 913			
 914			// get shop navigation
 915			if (preg_match('/({((.+)?)shop:categories((.+)?)})+/i', $body))
 916			{
 917				$template['shop:categories'] = '';
 918				
 919				if ($categories = $this->CI->shop->get_category_parents())
 920				{
 921					$i = 1;
 922					foreach($categories as $nav)
 923					{
 924						// get subnav
 925						if ($children = $this->CI->shop->get_category_children($nav['catID']))
 926						{
 927							$template['shop:categories'] .= '<li class="expanded ';
 928							if ($i == 1)
 929							{
 930								$template['shop:categories'] .= 'first ';
 931							}
 932							if ($i == sizeof($categories))
 933							{
 934								$template['shop:categories'] .= 'last ';
 935							}
 936							$template['shop:categories'] .= '"><a href="/shop/'.$nav['catSafe'].'">'.htmlentities($nav['catName'], NULL, 'UTF-8').'</a><ul class="subnav">';
 937							
 938							foreach($children as $child)
 939							{
 940								$template['shop:categories'] .= '<li class="';
 941								if ($child['catID'] == $this->CI->uri->segment(3) || $nav['catSafe'] == $this->CI->uri->segment(2))
 942								{
 943									$template['shop:categories'] .= 'active selected';
 944								}
 945								$template['shop:categories'] .= '"><a href="/shop/'.$nav['catSafe'].'/'.$child['catSafe'].'">'.htmlentities($child['catName'], NULL, 'UTF-8').'</a></li>';
 946							}
 947							$template['shop:categories'] .= '</ul>';
 948						}					
 949						else
 950						{
 951							$template['shop:categories'] .= '<li class="';
 952							if ($nav['catID'] == $this->CI->uri->segment(3) || $nav['catSafe'] == $this->CI->uri->segment(2))
 953							{
 954								$template['shop:categories'] .= 'active selected ';
 955							}
 956							if ($i == 1)
 957							{
 958								$template['shop:categories'] .= 'first ';
 959							}
 960							if ($i == sizeof($categories))
 961							{
 962								$template['shop:categories'] .= 'last ';
 963							}
 964							$template['shop:categories'] .= '"><a href="/shop/'.$nav['catSafe'].'">'.htmlentities($nav['catName'], NULL, 'UTF-8').'</a>';
 965						}
 966						
 967						$template['shop:categories'] .= '</li>';					
 968						$i++;
 969					}
 970				}
 971			}
 972		}
 973
 974		// message centre stuff
 975		if (preg_match('/({((.+)?)messages:unread((.+)?)})+/i', $body))
 976		{
 977			// load messages model
 978			$this->CI->load->model('community/messages_model', 'messages');
 979
 980			// get message count		
 981			@$template['messages:unread'] = ($messageCount = $this->CI->messages->get_unread_message_count()) ? $messageCount : 0;		
 982		}
 983		
 984		return $template;
 985	}
 986	
 987	function parse_images($body)
 988	{
 989		// parse for images
 990		preg_match_all('/image\:([a-z0-9\-_]+)/i', $body, $images);
 991		if ($images)
 992		{
 993			foreach($images[1] as $image => $value)
 994			{
 995				$imageHTML = '';
 996				if ($imageData = $this->get_image($value))
 997				{
 998					$imageHTML = display_image($imageData['src'], $imageData['imageName'], $imageData['maxsize'], 'id="'.$this->CI->core->encode($this->CI->session->userdata('lastPage').'|'.$imageData['imageID']).'" class="pic '.$imageData['class'].'"');
 999					$imageHTML = preg_replace('/src=("[^"]*")/i', 'src="/images/'.$imageData['imageRef'].strtolower($imageData['ext']).'"', $imageHTML);
1000				}
1001				elseif ($this->CI->session->userdata('session_admin'))
1002				{
1003					$imageHTML = '<a href="/admin/images" target="_parent"><img src="'.$this->CI->config->item('staticPath').'/images/btn_upload.png" alt="Upload Image" /></a>';
1004				}
1005				$body = str_replace('{image:'.$value.'}', $imageHTML, $body);
1006			}
1007		}	
1008
1009		// parse for thumbs
1010		preg_match_all('/thumb\:([a-z0-9\-_]+)/i', $body, $images);
1011		if ($images)
1012		{
1013			foreach($images[1] as $image => $value)
1014			{
1015				$imageHTML = '';
1016				if ($imageData = $this->get_image($value))
1017				{
1018					$imageHTML = display_image($imageData['thumbnail'], $imageData['imageName'], $imageData['maxsize'], 'id="'.$this->CI->core->encode($this->CI->session->userdata('lastPage').'|'.$imageData['imageID']).'" class="pic thumb '.$imageData['class'].'"');
1019					$imageHTML = preg_replace('/src=("[^"]*")/i', 'src="/thumbs/'.$imageData['imageRef'].strtolower($imageData['ext']).'"', $imageHTML);
1020				}
1021				elseif ($this->CI->session->userdata('session_admin'))
1022				{
1023					$imageHTML = '<a href="/admin/images" target="_parent"><img src="'.$this->CI->config->item('staticPath').'/images/btn_upload.png" alt="Upload Image" /></a>';
1024				}
1025				$body = str_replace('{thumb:'.$value.'}', $imageHTML, $body);
1026			}
1027		}	
1028		
1029		return $body;
1030	}
1031
1032	function get_image($imageRef)
1033	{	
1034		$this->CI->db->where('siteID', $this->siteID);
1035		$this->CI->db->where('deleted', 0);
1036		$this->CI->db->where('imageRef', $imageRef);
1037		$query = $this->CI->db->get('images');
1038		
1039		// get data
1040		if ($query->num_rows())
1041		{
1042			// path to uploads
1043			$pathToUploads = $this->uploadsPath;
1044
1045			$row = $query->row_array();
1046
1047			$image = $row['filename'];
1048			$ext = substr($image,strpos($image,'.'));
1049	
1050			$imagePath = $pathToUploads.'/'.$image;
1051			$thumbPath = str_replace($ext, '', $imagePath).'_thumb'.$ext;
1052
1053			$row['ext'] = $ext;
1054			$row['src'] = $imagePath;
1055			$row['thumbnail'] = (file_exists('.'.$thumbPath)) ? $thumbPath : $imagePath;
1056			
1057			return $row;
1058		}
1059		else
1060		{
1061			return FALSE;
1062		}		
1063	}
1064
1065	function parse_files($body)
1066	{
1067		// parse for files
1068		preg_match_all('/file\:([a-z0-9\-_]+)/i', $body, $files);
1069		if ($files)
1070		{
1071			foreach($files[1] as $file => $value)
1072			{
1073				$fileData = $this->get_file($value);
1074					
1075				$body = str_replace('{file:'.$value.'}', anchor(site_url('/files/'.$fileData['fileRef'].$fileData['extension']), 'Download', 'class="file '.str_replace('.', '', $fileData['extension']).'"'), $body);
1076			}
1077		}
1078		
1079		return $body;
1080	}
1081
1082	function get_file($fileRef)
1083	{
1084		// get data
1085		if ($file = $this->CI->uploads->load_file($fileRef, TRUE))
1086		{	
1087			return $file;
1088		}
1089		else
1090		{
1091			return false;
1092		}		
1093	}
1094}