PageRenderTime 43ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/controllers/common/parent.php

https://github.com/benstaker/webscrp-new
PHP | 645 lines | 304 code | 190 blank | 151 comment | 92 complexity | 4c0e89deca77fb07571f7ae470374935 MD5 | raw file
  1. <?php
  2. /**
  3. * Every *_Controller extends the Parent_Controller will
  4. * inherit all the properties and methods.
  5. */
  6. Class Parent_Controller {
  7. /**
  8. * Base path of the website.
  9. * @var string
  10. */
  11. protected $_basePath;
  12. /**
  13. * Model object
  14. * @var object
  15. */
  16. protected $_model;
  17. /**
  18. * Name of the template.
  19. * @var string
  20. */
  21. protected $_template;
  22. /**
  23. * Name of the page.
  24. * @var string
  25. */
  26. protected $_page;
  27. /**
  28. * View object.
  29. * @var object.
  30. */
  31. protected $_view;
  32. /**
  33. * Breadcrumbs navigation.
  34. * @var array
  35. */
  36. protected $_breadcrumbs;
  37. /**
  38. * Content to be outputted
  39. * @var array
  40. */
  41. protected $_content;
  42. /**
  43. * Sidebar content to be outputted
  44. * @var array
  45. */
  46. protected $_sidebar;
  47. /**
  48. * Messages to be outputted.
  49. * @var array
  50. */
  51. protected $_messages;
  52. /**
  53. * Whether to return only the data.
  54. * @var boolean
  55. */
  56. protected $_return;
  57. /**
  58. * GET variables.
  59. * @var array
  60. */
  61. protected $_getVars;
  62. /**
  63. * Scripts to be included.
  64. * @var array
  65. */
  66. protected $_scripts;
  67. /**
  68. * List of table headings.
  69. * @var array
  70. */
  71. protected $_tableHeadings;
  72. /**
  73. * Initialise the properties.
  74. * @param array $getVars GET variables
  75. * @param boolean $return Whether to only return data.
  76. */
  77. public function __construct($getVars = null){
  78. $this->_getVars = $getVars;
  79. $this->_return = $GLOBALS["return"];
  80. $this->_content = $this->_sidebar = $this->_messages = $this->_breadcrumbs = $this->_scripts = $this->_tableHeadings = array();
  81. $this->_page = $GLOBALS["options"]["page"];
  82. $this->_template = strtolower($this->_page);
  83. if($this->_return === false){
  84. // Store the base path.
  85. $this->_basePath = $GLOBALS["admin"] ? ADMIN_PATH . "/" . $this->_template : SITE_PATH . $this->_template;
  86. // If it's an admin page, add a parent breadcrumb.
  87. if($GLOBALS["admin"]) {
  88. $breadcrumb = array(ADMIN_PATH, "Control Panel");
  89. array_push($this->_breadcrumbs, $breadcrumb);
  90. }
  91. // Adds the page to the breadcrumb.
  92. $breadcrumb = array($this->_basePath, $this->_page);
  93. array_push($this->_breadcrumbs, $breadcrumb);
  94. }
  95. self::main();
  96. }
  97. /**
  98. * Call the assign() method.
  99. */
  100. public function __destruct(){
  101. self::assign();
  102. }
  103. /**
  104. * Creates the Model/View objects, then calls the action() method.
  105. * @param array $getVars GET variables.
  106. * @return [type] [description]
  107. */
  108. protected function main(){
  109. $this->_view = new View_Model($this->_page, !$this->_return);
  110. // Assigns the title to the view.
  111. $this->_view->assign("title", $this->_page);
  112. // Creates the Model, passing the View object
  113. // if the return property is false.
  114. $class = $this->_page."_Model";
  115. $this->_model = $this->_return === false ? new $class($this->_view) : new $class;
  116. $tempEntity = $this->_model->getEntity();
  117. session_start();
  118. //unset($_SESSION["cust_id"]);
  119. if(!isset($_SESSION["cust_id"]) || empty($_SESSION["cust_id"])){
  120. $this->_model->setEntity("customer");
  121. $customers = $this->_model->getAll();
  122. $lastCustomer = $customers[count($customers)-1];
  123. $customerID = $lastCustomer["cust_id"];
  124. while(true){
  125. if($this->_model->get($customerID)) $customerID++;
  126. else break;
  127. }
  128. $customerArray = array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "");
  129. if($this->_model->add($customerArray)) $_SESSION["cust_id"] = $this->_model->lastInsertID();
  130. }
  131. $this->_model->setEntity($tempEntity);
  132. if($GLOBALS["admin"]) array_push($this->_sidebar, file_get_contents(SIDEBAR_ROOT . "control-panel.php"));
  133. else {
  134. $GLOBALS["model"] = $this->_model;
  135. ob_start();
  136. require_once(SIDEBAR_ROOT . "categories.php");
  137. array_push($this->_sidebar, ob_get_clean());
  138. }
  139. self::action();
  140. }
  141. /**
  142. * Determines which action to perform.
  143. */
  144. protected function action(){
  145. // If a search query has been performed, remove
  146. // the query from the vars.
  147. if($this->_template === "search" && isset($_GET["query"])) array_shift($this->_getVars);
  148. // If an image has been requested, manually set
  149. // the action and remove id/thumbnail from vars.
  150. if($this->_template === "image" && isset($_GET["id"])){
  151. if(isset($_GET["thumbnail"])) array_shift($this->_getVars);
  152. array_shift($this->_getVars);
  153. $GLOBALS["options"]["action"] = "get";
  154. }
  155. // Check that the supplied argument is an array and isn't empty.
  156. if(isset($GLOBALS["options"]["action"])){
  157. // Store the ID.
  158. $id = isset($this->_getVars["id"]) ? $this->_getVars["id"] : false;
  159. // Call the appropriate method.
  160. switch($GLOBALS["options"]["action"]){
  161. case "add":
  162. static::add();
  163. break;
  164. case "edit":
  165. static::edit($id);
  166. break;
  167. case "get":
  168. static::get($id);
  169. break;
  170. case "getall":
  171. static::getAll();
  172. break;
  173. case "remove":
  174. static::remove($id);
  175. break;
  176. default:
  177. try {
  178. static::$GLOBALS["options"]["action"]();
  179. } catch(Exception $e) {
  180. // If the action does not exist, return to the page's home.
  181. echo 'Caught exception: ', $e->getMessage(), "\n";
  182. header("Location: ../" . static::getPage());
  183. }
  184. break;
  185. }
  186. if($GLOBALS["admin"] && !$GLOBALS["return"]) {
  187. // Adds the action breadcrumb.
  188. $breadcrumb = array($this->_basePath . "/" . $GLOBALS["options"]["action"], ucfirst($GLOBALS["options"]["action"]));
  189. array_push($this->_breadcrumbs, $breadcrumb);
  190. }
  191. } else static::home();
  192. }
  193. /**
  194. * Assigns data to the view.
  195. */
  196. protected function assign(){
  197. if($this->_return === false){
  198. $this->_view->assign("breadcrumbs", $this->_breadcrumbs);
  199. $this->_view->assign("content", $this->_content);
  200. $this->_view->assign("sidebar", $this->_sidebar);
  201. $this->_view->assign("message", $this->_messages);
  202. $this->_view->assign("scripts", $this->_scripts);
  203. } else {
  204. if(!empty($this->_content)) foreach($this->_content as $content) echo $content;
  205. if(!empty($this->_messages)){
  206. foreach($this->_messages as $messages) echo $messages;
  207. }
  208. }
  209. }
  210. /**
  211. * Returns the name of the page.
  212. * @return string Name of the page.
  213. */
  214. public function getPage(){
  215. return $this->_template;
  216. }
  217. /**
  218. * Outputs all the rows in the entity to a table.
  219. */
  220. protected function home(){
  221. // Attempts get all the rows from the database.
  222. if($items = $this->_model->getAll()){
  223. $columns = $this->_model->getColumns();
  224. $removableColumns = array("product" => array("prod_image_type", "prod_thumbnail"));
  225. foreach($removableColumns as $remove){
  226. if(is_array($remove)){
  227. foreach($remove as $column){
  228. if($index = array_search($column, $columns)) unset($columns[$index]);
  229. }
  230. }
  231. }
  232. if($this->_tableHeadings === null) $headings = $columns;
  233. else {
  234. if(count($this->_tableHeadings) === count($columns)) $headings = $this->_tableHeadings;
  235. else array_push($this->_messages, '<li class="error">The table headings are invalid [not the correct amount].</li>');
  236. }
  237. array_push($this->_content, "<h2>" . ucfirst($this->_template) . "</h2>");
  238. array_push($this->_content, "<p>You can change a cell by clicking on it. To remove a row, hover over the ID.</p>");
  239. $table = "<table id=\"" . $this->_template . "_table\" class=\"table\">\n";
  240. // Output the table headings.
  241. $table .= "<tr class=\"headings\">\n";
  242. $table .= "<th>&nbsp;</th>";
  243. foreach($headings as $heading) $table .= "<th>" . $heading . "</th>\n";
  244. $table .= "</tr>\n";
  245. $listIDs = "";
  246. foreach($items as $item){
  247. // Store list of IDs in hidden input.
  248. $listIDs .= $item[$columns[0]] . ",";
  249. // Output the table data.
  250. $table .= "<tr>";
  251. foreach($columns as $column){
  252. if($column == $columns[0]) $table .= '<td><a href="admin/' . $this->_template . '/remove/' . $item[$columns[0]] . '" class="remove" title="Remove the row">&nbsp;</a></td>';
  253. $table .= "<td id=\"" . $item[$columns[0]] . "_" . $column . "\"";
  254. if($column == $columns[0]) $table .= ' class="primary" ';
  255. $table .= " title=\"\">";
  256. if($this->_template === "product"){
  257. if($column === "prod_image") $item[$column] = "<img src='image/" . $item[$columns[0]] . "/1' />";
  258. }
  259. $table .= $item[$column]
  260. . "</td>\n";
  261. }
  262. $table .= "</tr>";
  263. }
  264. $listIDs = substr($listIDs, 0, -1);
  265. $table .= "</table>\n";
  266. $table .= '<input type="hidden" id="' . $this->_template . '_ids" value="' . $listIDs . '" />';
  267. // Store list of columns in hidden input.
  268. $listColumns = "";
  269. foreach($columns as $column) $listColumns .= $column . ",";
  270. $listColumns = substr($listColumns, 0, -1);
  271. $table .= '<input type="hidden" id="' . $this->_template . '_columns" value="' . $listColumns . '" />';
  272. array_push($this->_content, $table);
  273. array_push($this->_scripts, "edit.js");
  274. }
  275. }
  276. /**
  277. * Processes the form variables, then inserts data into the entity.
  278. */
  279. protected function add($outputScript = true){
  280. $error = false;
  281. // Make sure the form has been submitted.
  282. if($_SERVER['REQUEST_METHOD'] == "POST"){
  283. // Get the entities columns.
  284. $columns = $this->_model->getColumns();
  285. // Shift the array to remove the Primary Key.
  286. array_shift($columns);
  287. if($this->_template === "product"){
  288. if(isset($_FILES["prod_image"])){
  289. $error = true;
  290. // Check for any errors.
  291. $imageError = $_FILES["prod_image"]["error"];
  292. if($imageError == 4) $no_image = true;
  293. else $no_image = false;
  294. // Image details.
  295. $imageName = $_FILES["prod_image"]["name"];
  296. $imageType = $_FILES["prod_image"]["type"];
  297. $imageSize = $_FILES["prod_image"]["size"];
  298. $imageTemporary = $_FILES["prod_image"]["tmp_name"];
  299. $extensionArray = array("jpg", "jpeg", "gif", "png");
  300. $extension = explode(".", $imageName);
  301. $extension = end($extension);
  302. // If image type is valid.
  303. if(($imageType == "image/gif") || ($imageType == "image/jpeg") || ($imageType == "image/png") || ($imageType == "image/pjpeg") || $no_image){
  304. // If image is less than 500KB.
  305. if($imageSize < 512000 || $no_image){
  306. // If image extension is in array.
  307. if(in_array($extension, $extensionArray) || $no_image){
  308. // If there was an error.
  309. if($imageError > 0 && !$no_image) array_push($this->_messages, '<li class="error">Return Code: ' . $imageError . '</li>');
  310. else {
  311. // If there is no image.
  312. if(!$no_image){
  313. // Store image data into variable.
  314. $imageData = file_get_contents($imageTemporary);
  315. // Load image.
  316. $image="";
  317. switch($imageType){
  318. case "image/jpeg":
  319. case "image/pjpeg":
  320. $image=imagecreatefromjpeg($imageTemporary);
  321. break;
  322. case "image/png":
  323. $image=imagecreatefrompng($imageTemporary);
  324. break;
  325. case "image/gif":
  326. $image=imagecreatefromgif($imageTemporary);
  327. break;
  328. }
  329. $thumbnailWidth = 150;
  330. // Get image size.
  331. $width = imagesx($image);
  332. $height = imagesy($image);
  333. // Calculate thumbnail size.
  334. $newWidth = $thumbnailWidth;
  335. $newHeight = floor($height * ($thumbnailWidth / $width));
  336. // Create a new temporary image.
  337. $temporaryImage = imagecreatetruecolor($newWidth, $newHeight);
  338. // Copy and resize old image into new image.
  339. imagecopyresampled($temporaryImage, $image, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
  340. $temporaryImagePath = $imageTemporary . time();
  341. // Save thumbnail into a file.
  342. switch($imageType){
  343. case "image/jpeg":
  344. case "image/pjpeg":
  345. imagejpeg($temporaryImage, $temporaryImagePath, 9);
  346. break;
  347. case "image/png":
  348. imagepng($temporaryImage, $temporaryImagePath, 9);
  349. break;
  350. case "image/gif":
  351. imagegif($temporaryImage, $temporaryImagePath, 9);
  352. break;
  353. }
  354. // Store thumbnail data into variable.
  355. $fileHandler = fopen($temporaryImagePath, 'r');
  356. $imageThumbnailData = fread($fileHandler, filesize($temporaryImagePath));
  357. fclose($fileHandler);
  358. $error = false;
  359. } else {
  360. $imageData = $imageThumbnailData = file_get_contents(IMG_PATH . "no_image.jpg");
  361. $imageType = "image/jpeg";
  362. $error = false;
  363. }
  364. }
  365. } else array_push($this->_messages, '<li class="error">File-extension is invalid. Please upload either: .jpg, .jpeg, .gif, or .png.</li>');
  366. } else array_push($this->_messages, '<li class="error">File-size is too big. Please upload an image with a maximum size of 500KB.</li>');
  367. } else array_push($this->_messages, '<li class="error">File-type invalid. Please upload either: image/gif, image/jpeg, image/png, or image/pjpeg.</li>');
  368. $_POST["prod_image"] = $imageData;
  369. $_POST["prod_image_type"] = $imageType;
  370. $_POST["prod_thumbnail"] = $imageThumbnailData;
  371. }
  372. }
  373. if(isset($error) && !$error){
  374. // Populate the data array.
  375. $data = array();
  376. foreach($columns as $column){
  377. if(strpos($column, "_last_update") !== false) $_POST[$column] = time();
  378. if(strpos($column, "_date") !== false) $_POST[$column] = time();
  379. array_push($data, $_POST[$column]);
  380. }
  381. // Attempts to add the data to the entity.
  382. if($this->_model->add($data)){
  383. array_push($this->_messages, '<li class="success">Added the '.$this->_template.' successfully.</li>');
  384. if($GLOBALS["admin"]) array_push($this->_messages, redirect("admin/" . $this->_template, "1000"));
  385. else array_push($this->_messages, redirect($this->_template, "1000"));
  386. return true;
  387. }
  388. }
  389. } else if($outputScript) array_push($this->_scripts, "ajax.php?entity=" . $this->_template . "&form_action=add&admin=true");
  390. return false;
  391. }
  392. /**
  393. * Processes the form variables, then changes the row in the entity.
  394. */
  395. protected function edit($columns = null){
  396. // Make sure the form has been submitted.
  397. if($_SERVER['REQUEST_METHOD']=="POST"){
  398. // Populate the data array.
  399. $data = array();
  400. foreach($this->_model->getColumns() as $column){
  401. if(strpos($column, "_last_update") !== false) $_POST[$column] = time();
  402. array_push($data, $_POST[$column]);
  403. }
  404. // Attempts to edit the data in the entity.
  405. if($this->_model->edit($data, $columns)){
  406. array_push($this->_messages, '<li class="success">Edited the '.$this->_template.' successfully.</li>');
  407. if($GLOBALS["admin"]) array_push($this->_messages, redirect("admin/" . $this->_template, "1000"));
  408. else array_push($this->_messages, redirect($this->_template, "1000"));
  409. return true;
  410. }
  411. } else array_push($this->_scripts, "ajax.php?entity=" . $this->_template . "&form_action=edit");
  412. return false;
  413. }
  414. /**
  415. * Returns a row from the entity.
  416. * @param string $value This can either be the ID of the row, or a string to search for.
  417. * @return array The row.
  418. */
  419. protected function get($value = null){
  420. if($value == null) $value = $_GET["id"];
  421. // Attempts get a row from the table.
  422. if($row = $this->_model->get($value)) return $row;
  423. else return false;
  424. }
  425. /**
  426. * Returns all the froms from an entity.
  427. * @param array $where Conditions to search for.
  428. * @return array All the rows.
  429. */
  430. protected function getAll($where = null){
  431. // Attempts get all the rows from the table.
  432. if($items = $this->_model->getAll($where)) return $items;
  433. else return false;
  434. }
  435. /**
  436. * Processes the form variables, then removes the row from the entity.
  437. */
  438. protected function remove($id = null){
  439. // Make sure the form has been submitted.
  440. if($_SERVER['REQUEST_METHOD']=="POST" || $id != null){
  441. // Get the entities columns.
  442. $columns = $this->_model->getColumns();
  443. // ID of row to be removed.
  444. if(isset($_POST[$columns[0]])) $id = $_POST[$columns[0]];
  445. // Attempts to remove the row from the entity.
  446. if($this->_model->remove($id)){
  447. array_push($this->_messages, '<li class="success">Removed the '.$this->_template.' successfully.</li>');
  448. if($GLOBALS["admin"]) array_push($this->_messages, redirect("admin/" . $this->_template, "1000"));
  449. else array_push($this->_messages, redirect($this->_template, "1000"));
  450. return true;
  451. }
  452. } else array_push($this->_scripts, "ajax.php?entity=" . $this->_template . "&form_action=remove");
  453. return false;
  454. }
  455. }