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 if(isset($_GET['noimgs'])) return "<span title='$title'>".basename($src).'</span>';
86 $options = $options ?
" $options" : '';
87 return "<img src='$src' alt='$title' title='$title'$options; />";
90 function img_link($src, $link='#void', $title='img_link', $internal=true, $translate=true, $options='height=64') {
91 return $this->link($this->img($src,$title,$options),$link,$internal,$translate);
94 function textarea($name=false, $value='', $placeholder=false, $options=false, $prefix='') {
95 $html = T($prefix)."<textarea";
96 if($name) $html.= " name='$name'";
97 if($options) $html.= " $options";
98 if($placeholder) $html.= " placeholder='$placeholder'";
99 $html .= ">$value</textarea>";
103 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false, $prefix='') {
104 if($type == 'textarea') return $this->textarea($name, $value, $placeholder, $options, $prefix);
105 $html = T($prefix)."<input type='$type' ";
106 if($name) $html.= "name='$name' ";
107 if(!is_bool($value)) {
108 if($type == 'submit') $value = T($value);
109 $html.= "value='$value' ";
111 if($options) $html.= "$options ";
112 if($placeholder) $html.= "placeholder='$placeholder' ";
117 function form($action=false, $method=false, $inputs, $options=false) {
118 $action = $action ?
" action='$action'" : '';
119 $method = $method ?
" method='$method'" : '';
120 $options = $options ?
" $options" : '';
121 $html = "<form$action$method$options>";
122 foreach($inputs as $input) $html .= call_user_func_array(array($this,'input'), $input);
127 function select($name, $selectbox, $default=false) {
128 //echo('<pre>'); print_r($selectbox);
129 $html = "<select name='$name'>";
131 if(!is_bool($default)) {
132 $value=$default; $title=$selectbox[$value];
133 $html .= "<option value='$value'>$title (($value))</option>";
134 unset($selectbox[$value]);
136 foreach($selectbox as $value => $title) {
137 $html .= "<option value='$value'>$title (($value))</option>";
139 $html .= "</select>";
143 function ul($items,$tag=ul
,$head='',$class=false) {
144 $class = $class ?
" class='$class'" : '';
145 $html = "$head<$tag$class>";
146 foreach($items as $key => $value) {
148 if(is_numeric($key)) {
151 $html .= $this->link($key,$value);
159 function div($html, $options) {
160 $options = $options ?
" $options" : '';
161 return "<div$options>$html</div>";
164 function favicon($url='/favicon.ico') {
165 return '<link rel="shortcut icon" href="'.$url.'" /><link href="'.$url.'" rel="icon" type="image/gif" />';
169 function head($title=false,$charset='UTF-8',$more='') {
170 $title = $title ?
"\n<title>$title</title>" : '';
172 $html.= '<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />'.$title.$more;
173 $html.= $this->favicon(dirname($_SERVER['SCRIPT_NAME']).'/favicon.ico');
180 * Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
182 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
184 * @package Sklad_HTML
185 * @author Tomas Mudrunka
187 class Sklad_HTML
extends HTML
{ //TODO: Split into few more methods
188 function header($title='', $user=array()) {
190 $script = $_SERVER['SCRIPT_NAME'];
191 $search = htmlspecialchars(@trim
($_GET['q']));
192 $message = strip_tags(@trim
($_GET['message']),'<a><b><u><i><br>');
193 $fortune = fortune();
194 $instance = INSTANCE_ID
!= '' ?
'/'.INSTANCE_ID
: '';
195 $user_id = htmlspecialchars($user['id']);
196 $user_gid = htmlspecialchars($user['gid']);
197 $user_name = htmlspecialchars($user['name']);
199 //$title = T($title); //TODO
201 $html = $this->head("SōkoMan$title");
203 <h1 style="display: inline;"><a href="$script/">SōkoMan</a><small>$instance$title</small></h1>
204 <div style="float:right; text-align:right;">
205 Logged in as <b>$user_name</b> [UID: <b>$user_id</b>; GID: <b>$user_gid</b>]<br />
209 <style type="text/css">
210 * { font-family: arial; }
211 td,body { background-color: white; border: orange; }
212 .tr_nobr td { border-top: 3px solid orange; }
213 table { background-color: orange; border: orange; }
214 td textarea { width:100%; height:100%; }
215 a, a img { text-decoration:none; color: darkblue; border:none; }
216 li a, a:hover { text-decoration:underline; }
217 .tr_even td { background-color: lemonchiffon; }
218 .tr_nobr.tr_even td:first-child { border-left: 5px solid orange; }
219 .tr_nobr.tr_odd td:first-child { border-left: 5px solid white; }
220 .item_status_stored td { font-weight:bold; }
221 .item_status_deleted td { text-decoration:line-through; }
222 .item_status_destroyed td { font-style:italic; }
223 .floating_barcode { margin: 5px; }
224 .disabled { color: grey; }
225 /* table, table * { table-layout:fixed; width:100%; overflow:hidden; word-wrap:break-word; } */
226 /* td { position:absolute; } */
227 /* .cell_model_name { float:left; } */
243 .menu, .menu * menu {
248 border: 1px solid orange;
253 .menu li:hover menu, .menu li:hover {
255 background-color: yellow;
264 foreach(scandir(DIR_ASSISTANTS
) as $item) {
265 if($item == '.' ||
$item == '..') continue;
266 $item = preg_replace('/\.inc\.php$/','',$item,-1,$count);
267 if($count) $assistants[$item] = "assistant/$item";
270 $tables=array('item','barcode','model','category','producer','vendor','room','status','location');
272 foreach($tables as $table) {
273 $listable[$table] = $table;
274 $insertable[$table] = "$table/new";
277 $html .= $this->ul(array(
279 'Logout' => '?logout',
280 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
281 1 => $this->ul($insertable,'menu',$this->link('New','#')),
282 2 => $this->ul($listable,'menu',$this->link('List','#'))
283 ),'menu', '', 'menu');
285 $html .= '<div style="float: right;">';
288 //TODO: Do we really need this?
289 $html .= $this->form("$script/api/go", 'GET', array(
290 array('q','','text','smart id...', 'autofocus'),
291 array(false,'go','submit')
292 ), 'style="float: left;"');
295 $html .= $this->form('?', 'GET', array(
296 array('q',$search,'text','regexp...'),
297 array(false,'filter','submit')
298 ), 'style="float: left;"');
300 $html .= $this->form("$script/item", 'GET', array(
301 array('q',$search,'text','regexp...','autofocus'),
302 array(false,'search','submit')
303 ), 'style="float: left;"');
309 <hr style="clear: both;" />
310 <div style="background-color:#FFDDDD;">
311 <font color="red">$message</font>
313 <div style="text-align:right; color:darkgreen;">
321 function internal_url($link) {
322 return $_SERVER['SCRIPT_NAME'].'/'.$link;
325 function table_add_images(&$table) {
326 $image = array('model_id');
327 foreach($table as $id => $row) {
328 foreach($image as $column) if(isset($table[$id][$column])) {
329 $type = @array_shift
(preg_split('/_/', $column));
330 $src=URL_IMAGES
."/$type/".$table[$id][$column].'.jpg';
331 $table[$id][$type.'_image']=$this->img_link($src, $src, $table[$id][$column], false, false);
336 function render_barcode($barcode,$opts=false) {
337 return $this->img_link($this->internal_url("barcodeimg/$barcode"),$this->internal_url("barcodeimg/$barcode"),$barcode,false,false,$opts);
340 function table_add_barcodes(&$table) {
341 $image = array('barcode_name', 'model_barcode', 'item_serial');
342 foreach($table as $id => $row) {
343 foreach($image as $column) if(isset($table[$id][$column])) {
344 $table[$id][$column]=$this->render_barcode($table[$id][$column]);
349 function table_add_row_classes(&$table, $class_col='_row_classes') {
350 $image = array('status_name' => ' item_status_');
351 foreach($table as $id => $row) {
352 foreach($image as $column => $param) if(isset($table[$id][$column])) {
353 @$table[$id][$class_col] .= $param.$table[$id][$column];
358 function table_add_relations(&$table, $class, $suffix_relations='_relations') {
359 $where_url = '%d/?where[%c]==%v';
360 $relations = array( //TODO: Autodetect??? //TODO: Add [edit] link to all classes
362 'model_id' => array(array('item',$where_url),array('edit','model/%v/edit/')),
363 'model_barcode' => array(array('store','assistant/%d?barcode=%v')),
364 'barcode_name' => array(array('store','assistant/%d?barcode=%v')),
365 'model_name' => array(array('google','http://google.com/search?q=%v')) //TODO: add manufacturer to google query
368 'model_id' => array(array('model',$where_url)),
369 'barcode_id' => array(array('item',$where_url),array('edit','barcode/%v/edit/')),
370 'barcode_name' => array(array('store','assistant/%d?barcode=%v')),
373 'item_serial' => array(array('dispose','assistant/%d?serial=%v','in_stock'),array('sell','assistant/%d?serial=%v','in_stock')),
374 'item_id' => array(array('edit','item/%v/edit/'))
376 'category' => array('category_id' => array(array('item',$where_url), array('model',$where_url))),
377 'producer' => array('producer_id' => array(array('item',$where_url), array('model',$where_url))),
378 'vendor' => array('vendor_id' => array(array('item',$where_url))),
379 'room' => array('room_id' => array(array('item',$where_url))),
380 'status' => array('status_id' => array(array('item',$where_url))),
382 'location_id' => array(array('item',$where_url),array('edit','location/%v/edit/')),
383 'location_name' => array(array('smokeping','http://tartarus.brevnov.czf/cgi-bin/smokeping.cgi?filter=%v'))
386 $relations_conditions=array(
387 'in_stock' => 'return(@$table[$id]["status_name"] == "stored");',
388 'not_sold' => 'return(@$table[$id]["status_name"] != "sold");',
389 'not_sold_or_disposed' => 'return(@$table[$id]["status_name"] != "sold" && @$table[$id]["status_name"] != "disposed");'
391 foreach($table as $id => $row) {
392 foreach($row as $column => $value) {
393 if(isset($relations[$class][$column])) {
394 foreach($relations[$class][$column] as $destination) {
395 $destination_url = str_replace(
396 array('%d','%c','%v'),
397 array(urlencode($destination[0]),urlencode($column),urlencode($value)),
400 if(isset($destination[2]) && isset($relations_conditions[$destination[2]])) {
401 //$condition = $relations_conditions[$destination[2]]($table,$id);
402 if(!eval($relations_conditions[$destination[2]])) continue;
404 @$table[$id][$class.$suffix_relations] .= $this->link($destination[0], $destination_url, !preg_match('/http/', $destination_url) ).',';
411 function table_collapse(&$table) {
413 'item_id' => 'item_id',
414 'model_id' => 'model_name',
415 'category_id' => 'category_name',
416 'producer_id' => 'producer_name',
417 'vendor_id' => 'vendor_name',
418 'room_id' => 'room_name',
419 'location_id' => 'location_name',
420 'status_id' => 'status_name',
421 'item_author' => 'item_author_backend',
422 'item_customer' => 'item_customer',
425 foreach($table as $id => $row) {
426 foreach($collapse as $link => $title)
427 if(isset($table[$id][$link]) && isset($row[$title])) {
428 $type = @array_shift
(preg_split('/_/', $link));
429 if($link != $title) unset($table[$id][$link]);
430 switch($link) { //TODO: Move to array for easy configuration
432 case 'item_customer':
433 $table[$id][$title]=$this->link($row[$title], "?where[$link]==".$row[$link], false);
436 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
443 function table_sort(&$table) {
444 $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');
445 $table_sorted = array();
446 foreach($table as $id => $row) {
447 $table_sorted[$id] = array();
448 foreach($precedence as $column) if(isset($table[$id][$column])) {
449 $table_sorted[$id][$column]=$table[$id][$column];
450 unset($table[$id][$column]);
452 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
453 //foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
455 $table = $table_sorted;
458 function table_hide_columns(&$table, $class) { //TODO: Move to build_query_select() !!! :-)))
459 $fields_hide = array(
460 'item' => array('model_descript','model_price_in','model_price_out','barcode_name','model_barcode','model_countable','model_reserve','model_eshop_hide','room_descript','room_author','producer_name','producer_note','vendor_note','location_author','location_gps','location_description')
462 //print_r($table); die();
463 if(isset($fields_hide[$class])) foreach($table as $id => $row) {
464 foreach($fields_hide[$class] as $field) unset($table[$id][$field]);
468 function render_item_table($table,$class=false) {
471 'break_after' => array(
472 'item' => array('category_name'),
473 'model'=> array('model_descript')
476 'item' => array('model_image'=>2,'item_id'=>2),
477 'model'=> array('model_image'=>2)
480 'item' => array('model_name'=>6,'category_name'=>'100%'),
481 'model'=> array('model_name'=>4,'model_descript'=>'100%')
485 foreach(array_keys($cellspan) as $vari)
486 $
$vari = isset($cellspan[$vari][$class]) ?
$cellspan[$vari][$class] : array();
488 if(empty($table)) return '<h3>'.T('holy primordial emptiness is all you can find here...').'</h3><br />';
489 $this->table_add_row_classes($table);
490 $this->table_add_images($table);
491 if($class) $this->table_add_relations($table,$class);
492 $this->table_add_barcodes($table);
493 $this->table_collapse($table);
494 if($class) $this->table_hide_columns($table,$class);
495 $this->table_sort($table);
496 return $this->table($table,$colspan,$rowspan,$break_after);
499 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
501 'item' => array('item_note'),
502 'model' => array('model_descript')
506 foreach($columns as $column) {
507 $html.='<tr class="'. ($even ?
'tr_even' : 'tr_odd') .'"><td>'.T($class).':<b>'.T($column['Field']).'</b>: </td><td>';
509 $name="values[$class][".$column['Field'].'][]';
510 $val = $update && isset($current[$column['Field']]) ?
$current[$column['Field']] : false;
512 case (preg_match('/auto_increment/', $column['Extra']) ||
in_array($column['Field'], $hidecols)):
513 if(is_bool($val) && !$val) $val = '';
514 $html.=$this->input($name, $val, 'hidden');
515 $html.='<span class="disabled"><i>[AUTO]</i> '.$val.'</span>';
517 case isset($selectbox[$column['Field']]):
518 $html.=$this->select($name,$selectbox[$column['Field']],$val);
520 case isset($textarea[$class]) && in_array($column['Field'],$textarea[$class]):
521 $html.=$this->input($name, $val, 'textarea');
524 $html.=$this->input($name, $val);
533 function render_insert_form_multi($array) {
537 foreach($array as $key => $args) {
538 $parts=array('inputs');
539 if(!$head) { $head = true;
542 if(!isset($array[$key+
1])) {
545 } else $hr = '<hr />';
549 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
555 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true, $parts=false) {
558 //echo('<pre>'); print_r($selectbox);
559 //echo('<pre>'); print_r($current);
561 if(is_array($current)) {
563 $current = array_shift($current);
566 if(!is_array($hidecols)) $hidecols = array();
567 $hidecols = array_merge($hidecols, array('item_author', 'item_valid_from', 'item_valid_till')); //TODO Autodetect
569 if(!is_array($parts) ||
in_array('head', $parts)) {
570 $action = $action ?
" action='$action'" : false;
571 $html.="<form$action method='POST'>"; //TODO: use $this->form()
572 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
575 if(!is_array($parts) ||
in_array('inputs', $parts))
576 $html.=$this->render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update);
578 if(!is_array($parts) ||
in_array('foot', $parts)) {
579 $html .= '</div></span><br style="clear:both" />';
580 if($multi_insert) { //TODO, move to separate JS file
583 function duplicate_element(what, where) {
584 var node = document.getElementsByName(what)[0];
585 node.parentNode.appendChild(node.cloneNode(true));
588 <a href='#' onClick="duplicate_element('input_set')">+</a>
592 $btn = is_array($current) ?
'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
593 $html.=$this->input(false, $btn, 'submit');
601 * Trida poskytuje rozhrani k databazi skladu
604 * @author Tomas Mudrunka
606 class Sklad_DB
extends PDO
{
607 function __construct() {
608 $this->auth
= new Sklad_Auth();
611 DB_DSN
, DB_USER
, DB_PASS
,
612 array(PDO
::MYSQL_ATTR_INIT_COMMAND
=> "SET NAMES utf8") //Force UTF8 for MySQL
616 function escape($str) {
617 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
620 function quote_identifier($str) {
621 return '`'.$this->escape($str).'`'; //TODO HACK
624 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
627 'barcode' => array('model', 'category', 'producer'),
628 'item' => array('barcode', 'model', 'category', 'producer', 'vendor', 'room', 'location', 'status'),
629 'model' => array('category', 'producer')
630 ); //TODO Autodetect using foreign keys?
632 'model' => array('barcode'=>'model_id')
634 $fields_search = array(
635 'item' => array('item_id','item_serial','model_name','barcode_name','model_barcode','model_descript','producer_name','vendor_name'),
636 'model' => array('model_id','model_name','barcode_name','model_barcode','model_descript','producer_name')
638 $group_concat = array(
639 'model' => array('barcode_name'=>'model_id')
643 if(is_array($where)) foreach($where as $key => $value) $where[$key] = $key.' '.$value; //TODO: escape SQLi!!!
646 $class = $this->escape($class);
649 $group_concat_query = '';
651 if(isset($group_concat[$class])) foreach($group_concat[$class] as $gc => $gb) {
652 $group_concat_query .= ",group_concat($gc separator ', ')";
653 $group_by .= "GROUP BY $gb\n";
657 $sql="SELECT *$group_concat_query FROM `$class`\n";
658 //$sql="SELECT * FROM `$class`\n";
660 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN `$j` USING($j$suffix_id)\n";
661 if(isset($join2[$class])) foreach($join2[$class] as $j => $c) $sql .= "LEFT JOIN `$j` USING($c)\n";
664 $search = $this->quote($search);
665 if(!isset($fields_search[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
667 foreach($fields_search[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
668 $where[] = "FALSE $sql_search";
669 } elseif($id) $where[] = "$class$suffix_id = $id";
670 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
672 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
678 if(!$order) $order = $class.$suffix_id.' DESC';
679 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
680 //$sql .= "ORDER BY $order\n"; //TODO: fixnout az budou opraveny vicenasobny carovy kody
683 $limit = $this->escape((int)$limit);
684 $offset = $this->escape((int)$offset);
685 $sql .= "LIMIT $offset,$limit\n";
691 function safe_query($sql, $fatal=true) {
692 $result = $this->query($sql);
694 $error = $this->errorInfo();
695 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>");
701 function translate_query_results(&$result) {
702 $translate_cols = array('item_valid_till'); //TODO: Hardcoded
703 foreach($result as $key => $row) {
704 foreach($translate_cols as $col) if(isset($result[$key][$col])){
705 $result[$key][$col] = T($result[$key][$col]);
710 function load_backend_data_to_query_results(&$result,$suffix_backend='_backend') {
711 $translate_cols = array(
712 'item_author' => 'return($this->auth->get_username_by_id($result[$key][$col]));'
714 foreach($result as $key => $row) {
715 foreach($translate_cols as $col => $backend) if(isset($result[$key][$col])){
716 $result[$key][$col.$suffix_backend] = eval($backend);
721 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO
::FETCH_ASSOC
, $translate=true) {
722 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
723 $this->load_backend_data_to_query_results($result);
724 if($translate) $this->translate_query_results($result);
728 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
729 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
730 $result = $this->safe_query_fetch($sql);
731 if(!$result ||
!is_array($indexed)) return $result;
733 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
737 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
738 $class = $this->escape($class);
739 $sql = "SHOW COLUMNS FROM $class;";
740 $columns = $this->safe_query_fetch($sql);
741 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
742 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
747 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
748 $selectbox=array( //TODO: Hardcoded...
749 'model_countable' => array(0 => 'no', 1 => 'yes'),
750 'model_eshop_hide' => array(0 => 'no', 1 => 'yes'),
751 'vendor_id' => array('COMPULSORY' => 'select...')
753 foreach($columns as $column) {
754 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)!
755 if($class && $column['Field'] == $class.$suffix_id) continue;
756 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
757 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
759 $history = $this->contains_history($table) ?
" WHERE ${table}_valid_till=0" : '';
760 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
761 $result = $this->safe_query_fetch($sql, false);
762 if(!$result) continue;
763 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
765 //echo('<pre>'); print_r($selectbox);
766 //return array_filter($selectbox, 'ksort');
767 return array_filter($selectbox, 'natcasesort');
768 //array_multisort($selectbox); return $selectbox;
771 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
772 $history = $this->contains_history($table) ?
" AND ${table}_valid_till=0" : '';
773 $value=$this->quote($value);
774 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
775 $result = $this->safe_query_fetch($sql);
776 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
779 function contains_history($table) {
780 $history_tables = array('item'); //TODO Autodetect
781 return in_array($table, $history_tables);
784 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
786 $history = $this->contains_history($table);
789 $table = $this->escape($table);
791 //Get list of POSTed columns
792 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
793 $columns = implode(',',$columns_array);
797 //echo('<pre>'); die(print_r($values));
800 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
801 if($history_update) {
802 $sql .= "UPDATE $table";
803 $sql .= " SET ${table}_valid_till=NOW()";
804 $sql .= " WHERE ${table}_valid_till=0 AND (";
806 foreach($values as $row) {
807 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
815 //Insert into table (columns)
816 $sql .= "INSERT INTO $table ($columns) VALUES ";
818 //Values (a,b,c),(d,e,f)
820 foreach($values as $row) {
821 $row_quoted = array_map(array($this,'quote'), $row); //Check
823 foreach($row as $column => $value) {
825 case $table.'_valid_from':
826 $row_quoted[$column] = 'NOW()';
828 case $table.'_valid_till':
829 $row_quoted[$column] = '0';
831 case $table.'_author':
832 $row_quoted[$column] = $this->auth
->get_user_id();
833 //die($this->auth->get_user_id().'=USER');
838 $sql .= $comma.'('.implode(',',$row_quoted).')';
844 foreach($columns_array as $col) {
845 if($col == $table.'_id' ||
$col == $table.'_valid_till') continue;
846 $on_duplicate[] = "$col=VALUES($col)";
848 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
856 function insert_or_update($table, $values, $replace=true) {
857 $sql = $this->build_query_insert($table, $values, $replace);
858 $this->safe_query($sql);
859 return $this->lastInsertId();
862 function insert_or_update_multitab($values, $replace=true) {
864 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
868 function delete($table, $id, $suffix_id='_id') {
869 if($this->contains_history($table)) return false;
870 $key = $this->escape($table.$suffix_id);
871 $table = $this->escape($table);
872 $id = $this->quote($id);
873 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
878 * Trida poskytuje high-level rozhrani k databazi skladu
880 * @package Sklad_DB_Abstract
881 * @author Tomas Mudrunka
883 class Sklad_DB_Abstract
extends Sklad_DB
{
888 * Trida implementuje uzivatelske rozhrani skladu
891 * $sklad = new Sklad_UI();
892 * $sklad->process_http_request();
895 * @author Tomas Mudrunka
898 function __construct() {
899 $this->db
= new Sklad_DB();
900 $this->html
= new Sklad_HTML();
903 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
904 return $this->html
->render_item_table($this->db
->get_listing($class, $id, $limit, $offset, $where, $search, $history, false),$class);
907 function render_form_add($class) {
908 $columns = $this->db
->get_columns($class);
909 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
910 return $this->html
->render_insert_form($class, $columns, $selectbox);
913 function render_form_edit($class, $id, $multi_insert) {
914 $columns = $this->db
->get_columns($class);
915 $selectbox = $this->db
->columns_get_selectbox($columns, $class);
916 $current = $this->db
->get_listing($class, $id, 1);
917 return $this->html
->render_insert_form($class, $columns, $selectbox, $current, false, false, $multi_insert);
920 function render_single_record_details($class, $id, $barcode=true) {
922 $id_prev = $id - 1 > 0 ?
$id - 1 : 0;
923 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
925 $html.= $this->html
->link('<<', "$class/$id_prev/");
927 $html.= $this->html
->link('>>', "$class/$id_next/");
928 $html.= ' ';
929 $barcode && $html.='<span style="float:right;" class="floating_barcode">'.$this->html
->render_barcode(BARCODE_PREFIX
.strtoupper("$class/$id")).'</span>';
930 $html.= $this->html
->link('edit', "$class/$id/edit/");
931 if($this->db
->contains_history($class)) $html.= ' ][ '.$this->html
->link('history', "$class/$id/history/");
935 function render_listing_navigation($class, $id, $limit, $offset) {
936 $offset_next = $offset +
$limit;
937 $offset_prev = $offset - $limit > 0 ?
$offset - $limit : 0;
938 $get = $_SERVER['QUERY_STRING'] != '' ?
'?'.$_SERVER['QUERY_STRING'] : '';
939 $moreget = isset($get[0]) ?
'&' : '?';
941 $html.= $this->html
->link('<<', "$class/$id/$limit/$offset_prev/$get");
943 $html.= $this->html
->link('[*]', "$class/$id/0/0/$get$moreget".'noimgs');
945 $html.= $this->html
->link('>>', "$class/$id/$limit/$offset_next/$get");
946 $html.= ' ';
947 $html.= $this->html
->link('new', "$class/new/$get");
951 function render_listing_extensions($class, $id, $limit, $offset, $edit=false, $barcode=true) {
953 if(is_numeric($id)) {
954 $html.=$this->render_single_record_details($class, $id, $barcode);
956 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
958 if($edit && $barcode) {
959 $html.= $this->render_form_edit($class, $id, false);
960 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
961 $html.=$this->html
->form($action,'POST',array(
962 array(false,'DELETE','submit'),
963 array('sure', false, 'checkbox', false, false, 'sure?')
965 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
966 $html.=$this->html
->form($action,'POST',array(
967 array('image', false, 'file', false, 'size="30"'),
968 array(false, 'IMAGE', 'submit')
969 ), "enctype='multipart/form-data'");
974 function check_auth() {
975 new HTTP_Auth('WareHouse ['.BACKEND_AUTH
.']', true, array($this->db
->auth
,'check_auth'));
978 function post_redirect_get($location, $message='', $error=false, $translate=true) {
979 $messaget = $translate ?
T($message) : $message;
980 $url_args = $messaget != '' ?
'?message='.urlencode($messaget) : '';
981 $location = $this->html
->internal_url($location).$url_args;
982 header('Location: '.$location);
983 if($error) trigger_error($message);
984 $location=htmlspecialchars($location);
986 "<meta http-equiv='refresh' content='0; url=$location'>".
987 $messaget."<br />Location: <a href='$location'>$location</a>"
991 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
992 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
993 $filename="$dir/$name$ext";
994 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
995 foreach($vars as $var => $val) $
$var=$val;
998 $out=ob_get_contents();
1003 function check_input_validity($field, $value='', $ruleset=0) {
1004 $rules = array(0 => array(
1005 'model_barcode' => '/./',
1006 'barcode_name' => '/./',
1007 'item_serial' => '/./',
1008 'vendor_id' => '/^[0-9]*$/'
1010 if(isset($rules[$ruleset][$field]) && !preg_match($rules[$ruleset][$field], trim($value))) return false;
1014 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
1015 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
1016 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
1020 /* Tenhle foreach() prekopiruje promenne
1021 * z: $_POST['values'][$table][$column][$id];
1022 * do: $values[$table][$id][$column]
1024 if(isset($_POST['values'])) {
1026 foreach($_POST['values'] as $table => $columns) {
1027 foreach($columns as $column => $ids) {
1028 foreach($ids as $id => $val) {
1029 $values[$table][$id][$column] = trim($val);
1030 if(!$this->check_input_validity($column,$val)) {
1031 $message = "Spatny vstup: $column [$id] = \"$val\"; ". //XSS
1032 $this->html
->link('GO BACK', 'javascript:history.back()', false, false);
1033 $this->post_redirect_get('', $message, false, false);
1038 //die(print_r($values));
1041 if($action) switch($action) {
1045 if(!isset($replace)) $replace = true;
1046 $table = $class ?
$class : 'item';
1047 //print_r($values); //debug
1048 $last = $this->db
->insert_or_update_multitab($values, $replace);
1049 $last = $force_redirect ?
$force_redirect."?last=$last" : "$table/$last/";
1050 $next = "$table/new/";
1051 $message = $force_redirect ?
'' : 'Hotovo. Další záznam přidáte '.$this->html
->link('zde', $next).'.';
1052 $this->post_redirect_get($last, $message);
1055 if(!isset($_POST['sure']) ||
!$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
1056 $this->db
->delete($class, $id) ||
$this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
1057 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
1060 $image_classes = array('model'); //TODO, use this more widely across the code
1061 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
1062 $image_destination = DIR_IMAGES
."/$class/$id.jpg";
1063 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
1064 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
1065 chmod ($image_destination, 0664);
1066 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
1067 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
1070 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
1074 die('POSTed pyčo!');
1077 function process_http_request() {
1078 $listing_limit_classes = array('item','model');
1080 $this->check_auth();
1082 @ini_set
('magic_quotes_gpc' , 'off');
1083 if(get_magic_quotes_gpc()) {
1084 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
1087 $PATH_INFO=@trim
($_SERVER[PATH_INFO
]);
1088 if($PATH_INFO == '' ||
$PATH_INFO == '/') $PATH_INFO = FRONTEND_PAGE_WELCOME
;
1089 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
1091 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
1092 if($_SERVER['REQUEST_METHOD'] != 'POST' && $PATH_CHUNKS[1]!='barcodeimg' && $PATH_CHUNKS[1]!='api') //TODO: tyhle podminky naznacujou, ze je v navrhu nejaka drobna nedomyslenost...
1093 echo $this->html
->header($PATH_INFO,$this->db
->auth
->get_user());
1094 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
1096 die('Tell me why you cry');
1098 case 'assistant': case 'api': //assistant|api
1100 'assistant' => DIR_ASSISTANTS
,
1103 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ?
trim($PATH_CHUNKS[3]) : false;
1104 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
1105 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
1106 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
1107 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
1108 echo $this->safe_include($incdirs[$PATH_CHUNKS[1]],$PATH_CHUNKS[2],$assistant_vars);
1110 case 'barcodeimg': //barcode
1111 Barcode
::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
1114 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ?
trim($_GET['q']) : false;
1115 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ?
$PATH_CHUNKS[1] : 'item';
1116 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
1117 switch($PATH_CHUNKS[2]) {
1119 $this->process_http_request_post($PATH_CHUNKS[2], $class);
1120 echo $this->render_form_add($class);
1123 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ?
(int) $PATH_CHUNKS[2] : false);
1124 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
1126 switch($PATH_CHUNKS[3]) {
1127 case 'edit': //?/?/edit
1128 case 'image': //?/?/image
1129 case 'delete': //?/?/delete
1130 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
1133 $history = $PATH_CHUNKS[3] == 'history' ?
true : false;
1134 $limit = is_numeric($PATH_CHUNKS[3]) ?
(int) $PATH_CHUNKS[3] : (in_array($class, $listing_limit_classes) ? FRONTEND_LISTING_LIMIT
: 0);
1135 $offset = isset($PATH_CHUNKS[4]) ?
(int) $PATH_CHUNKS[4] : 0;
1136 $where = @is_array
($_GET['where']) ?
$_GET['where'] : false;
1137 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit, false);
1138 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
1139 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
1140 //print_r(array("<pre>",$_SERVER));
1150 $sklad = new Sklad_UI();
1151 $sklad->process_http_request();
1153 echo('<br style="clear:both;" /><hr />');
This page took 1.924313 seconds and 5 git commands to generate.