cc4d22a55bd142c4c8221502cd31ad01a727b21a
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 set_include_path(DIR_LIB
.PATH_SEPARATOR
.get_include_path());
23 require_once('Sklad_Auth.class/common.php');
24 require_once('HTTP_Auth.class.php');
25 require_once('Locale.class.php');
26 require_once('Barcode.class.php');
27 require_once('Fortune.php');
30 * Trida poskytuje vseobecne funkce pro generovani HTML kodu
32 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
35 * @author Tomas Mudrunka
38 function row($row,$type=false,$class=false,$parameters='') {
40 $class = $class ?
$class=" class='$class' " : '';
41 if($type) $html.="<$type>";
42 $html.="<tr$class$parameters>";
43 $td = $type == 'thead' ?
'th' : 'td';
44 foreach($row as $var) {
45 if(trim($var) == '') $var = ' ';
46 $html.="<$td>$var</$td>";
49 if($type) $html.="</$type>";
53 function table(&$table, $parity_class=array('tr_odd','tr_even'), $params='border=1', $row_params_field='_row_parameters') {
54 $html="<table $params>";
57 foreach($table as $row) {
59 unset($row[$row_params_field]);
60 $html.=$this->row(array_keys($row),'thead');
63 $class = $parity_class ?
$parity_class[$even] : false;
64 $params = isset($row[$row_params_field]) ?
$row[$row_params_field] : '';
65 unset($row[$row_params_field]);
66 $html.=$this->row($row,false,$class.$params);
73 function link($title='n/a', $link='#void', $internal=true, $translate=true) {
74 if($internal && (!isset($link[0]) ||
$link[0] != '#')) $link = $this->internal_url($link);
75 if($translate) $title = T($title);
76 return "<a href='$link'>".$title."</a>";
79 function img($src='#void', $title='img', $options='width=64') {
80 $options = $options ?
" $options" : '';
81 return "<img src='$src' alt='$title' title='$title'$options; />";
84 function img_link($src, $link='#void', $title='img_link', $internal=true, $translate=true, $options='width=64') {
85 return $this->link($this->img($src,$title,$options),$link,$internal,$translate);
88 function textarea($name=false, $value='', $placeholder=false, $options=false, $prefix='') {
89 $html = T($prefix)."<textarea";
90 if($name) $html.= " name='$name'";
91 if($options) $html.= " $options";
92 if($placeholder) $html.= " placeholder='$placeholder'";
93 $html .= ">$value</textarea>";
97 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false, $prefix='') {
98 if($type == 'textarea') return $this->textarea($name, $value, $placeholder, $options, $prefix);
99 $html = T($prefix)."<input type='$type' ";
100 if($name) $html.= "name='$name' ";
101 if(!is_bool($value)) {
102 if($type == 'submit') $value = T($value);
103 $html.= "value='$value' ";
105 if($options) $html.= "$options ";
106 if($placeholder) $html.= "placeholder='$placeholder' ";
111 function form($action=false, $method=false, $inputs, $options=false) {
112 $action = $action ?
" action='$action'" : '';
113 $method = $method ?
" method='$method'" : '';
114 $options = $options ?
" $options" : '';
115 $html = "<form$action$method$options>";
116 foreach($inputs as $input) $html .= call_user_func_array(array($this,'input'), $input);
121 function select($name, $selectbox, $default=false) {
122 //echo('<pre>'); print_r($selectbox);
123 $html = "<select name='$name'>";
125 if(!is_bool($default)) {
126 $value=$default; $title=$selectbox[$value];
127 $html .= "<option value='$value'>$value :: $title</option>";
128 unset($selectbox[$value]);
130 foreach($selectbox as $value => $title) {
131 $html .= "<option value='$value'>$value :: $title</option>";
133 $html .= "</select>";
137 function ul($items,$tag=ul
,$head='',$class=false) {
138 $class = $class ?
" class='$class'" : '';
139 $html = "$head<$tag$class>";
140 foreach($items as $key => $value) {
142 if(is_numeric($key)) {
145 $html .= $this->link($key,$value);
153 function div($html, $options) {
154 $options = $options ?
" $options" : '';
155 return "<div$options>$html</div>";
158 function favicon($url='/favicon.ico') {
159 return '<link rel="shortcut icon" href="'.$url.'" /><link href="'.$url.'" rel="icon" type="image/gif" />';
163 function head($title=false,$charset='UTF-8',$more='') {
164 $title = $title ?
"\n<title>$title</title>" : '';
166 $html.= '<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />'.$title.$more;
167 $html.= $this->favicon(dirname($_SERVER['SCRIPT_NAME']).'/favicon.ico');
174 * Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
176 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
178 * @package Sklad_HTML
179 * @author Tomas Mudrunka
181 class Sklad_HTML
extends HTML
{ //TODO: Split into few more methods
182 function header($title='', $user=array()) {
184 $script = $_SERVER['SCRIPT_NAME'];
185 $search = htmlspecialchars(@trim
($_GET['q']));
186 $message = strip_tags(@trim
($_GET['message']),'<a><b><u><i><br>');
187 $fortune = fortune();
188 $instance = INSTANCE_ID
!= '' ?
'/'.INSTANCE_ID
: '';
189 $user_id = htmlspecialchars($user['id']);
190 $user_gid = htmlspecialchars($user['gid']);
191 $user_name = htmlspecialchars($user['name']);
193 //$title = T($title); //TODO
195 $html = $this->head("SōkoMan$title");
197 <h1 style="display: inline;"><a href="$script/">SōkoMan</a><small>$instance$title</small></h1>
198 <div style="float:right; text-align:right;">
199 Logged in as <b>$user_name</b> [UID: <b>$user_id</b>; GID: <b>$user_gid</b>]<br />
203 <style type="text/css">
204 * { font-family: arial; }
205 td,body { background-color: white; }
206 table { background-color: orange; border: orange; }
207 a, a img { text-decoration:none; color: darkblue; border:none; }
208 li a, a:hover { text-decoration:underline; }
209 .tr_even td { background-color: lemonchiffon; }
210 .item_status_stored td { font-weight:bold; }
211 .item_status_deleted td { font-style:italic; }
227 .menu, .menu * menu {
232 border: 1px solid orange;
237 .menu li:hover menu, .menu li:hover {
239 background-color: yellow;
248 foreach(scandir(DIR_ASSISTANTS
) as $item) {
249 if($item == '.' ||
$item == '..') continue;
250 $item = preg_replace('/\.inc\.php$/','',$item,-1,$count);
251 if($count) $assistants[$item] = "assistant/$item";
254 $tables=array('item','model','category','producer','vendor','room','status');
256 foreach($tables as $table) {
257 $listable[$table] = $table;
258 $insertable[$table] = "$table/new";
261 $html .= $this->ul(array(
263 'Logout' => '?logout',
264 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
265 1 => $this->ul($insertable,'menu',$this->link('New','#')),
266 2 => $this->ul($listable,'menu',$this->link('List','#'))
267 ),'menu', '', 'menu');
269 $html .= '<div style="float: right;">';
272 //TODO: Do we really need this?
273 $html .= $this->form("$script/api/go", 'GET', array(
274 array('q','','text','smart id...', 'autofocus'),
275 array(false,'go','submit')
276 ), 'style="float: left;"');
279 $html .= $this->form('?', 'GET', array(
280 array('q',$search,'text','regexp...'),
281 array(false,'filter','submit')
282 ), 'style="float: left;"');
284 $html .= $this->form("$script/item", 'GET', array(
285 array('q',$search,'text','regexp...','autofocus'),
286 array(false,'search','submit')
287 ), 'style="float: left;"');
293 <hr style="clear: both;" />
294 <div style="background-color:#FFDDDD;">
295 <font color="red">$message</font>
297 <div style="text-align:right; color:darkgreen;">
305 function internal_url($link) {
306 return $_SERVER['SCRIPT_NAME'].'/'.$link;
309 function table_add_images(&$table) {
310 $image = array('model_id');
311 foreach($table as $id => $row) {
312 foreach($image as $column) if(isset($table[$id][$column])) {
313 $type = @array_shift
(preg_split('/_/', $column));
314 $src=URL_IMAGES
."/$type/".$table[$id][$column].'.jpg';
315 $table[$id][$type.'_image']=$this->img_link($src, $src, $table[$id][$column], false, false);
320 function render_barcode($barcode,$opts=false) {
321 return $this->img_link($this->internal_url("barcode/$barcode"),$this->internal_url("barcode/$barcode"),$barcode,false,false,$opts);
324 function table_add_barcodes(&$table) {
325 $image = array('model_barcode', 'item_serial');
326 foreach($table as $id => $row) {
327 foreach($image as $column) if(isset($table[$id][$column])) {
328 $table[$id][$column]=$this->render_barcode($table[$id][$column]);
333 function table_add_row_parameters(&$table, $param_col='_row_parameters') { //TODO: rename to table_add_row_classes()
334 $image = array('status_name' => ' item_status_');
335 foreach($table as $id => $row) {
336 foreach($image as $column => $param) if(isset($table[$id][$column])) {
337 @$table[$id][$param_col] .= $param.$table[$id][$column];
342 function table_add_relations(&$table, $class, $suffix_relations='_relations') {
343 $where_url = '%d/?where[%c]==%v';
344 $relations = array( //TODO: Autodetect???
346 'model_id' => array(array('item',$where_url),array('edit','model/%v/edit/')),
347 'model_barcode' => array(array('store','assistant/%d?barcode=%v')),
348 'model_name' => array(array('google','http://google.com/search?q=%v',true)) //TODO: add manufacturer to google query
351 'item_serial' => array(array('dispose','assistant/%d?serial=%v','in_stock'),array('sell','assistant/%d?serial=%v','in_stock')),
352 'item_id' => array(array('edit','item/%v/edit/'))
354 'category' => array('category_id' => array(array('item',$where_url), array('model',$where_url))),
355 'producer' => array('producer_id' => array(array('item',$where_url), array('model',$where_url))),
356 'vendor' => array('vendor_id' => array(array('item',$where_url))),
357 'room' => array('room_id' => array(array('item',$where_url))),
358 'status' => array('status_id' => array(array('item',$where_url)))
360 $relations_conditions=array(
361 'in_stock' => 'return(@$table[$id]["status_name"] == "stored");',
362 'not_sold' => 'return(@$table[$id]["status_name"] != "saled");',
363 'not_sold_or_disposed' => 'return(@$table[$id]["status_name"] != "saled" && @$table[$id]["status_name"] != "disposed");'
365 foreach($table as $id => $row) {
366 foreach($row as $column => $value) {
367 if(isset($relations[$class][$column])) {
368 foreach($relations[$class][$column] as $destination) {
369 $destination_url = str_replace(
370 array('%d','%c','%v'),
371 array(urlencode($destination[0]),urlencode($column),urlencode($value)),
374 if(isset($destination[2]) && isset($relations_conditions[$destination[2]])) {
375 //$condition = $relations_conditions[$destination[2]]($table,$id);
376 if(!eval($relations_conditions[$destination[2]])) continue;
378 @$table[$id][$class.$suffix_relations] .= $this->link($destination[0], $destination_url).',';
385 function table_collapse(&$table) {
387 'item_id' => 'item_id',
388 'model_id' => 'model_name',
389 'category_id' => 'category_name',
390 'producer_id' => 'producer_name',
391 'vendor_id' => 'vendor_name',
392 'room_id' => 'room_name',
393 'status_id' => 'status_name',
394 'item_author' => 'item_author_backend',
395 'item_customer' => 'item_customer',
398 foreach($table as $id => $row) {
399 foreach($collapse as $link => $title)
400 if(isset($table[$id][$link]) && isset($row[$title])) {
401 $type = @array_shift
(preg_split('/_/', $link));
402 if($link != $title) unset($table[$id][$link]);
403 switch($link) { //TODO: Move to array for easy configuration
405 case 'item_customer':
406 $table[$id][$title]=$this->link($row[$title], "?where[$link]==".$row[$link], false);
409 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
416 function table_sort(&$table) {
417 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name','item_quantity','item_price_in','item_price_out','model_price_in','model_price_out','item_relations','model_relations');
418 $table_sorted = array();
419 foreach($table as $id => $row) {
420 $table_sorted[$id] = array();
421 foreach($precedence as $column) if(isset($table[$id][$column])) {
422 $table_sorted[$id][T($column)]=$table[$id][$column];
423 unset($table[$id][$column]);
425 //$table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
426 foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
428 $table = $table_sorted;
431 function table_hide_columns(&$table, $class) { //TODO: Move to build_query_select() !!! :-)))
432 $fields_hide = array(
433 'item' => array('model_descript','model_price_in','model_price_out','model_barcode','model_countable','model_reserve','model_eshop_hide','room_descript','room_author','producer_name','producer_note','vendor_note')
435 //print_r($table); die();
436 if(isset($fields_hide[$class])) foreach($table as $id => $row) {
437 foreach($fields_hide[$class] as $field) unset($table[$id][$field]);
441 function render_item_table($table,$class=false) {
442 if(empty($table)) return '<h3>'.T('holy primordial emptiness is all you can find here...').'</h3><br />';
443 $this->table_add_row_parameters($table);
444 $this->table_add_images($table);
445 if($class) $this->table_add_relations($table,$class);
446 $this->table_add_barcodes($table);
447 $this->table_collapse($table);
448 if($class) $this->table_hide_columns($table,$class);
449 $this->table_sort($table);
450 return $this->table($table);
453 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
455 'item' => array('item_note'),
456 'model' => array('model_descript')
459 foreach($columns as $column) {
460 $html.=T($class).':<b>'.T($column['Field']).'</b>: ';
461 $name="values[$class][".$column['Field'].'][]';
462 $val = $update && isset($current[$column['Field']]) ?
$current[$column['Field']] : false;
464 case (preg_match('/auto_increment/', $column['Extra']) ||
in_array($column['Field'], $hidecols)):
465 if(is_bool($val) && !$val) $val = '';
466 $html.=$this->input($name, $val, 'hidden');
467 $html.=$val.'(AUTO)';
469 case isset($selectbox[$column['Field']]):
470 $html.=$this->select($name,$selectbox[$column['Field']],$val);
472 case isset($textarea[$class]) && in_array($column['Field'],$textarea[$class]):
473 $html.=$this->input($name, $val, 'textarea');
476 $html.=$this->input($name, $val);
484 function render_insert_form_multi($array) {
488 foreach($array as $key => $args) {
489 $parts=array('inputs');
490 if(!$head) { $head = true;
493 if(!isset($array[$key+
1])) {
496 } else $hr = '<hr />';
500 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
506 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true, $parts=false) {
509 //echo('<pre>'); print_r($selectbox);
510 //echo('<pre>'); print_r($current);
512 if(is_array($current)) {
514 $current = array_shift($current);
517 if(!is_array($hidecols)) $hidecols = array();
518 $hidecols = array_merge($hidecols, array('item_author', 'item_valid_from', 'item_valid_till')); //TODO Autodetect
520 if(!is_array($parts) ||
in_array('head', $parts)) {
521 $action = $action ?
" action='$action'" : false;
522 $html.="<form$action method='POST'>"; //TODO: use $this->form()
523 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
526 if(!is_array($parts) ||
in_array('inputs', $parts))
527 $html.=$this->render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update);
529 if(!is_array($parts) ||
in_array('foot', $parts)) {
530 $html .= '</div></span><br style="clear:both" />';
531 if($multi_insert) { //TODO, move to separate JS file
534 function duplicate_element(what, where) {
535 var node = document.getElementsByName(what)[0];
536 node.parentNode.appendChild(node.cloneNode(true));
539 <a href='#' onClick="duplicate_element('input_set')">+</a>
543 $btn = is_array($current) ?
'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
544 $html.=$this->input(false, $btn, 'submit');
552 * Trida poskytuje rozhrani k databazi skladu
555 * @author Tomas Mudrunka
557 class Sklad_DB
extends PDO
{
558 function __construct() {
559 $this->auth
= new Sklad_Auth();
562 DB_DSN
, DB_USER
, DB_PASS
,
563 array(PDO
::MYSQL_ATTR_INIT_COMMAND
=> "SET NAMES utf8") //Force UTF8 for MySQL
567 function escape($str) {
568 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
571 function quote_identifier($str) {
572 return '`'.$this->escape($str).'`'; //TODO HACK
575 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
578 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
579 'model' => array('category', 'producer')
580 ); //TODO Autodetect using foreign keys?
581 $fields_search = array(
582 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name'),
583 'model' => array('model_id','model_name','model_barcode','model_descript','producer_name')
587 if(is_array($where)) foreach($where as $key => $value) $where[$key] = $key.' '.$value; //TODO: escape SQLi!!!
590 $class = $this->escape($class);
593 $sql="SELECT * FROM `$class`\n";
595 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN `$j` USING($j$suffix_id)\n";
598 $search = $this->quote($search);
599 if(!isset($fields_search[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
601 foreach($fields_search[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
602 $where[] = "FALSE $sql_search";
603 } elseif($id) $where[] = "$class$suffix_id = $id";
604 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
606 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
608 if(!$order) $order = $class.$suffix_id.' DESC';
609 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
610 $sql .= "ORDER BY $order\n";
613 $limit = $this->escape((int)$limit);
614 $offset = $this->escape((int)$offset);
615 $sql .= "LIMIT $offset,$limit\n";
621 function safe_query($sql, $fatal=true) {
622 $result = $this->query($sql);
624 $error = $this->errorInfo();
625 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>");
631 function translate_query_results(&$result) {
632 $translate_cols = array('item_valid_till'); //TODO: Hardcoded
633 foreach($result as $key => $row) {
634 foreach($translate_cols as $col) if(isset($result[$key][$col])){
635 $result[$key][$col] = T($result[$key][$col]);
640 function load_backend_data_to_query_results(&$result,$suffix_backend='_backend') {
641 $translate_cols = array(
642 'item_author' => 'return($this->auth->get_username_by_id($result[$key][$col]));'
644 foreach($result as $key => $row) {
645 foreach($translate_cols as $col => $backend) if(isset($result[$key][$col])){
646 $result[$key][$col.$suffix_backend] = eval($backend);
651 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO
::FETCH_ASSOC
, $translate=true) {
652 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
653 $this->load_backend_data_to_query_results($result);
654 if($translate) $this->translate_query_results($result);
658 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
659 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
660 $result = $this->safe_query_fetch($sql);
661 if(!$result ||
!is_array($indexed)) return $result;
663 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
667 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
668 $class = $this->escape($class);
669 $sql = "SHOW COLUMNS FROM $class;";
670 $columns = $this->safe_query_fetch($sql);
671 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
672 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
677 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
678 $selectbox=array( //TODO: Hardcoded...
679 'model_countable' => array(0 => 'no', 1 => 'yes'),
680 'model_eshop_hide' => array(0 => 'no', 1 => 'yes'),
681 'vendor_id' => array('COMPULSORY' => 'select...')
683 foreach($columns as $column) {
684 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)!
685 if($class && $column['Field'] == $class.$suffix_id) continue;
686 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
687 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
689 $history = $this->contains_history($table) ?
" WHERE ${table}_valid_till=0" : '';
690 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
691 $result = $this->safe_query_fetch($sql, false);
692 if(!$result) continue;
693 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
695 //echo('<pre>'); print_r($selectbox);
696 return array_filter($selectbox, 'ksort');
699 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
700 $history = $this->contains_history($table) ?
" AND ${table}_valid_till=0" : '';
701 $value=$this->quote($value);
702 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
703 $result = $this->safe_query_fetch($sql);
704 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
707 function contains_history($table) {
708 $history_tables = array('item'); //TODO Autodetect
709 return in_array($table, $history_tables);
712 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
714 $history = $this->contains_history($table);
717 $table = $this->escape($table);
719 //Get list of POSTed columns
720 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
721 $columns = implode(',',$columns_array);
725 //echo('<pre>'); die(print_r($values));
728 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
729 if($history_update) {
730 $sql .= "UPDATE $table";
731 $sql .= " SET ${table}_valid_till=NOW()";
732 $sql .= " WHERE ${table}_valid_till=0 AND (";
734 foreach($values as $row) {
735 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
743 //Insert into table (columns)
744 $sql .= "INSERT INTO $table ($columns) VALUES ";
746 //Values (a,b,c),(d,e,f)
748 foreach($values as $row) {
749 $row_quoted = array_map(array($this,'quote'), $row); //Check
751 foreach($row as $column => $value) {
753 case $table.'_valid_from':
754 $row_quoted[$column] = 'NOW()';
756 case $table.'_valid_till':
757 $row_quoted[$column] = '0';
759 case $table.'_author':
760 $row_quoted[$column] = $this->auth
->get_user_id();
761 //die($this->auth->get_user_id().'=USER');
766 $sql .= $comma.'('.implode(',',$row_quoted).')';
772 foreach($columns_array as $col) {
773 if($col == $table.'_id' ||
$col == $table.'_valid_till') continue;
774 $on_duplicate[] = "$col=VALUES($col)";
776 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
784 function insert_or_update($table, $values, $replace=true) {
785 $sql = $this->build_query_insert($table, $values, $replace);
786 $this->safe_query($sql);
787 return $this->lastInsertId();
790 function insert_or_update_multitab($values, $replace=true) {
792 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
796 function delete($table, $id, $suffix_id='_id') {
797 if($this->contains_history($table)) return false;
798 $key = $this->escape($table.$suffix_id);
799 $table = $this->escape($table);
800 $id = $this->quote($id);
801 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
806 * Trida poskytuje high-level rozhrani k databazi skladu
808 * @package Sklad_DB_Abstract
809 * @author Tomas Mudrunka
811 class Sklad_DB_Abstract
extends Sklad_DB
{
816 * Trida implementuje uzivatelske rozhrani skladu
819 * $sklad = new Sklad_UI();
820 * $sklad->process_http_request();
823 * @author Tomas Mudrunka
826 function __construct() {
827 $this->db
= new Sklad_DB();
828 $this->html
= new Sklad_HTML();
831 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
832 return $this->html
->render_item_table($this->db
->get_listing($class, $id, $limit, $offset, $where, $search, $history, false),$class);
835 function render_form_add($class) {
836 $columns = $this->db
->get_columns($class);
837 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
838 return $this->html
->render_insert_form($class, $columns, $selectbox);
841 function render_form_edit($class, $id, $multi_insert) {
842 $columns = $this->db
->get_columns($class);
843 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
844 $current = $this->db
->get_listing($class, $id, 1);
845 return $this->html
->render_insert_form($class, $columns, $selectbox, $current, false, false, $multi_insert);
848 function render_single_record_details($class, $id) {
850 $id_prev = $id - 1 > 0 ?
$id - 1 : 0;
851 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
853 $html.= $this->html
->link('<<', "$class/$id_prev/");
855 $html.= $this->html
->link('>>', "$class/$id_next/");
857 $html.='<span style="float:right;">'.$this->html
->render_barcode(BARCODE_PREFIX
.strtoupper("$class/$id")).'</span>';
858 $html.= $this->html
->link('edit', "$class/$id/edit/");
859 if($this->db
->contains_history($class)) $html.= ' ][ '.$this->html
->link('history', "$class/$id/history/");
863 function render_listing_navigation($class, $id, $limit, $offset) {
864 $offset_next = $offset +
$limit;
865 $offset_prev = $offset - $limit > 0 ?
$offset - $limit : 0;
866 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
868 $html.= $this->html
->link('<<', "$class/$id/$limit/$offset_prev/$get");
870 $html.= $this->html
->link('>>', "$class/$id/$limit/$offset_next/$get");
872 $html.= $this->html
->link('new', "$class/new/$get");
876 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
878 if(is_numeric($id)) {
879 $html.=$this->render_single_record_details($class, $id);
881 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
884 $html.= $this->render_form_edit($class, $id, false);
885 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
886 $html.=$this->html
->form($action,'POST',array(
887 array(false,'DELETE','submit'),
888 array('sure', false, 'checkbox', false, false, 'sure?')
890 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
891 $html.=$this->html
->form($action,'POST',array(
892 array('image', false, 'file', false, 'size="30"'),
893 array(false, 'IMAGE', 'submit')
894 ), "enctype='multipart/form-data'");
899 function check_auth() {
900 new HTTP_Auth('WareHouse ['.BACKEND_AUTH
.']', true, array($this->db
->auth
,'check_auth'));
903 function post_redirect_get($location, $message='', $error=false, $translate=true) {
904 $messaget = $translate ?
T($message) : $message;
905 $url_args = $messaget != '' ?
'?message='.urlencode($messaget) : '';
906 $location = $this->html
->internal_url($location).$url_args;
907 header('Location: '.$location);
908 if($error) trigger_error($message);
909 $location=htmlspecialchars($location);
911 "<meta http-equiv='refresh' content='0; url=$location'>".
912 $messaget."<br />Location: <a href='$location'>$location</a>"
916 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
917 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
918 $filename="$dir/$name$ext";
919 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
920 foreach($vars as $var => $val) $
$var=$val;
923 $out=ob_get_contents();
928 function check_input_validity($field, $value='', $ruleset=0) {
929 $rules = array(0 => array(
930 'model_barcode' => '/./',
931 'item_serial' => '/./',
932 'vendor_id' => '/^[0-9]*$/'
934 if(isset($rules[$ruleset][$field]) && !preg_match($rules[$ruleset][$field], trim($value))) return false;
938 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
939 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
940 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
944 /* Tenhle foreach() prekopiruje promenne
945 * z: $_POST['values'][$table][$column][$id];
946 * do: $values[$table][$id][$column]
948 if(isset($_POST['values'])) {
950 foreach($_POST['values'] as $table => $columns) {
951 foreach($columns as $column => $ids) {
952 foreach($ids as $id => $val) {
953 $values[$table][$id][$column] = trim($val);
954 if(!$this->check_input_validity($column,$val)) {
955 $message = "Spatny vstup: $column [$id] = \"$val\"; ". //XSS
956 $this->html
->link('GO BACK', 'javascript:history.back()', false, false);
957 $this->post_redirect_get('', $message, false, false);
962 //die(print_r($values));
965 if($action) switch($action) {
969 if(!isset($replace)) $replace = true;
970 $table = $class ?
$class : 'item';
971 //print_r($values); //debug
972 $last = $this->db
->insert_or_update_multitab($values, $replace);
973 $last = $force_redirect ?
$force_redirect."?last=$last" : "$table/$last/";
974 $next = "$table/new/";
975 $message = $force_redirect ?
'' : 'Hotovo. Další záznam přidáte '.$this->html
->link('zde', $next).'.';
976 $this->post_redirect_get($last, $message);
979 if(!isset($_POST['sure']) ||
!$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
980 $this->db
->delete($class, $id) ||
$this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
981 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
984 $image_classes = array('model'); //TODO, use this more widely across the code
985 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
986 $image_destination = DIR_IMAGES
."/$class/$id.jpg";
987 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
988 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
989 chmod ($image_destination, 0664);
990 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
991 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
994 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
1001 function process_http_request() {
1002 $this->check_auth();
1004 @ini_set
('magic_quotes_gpc' , 'off');
1005 if(get_magic_quotes_gpc()) {
1006 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
1009 $PATH_INFO=@trim
($_SERVER[PATH_INFO
]);
1010 if($PATH_INFO == '' ||
$PATH_INFO == '/') $PATH_INFO = FRONTEND_PAGE_WELCOME
;
1011 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
1013 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
1014 if($_SERVER['REQUEST_METHOD'] != 'POST' && $PATH_CHUNKS[1]!='barcode' && $PATH_CHUNKS[1]!='api') //TODO: tyhle podminky naznacujou, ze je v navrhu nejaka drobna nedomyslenost...
1015 echo $this->html
->header($PATH_INFO,$this->db
->auth
->get_user());
1016 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
1018 die('Tell me why you cry');
1020 case 'assistant': case 'api': //assistant|api
1022 'assistant' => DIR_ASSISTANTS
,
1025 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ?
trim($PATH_CHUNKS[3]) : false;
1026 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
1027 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
1028 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
1029 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
1030 echo $this->safe_include($incdirs[$PATH_CHUNKS[1]],$PATH_CHUNKS[2],$assistant_vars);
1032 case 'barcode': //barcode
1033 Barcode
::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
1036 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ?
trim($_GET['q']) : false;
1037 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ?
$PATH_CHUNKS[1] : 'item';
1038 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
1039 switch($PATH_CHUNKS[2]) {
1041 $this->process_http_request_post($PATH_CHUNKS[2], $class);
1042 echo $this->render_form_add($class);
1045 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ?
(int) $PATH_CHUNKS[2] : false);
1046 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
1048 switch($PATH_CHUNKS[3]) {
1049 case 'edit': //?/?/edit
1050 case 'image': //?/?/image
1051 case 'delete': //?/?/delete
1052 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
1055 $history = $PATH_CHUNKS[3] == 'history' ?
true : false;
1056 $limit = is_numeric($PATH_CHUNKS[3]) ?
(int) $PATH_CHUNKS[3] : FRONTEND_LISTING_LIMIT
;
1057 $offset = isset($PATH_CHUNKS[4]) ?
(int) $PATH_CHUNKS[4] : 0;
1058 $where = @is_array
($_GET['where']) ?
$_GET['where'] : false;
1059 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
1060 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
1061 //print_r(array("<pre>",$_SERVER));
1071 $sklad = new Sklad_UI();
1072 $sklad->process_http_request();
1074 echo('<br style="clear:both;" /><hr />');
This page took 1.119829 seconds and 3 git commands to generate.