kazdy element td ma nyni css class
[mirrors/SokoMan.git] / index.php
1 <?php
2 /*
3 * SkladovySystem - Storage management system compatible with LMS
4 * Copyright (C) 2011 Tomas Mudrunka
5 *
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.
10 *
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.
15 *
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/>.
18 */
19
20 require_once('sklad.conf.php');
21 set_include_path(DIR_LIB.PATH_SEPARATOR.get_include_path());
22
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');
28
29 /**
30 * Trida poskytuje vseobecne funkce pro generovani HTML kodu
31 *
32 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
33 *
34 * @package HTML
35 * @author Tomas Mudrunka
36 */
37 class HTML {
38 function row($row,$type=false,$class=false,$parameters='') {
39 $html = '';
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 $id => $var) {
45 $tdclass = " class='cell_$id'";
46 if(trim($var) == '') $var = '&nbsp;';
47 $html.="<$td$tdclass>$var</$td>";
48 }
49 $html.='</tr>';
50 if($type) $html.="</$type>";
51 return $html;
52 }
53
54 function table(&$table, $parity_class=array('tr_odd','tr_even'), $params='border=1', $row_params_field='_row_parameters') {
55 $html="<table $params>";
56 $header=true;
57 $even=false;
58 foreach($table as $row) {
59 $params = isset($row[$row_params_field]) ? $row[$row_params_field] : '';
60 unset($row[$row_params_field]);
61 if($header) {
62 $html.=$this->row(T(array_keys($row)),'thead');
63 $header=false;
64 }
65 $class = $parity_class ? $parity_class[$even] : false;
66 $html.=$this->row($row,false,$class.$params);
67 $even = !$even;
68 }
69 $html.='</table>';
70 return $html;
71 }
72
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>";
77 }
78
79 function img($src='#void', $title='img', $options='width=64') {
80 $options = $options ? " $options" : '';
81 return "<img src='$src' alt='$title' title='$title'$options; />";
82 }
83
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);
86 }
87
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>";
94 return $html;
95 }
96
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' ";
104 }
105 if($options) $html.= "$options ";
106 if($placeholder) $html.= "placeholder='$placeholder' ";
107 $html .= '/>';
108 return $html;
109 }
110
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);
117 $html .= "</form>";
118 return $html;
119 }
120
121 function select($name, $selectbox, $default=false) {
122 //echo('<pre>'); print_r($selectbox);
123 $html = "<select name='$name'>";
124
125 if(!is_bool($default)) {
126 $value=$default; $title=$selectbox[$value];
127 $html .= "<option value='$value'>$value :: $title</option>";
128 unset($selectbox[$value]);
129 }
130 foreach($selectbox as $value => $title) {
131 $html .= "<option value='$value'>$value :: $title</option>";
132 }
133 $html .= "</select>";
134 return $html;
135 }
136
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) {
141 $html .= '<li>';
142 if(is_numeric($key)) {
143 $html .= $value;
144 } else {
145 $html .= $this->link($key,$value);
146 }
147 $html .= '</li>';
148 }
149 $html .= "</$tag>";
150 return $html;
151 }
152
153 function div($html, $options) {
154 $options = $options ? " $options" : '';
155 return "<div$options>$html</div>";
156 }
157
158 function favicon($url='/favicon.ico') {
159 return '<link rel="shortcut icon" href="'.$url.'" /><link href="'.$url.'" rel="icon" type="image/gif" />';
160
161 }
162
163 function head($title=false,$charset='UTF-8',$more='') {
164 $title = $title ? "\n<title>$title</title>" : '';
165 $html= '<head>';
166 $html.= '<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />'.$title.$more;
167 $html.= $this->favicon(dirname($_SERVER['SCRIPT_NAME']).'/favicon.ico');
168 $html.= '</head>';
169 return $html;
170 }
171 }
172
173 /**
174 * Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
175 *
176 * Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
177 *
178 * @package Sklad_HTML
179 * @author Tomas Mudrunka
180 */
181 class Sklad_HTML extends HTML { //TODO: Split into few more methods
182 function header($title='', $user=array()) {
183 $home = URL_HOME;
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']);
192 $time = date('r');
193 //$title = T($title); //TODO
194
195 $html = $this->head("SōkoMan$title");
196 $html .= <<<EOF
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 />
200 Page loaded at $time
201 </div>
202
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 { text-decoration:line-through; }
212 .item_status_destroyed td { font-style:italic; }
213 /* table, table * { table-layout:fixed; width:100%; overflow:hidden; word-wrap:break-word; } */
214 /* td { position:absolute; } */
215
216
217 .menu li {
218 float: left;
219 padding: 0.2em;
220 }
221
222 .menu * li {
223 float: none;
224 }
225
226 .menu * menu {
227 position: absolute;
228 padding: 0.2em;
229 }
230
231 .menu, .menu * menu {
232 list-style: none;
233 }
234
235 .menu * menu {
236 border: 1px solid orange;
237 display: none;
238 margin: 0;
239 }
240
241 .menu li:hover menu, .menu li:hover {
242 display: block;
243 background-color: yellow;
244 }
245
246 </style>
247
248 <div>
249 EOF;
250
251 $assistants=array();
252 foreach(scandir(DIR_ASSISTANTS) as $item) {
253 if($item == '.' || $item == '..') continue;
254 $item = preg_replace('/\.inc\.php$/','',$item,-1,$count);
255 if($count) $assistants[$item] = "assistant/$item";
256 }
257
258 $tables=array('item','model','category','producer','vendor','room','status');
259
260 foreach($tables as $table) {
261 $listable[$table] = $table;
262 $insertable[$table] = "$table/new";
263 }
264
265 $html .= $this->ul(array(
266 'Home' => '',
267 'Logout' => '?logout',
268 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
269 1 => $this->ul($insertable,'menu',$this->link('New','#')),
270 2 => $this->ul($listable,'menu',$this->link('List','#'))
271 ),'menu', '', 'menu');
272
273 $html .= '<div style="float: right;">';
274
275 /*
276 //TODO: Do we really need this?
277 $html .= $this->form("$script/api/go", 'GET', array(
278 array('q','','text','smart id...', 'autofocus'),
279 array(false,'go','submit')
280 ), 'style="float: left;"');
281 */
282
283 $html .= $this->form('?', 'GET', array(
284 array('q',$search,'text','regexp...'),
285 array(false,'filter','submit')
286 ), 'style="float: left;"');
287
288 $html .= $this->form("$script/item", 'GET', array(
289 array('q',$search,'text','regexp...','autofocus'),
290 array(false,'search','submit')
291 ), 'style="float: left;"');
292
293 $html .= '</div>';
294
295 $html .= <<<EOF
296 </div>
297 <hr style="clear: both;" />
298 <div style="background-color:#FFDDDD;">
299 <font color="red">$message</font>
300 </div>
301 <div style="text-align:right; color:darkgreen;">
302 $fortune
303 </div>
304 EOF;
305
306 return $html;
307 }
308
309 function internal_url($link) {
310 return $_SERVER['SCRIPT_NAME'].'/'.$link;
311 }
312
313 function table_add_images(&$table) {
314 $image = array('model_id');
315 foreach($table as $id => $row) {
316 foreach($image as $column) if(isset($table[$id][$column])) {
317 $type = @array_shift(preg_split('/_/', $column));
318 $src=URL_IMAGES."/$type/".$table[$id][$column].'.jpg';
319 $table[$id][$type.'_image']=$this->img_link($src, $src, $table[$id][$column], false, false);
320 }
321 }
322 }
323
324 function render_barcode($barcode,$opts=false) {
325 return $this->img_link($this->internal_url("barcode/$barcode"),$this->internal_url("barcode/$barcode"),$barcode,false,false,$opts);
326 }
327
328 function table_add_barcodes(&$table) {
329 $image = array('model_barcode', 'item_serial');
330 foreach($table as $id => $row) {
331 foreach($image as $column) if(isset($table[$id][$column])) {
332 $table[$id][$column]=$this->render_barcode($table[$id][$column]);
333 }
334 }
335 }
336
337 function table_add_row_parameters(&$table, $param_col='_row_parameters') { //TODO: rename to table_add_row_classes()
338 $image = array('status_name' => ' item_status_');
339 foreach($table as $id => $row) {
340 foreach($image as $column => $param) if(isset($table[$id][$column])) {
341 @$table[$id][$param_col] .= $param.$table[$id][$column];
342 }
343 }
344 }
345
346 function table_add_relations(&$table, $class, $suffix_relations='_relations') {
347 $where_url = '%d/?where[%c]==%v';
348 $relations = array( //TODO: Autodetect???
349 'model' => array(
350 'model_id' => array(array('item',$where_url),array('edit','model/%v/edit/')),
351 'model_barcode' => array(array('store','assistant/%d?barcode=%v')),
352 'model_name' => array(array('google','http://google.com/search?q=%v',true)) //TODO: add manufacturer to google query
353 ),
354 'item' => array(
355 'item_serial' => array(array('dispose','assistant/%d?serial=%v','in_stock'),array('sell','assistant/%d?serial=%v','in_stock')),
356 'item_id' => array(array('edit','item/%v/edit/'))
357 ),
358 'category' => array('category_id' => array(array('item',$where_url), array('model',$where_url))),
359 'producer' => array('producer_id' => array(array('item',$where_url), array('model',$where_url))),
360 'vendor' => array('vendor_id' => array(array('item',$where_url))),
361 'room' => array('room_id' => array(array('item',$where_url))),
362 'status' => array('status_id' => array(array('item',$where_url)))
363 );
364 $relations_conditions=array(
365 'in_stock' => 'return(@$table[$id]["status_name"] == "stored");',
366 'not_sold' => 'return(@$table[$id]["status_name"] != "saled");',
367 'not_sold_or_disposed' => 'return(@$table[$id]["status_name"] != "saled" && @$table[$id]["status_name"] != "disposed");'
368 );
369 foreach($table as $id => $row) {
370 foreach($row as $column => $value) {
371 if(isset($relations[$class][$column])) {
372 foreach($relations[$class][$column] as $destination) {
373 $destination_url = str_replace(
374 array('%d','%c','%v'),
375 array(urlencode($destination[0]),urlencode($column),urlencode($value)),
376 $destination[1]
377 );
378 if(isset($destination[2]) && isset($relations_conditions[$destination[2]])) {
379 //$condition = $relations_conditions[$destination[2]]($table,$id);
380 if(!eval($relations_conditions[$destination[2]])) continue;
381 }
382 @$table[$id][$class.$suffix_relations] .= $this->link($destination[0], $destination_url).',';
383 }
384 }
385 }
386 }
387 }
388
389 function table_collapse(&$table) {
390 $collapse = array(
391 'item_id' => 'item_id',
392 'model_id' => 'model_name',
393 'category_id' => 'category_name',
394 'producer_id' => 'producer_name',
395 'vendor_id' => 'vendor_name',
396 'room_id' => 'room_name',
397 'status_id' => 'status_name',
398 'item_author' => 'item_author_backend',
399 'item_customer' => 'item_customer',
400 );
401
402 foreach($table as $id => $row) {
403 foreach($collapse as $link => $title)
404 if(isset($table[$id][$link]) && isset($row[$title])) {
405 $type = @array_shift(preg_split('/_/', $link));
406 if($link != $title) unset($table[$id][$link]);
407 switch($link) { //TODO: Move to array for easy configuration
408 case 'item_author':
409 case 'item_customer':
410 $table[$id][$title]=$this->link($row[$title], "?where[$link]==".$row[$link], false);
411 break;
412 default:
413 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
414 break;
415 }
416 }
417 }
418 }
419
420 function table_sort(&$table) {
421 $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');
422 $table_sorted = array();
423 foreach($table as $id => $row) {
424 $table_sorted[$id] = array();
425 foreach($precedence as $column) if(isset($table[$id][$column])) {
426 $table_sorted[$id][$column]=$table[$id][$column];
427 unset($table[$id][$column]);
428 }
429 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
430 //foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
431 }
432 $table = $table_sorted;
433 }
434
435 function table_hide_columns(&$table, $class) { //TODO: Move to build_query_select() !!! :-)))
436 $fields_hide = array(
437 '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')
438 );
439 //print_r($table); die();
440 if(isset($fields_hide[$class])) foreach($table as $id => $row) {
441 foreach($fields_hide[$class] as $field) unset($table[$id][$field]);
442 }
443 }
444
445 function render_item_table($table,$class=false) {
446 if(empty($table)) return '<h3>'.T('holy primordial emptiness is all you can find here...').'</h3><br />';
447 $this->table_add_row_parameters($table);
448 $this->table_add_images($table);
449 if($class) $this->table_add_relations($table,$class);
450 $this->table_add_barcodes($table);
451 $this->table_collapse($table);
452 if($class) $this->table_hide_columns($table,$class);
453 $this->table_sort($table);
454 return $this->table($table);
455 }
456
457 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
458 $textarea = array(
459 'item' => array('item_note'),
460 'model' => array('model_descript')
461 );
462 $html = '';
463 foreach($columns as $column) {
464 $html.=T($class).':<b>'.T($column['Field']).'</b>: ';
465 $name="values[$class][".$column['Field'].'][]';
466 $val = $update && isset($current[$column['Field']]) ? $current[$column['Field']] : false;
467 switch(true) {
468 case (preg_match('/auto_increment/', $column['Extra']) || in_array($column['Field'], $hidecols)):
469 if(is_bool($val) && !$val) $val = '';
470 $html.=$this->input($name, $val, 'hidden');
471 $html.=$val.'(AUTO)';
472 break;
473 case isset($selectbox[$column['Field']]):
474 $html.=$this->select($name,$selectbox[$column['Field']],$val);
475 break;
476 case isset($textarea[$class]) && in_array($column['Field'],$textarea[$class]):
477 $html.=$this->input($name, $val, 'textarea');
478 break;
479 default:
480 $html.=$this->input($name, $val);
481 break;
482 }
483 $html.='<br />';
484 }
485 return $html;
486 }
487
488 function render_insert_form_multi($array) {
489 $html = '';
490 $head=false;
491
492 foreach($array as $key => $args) {
493 $parts=array('inputs');
494 if(!$head) { $head = true;
495 $parts[]='head';
496 }
497 if(!isset($array[$key+1])) {
498 $parts[]='foot';
499 $hr = '';
500 } else $hr = '<hr />';
501 //$args[] = false;
502 $args[] = $parts;
503
504 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
505 $html .= $hr;
506 }
507 return $html;
508 }
509
510 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true, $parts=false) {
511 $html = '';
512 //print_r($parts);
513 //echo('<pre>'); print_r($selectbox);
514 //echo('<pre>'); print_r($current);
515 $update = false;
516 if(is_array($current)) {
517 $update = true;
518 $current = array_shift($current);
519 }
520
521 if(!is_array($hidecols)) $hidecols = array();
522 $hidecols = array_merge($hidecols, array('item_author', 'item_valid_from', 'item_valid_till')); //TODO Autodetect
523
524 if(!is_array($parts) || in_array('head', $parts)) {
525 $action = $action ? " action='$action'" : false;
526 $html.="<form$action method='POST'>"; //TODO: use $this->form()
527 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
528 }
529
530 if(!is_array($parts) || in_array('inputs', $parts))
531 $html.=$this->render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update);
532
533 if(!is_array($parts) || in_array('foot', $parts)) {
534 $html .= '</div></span><br style="clear:both" />';
535 if($multi_insert) { //TODO, move to separate JS file
536 $html.=<<<EOF
537 <script>
538 function duplicate_element(what, where) {
539 var node = document.getElementsByName(what)[0];
540 node.parentNode.appendChild(node.cloneNode(true));
541 }
542 </script>
543 <a href='#' onClick="duplicate_element('input_set')">+</a>
544 EOF;
545 }
546
547 $btn = is_array($current) ? 'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
548 $html.=$this->input(false, $btn, 'submit');
549 $html.='</form>';
550 }
551 return $html;
552 }
553 }
554
555 /**
556 * Trida poskytuje rozhrani k databazi skladu
557 *
558 * @package Sklad_DB
559 * @author Tomas Mudrunka
560 */
561 class Sklad_DB extends PDO {
562 function __construct() {
563 $this->auth = new Sklad_Auth();
564
565 parent::__construct(
566 DB_DSN, DB_USER, DB_PASS,
567 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") //Force UTF8 for MySQL
568 );
569 }
570
571 function escape($str) {
572 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
573 }
574
575 function quote_identifier($str) {
576 return '`'.$this->escape($str).'`'; //TODO HACK
577 }
578
579 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
580 //Configuration
581 $join = array(
582 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
583 'model' => array('category', 'producer')
584 ); //TODO Autodetect using foreign keys?
585 $fields_search = array(
586 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name'),
587 'model' => array('model_id','model_name','model_barcode','model_descript','producer_name')
588 ); //TODO Autodetect
589
590 //Init
591 if(is_array($where)) foreach($where as $key => $value) $where[$key] = $key.' '.$value; //TODO: escape SQLi!!!
592
593 //Escaping
594 $class = $this->escape($class);
595
596 //SELECT
597 $sql="SELECT * FROM `$class`\n";
598 //JOIN
599 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN `$j` USING($j$suffix_id)\n";
600 //WHERE/REGEXP
601 if($search) {
602 $search = $this->quote($search);
603 if(!isset($fields_search[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
604 $sql_search = '';
605 foreach($fields_search[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
606 $where[] = "FALSE $sql_search";
607 } elseif($id) $where[] = "$class$suffix_id = $id";
608 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
609
610 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
611 //ORDER
612 if(!$order) $order = $class.$suffix_id.' DESC';
613 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
614 $sql .= "ORDER BY $order\n";
615 //LIMIT/OFFSET
616 if($limit) {
617 $limit = $this->escape((int)$limit);
618 $offset = $this->escape((int)$offset);
619 $sql .= "LIMIT $offset,$limit\n";
620 }
621
622 return $sql;
623 }
624
625 function safe_query($sql, $fatal=true) {
626 $result = $this->query($sql);
627 if(!$result) {
628 $error = $this->errorInfo();
629 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>");
630 if($fatal) die();
631 }
632 return $result;
633 }
634
635 function translate_query_results(&$result) {
636 $translate_cols = array('item_valid_till'); //TODO: Hardcoded
637 foreach($result as $key => $row) {
638 foreach($translate_cols as $col) if(isset($result[$key][$col])){
639 $result[$key][$col] = T($result[$key][$col]);
640 }
641 }
642 }
643
644 function load_backend_data_to_query_results(&$result,$suffix_backend='_backend') {
645 $translate_cols = array(
646 'item_author' => 'return($this->auth->get_username_by_id($result[$key][$col]));'
647 ); //TODO: Hardcoded
648 foreach($result as $key => $row) {
649 foreach($translate_cols as $col => $backend) if(isset($result[$key][$col])){
650 $result[$key][$col.$suffix_backend] = eval($backend);
651 }
652 }
653 }
654
655 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO::FETCH_ASSOC, $translate=true) {
656 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
657 $this->load_backend_data_to_query_results($result);
658 if($translate) $this->translate_query_results($result);
659 return $result;
660 }
661
662 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
663 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
664 $result = $this->safe_query_fetch($sql);
665 if(!$result || !is_array($indexed)) return $result;
666
667 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
668 return $indexed;
669 }
670
671 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
672 $class = $this->escape($class);
673 $sql = "SHOW COLUMNS FROM $class;";
674 $columns = $this->safe_query_fetch($sql);
675 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
676 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
677 }*/
678 return $columns;
679 }
680
681 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
682 $selectbox=array( //TODO: Hardcoded...
683 'model_countable' => array(0 => 'no', 1 => 'yes'),
684 'model_eshop_hide' => array(0 => 'no', 1 => 'yes'),
685 'vendor_id' => array('COMPULSORY' => 'select...')
686 );
687 foreach($columns as $column) {
688 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)!
689 if($class && $column['Field'] == $class.$suffix_id) continue;
690 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
691 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
692
693 $history = $this->contains_history($table) ? " WHERE ${table}_valid_till=0" : '';
694 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
695 $result = $this->safe_query_fetch($sql, false);
696 if(!$result) continue;
697 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
698 }
699 //echo('<pre>'); print_r($selectbox);
700 return array_filter($selectbox, 'ksort');
701 }
702
703 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
704 $history = $this->contains_history($table) ? " AND ${table}_valid_till=0" : '';
705 $value=$this->quote($value);
706 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
707 $result = $this->safe_query_fetch($sql);
708 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
709 }
710
711 function contains_history($table) {
712 $history_tables = array('item'); //TODO Autodetect
713 return in_array($table, $history_tables);
714 }
715
716 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
717 //Init
718 $history = $this->contains_history($table);
719
720 //Escaping
721 $table = $this->escape($table);
722
723 //Get list of POSTed columns
724 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
725 $columns = implode(',',$columns_array);
726
727 //Build query
728 $sql = '';
729 //echo('<pre>'); die(print_r($values));
730
731 if($history) {
732 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
733 if($history_update) {
734 $sql .= "UPDATE $table";
735 $sql .= " SET ${table}_valid_till=NOW()";
736 $sql .= " WHERE ${table}_valid_till=0 AND (";
737 $or = '';
738 foreach($values as $row) {
739 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
740 $or = ' OR';
741 }
742 $sql .= " );\n\n";
743 $replace = false;
744 }
745 }
746
747 //Insert into table (columns)
748 $sql .= "INSERT INTO $table ($columns) VALUES ";
749
750 //Values (a,b,c),(d,e,f)
751 $comma='';
752 foreach($values as $row) {
753 $row_quoted = array_map(array($this,'quote'), $row); //Check
754 if($history) {
755 foreach($row as $column => $value) {
756 switch($column) {
757 case $table.'_valid_from':
758 $row_quoted[$column] = 'NOW()';
759 break;
760 case $table.'_valid_till':
761 $row_quoted[$column] = '0';
762 break;
763 case $table.'_author':
764 $row_quoted[$column] = $this->auth->get_user_id();
765 //die($this->auth->get_user_id().'=USER');
766 break;
767 }
768 }
769 }
770 $sql .= $comma.'('.implode(',',$row_quoted).')';
771 $comma = ',';
772 }
773
774 //On duplicate key
775 if($replace) {
776 foreach($columns_array as $col) {
777 if($col == $table.'_id' || $col == $table.'_valid_till') continue;
778 $on_duplicate[] = "$col=VALUES($col)";
779 }
780 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
781 }
782
783 //Terminate
784 $sql .= ';';
785 return $sql;
786 }
787
788 function insert_or_update($table, $values, $replace=true) {
789 $sql = $this->build_query_insert($table, $values, $replace);
790 $this->safe_query($sql);
791 return $this->lastInsertId();
792 }
793
794 function insert_or_update_multitab($values, $replace=true) {
795 $last=false;
796 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
797 return $last;
798 }
799
800 function delete($table, $id, $suffix_id='_id') {
801 if($this->contains_history($table)) return false;
802 $key = $this->escape($table.$suffix_id);
803 $table = $this->escape($table);
804 $id = $this->quote($id);
805 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
806 }
807 }
808
809 /**
810 * Trida poskytuje high-level rozhrani k databazi skladu
811 *
812 * @package Sklad_DB_Abstract
813 * @author Tomas Mudrunka
814 */
815 class Sklad_DB_Abstract extends Sklad_DB {
816 //TODO Code
817 }
818
819 /**
820 * Trida implementuje uzivatelske rozhrani skladu
821 *
822 * Example usage:
823 * $sklad = new Sklad_UI();
824 * $sklad->process_http_request();
825 *
826 * @package Sklad_UI
827 * @author Tomas Mudrunka
828 */
829 class Sklad_UI {
830 function __construct() {
831 $this->db = new Sklad_DB();
832 $this->html = new Sklad_HTML();
833 }
834
835 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
836 return $this->html->render_item_table($this->db->get_listing($class, $id, $limit, $offset, $where, $search, $history, false),$class);
837 }
838
839 function render_form_add($class) {
840 $columns = $this->db->get_columns($class);
841 $selectbox = $this->db->columns_get_selectbox($columns, $class);
842 return $this->html->render_insert_form($class, $columns, $selectbox);
843 }
844
845 function render_form_edit($class, $id, $multi_insert) {
846 $columns = $this->db->get_columns($class);
847 $selectbox = $this->db->columns_get_selectbox($columns, $class);
848 $current = $this->db->get_listing($class, $id, 1);
849 return $this->html->render_insert_form($class, $columns, $selectbox, $current, false, false, $multi_insert);
850 }
851
852 function render_single_record_details($class, $id) {
853 $id_next = $id + 1;
854 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
855 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
856 $html='';
857 $html.= $this->html->link('<<', "$class/$id_prev/");
858 $html.= '-';
859 $html.= $this->html->link('>>', "$class/$id_next/");
860 $html.= '<br />';
861 $html.='<span style="float:right;">'.$this->html->render_barcode(BARCODE_PREFIX.strtoupper("$class/$id")).'</span>';
862 $html.= $this->html->link('edit', "$class/$id/edit/");
863 if($this->db->contains_history($class)) $html.= ' ][ '.$this->html->link('history', "$class/$id/history/");
864 return $html;
865 }
866
867 function render_listing_navigation($class, $id, $limit, $offset) {
868 $offset_next = $offset + $limit;
869 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
870 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
871 $html='';
872 $html.= $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
873 $html.= '-';
874 $html.= $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
875 $html.= '<br />';
876 $html.= $this->html->link('new', "$class/new/$get");
877 return $html;
878 }
879
880 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
881 $html='';
882 if(is_numeric($id)) {
883 $html.=$this->render_single_record_details($class, $id);
884 } else {
885 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
886 }
887 if($edit) {
888 $html.= $this->render_form_edit($class, $id, false);
889 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
890 $html.=$this->html->form($action,'POST',array(
891 array(false,'DELETE','submit'),
892 array('sure', false, 'checkbox', false, false, 'sure?')
893 ));
894 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
895 $html.=$this->html->form($action,'POST',array(
896 array('image', false, 'file', false, 'size="30"'),
897 array(false, 'IMAGE', 'submit')
898 ), "enctype='multipart/form-data'");
899 }
900 return $html;
901 }
902
903 function check_auth() {
904 new HTTP_Auth('WareHouse ['.BACKEND_AUTH.']', true, array($this->db->auth,'check_auth'));
905 }
906
907 function post_redirect_get($location, $message='', $error=false, $translate=true) {
908 $messaget = $translate ? T($message) : $message;
909 $url_args = $messaget != '' ? '?message='.urlencode($messaget) : '';
910 $location = $this->html->internal_url($location).$url_args;
911 header('Location: '.$location);
912 if($error) trigger_error($message);
913 $location=htmlspecialchars($location);
914 die(
915 "<meta http-equiv='refresh' content='0; url=$location'>".
916 $messaget."<br />Location: <a href='$location'>$location</a>"
917 );
918 }
919
920 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
921 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
922 $filename="$dir/$name$ext";
923 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
924 foreach($vars as $var => $val) $$var=$val;
925 ob_start();
926 include($filename);
927 $out=ob_get_contents();
928 ob_end_clean();
929 return $out;
930 }
931
932 function check_input_validity($field, $value='', $ruleset=0) {
933 $rules = array(0 => array(
934 'model_barcode' => '/./',
935 'item_serial' => '/./',
936 'vendor_id' => '/^[0-9]*$/'
937 ));
938 if(isset($rules[$ruleset][$field]) && !preg_match($rules[$ruleset][$field], trim($value))) return false;
939 return true;
940 }
941
942 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
943 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
944 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
945
946 //SephirPOST:
947
948 /* Tenhle foreach() prekopiruje promenne
949 * z: $_POST['values'][$table][$column][$id];
950 * do: $values[$table][$id][$column]
951 */
952 if(isset($_POST['values'])) {
953 $values=array();
954 foreach($_POST['values'] as $table => $columns) {
955 foreach($columns as $column => $ids) {
956 foreach($ids as $id => $val) {
957 $values[$table][$id][$column] = trim($val);
958 if(!$this->check_input_validity($column,$val)) {
959 $message = "Spatny vstup: $column [$id] = \"$val\"; ". //XSS
960 $this->html->link('GO BACK', 'javascript:history.back()', false, false);
961 $this->post_redirect_get('', $message, false, false);
962 }
963 }
964 }
965 }
966 //die(print_r($values));
967 }
968
969 if($action) switch($action) {
970 case 'new':
971 $replace = false;
972 case 'edit':
973 if(!isset($replace)) $replace = true;
974 $table = $class ? $class : 'item';
975 //print_r($values); //debug
976 $last = $this->db->insert_or_update_multitab($values, $replace);
977 $last = $force_redirect ? $force_redirect."?last=$last" : "$table/$last/";
978 $next = "$table/new/";
979 $message = $force_redirect ? '' : 'Hotovo. Další záznam přidáte '.$this->html->link('zde', $next).'.';
980 $this->post_redirect_get($last, $message);
981 break;
982 case 'delete':
983 if(!isset($_POST['sure']) || !$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
984 $this->db->delete($class, $id) || $this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
985 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
986 break;
987 case 'image':
988 $image_classes = array('model'); //TODO, use this more widely across the code
989 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
990 $image_destination = DIR_IMAGES."/$class/$id.jpg";
991 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
992 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
993 chmod ($image_destination, 0664);
994 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
995 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
996 break;
997 default:
998 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
999 break;
1000 }
1001
1002 die('POSTed pyčo!');
1003 }
1004
1005 function process_http_request() {
1006 $this->check_auth();
1007
1008 @ini_set('magic_quotes_gpc' , 'off');
1009 if(get_magic_quotes_gpc()) {
1010 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
1011 }
1012
1013 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
1014 if($PATH_INFO == '' || $PATH_INFO == '/') $PATH_INFO = FRONTEND_PAGE_WELCOME;
1015 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
1016 //Sephirot:
1017 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
1018 if($_SERVER['REQUEST_METHOD'] != 'POST' && $PATH_CHUNKS[1]!='barcode' && $PATH_CHUNKS[1]!='api') //TODO: tyhle podminky naznacujou, ze je v navrhu nejaka drobna nedomyslenost...
1019 echo $this->html->header($PATH_INFO,$this->db->auth->get_user());
1020 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
1021 case 'test': //test
1022 die('Tell me why you cry');
1023 break;
1024 case 'assistant': case 'api': //assistant|api
1025 $incdirs = array(
1026 'assistant' => DIR_ASSISTANTS,
1027 'api' => DIR_APIS
1028 );
1029 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ? trim($PATH_CHUNKS[3]) : false;
1030 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
1031 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
1032 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
1033 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
1034 echo $this->safe_include($incdirs[$PATH_CHUNKS[1]],$PATH_CHUNKS[2],$assistant_vars);
1035 break;
1036 case 'barcode': //barcode
1037 Barcode::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
1038 break;
1039 default: //?
1040 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
1041 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
1042 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
1043 switch($PATH_CHUNKS[2]) {
1044 case 'new': //?/new
1045 $this->process_http_request_post($PATH_CHUNKS[2], $class);
1046 echo $this->render_form_add($class);
1047 break;
1048 default: //?/?
1049 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
1050 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
1051 $edit=false;
1052 switch($PATH_CHUNKS[3]) {
1053 case 'edit': //?/?/edit
1054 case 'image': //?/?/image
1055 case 'delete': //?/?/delete
1056 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
1057 $edit=true;
1058 default: //?/?/?
1059 $history = $PATH_CHUNKS[3] == 'history' ? true : false;
1060 $limit = is_numeric($PATH_CHUNKS[3]) ? (int) $PATH_CHUNKS[3] : FRONTEND_LISTING_LIMIT;
1061 $offset = isset($PATH_CHUNKS[4]) ? (int) $PATH_CHUNKS[4] : 0;
1062 $where = @is_array($_GET['where']) ? $_GET['where'] : false;
1063 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
1064 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
1065 //print_r(array("<pre>",$_SERVER));
1066 break;
1067 }
1068 break;
1069 }
1070 break;
1071 }
1072 }
1073 }
1074
1075 $sklad = new Sklad_UI();
1076 $sklad->process_http_request();
1077
1078 echo('<br style="clear:both;" /><hr />');
This page took 1.18563 seconds and 5 git commands to generate.