3 * SkladovySystem - Storage management system compatible with LMS
4 * Copyright (C) 2011 Tomas Mudrunka
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as
8 * published by the Free Software Foundation, either version 3 of the
9 * License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 require_once('sklad.conf.php');
21 require_once('Sklad_LMS-fake.class.php');
22 require_once('HTTP_Auth.class.php');
25 * Trida poskytuje vseobecne funkce pro generovani HTML kodu
27 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
30 * @author Tomas Mudrunka
35 foreach($row as $var) {
36 if(trim($var) == '') $var = ' ';
37 $html.="<td>$var</td>";
43 function table(&$table, $params='border=1') {
44 $html="<table $params>";
46 foreach($table as $row) {
48 $html.=$this->row(array_keys($row));
51 $html.=$this->row($row);
57 function link($title='n/a', $link='#void', $internal=true) {
58 if($internal) $link = $this->internal_url($link);
59 return "<a href='$link'>$title</a>";
62 function img($src='#void', $title='img') {
63 return "<img src='$src' alt='$title' title='$title' width=64 />";
66 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false) {
67 $html = "<input type='$type' ";
68 if($name) $html.= "name='$name' ";
69 if(!is_bool($value)) $html.= "value='$value' ";
70 if($options) $html.= "$options ";
71 if($placeholder) $html.= "placeholder='$placeholder' ";
76 function select($name, $selectbox, $default=false) {
77 //echo('<pre>'); print_r($selectbox);
78 $html = "<select name='$name'>";
81 $value=$default; $title=$selectbox[$value];
82 $html .= "<option value='$value'>$value :: $title</option>";
83 unset($selectbox[$value]);
85 foreach($selectbox as $value => $title) {
86 $html .= "<option value='$value'>$value :: $title</option>";
94 * Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
96 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
99 * @author Tomas Mudrunka
101 class Sklad_HTML
extends HTML
{
102 function header($title='') {
104 $script = $_SERVER['SCRIPT_NAME'];
105 $search = htmlspecialchars(@trim
($_GET['q']));
106 $message = strip_tags(@trim
($_GET['message']),'<a><b><u><i>');
109 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
111 <h1><a href="$script/">SystémSklad</a><small>$title</small></h1>
113 <style type="text/css">
114 .menu li, .menu * li {
121 background-color: yellow;
124 .menu, .menu * menu {
133 .menu li:hover menu {
140 <li><a href="?logout">Logout</a></li>
141 <li><a href="$script/">Home</a></li>
142 <li><a href="#">Assistants</A>
144 <li><a href="$script/assistant/new-item">new-item</a></li>
147 <li><a href="#">List</a>
149 <li><a href="$script/item">item</a></li>
150 <li><a href="$script/model">model</a></li>
151 <li><a href="$script/category">category</a></li>
152 <li><a href="$script/producer">producer</a></li>
153 <li><a href="$script/vendor">vendor</a></li>
154 <li><a href="$script/room">room</a></li>
155 <li><a href="$script/status">status</a></li>
158 <li><a href="#">New</a>
160 <li><a href="$script/item/new">item</a></li>
161 <li><a href="$script/model/new">model</a></li>
162 <li><a href="$script/category/new">category</a></li>
163 <li><a href="$script/producer/new">producer</a></li>
164 <li><a href="$script/vendor/new">vendor</a></li>
165 <li><a href="$script/room/new">room</a></li>
166 <li><a href="$script/status/new">status</a></li>
171 <div style="float: right;">
172 <form action="?" method="GET">
173 <input type="text" name="q" placeholder="regexp..." value="$search" />
174 <input type="submit" value="filter" />
176 <!-- form action="$script/" method="GET">
177 <input type="text" name="q" placeholder="regexp..." value="$search" />
178 <input type="submit" value="search items" />
182 <hr style="clear: both;" />
183 <div style="background-color:#FFDDDD;">
184 <font color="red">$message</font>
189 function internal_url($link) {
190 return $_SERVER['SCRIPT_NAME'].'/'.$link;
193 function table_add_images(&$table) {
194 $image = array('model_id');
195 foreach($table as $id => $row) {
196 foreach($image as $column) if(isset($table[$id][$column])) {
197 $type = @array_shift
(preg_split('/_/', $column));
198 $src=URL_IMAGES
."/$type/".$table[$id][$column].'.jpg';
199 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
204 function table_collapse(&$table) {
206 'item_id' => 'item_id',
207 'model_id' => 'model_name',
208 'category_id' => 'category_name',
209 'producer_id' => 'producer_name',
210 'vendor_id' => 'vendor_name',
211 'room_id' => 'room_name',
212 'status_id' => 'status_name',
214 foreach($table as $id => $row) {
215 foreach($collapse as $link => $title)
216 if(isset($table[$id][$link])) {
217 $type = @array_shift
(preg_split('/_/', $link));
218 if($link != $title) unset($table[$id][$link]);
219 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
224 function table_sort(&$table) {
225 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
226 $table_sorted = array();
227 foreach($table as $id => $row) {
228 $table_sorted[$id] = array();
229 foreach($precedence as $column) if(isset($table[$id][$column])) {
230 $table_sorted[$id][$column]=$table[$id][$column];
231 unset($table[$id][$column]);
233 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
235 $table = $table_sorted;
238 function render_item_table($table) {
239 $this->table_add_images($table);
240 $this->table_collapse($table);
241 $this->table_sort($table);
242 return $this->table($table);
245 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $multi_insert=true) {
246 //echo('<pre>'); print_r($selectbox);
247 //echo('<pre>'); print_r($current);
249 if(is_array($current)) {
251 $current = array_shift($current);
254 $html='<form method="POST">';
255 if($multi_insert) $html.='<div name="input_set" style="float:left; border:1px solid grey;">';
256 //$html.=$this->input('table', $class, 'hidden');
257 foreach($columns as $column) {
258 $html.=$class.':<b>'.$column['Field'].'</b>: ';
259 $name="values[$class][".$column['Field'].'][]';
260 $val = $update ?
$current[$column['Field']] : false;
262 case preg_match('/auto_increment/', $column['Extra']):
264 $html.=$this->input($name, $val, 'hidden');
265 $html.=$val.'(AUTO)';
267 case isset($selectbox[$column['Field']]):
268 $html.=$this->select($name,$selectbox[$column['Field']],$val);
271 $html.=$this->input($name, $val);
278 //TODO, move to separate JS file
281 <span name="input_set_next"></span><br style="clear:both" />
283 function duplicate_element(what, where) {
284 document.getElementsByName(where)[0].outerHTML =
285 document.getElementsByName(what)[0].outerHTML
286 + document.getElementsByName(where)[0].outerHTML;
289 <a href='#' onClick="duplicate_element('input_set', 'input_set_next')">+</a>
293 $btn = is_array($current) ?
'UPDATE' : 'INSERT';
294 $html.=$this->input(false, $btn, 'submit');
301 * Trida poskytuje rozhrani k databazi skladu
304 * @author Tomas Mudrunka
306 class Sklad_DB
extends PDO
{
307 function __construct() {
308 $this->lms
= new Sklad_LMS();
311 DB_DSN
, DB_USER
, DB_PASS
,
312 array(PDO
::MYSQL_ATTR_INIT_COMMAND
=> "SET NAMES utf8") //Force UTF8 for MySQL
316 function escape($str) {
317 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
320 function build_query_select($class, $id=false, $limit=false, $offset=0, $search=false, $history=false, $order=false, $suffix_id='_id') {
323 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
324 'model' => array('category', 'producer')
325 ); //TODO Autodetect using foreign keys?
326 $search_fields = array(
327 'item' => array('item_id','model_name','model_barcode','model_descript','producer_name','vendor_name')
331 $class = $this->escape($class);
334 $sql="SELECT * FROM $class\n";
336 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$suffix_id)\n";
340 $search = $this->quote($search);
341 if(!isset($search_fields[$class])) {
342 $this->post_redirect_get($class, "Ve tride $class zatim vyhledavat nemozno :-(");
344 $where[0] = 'FALSE ';
345 foreach($search_fields[$class] as $column) $where[0] .= "OR $column REGEXP $search ";
346 } elseif($id) $where[1] = "$class$suffix_id = $id";
347 if(!$history && $this->contains_history($class)) $where[2] = $class.'_valid_till=0';
348 if($where) $sql .= 'WHERE '.implode(' AND ', $where)."\n";
351 $limit = $this->escape((int)$limit);
352 $offset = $this->escape((int)$offset);
353 $sql .= "LIMIT $offset,$limit\n";
356 if(!$order) $order = $class.$suffix_id;
357 $sql .= "ORDER BY $order";
362 function safe_query($sql, $fatal=true) {
363 $result = $this->query($sql);
365 $error = $this->errorInfo();
366 trigger_error("<font color=red><b>QUERY FAILED ($error[0],$error[1]): </b>$error[2]<br /><br /><b>QUERY:</b>\n<pre>$sql</pre></font>");
372 function get_listing($class, $id=false, $limit=false, $offset=0, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
373 $sql = $this->build_query_select($class, $id, $limit, $offset, $search, $history);
374 $result = $this->safe_query($sql)->fetchAll(PDO
::FETCH_ASSOC
);
375 if(!$result ||
!is_array($indexed)) return $result;
377 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
381 function get_columns($class) {
382 $class = $this->escape($class);
383 $sql = "SHOW COLUMNS FROM $class;";
384 return $this->safe_query($sql)->fetchAll(PDO
::FETCH_ASSOC
);
387 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
389 foreach($columns as $column) {
390 if($column['Field'] == 'user_id') continue; //TODO HACK Blacklist: tabulka nemusi obsahovat *_name!!! momentalne se to tyka jen tabulky user (a item - u ty to nevadi)!
391 if($class && $column['Field'] == $class.$suffix_id) continue;
392 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
393 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
395 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table;"; //TODO History
396 $result = $this->safe_query($sql, false);
397 if(!$result) continue;
398 $result = $result->fetchAll(PDO
::FETCH_ASSOC
);
399 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
401 //echo('<pre>'); print_r($selectbox);
402 return array_filter($selectbox, 'ksort');
405 function contains_history($table) {
406 $history_tables = array('item'); //TODO Autodetect
407 return in_array($table, $history_tables);
410 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
412 $history = $this->contains_history($table);
415 $table = $this->escape($table);
417 //Get list of POSTed columns
418 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
419 $columns = implode(',',$columns_array);
423 //echo('<pre>'); die(print_r($values));
426 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
427 if($history_update) {
428 $sql .= "UPDATE $table";
429 $sql .= ' SET '.$table.'_valid_till=NOW()';
430 $sql .= ' WHERE '.$table.'_valid_till=0 AND (';
432 foreach($values as $row) {
433 $sql .= $or.' '.$table.'_id='.$row[$table.'_id'];
441 //Insert into table (columns)
442 $sql .= "INSERT INTO $table ($columns) VALUES ";
444 //Values (a,b,c),(d,e,f)
446 foreach($values as $row) {
447 $row_quoted = array_map(array($this,'quote'), $row); //Check
449 foreach($row as $column => $value) {
451 case $table.'_valid_from':
452 $row_quoted[$column] = 'NOW()';
454 case $table.'_valid_till':
455 $row_quoted[$column] = '0';
457 case $table.'_author':
458 $row_quoted[$column] = $this->lms
->get_authorized_user_id();
459 //die($this->lms->get_authorized_user_id().'=USER');
464 $sql .= $comma.'('.implode(',',$row_quoted).')';
470 foreach($columns_array as $col) {
471 if($col == $table.'_id' ||
$col == $table.'_valid_till') continue;
472 $on_duplicate[] = "$col=VALUES($col)";
474 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
482 function insert_or_update($table, $values) {
483 $sql = $this->build_query_insert($table, $values);
484 $this->safe_query($sql);
485 return $this->lastInsertId();
488 function insert_or_update_multitab($values) {
490 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows);
494 function delete($table, $id, $suffix_id='_id') {
495 if($this->contains_history($table)) return false;
496 $key = $this->escape($table.$suffix_id);
497 $table = $this->escape($table);
498 $id = $this->quote($id);
499 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
504 * Trida poskytuje high-level rozhrani k databazi skladu
506 * @package Sklad_DB_Abstract
507 * @author Tomas Mudrunka
509 class Sklad_DB_Abstract
extends Sklad_DB
{
514 * Trida implementuje uzivatelske rozhrani skladu
517 * $sklad = new Sklad_UI();
518 * $sklad->process_http_request();
521 * @author Tomas Mudrunka
524 function __construct() {
525 $this->db
= new Sklad_DB();
526 $this->html
= new Sklad_HTML();
529 function render_items($class, $id=false, $limit=false, $offset=0, $search=false, $history=false) {
530 return $this->html
->render_item_table($this->db
->get_listing($class, $id, $limit, $offset, $search, $history, false));
533 function render_form_add($class) {
534 $columns = $this->db
->get_columns($class);
535 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
536 return $this->html
->render_insert_form($class, $columns, $selectbox);
539 function render_form_edit($class, $id) {
540 $columns = $this->db
->get_columns($class);
541 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
542 $current = $this->db
->get_listing($class, $id);
543 return $this->html
->render_insert_form($class, $columns, $selectbox, $current);
546 function render_single_record_details($class, $id) {
548 $id_prev = $id - 1 > 0 ?
$id - 1 : 0;
549 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
551 $html.= $this->html
->link('<<', "$class/$id_prev/");
553 $html.= $this->html
->link('>>', "$class/$id_next/");
555 $html.= $this->html
->link('edit', "$class/$id/edit/");
556 if($this->db
->contains_history($class)) $html.= ' ][ '.$this->html
->link('history', "$class/$id/history/");
560 function render_listing_navigation($class, $id, $limit, $offset) {
561 $offset_next = $offset +
$limit;
562 $offset_prev = $offset - $limit > 0 ?
$offset - $limit : 0;
563 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
565 $html.= $this->html
->link('<<', "$class/$id/$limit/$offset_prev/$get");
567 $html.= $this->html
->link('>>', "$class/$id/$limit/$offset_next/$get");
569 $html.= $this->html
->link('new', "$class/new/$get");
573 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
575 if(is_numeric($id)) {
576 $html.=$this->render_single_record_details($class, $id);
578 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
581 $html.= $this->render_form_edit($class, $id);
582 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
583 $html.= "<form action='$action' method='POST'>";
584 $html.= $this->html
->input(false, 'DELETE', 'submit');
585 $html.= 'sure?'.$this->html
->input('sure', false, 'checkbox');
587 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
588 $html.= "<form action='$action' method='POST' enctype='multipart/form-data'>";
589 $html.= $this->html
->input('image', false, 'file', false, 'size="30"');
590 $html.= $this->html
->input(false, 'IMAGE', 'submit');
596 function check_auth() {
597 new HTTP_Auth('SkladovejSystem', true, array($this->db
->lms
,'check_auth'));
600 function post_redirect_get($location, $message='', $error=false) {
601 $location = $this->html
->internal_url($location).'?message='.urlencode($message);
602 header('Location: '.$location);
603 if($error) trigger_error($message);
604 die("Location: <a href='$location'>$location</a>");
607 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
608 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
609 $filename="$dir/$name$ext";
610 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
611 foreach($vars as $var => $val) $
$var=$val;
614 $out=ob_get_contents();
619 function process_http_request_post($action=false, $class=false, $id=false) {
620 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
621 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
625 /* Tenhle foreach() prekopiruje promenne
626 * z: $_POST['values'][$table][$column][$id];
627 * do: $values[$table][$id][$column]
629 if(isset($_POST['values'])) {
631 foreach($_POST['values'] as $table => $columns) {
632 foreach($columns as $column => $ids) {
633 foreach($ids as $id => $val) $values[$table][$id][$column] = $val;
636 //die(print_r($values));
639 if($action) switch($action) {
642 $table = $class ?
$class : 'item';
643 //print_r($values); //debug
644 $last = $this->db
->insert_or_update_multitab($values);
645 $last = "$table/$last/";
646 $next = "$table/new/";
647 $this->post_redirect_get($last, 'Hotovo. Další záznam přidáte '.$this->html
->link('zde', $next).'.');
650 if(!isset($_POST['sure']) ||
!$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
651 $this->db
->delete($class, $id) ||
$this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
652 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
655 $image_classes = array('model'); //TODO, use this more widely across the code
656 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
657 $image_destination = DIR_IMAGES
."/$class/$id.jpg";
658 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Kazde neco se musi nejak jmenovat!', true);
659 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
660 chmod ($image_destination, 0664);
661 $this->post_redirect_get("$class/$id", 'Obrazek se naladoval :)');
662 } else $this->post_redirect_get("$class/$id/edit", 'Soubor se nenahral :(', true);
665 trigger_error('Nothin\' to do here my cutie :-*');
672 function process_http_request() {
675 @ini_set
('magic_quotes_gpc' , 'off');
676 if(get_magic_quotes_gpc()) {
677 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
680 $PATH_INFO=@trim
($_SERVER[PATH_INFO
]);
681 if($_SERVER['REQUEST_METHOD'] != 'POST') echo $this->html
->header($PATH_INFO); //TODO tahle podminka naznacuje ze je v navrhu nejaka drobna nedomyslenost...
685 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
686 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
687 switch($PATH_CHUNKS[1]) {
689 die('Tell me why you cry');
691 case 'assistant': //assistant
692 $assistant_vars['step'] = isset($PATH_CHUNKS[3]) && is_numeric($PATH_CHUNKS[3]) ?
trim($PATH_CHUNKS[3]) : false;
693 echo $this->safe_include(DIR_ASSISTANTS
,$PATH_CHUNKS[2],$assistant_vars);
696 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ?
trim($_GET['q']) : false;
697 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ?
$PATH_CHUNKS[1] : 'item';
698 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
699 switch($PATH_CHUNKS[2]) {
701 $this->process_http_request_post($PATH_CHUNKS[2], $class);
702 echo $this->render_form_add($class);
705 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ?
(int) $PATH_CHUNKS[2] : false);
706 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
708 switch($PATH_CHUNKS[3]) {
709 case 'edit': //?/?/edit
710 case 'image': //?/?/image
711 case 'delete': //?/?/delete
712 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
715 $history = $PATH_CHUNKS[3] == 'history' ?
true : false;
716 $limit = (int) (isset($PATH_CHUNKS[3]) ?
$PATH_CHUNKS[3] : '0');
717 $offset = (int) (isset($PATH_CHUNKS[4]) ?
$PATH_CHUNKS[4] : '0');
718 echo $this->render_items($class, $id, $limit, $offset, $search, $history);
719 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
720 //print_r(array("<pre>",$_SERVER));
730 $sklad = new Sklad_UI();
731 $sklad->process_http_request();
This page took 1.002494 seconds and 5 git commands to generate.