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