PageRenderTime 46ms CodeModel.GetById 8ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/halogy/application/modules/halogy/controllers/admin.php

https://bitbucket.org/haloweb/halogy-1.0/
PHP | 546 lines | 377 code | 88 blank | 81 comment | 57 complexity | 402e91823845954d34f803a0fa01a948 MD5 | raw file
  1<?php
  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 Admin extends Controller {
 20
 21	// set defaults
 22	var $includes_path = '/includes/admin';				// path to includes for header and footer
 23	var $redirect = '/admin/dashboard';
 24	var $permissions = array();
 25	
 26	function Admin()
 27	{
 28		parent::Controller();
 29
 30		// get siteID, if available
 31		if (defined('SITEID'))
 32		{
 33			$this->siteID = SITEID;
 34		}
 35	}
 36
 37	function index()
 38	{
 39		redirect($this->redirect);
 40	}
 41
 42	function dashboard($days = '')
 43	{
 44		// logout if not admin
 45		if ($this->session->userdata('session_user') && !$this->permission->permissions)
 46		{
 47			show_error('Sorry, you do not have permission to administer this website. Please go back or '.anchor('/admin/logout', 'log out').'.');
 48		}
 49		if (!$this->session->userdata('session_admin'))
 50		{
 51			redirect('/admin/login/'.$this->core->encode($this->uri->uri_string()));
 52		}
 53
 54		// load model and libs
 55		$this->load->model('halogy_model', 'halogy');
 56		$this->load->library('parser');
 57
 58		// show any errors that have resulted from a redirect
 59		if ($days === 'permissions')
 60		{
 61			$this->form_validation->set_error('Sorry, you do not have permissions to do what you just tried to do.');
 62		}
 63
 64		// set message
 65		$output['message'] = '';
 66
 67		// get new blog comments
 68		$newComments = $this->halogy->get_blog_new_comments();
 69		if ($newComments)
 70		{
 71			$output['message'] .= '<p>You have <strong>'.$newComments.' new pending comment(s).</strong> You can <a href="/admin/blog/comments">view your comments here</a>.</p>';
 72		}
 73
 74		// get new blog comments
 75		$newTickets = $this->halogy->get_new_tickets();
 76		if ($newTickets)
 77		{
 78			$output['message'] .= '<p>You have <strong>'.$newTickets.' new ticket(s).</strong> You can <a href="/admin/webforms/tickets">view your tickets here</a>.</p>';
 79		}		
 80
 81		// get new orders
 82		if (@in_array('shop', $this->permission->sitePermissions))
 83		{
 84			$this->load->model('shop/shop_model', 'shop');
 85
 86			if ($newOrders = $this->shop->get_new_orders())
 87			{
 88				$output['message'] .= '<p>You have <strong>'.sizeof($newOrders).' new order(s).</strong> You can <a href="/admin/shop/orders">view your orders here</a>.</p>';
 89			}
 90		}
 91		
 92		// import default template for new sites
 93		if (!$this->halogy->get_num_pages())
 94		{
 95			$this->load->model('sites_model', 'sites');
 96			$this->sites->add_templates($this->siteID);
 97			
 98			$output['message'] = '<p><strong>Congratulations</strong> - your new site is set up and ready to go!</strong> You can view your site <a href="/">here</a>.</p>';
 99		}
100
101		// get stats
102		$data['recentActivity'] = $this->halogy->get_recent_activity();		
103		$data['todaysActivity'] = $this->halogy->get_activity('today');
104		$data['yesterdaysActivity'] = $this->halogy->get_activity('yesterday');		
105		$output['activity'] = $this->parser->parse('activity_ajax', $data, TRUE);
106
107		// get stats
108		$output['days'] = (is_numeric($days)) ? $days : '30';
109		$output['numPageViews'] = $this->halogy->get_num_page_views();
110		$output['numPages'] = $this->halogy->get_num_pages();
111		$output['quota'] = $this->site->get_quota();
112		$output['numUsers'] = ($count = $this->halogy->get_num_users()) ? $count : 0;
113		$output['numUsersToday'] = ($count = $this->halogy->get_num_users_today()) ? $count : 0;
114		$output['numUsersYesterday'] = ($count = $this->halogy->get_num_users_yesterday()) ? $count : 0;
115		$output['numUsersWeek'] = ($count = $this->halogy->get_num_users_week()) ? $count : 0;
116		$output['numUsersLastWeek'] = ($count = $this->halogy->get_num_users_last_week()) ? $count : 0;		
117		$output['numBlogPosts'] = $this->halogy->get_blog_posts_count();
118		$output['popularPages'] = $this->halogy->get_popular_pages();
119		$output['popularBlogPosts'] = $this->halogy->get_popular_blog_posts();
120		$output['popularShopProducts'] = $this->halogy->get_popular_shop_products();
121				
122		$this->load->view($this->includes_path.'/header');
123		$this->load->view('dashboard', $output);
124		$this->load->view($this->includes_path.'/footer');		
125	}
126
127	function stats($limit = 30)
128	{		
129		// logout if not admin
130		if ($this->session->userdata('session_admin'))
131		{
132			$visitations = 0;
133			$signups = 0;
134	
135			$this->db->select("COUNT(*) as visitations, UNIX_TIMESTAMP(MIN(date))*1000 as dateMicro, DATE_FORMAT(date,'%y%m%d') as dateFmt", FALSE);
136			$this->db->where('siteID', $this->siteID);
137			$this->db->where('date >=', "DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL ".$this->db->escape($limit)." DAY)", FALSE);
138			$this->db->order_by('dateFmt', 'desc');
139			$this->db->group_by('dateFmt');
140			
141			$query = $this->db->get('tracking');
142	
143			if ($query->num_rows())
144			{
145				$visitations = array();
146	
147				$i=0;			
148				$result = $query->result_array();
149				foreach($result as $row)
150				{
151					$i++;
152					$visitations[$i] = '['.$row['dateMicro'].','.$row['visitations'].']';
153				}
154				$visitations = implode(',', $visitations);
155			}
156			
157			$this->db->select("COUNT(*) as signups, UNIX_TIMESTAMP(MIN(dateCreated))*1000 as dateMicro, DATE_FORMAT(dateCreated,'%y%m%d') as dateFmt", FALSE);
158			$this->db->where('siteID', $this->siteID);
159			$this->db->where('dateCreated >=', "DATE_SUB(CONCAT(CURDATE(), ' 00:00:00'), INTERVAL ".$this->db->escape($limit)." DAY)", FALSE);
160			$this->db->order_by('dateFmt', 'desc');
161			$this->db->group_by('dateFmt');
162			
163			$query = $this->db->get('users');
164	
165			if ($query->num_rows())
166			{
167				$signups = array();
168	
169				$i=0;			
170				$result = $query->result_array();
171				foreach($result as $row)
172				{
173					$i++;
174					$signups[$i] = '['.$row['dateMicro'].','.$row['signups'].']';
175				}
176				$signups = implode(',', $signups);
177			}
178	
179			$this->output->set_output('{ "visits" : ['.$visitations.'] ,  "signups" : ['.$signups.'] }');
180		}
181	}
182
183	function activity_ajax()
184	{
185		// logout if not admin
186		if ($this->session->userdata('session_admin'))
187		{
188			// load model
189			$this->load->model('halogy_model', 'halogy');
190	
191			// get stats
192			$output['recentActivity'] = $this->halogy->get_recent_activity();		
193			$output['todaysActivity'] = $this->halogy->get_activity('today');
194			$output['yesterdaysActivity'] = $this->halogy->get_activity('yesterday');
195	
196			$this->load->view('activity_ajax', $output);
197		}
198	}
199
200	function tracking()
201	{
202		// logout if not admin
203		if (!$this->session->userdata('session_admin'))
204		{
205			redirect('/admin/login/'.$this->core->encode($this->uri->uri_string()));
206		}
207		
208		$this->load->view($this->includes_path.'/header');
209		$this->load->view('tracking');
210		$this->load->view($this->includes_path.'/footer');
211	}
212
213	function tracking_ajax()
214	{
215		// logout if not admin
216		if ($this->session->userdata('session_admin'))
217		{		
218			$output = $this->core->viewall('tracking', null, array('trackingID', 'desc'));
219	
220			$this->load->view('tracking_ajax', $output);
221		}
222	}
223
224	function login($redirect = '')
225	{
226		// load libs etc
227		$this->load->library('auth');
228		
229		if (!$this->session->userdata('session_admin'))
230		{
231			if ($_POST)
232			{	
233				// set redirect to default if not given
234				if ($redirect == '')
235				{
236					$redirect = $this->redirect;
237				}
238				else
239				{
240					$redirect = $this->core->decode($redirect);
241				}
242				
243				// set admin session name, if given
244				if ($this->auth->login($this->input->post('username'), $this->input->post('password'), 'session_user'))
245				{
246					// for use with ce
247					if ($this->session->userdata('groupID') != 0 && $this->permission->get_group_permissions($this->session->userdata('groupID')))
248					{
249						$this->session->set_userdata('session_admin', TRUE);
250					}
251					
252					// update quota
253					$quota = $this->site->get_quota();
254					$this->core->set['quota'] = ($quota > 0) ? (floor($quota / $this->site->plans['storage'] * 100)) : 0;
255					$this->core->update('sites', array('siteID' => $this->siteID));
256
257					redirect($redirect);
258				}
259
260				// get error message
261				else
262				{
263					$this->form_validation->set_error($this->auth->error);
264				}
265			}
266		}
267		else
268		{
269			if ($redirect != '')
270			{
271				redirect($redirect);
272			}
273		}
274		
275		// view
276		$this->load->view($this->includes_path.'/header');
277		$this->load->view('login');
278		$this->load->view($this->includes_path.'/footer');	
279	}
280
281	function logout($redirect = '')
282	{
283		// load libs etc
284		$this->load->library('auth');
285		
286		// set redirect to default if not given
287		if ($redirect == '')
288		{
289			$redirect = '';
290		}
291		else
292		{
293			$redirect = $this->core->decode($redirect);
294		}
295		$this->auth->logout($redirect);
296	}
297
298	function site()
299	{
300		// logout if not admin
301		if (!$this->session->userdata('session_admin'))
302		{
303			redirect('/admin/login/'.$this->core->encode($this->uri->uri_string()));
304		}
305
306		// check they are administrator
307		if ($this->session->userdata('groupID') != $this->site->config['groupID'] && $this->session->userdata('groupID') >= 0)
308		{
309			redirect('/admin/dashboard/permissions');
310		}
311		
312		// set object ID
313		$objectID = array('siteID' => $this->siteID);
314
315		// get values
316		$output['data'] = $this->core->get_values('sites', $objectID);
317
318		// set defaults
319		$output['data']['shopVariation1'] = ($this->input->post('shopVariation1')) ? $this->input->post('shopVariation1') : $this->site->config['shopVariation1'];
320		$output['data']['shopVariation2'] = ($this->input->post('shopVariation2')) ? $this->input->post('shopVariation2') : $this->site->config['shopVariation2'];
321		$output['data']['shopVariation3'] = ($this->input->post('shopVariation3')) ? $this->input->post('shopVariation3') : $this->site->config['shopVariation3'];
322		$output['data']['emailHeader'] = ($this->input->post('emailHeader')) ? $this->input->post('emailHeader') : $this->site->config['emailHeader'];
323		$output['data']['emailFooter'] = ($this->input->post('emailFooter')) ? $this->input->post('emailFooter') : $this->site->config['emailFooter'];
324		$output['data']['emailTicket'] = ($this->input->post('emailTicket')) ? $this->input->post('emailTicket') : $this->site->config['emailTicket'];
325		$output['data']['emailAccount'] = ($this->input->post('emailAccount')) ? $this->input->post('emailAccount') : $this->site->config['emailAccount'];
326		$output['data']['emailOrder'] = ($this->input->post('emailOrder')) ? $this->input->post('emailOrder') : $this->site->config['emailOrder'];
327		$output['data']['emailDispatch'] = ($this->input->post('emailDispatch')) ? $this->input->post('emailDispatch') : $this->site->config['emailDispatch'];
328		$output['data']['emailDonation'] = ($this->input->post('emailDonation')) ? $this->input->post('emailDonation') : $this->site->config['emailDonation'];
329		$output['data']['emailSubscription'] = ($this->input->post('emailSubscription')) ? $this->input->post('emailSubscription') : $this->site->config['emailSubscription'];
330				
331		// handle post
332		if (count($_POST))
333		{
334			// check some things aren't being posted
335			if ($this->input->post('siteID') || $this->input->post('siteDomain') || $this->input->post('groupID'))
336			{
337				show_error('You do not have permission to change those things.');
338			}
339			
340			// required
341			$this->core->required = array(
342				'siteName' => array('label' => 'Name of Site', 'rules' => 'required|trim'),
343				'siteURL' => array('label' => 'URL', 'rules' => 'required|trim'),
344				'siteEmail' => array('label' => 'Email', 'rules' => 'required|valid_email|trim'),
345			);	
346	
347			// set date
348			$this->core->set['dateModified'] = date("Y-m-d H:i:s");
349			
350			// update
351			if ($this->core->update('sites', $objectID))
352			{
353				// where to redirect to
354				$output['message'] = '<p>Your details have been updated.</p>';
355			}
356		}
357
358		// get permission groups
359		$output['groups'] = $this->permission->get_groups();
360		
361		// templates
362		$this->load->view($this->includes_path.'/header');
363		$this->load->view('site',$output);
364		$this->load->view($this->includes_path.'/footer');
365	}
366	
367	function setup()
368	{
369		echo 'tset';
370	}
371	
372	function backup()
373	{
374		// check permissions for this page
375		if ($this->session->userdata('groupID') >= 0)
376		{
377			redirect('/admin/dashboard');
378		}	
379
380		$filename = 'halogy_backup_'.date('Y-m-d_H-i', time());
381		
382		// Set up our default preferences
383		$prefs = array(
384							'tables'		=> $this->db->list_tables(),
385							'ignore'		=> array('ha_ci_sessions', 'ha_captcha', 'ha_permissions', 'ha_zipcodes'),
386							'filename'		=> $filename.'.sql',
387							'format'		=> 'gzip', // gzip, zip, txt
388							'add_drop'		=> FALSE,
389							'add_insert'	=> TRUE,
390							'newline'		=> "\n"
391						);
392
393		// Is the encoder supported?  If not, we'll either issue an
394		// error or use plain text depending on the debug settings
395		if (($prefs['format'] == 'gzip' AND ! @function_exists('gzencode'))
396		 OR ($prefs['format'] == 'zip'  AND ! @function_exists('gzcompress')))
397		{
398			if ($this->db->db_debug)
399			{
400				return $this->db->display_error('db_unsuported_compression');
401			}
402		
403			$prefs['format'] = 'txt';
404		}
405
406		// Load the Zip class and output it
407		$this->load->library('zip');
408		$this->zip->add_data($prefs['filename'], $this->_backup($prefs));
409		$backup = $this->zip->get_zip();
410				
411		// Load the download helper and send the file to your desktop
412		$this->load->helper('download');
413		force_download($filename.'.zip', $backup); 		
414	}
415
416	function _backup($params = array())
417	{
418		if (count($params) == 0)
419		{
420			return FALSE;
421		}
422
423		// Extract the prefs for simplicity
424		extract($params);
425	
426		// Build the output
427		$output = '';
428		foreach ((array)$tables as $table)
429		{
430			// Is the table in the "ignore" list?
431			if (in_array($table, (array)$ignore, TRUE))
432			{
433				continue;
434			}
435
436			// Get the table schema
437			$query = $this->db->query("SHOW CREATE TABLE `".$this->db->database.'`.'.$table);
438			
439			// No result means the table name was invalid
440			if ($query === FALSE)
441			{
442				continue;
443			}
444			
445			// Write out the table schema
446			$output .= '#'.$newline.'# TABLE STRUCTURE FOR: '.$table.$newline.'#'.$newline.$newline;
447
448 			if ($add_drop == TRUE)
449 			{
450				$output .= 'DROP TABLE IF EXISTS '.$table.';'.$newline.$newline;
451			}
452			
453			$i = 0;
454			$result = $query->result_array();
455			foreach ($result[0] as $val)
456			{
457				if ($i++ % 2)
458				{ 					
459					$output .= $val.';'.$newline.$newline;
460				}
461			}
462			
463			// If inserts are not needed we're done...
464			if ($add_insert == FALSE)
465			{
466				continue;
467			}
468
469			// Grab all the data from the current table
470			$query = $this->db->query("SELECT * FROM $table WHERE siteID = ".$this->siteID);
471			
472			if ($query->num_rows() == 0)
473			{
474				continue;
475			}
476		
477			// Fetch the field names and determine if the field is an
478			// integer type.  We use this info to decide whether to
479			// surround the data with quotes or not
480			
481			$i = 0;
482			$field_str = '';
483			$is_int = array();
484			while ($field = mysql_fetch_field($query->result_id))
485			{
486				// Most versions of MySQL store timestamp as a string
487				$is_int[$i] = (in_array(
488										strtolower(mysql_field_type($query->result_id, $i)),
489										array('tinyint', 'smallint', 'mediumint', 'int', 'bigint'), //, 'timestamp'), 
490										TRUE)
491										) ? TRUE : FALSE;
492										
493				// Create a string of field names
494				$field_str .= '`'.$field->name.'`, ';
495				$i++;
496			}
497			
498			// Trim off the end comma
499			$field_str = preg_replace( "/, $/" , "" , $field_str);
500			
501			
502			// Build the insert string
503			foreach ($query->result_array() as $row)
504			{
505				$val_str = '';
506			
507				$i = 0;
508				foreach ($row as $v)
509				{
510					// Is the value NULL?
511					if ($v === NULL)
512					{
513						$val_str .= 'NULL';
514					}
515					else
516					{
517						// Escape the data if it's not an integer
518						if ($is_int[$i] == FALSE)
519						{
520							$val_str .= $this->db->escape($v);
521						}
522						else
523						{
524							$val_str .= $v;
525						}					
526					}					
527					
528					// Append a comma
529					$val_str .= ', ';
530					$i++;
531				}
532				
533				// Remove the comma at the end of the string
534				$val_str = preg_replace( "/, $/" , "" , $val_str);
535								
536				// Build the INSERT string
537				$output .= 'INSERT INTO '.$table.' ('.$field_str.') VALUES ('.$val_str.');'.$newline;
538			}
539			
540			$output .= $newline.$newline;
541		}
542
543		return $output;
544	}
545
546}