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 podpurne funkce pro generovani HTML kodu specificke pro sklad
27 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
30 * @author Tomas Mudrunka
33 function header($title='') {
35 $script = $_SERVER['SCRIPT_NAME'];
36 $search = htmlspecialchars(@trim
($_GET['q']));
37 $message = htmlspecialchars(@trim
($_GET['message']));
40 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
42 <h1><a href="$script/">SystémSklad</a><small>$title</small></h1>
44 <style type="text/css">
45 .menu li, .menu * li {
52 background-color: yellow;
71 <li><a href="?logout">Logout</a></li>
72 <li><a href="$script/">Home</a></li>
73 <li><a href="#">Assistants</A>
75 <li><a href="$script/assistant/new-item">new-item</a></li>
78 <li><a href="#">List</a>
80 <li><a href="$script/item">item</a></li>
81 <li><a href="$script/model">model</a></li>
82 <li><a href="$script/category">category</a></li>
83 <li><a href="$script/producer">producer</a></li>
84 <li><a href="$script/vendor">vendor</a></li>
85 <li><a href="$script/room">room</a></li>
86 <li><a href="$script/status">status</a></li>
89 <li><a href="#">New</a>
91 <li><a href="$script/item/new">item</a></li>
92 <li><a href="$script/model/new">model</a></li>
93 <li><a href="$script/category/new">category</a></li>
94 <li><a href="$script/producer/new">producer</a></li>
95 <li><a href="$script/vendor/new">vendor</a></li>
96 <li><a href="$script/room/new">room</a></li>
97 <li><a href="$script/status/new">status</a></li>
102 <div style="float: right;">
103 <form action="?" method="GET">
104 <input type="text" name="q" placeholder="regexp..." value="$search" />
105 <input type="submit" value="filter" />
107 <!-- form action="$script/" method="GET">
108 <input type="text" name="q" placeholder="regexp..." value="$search" />
109 <input type="submit" value="search items" />
113 <hr style="clear: both;" />
114 <div style="background-color:#FFDDDD;">
115 <font color="red">$message</font>
122 foreach($row as $var) {
123 if(trim($var) == '') $var = ' ';
124 $html.="<td>$var</td>";
130 function table(&$table, $params='border=1') {
131 $html="<table $params>";
133 foreach($table as $row) {
135 $html.=$this->row(array_keys($row));
138 $html.=$this->row($row);
144 function internal_url($link) {
145 return $_SERVER['SCRIPT_NAME'].'/'.$link;
148 function link($title='n/a', $link='#void', $internal=true) {
149 if($internal) $link = $this->internal_url($link);
150 return "<a href='$link'>$title</a>";
153 function img($src='#void', $title='img') {
154 return "<img src='$src' alt='$title' title='$title' width=64 />";
157 function table_add_images(&$table) {
158 $image = array('model_id');
159 foreach($table as $id => $row) {
160 foreach($image as $column) if(isset($table[$id][$column])) {
161 $type = @array_shift
(preg_split('/_/', $column));
162 $src=URL_IMAGES
."/$type/".$table[$id][$column].'.jpg';
163 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
168 function table_collapse(&$table) {
170 'item_id' => 'item_id',
171 'model_id' => 'model_name',
172 'category_id' => 'category_name',
173 'producer_id' => 'producer_name',
174 'vendor_id' => 'vendor_name',
175 'room_id' => 'room_name',
176 'status_id' => 'status_name',
178 foreach($table as $id => $row) {
179 foreach($collapse as $link => $title)
180 if(isset($table[$id][$link])) {
181 $type = @array_shift
(preg_split('/_/', $link));
182 if($link != $title) unset($table[$id][$link]);
183 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
188 function table_sort(&$table) {
189 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
190 $table_sorted = array();
191 foreach($table as $id => $row) {
192 $table_sorted[$id] = array();
193 foreach($precedence as $column) if(isset($table[$id][$column])) {
194 $table_sorted[$id][$column]=$table[$id][$column];
195 unset($table[$id][$column]);
197 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
199 $table = $table_sorted;
202 function render_item_table($table) {
203 $this->table_add_images($table);
204 $this->table_collapse($table);
205 $this->table_sort($table);
206 return $this->table($table);
209 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false) {
210 $html = "<input type='$type' ";
211 if($name) $html.= "name='$name' ";
212 if(!is_bool($value)) $html.= "value='$value' ";
213 if($options) $html.= "$options ";
214 if($placeholder) $html.= "placeholder='$placeholder' ";
219 function select($name, $selectbox, $default=false) {
220 //echo('<pre>'); print_r($selectbox);
221 $html = "<select name='$name'>";
224 $value=$default; $title=$selectbox[$value];
225 $html .= "<option value='$value'>$value :: $title</option>";
226 unset($selectbox[$value]);
228 foreach($selectbox as $value => $title) {
229 $html .= "<option value='$value'>$value :: $title</option>";
231 $html .= "</select>";
235 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $multi_insert=true) {
236 //echo('<pre>'); print_r($selectbox);
237 //echo('<pre>'); print_r($current);
239 if(is_array($current)) {
241 $current = array_shift($current);
244 $html='<form method="POST">';
245 if($multi_insert) $html.='<div name="input_set" style="float:left; border:1px solid grey;">';
246 //$html.=$this->input('table', $class, 'hidden');
247 foreach($columns as $column) {
248 $html.=$class.':<b>'.$column['Field'].'</b>: ';
249 $name="values[$class][".$column['Field'].'][]';
250 $val = $update ?
$current[$column['Field']] : false;
252 case preg_match('/auto_increment/', $column['Extra']):
254 $html.=$this->input($name, $val, 'hidden');
255 $html.=$val.'(AUTO)';
257 case isset($selectbox[$column['Field']]):
258 $html.=$this->select($name,$selectbox[$column['Field']],$val);
261 $html.=$this->input($name, $val);
268 //TODO, move to separate JS file
271 <span name="input_set_next"></span><br style="clear:both" />
273 function duplicate_element(what, where) {
274 document.getElementsByName(where)[0].outerHTML =
275 document.getElementsByName(what)[0].outerHTML
276 + document.getElementsByName(where)[0].outerHTML;
279 <a href='#' onClick="duplicate_element('input_set', 'input_set_next')">+</a>
283 $btn = is_array($current) ?
'UPDATE' : 'INSERT';
284 $html.=$this->input(false, $btn, 'submit');
291 * Trida poskytuje rozhrani k databazi skladu
294 * @author Tomas Mudrunka
296 class Sklad_DB
extends PDO
{
297 function __construct() {
298 $this->lms
= new Sklad_LMS();
301 DB_DSN
, DB_USER
, DB_PASS
,
302 array(PDO
::MYSQL_ATTR_INIT_COMMAND
=> "SET NAMES utf8") //Force UTF8 for MySQL
306 function escape($str) {
307 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
310 function build_query_select($class, $id=false, $limit=false, $offset=0, $search=false, $history=false, $order=false, $suffix_id='_id') {
313 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
314 'model' => array('category', 'producer')
315 ); //TODO Autodetect using foreign keys?
316 $search_fields = array(
317 'item' => array('item_id','model_name','model_barcode','model_descript','producer_name','vendor_name')
321 $class = $this->escape($class);
324 $sql="SELECT * FROM $class\n";
326 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$suffix_id)\n";
330 $search = $this->quote($search);
331 if(!isset($search_fields[$class])) {
332 trigger_error("Ve tride $class zatim vyhledavat nemozno :-(");
335 $where[0] = 'FALSE ';
336 foreach($search_fields[$class] as $column) $where[0] .= "OR $column REGEXP $search ";
337 } elseif($id) $where[1] = "$class$suffix_id = $id";
338 if(!$history && $this->contains_history($class)) $where[2] = $class.'_valid_till=0';
339 if($where) $sql .= 'WHERE '.implode(' AND ', $where)."\n";
342 $limit = $this->escape((int)$limit);
343 $offset = $this->escape((int)$offset);
344 $sql .= "LIMIT $offset,$limit\n";
347 if(!$order) $order = $class.$suffix_id;
348 $sql .= "ORDER BY $order";
353 function safe_query($sql, $fatal=true) {
354 $result = $this->query($sql);
356 $error = $this->errorInfo();
357 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>");
363 function get_listing($class, $id=false, $limit=false, $offset=0, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
364 $sql = $this->build_query_select($class, $id, $limit, $offset, $search, $history);
365 $result = $this->safe_query($sql)->fetchAll(PDO
::FETCH_ASSOC
);
366 if(!$result ||
!is_array($indexed)) return $result;
368 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
372 function get_columns($class) {
373 $class = $this->escape($class);
374 $sql = "SHOW COLUMNS FROM $class;";
375 return $this->safe_query($sql)->fetchAll(PDO
::FETCH_ASSOC
);
378 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
380 foreach($columns as $column) {
381 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)!
382 if($class && $column['Field'] == $class.$suffix_id) continue;
383 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
384 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
386 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table;"; //TODO History
387 $result = $this->safe_query($sql, false);
388 if(!$result) continue;
389 $result = $result->fetchAll(PDO
::FETCH_ASSOC
);
390 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
392 //echo('<pre>'); print_r($selectbox);
393 return array_filter($selectbox, 'ksort');
396 function contains_history($table) {
397 $history_tables = array('item'); //TODO Autodetect
398 return in_array($table, $history_tables);
401 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
403 $history = $this->contains_history($table);
406 $table = $this->escape($table);
408 //Get list of POSTed columns
409 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
410 $columns = implode(',',$columns_array);
414 //echo('<pre>'); die(print_r($values));
417 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
418 if($history_update) {
419 $sql .= "UPDATE $table";
420 $sql .= ' SET '.$table.'_valid_till=NOW()';
421 $sql .= ' WHERE '.$table.'_valid_till=0 AND (';
423 foreach($values as $row) {
424 $sql .= $or.' '.$table.'_id='.$row[$table.'_id'];
432 //Insert into table (columns)
433 $sql .= "INSERT INTO $table ($columns) VALUES ";
435 //Values (a,b,c),(d,e,f)
437 foreach($values as $row) {
438 $row_quoted = array_map(array($this,'quote'), $row); //Check
440 foreach($row as $column => $value) {
442 case $table.'_valid_from':
443 $row_quoted[$column] = 'NOW()';
445 case $table.'_valid_till':
446 $row_quoted[$column] = '0';
448 case $table.'_author':
449 $row_quoted[$column] = $this->lms
->get_authorized_user_id();
450 //die($this->lms->get_authorized_user_id().'=USER');
455 $sql .= $comma.'('.implode(',',$row_quoted).')';
461 foreach($columns_array as $col) {
462 if($col == $table.'_id' ||
$col == $table.'_valid_till') continue;
463 $on_duplicate[] = "$col=VALUES($col)";
465 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
473 function insert_or_update($table, $values) {
474 $sql = $this->build_query_insert($table, $values);
475 $this->safe_query($sql);
476 return $this->lastInsertId();
479 function insert_or_update_multitab($values) {
481 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows);
485 function delete($table, $id, $suffix_id='_id') {
486 if($this->contains_history($table)) die(trigger_error("V tabulce $table jentak neco mazat nebudes chlapecku :-P")); //TODO post redirect get
487 $key = $this->escape($table.$suffix_id);
488 $table = $this->escape($table);
489 $id = $this->quote($id);
490 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
495 * Trida implementuje uzivatelske rozhrani skladu
498 * $sklad = new Sklad_UI();
499 * $sklad->process_http_request();
502 * @author Tomas Mudrunka
505 function __construct() {
506 $this->db
= new Sklad_DB();
507 $this->html
= new Sklad_HTML();
510 function render_items($class, $id=false, $limit=false, $offset=0, $search=false, $history=false) {
511 return $this->html
->render_item_table($this->db
->get_listing($class, $id, $limit, $offset, $search, $history, false));
514 function render_form_add($class) {
515 $columns = $this->db
->get_columns($class);
516 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
517 return $this->html
->render_insert_form($class, $columns, $selectbox);
520 function render_form_edit($class, $id) {
521 $columns = $this->db
->get_columns($class);
522 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
523 $current = $this->db
->get_listing($class, $id);
524 return $this->html
->render_insert_form($class, $columns, $selectbox, $current);
527 function render_single_record_details($class, $id) {
529 $id_prev = $id - 1 > 0 ?
$id - 1 : 0;
530 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
532 $html.= $this->html
->link('<<', "$class/$id_prev/");
534 $html.= $this->html
->link('>>', "$class/$id_next/");
536 $html.= $this->html
->link('edit', "$class/$id/edit/");
537 if($this->db
->contains_history($class)) $html.= ' ][ '.$this->html
->link('history', "$class/$id/history/");
541 function render_listing_navigation($class, $id, $limit, $offset) {
542 $offset_next = $offset +
$limit;
543 $offset_prev = $offset - $limit > 0 ?
$offset - $limit : 0;
544 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
546 $html.= $this->html
->link('<<', "$class/$id/$limit/$offset_prev/$get");
548 $html.= $this->html
->link('>>', "$class/$id/$limit/$offset_next/$get");
550 $html.= $this->html
->link('new', "$class/new/$get");
554 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
556 if(is_numeric($id)) {
557 $html.=$this->render_single_record_details($class, $id);
559 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
562 $html.='<br />TODO UPDATE FORM!<br />'; //TODO: Asi uz je hotovy...
563 $html.= $this->render_form_edit($class, $id);
564 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
565 $html.= "<form action='$action' method='POST'>";
566 $html.= $this->html
->input(false, 'DELETE', 'submit');
567 $html.= 'sure?'.$this->html
->input('sure', false, 'checkbox');
569 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
570 $html.= "<form action='$action' method='POST' enctype='multipart/form-data'>";
571 $html.= $this->html
->input('image', false, 'file', false, 'size="30"');
572 $html.= $this->html
->input(false, 'IMAGE', 'submit');
578 function check_auth() {
579 new HTTP_Auth('SkladovejSystem', true, array($this->db
->lms
,'check_auth'));
582 function post_redirect_get($location, $message='') {
583 $location = $this->html
->internal_url($location).'?message='.urlencode($message);
584 header('Location: '.$location);
585 die("Location: $location");
588 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
589 if(preg_match('/[^a-zA-Z0-9-]/',$name)) die(trigger_error('SAFE INCLUDE: Securityfuck.'));
590 $filename="$dir/$name$ext";
591 if(!is_file($filename)) die(trigger_error('SAFE INCLUDE: Fuckfound.'));
592 foreach($vars as $var => $val) $
$var=$val;
595 $out=ob_get_contents();
600 function process_http_request_post($action=false, $class=false, $id=false) {
601 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
602 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
606 /* Tenhle foreach() prekopiruje promenne
607 * z: $_POST['values'][$table][$column][$id];
608 * do: $values[$table][$id][$column]
610 if(isset($_POST['values'])) {
612 foreach($_POST['values'] as $table => $columns) {
613 foreach($columns as $column => $ids) {
614 foreach($ids as $id => $val) $values[$table][$id][$column] = $val;
617 //die(print_r($values));
620 if($action) switch($action) {
623 //if(!isset($_POST['table'])) die(trigger_error("Jest nutno specifikovat tabulku voe!"));
624 //$table=$_POST['table'];
626 //print_r($values); //debug
627 $last = $this->db
->insert_or_update_multitab($values);
628 $last = "$table/$last/";
629 $next = "$table/new/";
630 echo 'Hotovo. Poslední vložený záznam naleznete '.$this->html
->link('zde', $last).'.<br />'.
631 'Další záznam přidáte '.$this->html
->link('zde', $next).'.';
635 if(!isset($_POST['sure']) ||
!$_POST['sure']) die(trigger_error('Sure user expected :-)'));
636 $this->db
->delete($class, $id);
637 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
640 $image_classes = array('model'); //TODO, use this more widely across the code
641 if(!in_array($class, $image_classes)) die(trigger_error("Nekdo nechce k DB Tride '$class' prirazovat obrazky!"));
642 $image_destination = DIR_IMAGES
."/$class/$id.jpg";
643 if($_FILES['image']['name'] == '') die(trigger_error('Kazde neco se musi nejak jmenovat!'));
644 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
645 chmod ($image_destination, 0664);
646 $this->post_redirect_get("$class/$id", 'Obrazek se naladoval :)');
647 } else die(trigger_error('Soubor se nenahral :('));
650 trigger_error('Nothin\' to do here my cutie :-*');
657 function process_http_request() {
660 @ini_set
('magic_quotes_gpc' , 'off');
661 if(get_magic_quotes_gpc()) {
662 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
665 $PATH_INFO=@trim
($_SERVER[PATH_INFO
]);
666 if($_SERVER['REQUEST_METHOD'] != 'POST') echo $this->html
->header($PATH_INFO); //TODO tahle podminka naznacuje ze je v navrhu nejaka drobna nedomyslenost...
670 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
671 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
672 switch($PATH_CHUNKS[1]) {
674 die('Tell me why you cry');
676 case 'assistant': //assistant
677 $assistant_vars['step'] = isset($PATH_CHUNKS[3]) && is_numeric($PATH_CHUNKS[3]) ?
trim($PATH_CHUNKS[3]) : false;
678 echo $this->safe_include(DIR_ASSISTANTS
,$PATH_CHUNKS[2],$assistant_vars);
681 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ?
trim($_GET['q']) : false;
682 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ?
$PATH_CHUNKS[1] : 'item';
683 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
684 switch($PATH_CHUNKS[2]) {
686 $this->process_http_request_post($PATH_CHUNKS[2], $class);
687 echo $this->render_form_add($class);
690 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ?
(int) $PATH_CHUNKS[2] : false);
691 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
693 switch($PATH_CHUNKS[3]) {
694 case 'edit': //?/?/edit
695 case 'image': //?/?/image
696 case 'delete': //?/?/delete
697 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
700 $history = $PATH_CHUNKS[3] == 'history' ?
true : false;
701 $limit = (int) (isset($PATH_CHUNKS[3]) ?
$PATH_CHUNKS[3] : '0');
702 $offset = (int) (isset($PATH_CHUNKS[4]) ?
$PATH_CHUNKS[4] : '0');
703 echo $this->render_items($class, $id, $limit, $offset, $search, $history);
704 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
705 //print_r(array("<pre>",$_SERVER));
715 $sklad = new Sklad_UI();
716 $sklad->process_http_request();
This page took 0.981683 seconds and 5 git commands to generate.