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>
45 <li><a href="?logout">Logout</a></li>
46 <li><a href="$script/">Home</a></li>
48 <form action="?" method="GET">
49 <input type="text" name="q" placeholder="regexp..." value="$search" />
50 <input type="submit" value="filter" />
52 <!-- form action="$script/" method="GET">
53 <input type="text" name="q" placeholder="regexp..." value="$search" />
54 <input type="submit" value="search items" />
57 <div style="background-color:#FFDDDD;">
58 <font color="red">$message</font>
65 foreach($row as $var) {
66 if(trim($var) == '') $var = ' ';
67 $html.="<td>$var</td>";
73 function table(&$table, $params='border=1') {
74 $html="<table $params>";
76 foreach($table as $row) {
78 $html.=$this->row(array_keys($row));
81 $html.=$this->row($row);
87 function internal_url($link) {
88 return $_SERVER['SCRIPT_NAME'].'/'.$link;
91 function link($title='n/a', $link='#void', $internal=true) {
92 if($internal) $link = $this->internal_url($link);
93 return "<a href='$link'>$title</a>";
96 function img($src='#void', $title='img') {
97 return "<img src='$src' alt='$title' title='$title' width=64 />";
100 function table_add_images(&$table) {
101 $image = array('model_id');
102 foreach($table as $id => $row) {
103 foreach($image as $column) if(isset($table[$id][$column])) {
104 $type = @array_shift
(preg_split('/_/', $column));
105 $src=URL_IMAGES
."/$type/".$table[$id][$column].'.jpg';
106 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
111 function table_collapse(&$table) {
113 'item_id' => 'item_id',
114 'model_id' => 'model_name',
115 'category_id' => 'category_name',
116 'producer_id' => 'producer_name',
117 'vendor_id' => 'vendor_name',
118 'room_id' => 'room_name',
119 'status_id' => 'status_name',
121 foreach($table as $id => $row) {
122 foreach($collapse as $link => $title)
123 if(isset($table[$id][$link])) {
124 $type = @array_shift
(preg_split('/_/', $link));
125 if($link != $title) unset($table[$id][$link]);
126 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
131 function table_sort(&$table) {
132 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
133 $table_sorted = array();
134 foreach($table as $id => $row) {
135 $table_sorted[$id] = array();
136 foreach($precedence as $column) if(isset($table[$id][$column])) {
137 $table_sorted[$id][$column]=$table[$id][$column];
138 unset($table[$id][$column]);
140 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
142 $table = $table_sorted;
145 function render_item_table($table) {
146 $this->table_add_images($table);
147 $this->table_collapse($table);
148 $this->table_sort($table);
149 return $this->table($table);
152 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false) {
153 $html = "<input type='$type' ";
154 if($name) $html.= "name='$name' ";
155 if(!is_bool($value)) $html.= "value='$value' ";
156 if($options) $html.= "$options ";
157 if($placeholder) $html.= "placeholder='$placeholder' ";
162 function select($name, $selectbox, $default=false) {
163 //echo('<pre>'); print_r($selectbox);
164 $html = "<select name='$name'>";
167 $value=$default; $title=$selectbox[$value];
168 $html .= "<option value='$value'>$value :: $title</option>";
169 unset($selectbox[$value]);
171 foreach($selectbox as $value => $title) {
172 $html .= "<option value='$value'>$value :: $title</option>";
174 $html .= "</select>";
178 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $multi_insert=true) {
179 //echo('<pre>'); print_r($selectbox);
180 //echo('<pre>'); print_r($current);
182 if(is_array($current)) {
184 $current = array_shift($current);
187 $html='<form method="POST">';
188 if($multi_insert) $html.='<div name="input_set" style="float:left; border:1px solid grey;">';
189 //$html.=$this->input('table', $class, 'hidden');
190 foreach($columns as $column) {
191 $html.=$class.':<b>'.$column['Field'].'</b>: ';
192 $name="values[$class][".$column['Field'].'][]';
193 $val = $update ?
$current[$column['Field']] : false;
195 case preg_match('/auto_increment/', $column['Extra']):
197 $html.=$this->input($name, $val, 'hidden');
198 $html.=$val.'(AUTO)';
200 case isset($selectbox[$column['Field']]):
201 $html.=$this->select($name,$selectbox[$column['Field']],$val);
204 $html.=$this->input($name, $val);
211 //TODO, move to separate JS file
214 <span name="input_set_next"></span><br style="clear:both" />
216 function duplicate_element(what, where) {
217 document.getElementsByName(where)[0].outerHTML =
218 document.getElementsByName(what)[0].outerHTML
219 + document.getElementsByName(where)[0].outerHTML;
222 <a href='#' onClick="duplicate_element('input_set', 'input_set_next')">+</a>
226 $btn = is_array($current) ?
'UPDATE' : 'INSERT';
227 $html.=$this->input(false, $btn, 'submit');
234 * Trida poskytuje rozhrani k databazi skladu
237 * @author Tomas Mudrunka
239 class Sklad_DB
extends PDO
{
240 function __construct() {
241 $this->lms
= new Sklad_LMS();
244 DB_DSN
, DB_USER
, DB_PASS
,
245 array(PDO
::MYSQL_ATTR_INIT_COMMAND
=> "SET NAMES utf8") //Force UTF8 for MySQL
249 function escape($str) {
250 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
253 function build_query_select($class, $id=false, $limit=false, $offset=0, $search=false, $history=false, $order=false, $suffix_id='_id') {
256 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
257 'model' => array('category', 'producer')
258 ); //TODO Autodetect using foreign keys?
259 $search_fields = array(
260 'item' => array('item_id','model_name','model_barcode','model_descript','producer_name','vendor_name')
264 $class = $this->escape($class);
267 $sql="SELECT * FROM $class\n";
269 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$suffix_id)\n";
273 $search = $this->quote($search);
274 if(!isset($search_fields[$class])) {
275 trigger_error("Ve tride $class zatim vyhledavat nemozno :-(");
278 $where[0] = 'FALSE ';
279 foreach($search_fields[$class] as $column) $where[0] .= "OR $column REGEXP $search ";
280 } elseif($id) $where[1] = "$class$suffix_id = $id";
281 if(!$history && $this->contains_history($class)) $where[2] = $class.'_valid_till=0';
282 if($where) $sql .= 'WHERE '.implode(' AND ', $where)."\n";
285 $limit = $this->escape((int)$limit);
286 $offset = $this->escape((int)$offset);
287 $sql .= "LIMIT $offset,$limit\n";
290 if(!$order) $order = $class.$suffix_id;
291 $sql .= "ORDER BY $order";
296 function safe_query($sql, $fatal=true) {
297 $result = $this->query($sql);
299 $error = $this->errorInfo();
300 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>");
306 function get_listing($class, $id=false, $limit=false, $offset=0, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
307 $sql = $this->build_query_select($class, $id, $limit, $offset, $search, $history);
308 $result = $this->safe_query($sql)->fetchAll(PDO
::FETCH_ASSOC
);
309 if(!$result ||
!is_array($indexed)) return $result;
311 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
315 function get_columns($class) {
316 $class = $this->escape($class);
317 $sql = "SHOW COLUMNS FROM $class;";
318 return $this->safe_query($sql)->fetchAll(PDO
::FETCH_ASSOC
);
321 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
323 foreach($columns as $column) {
324 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)!
325 if($class && $column['Field'] == $class.$suffix_id) continue;
326 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
327 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
329 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table;"; //TODO History
330 $result = $this->safe_query($sql, false);
331 if(!$result) continue;
332 $result = $result->fetchAll(PDO
::FETCH_ASSOC
);
333 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
335 //echo('<pre>'); print_r($selectbox);
336 return array_filter($selectbox, 'ksort');
339 function contains_history($table) {
340 $history_tables = array('item'); //TODO Autodetect
341 return in_array($table, $history_tables);
344 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
346 $history = $this->contains_history($table);
349 $table = $this->escape($table);
351 //Get list of POSTed columns
352 $columns = implode(',',array_map(array($this,'escape'), array_keys($values[0])));
356 //echo('<pre>'); die(print_r($values));
359 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
360 if($history_update) {
361 $sql .= "UPDATE $table";
362 $sql .= ' SET '.$table.'_valid_till=NOW()';
363 $sql .= ' WHERE '.$table.'_valid_till=0 AND (';
365 foreach($values as $row) {
366 $sql .= $or.' '.$table.'_id='.$row[$table.'_id'];
374 //Insert into table (columns)
375 $sql .= $replace ?
'REPLACE' : 'INSERT';
376 $sql .= " INTO $table ($columns) VALUES ";
378 //Values (a,b,c),(d,e,f)
380 foreach($values as $row) {
381 $row_quoted = array_map(array($this,'quote'), $row); //Check
383 foreach($row as $column => $value) {
385 case $table.'_valid_from':
386 $row_quoted[$column] = 'NOW()';
388 case $table.'_valid_till':
389 $row_quoted[$column] = '0';
391 case $table.'_author':
392 $row_quoted[$column] = $this->lms
->get_authorized_user_id();
393 //die($this->lms->get_authorized_user_id().'=USER');
398 $sql .= $comma.'('.implode(',',$row_quoted).')';
407 function insert_or_update($table, $values) {
408 $sql = $this->build_query_insert($table, $values);
409 $this->safe_query($sql);
410 return $this->lastInsertId();
413 function insert_or_update_multitab($values) {
415 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows);
419 function delete($table, $id, $suffix_id='_id') {
420 if($this->contains_history($table)) die(trigger_error("V tabulce $table jentak neco mazat nebudes chlapecku :-P")); //TODO post redirect get
421 $key = $this->escape($table.$suffix_id);
422 $table = $this->escape($table);
423 $id = $this->quote($id);
424 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
429 * Trida implementuje uzivatelske rozhrani skladu
432 * $sklad = new Sklad_UI();
433 * $sklad->process_http_request();
436 * @author Tomas Mudrunka
439 function __construct() {
440 $this->db
= new Sklad_DB();
441 $this->html
= new Sklad_HTML();
444 function render_items($class, $id=false, $limit=false, $offset=0, $search=false, $history=false) {
445 return $this->html
->render_item_table($this->db
->get_listing($class, $id, $limit, $offset, $search, $history, false));
448 function render_form_add($class) {
449 $columns = $this->db
->get_columns($class);
450 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
451 return $this->html
->render_insert_form($class, $columns, $selectbox);
454 function render_form_edit($class, $id) {
455 $columns = $this->db
->get_columns($class);
456 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
457 $current = $this->db
->get_listing($class, $id);
458 return $this->html
->render_insert_form($class, $columns, $selectbox, $current);
461 function render_single_record_details($class, $id) {
463 $id_prev = $id - 1 > 0 ?
$id - 1 : 0;
464 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
466 $html.= $this->html
->link('<<', "$class/$id_prev/");
468 $html.= $this->html
->link('>>', "$class/$id_next/");
470 $html.= $this->html
->link('edit', "$class/$id/edit/");
471 if($this->db
->contains_history($class)) $html.= ' ][ '.$this->html
->link('history', "$class/$id/history/");
475 function render_listing_navigation($class, $id, $limit, $offset) {
476 $offset_next = $offset +
$limit;
477 $offset_prev = $offset - $limit > 0 ?
$offset - $limit : 0;
478 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
480 $html.= $this->html
->link('<<', "$class/$id/$limit/$offset_prev/$get");
482 $html.= $this->html
->link('>>', "$class/$id/$limit/$offset_next/$get");
484 $html.= $this->html
->link('new', "$class/new/$get");
488 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
490 if(is_numeric($id)) {
491 $html.=$this->render_single_record_details($class, $id);
493 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
496 $html.='<br />TODO UPDATE FORM!<br />'; //TODO: Asi uz je hotovy...
497 $html.= $this->render_form_edit($class, $id);
498 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
499 $html.= "<form action='$action' method='POST'>";
500 $html.= $this->html
->input(false, 'DELETE', 'submit');
501 $html.= 'sure?'.$this->html
->input('sure', false, 'checkbox');
503 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
504 $html.= "<form action='$action' method='POST' enctype='multipart/form-data'>";
505 $html.= $this->html
->input('image', false, 'file', false, 'size="30"');
506 $html.= $this->html
->input(false, 'IMAGE', 'submit');
512 function check_auth() {
513 new HTTP_Auth('SkladovejSystem', true, array($this->db
->lms
,'check_auth'));
516 function post_redirect_get($location, $message='') {
517 $location = $this->html
->internal_url($location).'?message='.urlencode($message);
518 header('Location: '.$location);
519 die("Location: $location");
522 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
523 if(preg_match('/[^a-zA-Z0-9-]/',$name)) die(trigger_error('SAFE INCLUDE: Securityfuck.'));
524 $filename="$dir/$name$ext";
525 if(!is_file($filename)) die(trigger_error('SAFE INCLUDE: Fuckfound.'));
526 foreach($vars as $var => $val) $
$var=$val;
529 $out=ob_get_contents();
534 function process_http_request_post($action=false, $class=false, $id=false) {
535 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
536 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
540 /* Tenhle foreach() prekopiruje promenne
541 * z: $_POST['values'][$table][$column][$id];
542 * do: $values[$table][$id][$column]
544 if(isset($_POST['values'])) {
546 foreach($_POST['values'] as $table => $columns) {
547 foreach($columns as $column => $ids) {
548 foreach($ids as $id => $val) $values[$table][$id][$column] = $val;
551 //die(print_r($values));
554 if($action) switch($action) {
557 //if(!isset($_POST['table'])) die(trigger_error("Jest nutno specifikovat tabulku voe!"));
558 //$table=$_POST['table'];
560 //print_r($values); //debug
561 $last = $this->db
->insert_or_update_multitab($values);
562 $last = "$table/$last/";
563 $next = "$table/new/";
564 echo 'Hotovo. Poslední vložený záznam naleznete '.$this->html
->link('zde', $last).'.<br />'.
565 'Další záznam přidáte '.$this->html
->link('zde', $next).'.';
569 if(!isset($_POST['sure']) ||
!$_POST['sure']) die(trigger_error('Sure user expected :-)'));
570 $this->db
->delete($class, $id);
571 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
574 $image_classes = array('model'); //TODO, use this more widely across the code
575 if(!in_array($class, $image_classes)) die(trigger_error("Nekdo nechce k DB Tride '$class' prirazovat obrazky!"));
576 $image_destination = DIR_IMAGES
."/$class/$id.jpg";
577 if($_FILES['image']['name'] == '') die(trigger_error('Kazde neco se musi nejak jmenovat!'));
578 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
579 chmod ($image_destination, 0664);
580 $this->post_redirect_get("$class/$id", 'Obrazek se naladoval :)');
581 } else die(trigger_error('Soubor se nenahral :('));
584 trigger_error('Nothin\' to do here my cutie :-*');
591 function process_http_request() {
594 @ini_set
('magic_quotes_gpc' , 'off');
595 if(get_magic_quotes_gpc()) {
596 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
599 $PATH_INFO=@trim
($_SERVER[PATH_INFO
]);
600 if($_SERVER['REQUEST_METHOD'] != 'POST') echo $this->html
->header($PATH_INFO); //TODO tahle podminka naznacuje ze je v navrhu nejaka drobna nedomyslenost...
604 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
605 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
606 switch($PATH_CHUNKS[1]) {
608 die('Tell me why you cry');
610 case 'assistant': //assistant
611 $assistant_vars['step'] = isset($PATH_CHUNKS[3]) && is_numeric($PATH_CHUNKS[3]) ?
trim($PATH_CHUNKS[3]) : false;
612 echo $this->safe_include(DIR_ASSISTANTS
,$PATH_CHUNKS[2],$assistant_vars);
615 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ?
trim($_GET['q']) : false;
616 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ?
$PATH_CHUNKS[1] : 'item';
617 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
618 switch($PATH_CHUNKS[2]) {
620 $this->process_http_request_post($PATH_CHUNKS[2], $class);
621 echo $this->render_form_add($class);
624 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ?
(int) $PATH_CHUNKS[2] : false);
625 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
627 switch($PATH_CHUNKS[3]) {
628 case 'edit': //?/?/edit
629 case 'image': //?/?/image
630 case 'delete': //?/?/delete
631 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
634 $history = $PATH_CHUNKS[3] == 'history' ?
true : false;
635 $limit = (int) (isset($PATH_CHUNKS[3]) ?
$PATH_CHUNKS[3] : '0');
636 $offset = (int) (isset($PATH_CHUNKS[4]) ?
$PATH_CHUNKS[4] : '0');
637 echo $this->render_items($class, $id, $limit, $offset, $search, $history);
638 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
639 //print_r(array("<pre>",$_SERVER));
649 $sklad = new Sklad_UI();
650 $sklad->process_http_request();
This page took 1.645338 seconds and 5 git commands to generate.