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='',$colspan=array(),$rowspan=array(),$break_after=array()) {
40 $class_br = $class ?
" class='$class' " : '';
41 $class = $class ?
" class='$class tr_nobr' " : '';
42 if($type) $html.="<$type>";
43 $html.="<tr$class$parameters>";
44 $td = $type == 'thead' ?
'th' : 'td';
45 foreach($row as $id => $var) {
46 $tdclass = " class='cell_$id'";
47 if(trim($var) == '') $var = ' ';
48 $rs = isset($rowspan[$id]) ?
" rowspan='$rowspan[$id]'" : '';
49 $cs = isset($colspan[$id]) ?
" colspan='$colspan[$id]'" : '';
50 $html.="<$td$rs$cs$tdclass>$var</$td>";
51 if(in_array($id,$break_after,true)) $html.='</tr>'."<tr$class_br$parameters>";
54 if($type) $html.="</$type>";
58 function table(&$table,$colspan=array(),$rowspan=array(),$break_after=array(),$parity_class=array('tr_odd','tr_even'),$params='border=1',$row_classes_field='_row_classes') {
59 $html="<table $params>";
62 foreach($table as $row) {
63 $params = isset($row[$row_classes_field]) ?
$row[$row_classes_field] : '';
64 unset($row[$row_classes_field]);
66 $keys = array(); foreach($row as $key => $val) $keys[$key]=$key;
67 $html.=$this->row(T($keys),'thead',false,'',$colspan,$rowspan,$break_after);
70 $class = $parity_class ?
$parity_class[$even] : false;
71 $html.=$this->row($row,false,$class.$params,'',$colspan,$rowspan,$break_after);
78 function link($title='n/a', $link='#void', $internal=true, $translate=true) {
79 if($internal && (!isset($link[0]) ||
$link[0] != '#')) $link = $this->internal_url($link);
80 if($translate) $title = T($title);
81 return "<a href='$link'>".$title."</a>";
84 function img($src='#void', $title='img', $options='height=64') {
85 $options = $options ?
" $options" : '';
86 return "<img src='$src' alt='$title' title='$title'$options; />";
89 function img_link($src, $link='#void', $title='img_link', $internal=true, $translate=true, $options='height=64') {
90 return $this->link($this->img($src,$title,$options),$link,$internal,$translate);
93 function textarea($name=false, $value='', $placeholder=false, $options=false, $prefix='') {
94 $html = T($prefix)."<textarea";
95 if($name) $html.= " name='$name'";
96 if($options) $html.= " $options";
97 if($placeholder) $html.= " placeholder='$placeholder'";
98 $html .= ">$value</textarea>";
102 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false, $prefix='') {
103 if($type == 'textarea') return $this->textarea($name, $value, $placeholder, $options, $prefix);
104 $html = T($prefix)."<input type='$type' ";
105 if($name) $html.= "name='$name' ";
106 if(!is_bool($value)) {
107 if($type == 'submit') $value = T($value);
108 $html.= "value='$value' ";
110 if($options) $html.= "$options ";
111 if($placeholder) $html.= "placeholder='$placeholder' ";
116 function form($action=false, $method=false, $inputs, $options=false) {
117 $action = $action ?
" action='$action'" : '';
118 $method = $method ?
" method='$method'" : '';
119 $options = $options ?
" $options" : '';
120 $html = "<form$action$method$options>";
121 foreach($inputs as $input) $html .= call_user_func_array(array($this,'input'), $input);
126 function select($name, $selectbox, $default=false) {
127 //echo('<pre>'); print_r($selectbox);
128 $html = "<select name='$name'>";
130 if(!is_bool($default)) {
131 $value=$default; $title=$selectbox[$value];
132 $html .= "<option value='$value'>$title (($value))</option>";
133 unset($selectbox[$value]);
135 foreach($selectbox as $value => $title) {
136 $html .= "<option value='$value'>$title (($value))</option>";
138 $html .= "</select>";
142 function ul($items,$tag=ul
,$head='',$class=false) {
143 $class = $class ?
" class='$class'" : '';
144 $html = "$head<$tag$class>";
145 foreach($items as $key => $value) {
147 if(is_numeric($key)) {
150 $html .= $this->link($key,$value);
158 function div($html, $options) {
159 $options = $options ?
" $options" : '';
160 return "<div$options>$html</div>";
163 function favicon($url='/favicon.ico') {
164 return '<link rel="shortcut icon" href="'.$url.'" /><link href="'.$url.'" rel="icon" type="image/gif" />';
168 function head($title=false,$charset='UTF-8',$more='') {
169 $title = $title ?
"\n<title>$title</title>" : '';
171 $html.= '<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />'.$title.$more;
172 $html.= $this->favicon(dirname($_SERVER['SCRIPT_NAME']).'/favicon.ico');
179 * Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
181 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
183 * @package Sklad_HTML
184 * @author Tomas Mudrunka
186 class Sklad_HTML
extends HTML
{ //TODO: Split into few more methods
187 function header($title='', $user=array()) {
189 $script = $_SERVER['SCRIPT_NAME'];
190 $search = htmlspecialchars(@trim
($_GET['q']));
191 $message = strip_tags(@trim
($_GET['message']),'<a><b><u><i><br>');
192 $fortune = fortune();
193 $instance = INSTANCE_ID
!= '' ?
'/'.INSTANCE_ID
: '';
194 $user_id = htmlspecialchars($user['id']);
195 $user_gid = htmlspecialchars($user['gid']);
196 $user_name = htmlspecialchars($user['name']);
198 //$title = T($title); //TODO
200 $html = $this->head("SōkoMan$title");
202 <h1 style="display: inline;"><a href="$script/">SōkoMan</a><small>$instance$title</small></h1>
203 <div style="float:right; text-align:right;">
204 Logged in as <b>$user_name</b> [UID: <b>$user_id</b>; GID: <b>$user_gid</b>]<br />
208 <style type="text/css">
209 * { font-family: arial; }
210 td,body { background-color: white; border: orange; }
211 .tr_nobr td { border-top: 3px solid orange; }
212 table { background-color: orange; border: orange; }
213 td textarea { width:100%; height:100%; }
214 a, a img { text-decoration:none; color: darkblue; border:none; }
215 li a, a:hover { text-decoration:underline; }
216 .tr_even td { background-color: lemonchiffon; }
217 .tr_nobr.tr_even td:first-child { border-left: 5px solid orange; }
218 .tr_nobr.tr_odd td:first-child { border-left: 5px solid white; }
219 .item_status_stored td { font-weight:bold; }
220 .item_status_deleted td { text-decoration:line-through; }
221 .item_status_destroyed td { font-style:italic; }
222 .floating_barcode { margin: 5px; }
223 .disabled { color: grey; }
224 /* table, table * { table-layout:fixed; width:100%; overflow:hidden; word-wrap:break-word; } */
225 /* td { position:absolute; } */
226 /* .cell_model_name { float:left; } */
242 .menu, .menu * menu {
247 border: 1px solid orange;
252 .menu li:hover menu, .menu li:hover {
254 background-color: yellow;
263 foreach(scandir(DIR_ASSISTANTS
) as $item) {
264 if($item == '.' ||
$item == '..') continue;
265 $item = preg_replace('/\.inc\.php$/','',$item,-1,$count);
266 if($count) $assistants[$item] = "assistant/$item";
269 $tables=array('item','model','category','producer','vendor','room','status');
271 foreach($tables as $table) {
272 $listable[$table] = $table;
273 $insertable[$table] = "$table/new";
276 $html .= $this->ul(array(
278 'Logout' => '?logout',
279 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
280 1 => $this->ul($insertable,'menu',$this->link('New','#')),
281 2 => $this->ul($listable,'menu',$this->link('List','#'))
282 ),'menu', '', 'menu');
284 $html .= '<div style="float: right;">';
287 //TODO: Do we really need this?
288 $html .= $this->form("$script/api/go", 'GET', array(
289 array('q','','text','smart id...', 'autofocus'),
290 array(false,'go','submit')
291 ), 'style="float: left;"');
294 $html .= $this->form('?', 'GET', array(
295 array('q',$search,'text','regexp...'),
296 array(false,'filter','submit')
297 ), 'style="float: left;"');
299 $html .= $this->form("$script/item", 'GET', array(
300 array('q',$search,'text','regexp...','autofocus'),
301 array(false,'search','submit')
302 ), 'style="float: left;"');
308 <hr style="clear: both;" />
309 <div style="background-color:#FFDDDD;">
310 <font color="red">$message</font>
312 <div style="text-align:right; color:darkgreen;">
320 function internal_url($link) {
321 return $_SERVER['SCRIPT_NAME'].'/'.$link;
324 function table_add_images(&$table) {
325 $image = array('model_id');
326 foreach($table as $id => $row) {
327 foreach($image as $column) if(isset($table[$id][$column])) {
328 $type = @array_shift
(preg_split('/_/', $column));
329 $src=URL_IMAGES
."/$type/".$table[$id][$column].'.jpg';
330 $table[$id][$type.'_image']=$this->img_link($src, $src, $table[$id][$column], false, false);
335 function render_barcode($barcode,$opts=false) {
336 return $this->img_link($this->internal_url("barcode/$barcode"),$this->internal_url("barcode/$barcode"),$barcode,false,false,$opts);
339 function table_add_barcodes(&$table) {
340 $image = array('model_barcode', 'item_serial');
341 foreach($table as $id => $row) {
342 foreach($image as $column) if(isset($table[$id][$column])) {
343 $table[$id][$column]=$this->render_barcode($table[$id][$column]);
348 function table_add_row_classes(&$table, $class_col='_row_classes') {
349 $image = array('status_name' => ' item_status_');
350 foreach($table as $id => $row) {
351 foreach($image as $column => $param) if(isset($table[$id][$column])) {
352 @$table[$id][$class_col] .= $param.$table[$id][$column];
357 function table_add_relations(&$table, $class, $suffix_relations='_relations') {
358 $where_url = '%d/?where[%c]==%v';
359 $relations = array( //TODO: Autodetect???
361 'model_id' => array(array('item',$where_url),array('edit','model/%v/edit/')),
362 'model_barcode' => array(array('store','assistant/%d?barcode=%v')),
363 'model_name' => array(array('google','http://google.com/search?q=%v',true)) //TODO: add manufacturer to google query
366 'item_serial' => array(array('dispose','assistant/%d?serial=%v','in_stock'),array('sell','assistant/%d?serial=%v','in_stock')),
367 'item_id' => array(array('edit','item/%v/edit/'))
369 'category' => array('category_id' => array(array('item',$where_url), array('model',$where_url))),
370 'producer' => array('producer_id' => array(array('item',$where_url), array('model',$where_url))),
371 'vendor' => array('vendor_id' => array(array('item',$where_url))),
372 'room' => array('room_id' => array(array('item',$where_url))),
373 'status' => array('status_id' => array(array('item',$where_url)))
375 $relations_conditions=array(
376 'in_stock' => 'return(@$table[$id]["status_name"] == "stored");',
377 'not_sold' => 'return(@$table[$id]["status_name"] != "sold");',
378 'not_sold_or_disposed' => 'return(@$table[$id]["status_name"] != "sold" && @$table[$id]["status_name"] != "disposed");'
380 foreach($table as $id => $row) {
381 foreach($row as $column => $value) {
382 if(isset($relations[$class][$column])) {
383 foreach($relations[$class][$column] as $destination) {
384 $destination_url = str_replace(
385 array('%d','%c','%v'),
386 array(urlencode($destination[0]),urlencode($column),urlencode($value)),
389 if(isset($destination[2]) && isset($relations_conditions[$destination[2]])) {
390 //$condition = $relations_conditions[$destination[2]]($table,$id);
391 if(!eval($relations_conditions[$destination[2]])) continue;
393 @$table[$id][$class.$suffix_relations] .= $this->link($destination[0], $destination_url).',';
400 function table_collapse(&$table) {
402 'item_id' => 'item_id',
403 'model_id' => 'model_name',
404 'category_id' => 'category_name',
405 'producer_id' => 'producer_name',
406 'vendor_id' => 'vendor_name',
407 'room_id' => 'room_name',
408 'status_id' => 'status_name',
409 'item_author' => 'item_author_backend',
410 'item_customer' => 'item_customer',
413 foreach($table as $id => $row) {
414 foreach($collapse as $link => $title)
415 if(isset($table[$id][$link]) && isset($row[$title])) {
416 $type = @array_shift
(preg_split('/_/', $link));
417 if($link != $title) unset($table[$id][$link]);
418 switch($link) { //TODO: Move to array for easy configuration
420 case 'item_customer':
421 $table[$id][$title]=$this->link($row[$title], "?where[$link]==".$row[$link], false);
424 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
431 function table_sort(&$table) {
432 $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');
433 $table_sorted = array();
434 foreach($table as $id => $row) {
435 $table_sorted[$id] = array();
436 foreach($precedence as $column) if(isset($table[$id][$column])) {
437 $table_sorted[$id][$column]=$table[$id][$column];
438 unset($table[$id][$column]);
440 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
441 //foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
443 $table = $table_sorted;
446 function table_hide_columns(&$table, $class) { //TODO: Move to build_query_select() !!! :-)))
447 $fields_hide = array(
448 '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')
450 //print_r($table); die();
451 if(isset($fields_hide[$class])) foreach($table as $id => $row) {
452 foreach($fields_hide[$class] as $field) unset($table[$id][$field]);
456 function render_item_table($table,$class=false) {
459 'break_after' => array(
460 'item' => array('category_name'),
461 'model'=> array('model_descript')
464 'item' => array('model_image'=>2,'item_id'=>2),
465 'model'=> array('model_image'=>2)
468 'item' => array('model_name'=>6,'category_name'=>'100%'),
469 'model'=> array('model_name'=>4,'model_descript'=>'100%')
473 foreach(array_keys($cellspan) as $vari)
474 $
$vari = isset($cellspan[$vari][$class]) ?
$cellspan[$vari][$class] : array();
476 if(empty($table)) return '<h3>'.T('holy primordial emptiness is all you can find here...').'</h3><br />';
477 $this->table_add_row_classes($table);
478 $this->table_add_images($table);
479 if($class) $this->table_add_relations($table,$class);
480 $this->table_add_barcodes($table);
481 $this->table_collapse($table);
482 if($class) $this->table_hide_columns($table,$class);
483 $this->table_sort($table);
484 return $this->table($table,$colspan,$rowspan,$break_after);
487 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
489 'item' => array('item_note'),
490 'model' => array('model_descript')
493 foreach($columns as $column) {
494 $html.='<tr><td>'.T($class).':<b>'.T($column['Field']).'</b>: </td><td>';
495 $name="values[$class][".$column['Field'].'][]';
496 $val = $update && isset($current[$column['Field']]) ?
$current[$column['Field']] : false;
498 case (preg_match('/auto_increment/', $column['Extra']) ||
in_array($column['Field'], $hidecols)):
499 if(is_bool($val) && !$val) $val = '';
500 $html.=$this->input($name, $val, 'hidden');
501 $html.='<span class="disabled"><i>[AUTO]</i> '.$val.'</span>';
503 case isset($selectbox[$column['Field']]):
504 $html.=$this->select($name,$selectbox[$column['Field']],$val);
506 case isset($textarea[$class]) && in_array($column['Field'],$textarea[$class]):
507 $html.=$this->input($name, $val, 'textarea');
510 $html.=$this->input($name, $val);
519 function render_insert_form_multi($array) {
523 foreach($array as $key => $args) {
524 $parts=array('inputs');
525 if(!$head) { $head = true;
528 if(!isset($array[$key+
1])) {
531 } else $hr = '<hr />';
535 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
541 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true, $parts=false) {
544 //echo('<pre>'); print_r($selectbox);
545 //echo('<pre>'); print_r($current);
547 if(is_array($current)) {
549 $current = array_shift($current);
552 if(!is_array($hidecols)) $hidecols = array();
553 $hidecols = array_merge($hidecols, array('item_author', 'item_valid_from', 'item_valid_till')); //TODO Autodetect
555 if(!is_array($parts) ||
in_array('head', $parts)) {
556 $action = $action ?
" action='$action'" : false;
557 $html.="<form$action method='POST'>"; //TODO: use $this->form()
558 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
561 if(!is_array($parts) ||
in_array('inputs', $parts))
562 $html.=$this->render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update);
564 if(!is_array($parts) ||
in_array('foot', $parts)) {
565 $html .= '</div></span><br style="clear:both" />';
566 if($multi_insert) { //TODO, move to separate JS file
569 function duplicate_element(what, where) {
570 var node = document.getElementsByName(what)[0];
571 node.parentNode.appendChild(node.cloneNode(true));
574 <a href='#' onClick="duplicate_element('input_set')">+</a>
578 $btn = is_array($current) ?
'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
579 $html.=$this->input(false, $btn, 'submit');
587 * Trida poskytuje rozhrani k databazi skladu
590 * @author Tomas Mudrunka
592 class Sklad_DB
extends PDO
{
593 function __construct() {
594 $this->auth
= new Sklad_Auth();
597 DB_DSN
, DB_USER
, DB_PASS
,
598 array(PDO
::MYSQL_ATTR_INIT_COMMAND
=> "SET NAMES utf8") //Force UTF8 for MySQL
602 function escape($str) {
603 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
606 function quote_identifier($str) {
607 return '`'.$this->escape($str).'`'; //TODO HACK
610 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
613 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
614 'model' => array('category', 'producer')
615 ); //TODO Autodetect using foreign keys?
616 $fields_search = array(
617 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name'),
618 'model' => array('model_id','model_name','model_barcode','model_descript','producer_name')
622 if(is_array($where)) foreach($where as $key => $value) $where[$key] = $key.' '.$value; //TODO: escape SQLi!!!
625 $class = $this->escape($class);
628 $sql="SELECT * FROM `$class`\n";
630 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN `$j` USING($j$suffix_id)\n";
633 $search = $this->quote($search);
634 if(!isset($fields_search[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
636 foreach($fields_search[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
637 $where[] = "FALSE $sql_search";
638 } elseif($id) $where[] = "$class$suffix_id = $id";
639 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
641 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
643 if(!$order) $order = $class.$suffix_id.' DESC';
644 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
645 $sql .= "ORDER BY $order\n";
648 $limit = $this->escape((int)$limit);
649 $offset = $this->escape((int)$offset);
650 $sql .= "LIMIT $offset,$limit\n";
656 function safe_query($sql, $fatal=true) {
657 $result = $this->query($sql);
659 $error = $this->errorInfo();
660 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>");
666 function translate_query_results(&$result) {
667 $translate_cols = array('item_valid_till'); //TODO: Hardcoded
668 foreach($result as $key => $row) {
669 foreach($translate_cols as $col) if(isset($result[$key][$col])){
670 $result[$key][$col] = T($result[$key][$col]);
675 function load_backend_data_to_query_results(&$result,$suffix_backend='_backend') {
676 $translate_cols = array(
677 'item_author' => 'return($this->auth->get_username_by_id($result[$key][$col]));'
679 foreach($result as $key => $row) {
680 foreach($translate_cols as $col => $backend) if(isset($result[$key][$col])){
681 $result[$key][$col.$suffix_backend] = eval($backend);
686 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO
::FETCH_ASSOC
, $translate=true) {
687 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
688 $this->load_backend_data_to_query_results($result);
689 if($translate) $this->translate_query_results($result);
693 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
694 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
695 $result = $this->safe_query_fetch($sql);
696 if(!$result ||
!is_array($indexed)) return $result;
698 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
702 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
703 $class = $this->escape($class);
704 $sql = "SHOW COLUMNS FROM $class;";
705 $columns = $this->safe_query_fetch($sql);
706 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
707 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
712 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
713 $selectbox=array( //TODO: Hardcoded...
714 'model_countable' => array(0 => 'no', 1 => 'yes'),
715 'model_eshop_hide' => array(0 => 'no', 1 => 'yes'),
716 'vendor_id' => array('COMPULSORY' => 'select...')
718 foreach($columns as $column) {
719 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)!
720 if($class && $column['Field'] == $class.$suffix_id) continue;
721 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
722 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
724 $history = $this->contains_history($table) ?
" WHERE ${table}_valid_till=0" : '';
725 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
726 $result = $this->safe_query_fetch($sql, false);
727 if(!$result) continue;
728 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
730 //echo('<pre>'); print_r($selectbox);
731 //return array_filter($selectbox, 'ksort');
732 return array_filter($selectbox, 'natcasesort');
733 //array_multisort($selectbox); return $selectbox;
736 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
737 $history = $this->contains_history($table) ?
" AND ${table}_valid_till=0" : '';
738 $value=$this->quote($value);
739 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
740 $result = $this->safe_query_fetch($sql);
741 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
744 function contains_history($table) {
745 $history_tables = array('item'); //TODO Autodetect
746 return in_array($table, $history_tables);
749 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
751 $history = $this->contains_history($table);
754 $table = $this->escape($table);
756 //Get list of POSTed columns
757 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
758 $columns = implode(',',$columns_array);
762 //echo('<pre>'); die(print_r($values));
765 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
766 if($history_update) {
767 $sql .= "UPDATE $table";
768 $sql .= " SET ${table}_valid_till=NOW()";
769 $sql .= " WHERE ${table}_valid_till=0 AND (";
771 foreach($values as $row) {
772 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
780 //Insert into table (columns)
781 $sql .= "INSERT INTO $table ($columns) VALUES ";
783 //Values (a,b,c),(d,e,f)
785 foreach($values as $row) {
786 $row_quoted = array_map(array($this,'quote'), $row); //Check
788 foreach($row as $column => $value) {
790 case $table.'_valid_from':
791 $row_quoted[$column] = 'NOW()';
793 case $table.'_valid_till':
794 $row_quoted[$column] = '0';
796 case $table.'_author':
797 $row_quoted[$column] = $this->auth
->get_user_id();
798 //die($this->auth->get_user_id().'=USER');
803 $sql .= $comma.'('.implode(',',$row_quoted).')';
809 foreach($columns_array as $col) {
810 if($col == $table.'_id' ||
$col == $table.'_valid_till') continue;
811 $on_duplicate[] = "$col=VALUES($col)";
813 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
821 function insert_or_update($table, $values, $replace=true) {
822 $sql = $this->build_query_insert($table, $values, $replace);
823 $this->safe_query($sql);
824 return $this->lastInsertId();
827 function insert_or_update_multitab($values, $replace=true) {
829 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
833 function delete($table, $id, $suffix_id='_id') {
834 if($this->contains_history($table)) return false;
835 $key = $this->escape($table.$suffix_id);
836 $table = $this->escape($table);
837 $id = $this->quote($id);
838 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
843 * Trida poskytuje high-level rozhrani k databazi skladu
845 * @package Sklad_DB_Abstract
846 * @author Tomas Mudrunka
848 class Sklad_DB_Abstract
extends Sklad_DB
{
853 * Trida implementuje uzivatelske rozhrani skladu
856 * $sklad = new Sklad_UI();
857 * $sklad->process_http_request();
860 * @author Tomas Mudrunka
863 function __construct() {
864 $this->db
= new Sklad_DB();
865 $this->html
= new Sklad_HTML();
868 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
869 return $this->html
->render_item_table($this->db
->get_listing($class, $id, $limit, $offset, $where, $search, $history, false),$class);
872 function render_form_add($class) {
873 $columns = $this->db
->get_columns($class);
874 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
875 return $this->html
->render_insert_form($class, $columns, $selectbox);
878 function render_form_edit($class, $id, $multi_insert) {
879 $columns = $this->db
->get_columns($class);
880 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
881 $current = $this->db
->get_listing($class, $id, 1);
882 return $this->html
->render_insert_form($class, $columns, $selectbox, $current, false, false, $multi_insert);
885 function render_single_record_details($class, $id, $barcode=true) {
887 $id_prev = $id - 1 > 0 ?
$id - 1 : 0;
888 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
890 $html.= $this->html
->link('<<', "$class/$id_prev/");
892 $html.= $this->html
->link('>>', "$class/$id_next/");
893 $html.= ' ';
894 $barcode && $html.='<span style="float:right;" class="floating_barcode">'.$this->html
->render_barcode(BARCODE_PREFIX
.strtoupper("$class/$id")).'</span>';
895 $html.= $this->html
->link('edit', "$class/$id/edit/");
896 if($this->db
->contains_history($class)) $html.= ' ][ '.$this->html
->link('history', "$class/$id/history/");
900 function render_listing_navigation($class, $id, $limit, $offset) {
901 $offset_next = $offset +
$limit;
902 $offset_prev = $offset - $limit > 0 ?
$offset - $limit : 0;
903 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
905 $html.= $this->html
->link('<<', "$class/$id/$limit/$offset_prev/$get");
907 $html.= $this->html
->link('>>', "$class/$id/$limit/$offset_next/$get");
908 $html.= ' ';
909 $html.= $this->html
->link('new', "$class/new/$get");
913 function render_listing_extensions($class, $id, $limit, $offset, $edit=false, $barcode=true) {
915 if(is_numeric($id)) {
916 $html.=$this->render_single_record_details($class, $id, $barcode);
918 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
920 if($edit && $barcode) {
921 $html.= $this->render_form_edit($class, $id, false);
922 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
923 $html.=$this->html
->form($action,'POST',array(
924 array(false,'DELETE','submit'),
925 array('sure', false, 'checkbox', false, false, 'sure?')
927 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
928 $html.=$this->html
->form($action,'POST',array(
929 array('image', false, 'file', false, 'size="30"'),
930 array(false, 'IMAGE', 'submit')
931 ), "enctype='multipart/form-data'");
936 function check_auth() {
937 new HTTP_Auth('WareHouse ['.BACKEND_AUTH
.']', true, array($this->db
->auth
,'check_auth'));
940 function post_redirect_get($location, $message='', $error=false, $translate=true) {
941 $messaget = $translate ?
T($message) : $message;
942 $url_args = $messaget != '' ?
'?message='.urlencode($messaget) : '';
943 $location = $this->html
->internal_url($location).$url_args;
944 header('Location: '.$location);
945 if($error) trigger_error($message);
946 $location=htmlspecialchars($location);
948 "<meta http-equiv='refresh' content='0; url=$location'>".
949 $messaget."<br />Location: <a href='$location'>$location</a>"
953 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
954 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
955 $filename="$dir/$name$ext";
956 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
957 foreach($vars as $var => $val) $
$var=$val;
960 $out=ob_get_contents();
965 function check_input_validity($field, $value='', $ruleset=0) {
966 $rules = array(0 => array(
967 'model_barcode' => '/./',
968 'item_serial' => '/./',
969 'vendor_id' => '/^[0-9]*$/'
971 if(isset($rules[$ruleset][$field]) && !preg_match($rules[$ruleset][$field], trim($value))) return false;
975 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
976 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
977 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
981 /* Tenhle foreach() prekopiruje promenne
982 * z: $_POST['values'][$table][$column][$id];
983 * do: $values[$table][$id][$column]
985 if(isset($_POST['values'])) {
987 foreach($_POST['values'] as $table => $columns) {
988 foreach($columns as $column => $ids) {
989 foreach($ids as $id => $val) {
990 $values[$table][$id][$column] = trim($val);
991 if(!$this->check_input_validity($column,$val)) {
992 $message = "Spatny vstup: $column [$id] = \"$val\"; ". //XSS
993 $this->html
->link('GO BACK', 'javascript:history.back()', false, false);
994 $this->post_redirect_get('', $message, false, false);
999 //die(print_r($values));
1002 if($action) switch($action) {
1006 if(!isset($replace)) $replace = true;
1007 $table = $class ?
$class : 'item';
1008 //print_r($values); //debug
1009 $last = $this->db
->insert_or_update_multitab($values, $replace);
1010 $last = $force_redirect ?
$force_redirect."?last=$last" : "$table/$last/";
1011 $next = "$table/new/";
1012 $message = $force_redirect ?
'' : 'Hotovo. Další záznam přidáte '.$this->html
->link('zde', $next).'.';
1013 $this->post_redirect_get($last, $message);
1016 if(!isset($_POST['sure']) ||
!$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
1017 $this->db
->delete($class, $id) ||
$this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
1018 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
1021 $image_classes = array('model'); //TODO, use this more widely across the code
1022 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
1023 $image_destination = DIR_IMAGES
."/$class/$id.jpg";
1024 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
1025 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
1026 chmod ($image_destination, 0664);
1027 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
1028 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
1031 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
1035 die('POSTed pyčo!');
1038 function process_http_request() {
1039 $this->check_auth();
1041 @ini_set
('magic_quotes_gpc' , 'off');
1042 if(get_magic_quotes_gpc()) {
1043 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
1046 $PATH_INFO=@trim
($_SERVER[PATH_INFO
]);
1047 if($PATH_INFO == '' ||
$PATH_INFO == '/') $PATH_INFO = FRONTEND_PAGE_WELCOME
;
1048 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
1050 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
1051 if($_SERVER['REQUEST_METHOD'] != 'POST' && $PATH_CHUNKS[1]!='barcode' && $PATH_CHUNKS[1]!='api') //TODO: tyhle podminky naznacujou, ze je v navrhu nejaka drobna nedomyslenost...
1052 echo $this->html
->header($PATH_INFO,$this->db
->auth
->get_user());
1053 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
1055 die('Tell me why you cry');
1057 case 'assistant': case 'api': //assistant|api
1059 'assistant' => DIR_ASSISTANTS
,
1062 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ?
trim($PATH_CHUNKS[3]) : false;
1063 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
1064 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
1065 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
1066 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
1067 echo $this->safe_include($incdirs[$PATH_CHUNKS[1]],$PATH_CHUNKS[2],$assistant_vars);
1069 case 'barcode': //barcode
1070 Barcode
::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
1073 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ?
trim($_GET['q']) : false;
1074 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ?
$PATH_CHUNKS[1] : 'item';
1075 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
1076 switch($PATH_CHUNKS[2]) {
1078 $this->process_http_request_post($PATH_CHUNKS[2], $class);
1079 echo $this->render_form_add($class);
1082 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ?
(int) $PATH_CHUNKS[2] : false);
1083 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
1085 switch($PATH_CHUNKS[3]) {
1086 case 'edit': //?/?/edit
1087 case 'image': //?/?/image
1088 case 'delete': //?/?/delete
1089 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
1092 $history = $PATH_CHUNKS[3] == 'history' ?
true : false;
1093 $limit = is_numeric($PATH_CHUNKS[3]) ?
(int) $PATH_CHUNKS[3] : FRONTEND_LISTING_LIMIT
;
1094 $offset = isset($PATH_CHUNKS[4]) ?
(int) $PATH_CHUNKS[4] : 0;
1095 $where = @is_array
($_GET['where']) ?
$_GET['where'] : false;
1096 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit, false);
1097 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
1098 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
1099 //print_r(array("<pre>",$_SERVER));
1109 $sklad = new Sklad_UI();
1110 $sklad->process_http_request();
1112 echo('<br style="clear:both;" /><hr />');
This page took 1.838852 seconds and 4 git commands to generate.