Fixnuta drobna bezpecnostni nedoladenost
[mirrors/SokoMan.git] / index.php
CommitLineData
cdfce7c2
TM
1<?php
2/*
3 * SkladovySystem - Storage management system compatible with LMS
78bf26a5 4 * Copyright (C) 2011 Tomas Mudrunka
cdfce7c2
TM
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
20require_once('sklad.conf.php');
5f093236
TM
21set_include_path(DIR_LIB.PATH_SEPARATOR.get_include_path());
22
cdfce7c2
TM
23require_once('Sklad_LMS-fake.class.php');
24require_once('HTTP_Auth.class.php');
326a9fc9 25require_once('Locale.class.php');
81ab8aef 26require_once('Barcode.class.php');
cdfce7c2 27
0a027cc7
TM
28/**
29* Trida poskytuje vseobecne funkce pro generovani HTML kodu
30*
31* Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
32*
33* @package HTML
34* @author Tomas Mudrunka
35*/
36class HTML {
933b760a
TM
37 function row($row,$type=false) {
38 $html = '';
39 if($type) $html.="<$type>";
40 $html.='<tr>';
41 $td = $type == 'thead' ? 'th' : 'td';
0a027cc7
TM
42 foreach($row as $var) {
43 if(trim($var) == '') $var = '&nbsp;';
933b760a 44 $html.="<$td>$var</$td>";
0a027cc7
TM
45 }
46 $html.='</tr>';
933b760a 47 if($type) $html.="</$type>";
0a027cc7
TM
48 return $html;
49 }
50
51 function table(&$table, $params='border=1') {
52 $html="<table $params>";
53 $header=true;
54 foreach($table as $row) {
55 if($header) {
933b760a 56 $html.=$this->row(array_keys($row),'thead');
0a027cc7
TM
57 $header=false;
58 }
59 $html.=$this->row($row);
60 }
61 $html.='</table>';
62 return $html;
63 }
64
81ab8aef 65 function link($title='n/a', $link='#void', $internal=true, $translate=true) {
35916247 66 if($internal && (!isset($link[0]) || $link[0] != '#')) $link = $this->internal_url($link);
81ab8aef
TM
67 if($translate) $title = T($title);
68 return "<a href='$link'>".$title."</a>";
0a027cc7
TM
69 }
70
81ab8aef
TM
71 function img($src='#void', $title='img', $options='width=64') {
72 $options = $options ? " $options" : '';
73 return "<img src='$src' alt='$title' title='$title'$options; />";
0a027cc7
TM
74 }
75
35916247
TM
76 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false, $prefix='') {
77 $html = T($prefix)."<input type='$type' ";
0a027cc7 78 if($name) $html.= "name='$name' ";
326a9fc9
TM
79 if(!is_bool($value)) {
80 if($type == 'submit') $value = T($value);
81 $html.= "value='$value' ";
82 }
0a027cc7
TM
83 if($options) $html.= "$options ";
84 if($placeholder) $html.= "placeholder='$placeholder' ";
85 $html .= '/>';
86 return $html;
87 }
88
35916247
TM
89 function form($action=false, $method=false, $inputs, $options=false) {
90 $action = $action ? " action='$action'" : '';
91 $method = $method ? " method='$method'" : '';
92 $options = $options ? " $options" : '';
93 $html = "<form$action$method$options>";
94 foreach($inputs as $input) $html .= call_user_func_array(array($this,'input'), $input);
95 $html .= "</form>";
96 return $html;
97 }
98
0a027cc7
TM
99 function select($name, $selectbox, $default=false) {
100 //echo('<pre>'); print_r($selectbox);
101 $html = "<select name='$name'>";
102
103 if($default) {
104 $value=$default; $title=$selectbox[$value];
105 $html .= "<option value='$value'>$value :: $title</option>";
106 unset($selectbox[$value]);
107 }
108 foreach($selectbox as $value => $title) {
109 $html .= "<option value='$value'>$value :: $title</option>";
110 }
111 $html .= "</select>";
112 return $html;
113 }
35916247
TM
114
115 function ul($items,$tag=ul,$head='',$class=false) {
116 $class = $class ? " class='$class'" : '';
117 $html = "$head<$tag$class>";
118 foreach($items as $key => $value) {
119 $html .= '<li>';
120 if(is_numeric($key)) {
121 $html .= $value;
122 } else {
123 $html .= $this->link($key,$value);
124 }
125 $html .= '</li>';
126 }
127 $html .= "</$tag>";
128 return $html;
129 }
130
131 function div($html, $options) {
132 $options = $options ? " $options" : '';
133 return "<div$options>$html</div>";
134 }
ec106ddf
TM
135
136 function head($title=false,$charset='UTF-8',$more='') {
137 $title = $title ? "\n<title>$title</title>" : '';
138 $html= '<head>';
139 $html.= '<meta http-equiv="Content-Type" content="text/html; charset='.$charset.'" />'.$title.$more;
140 $html.= '</head>';
141 return $html;
142 }
0a027cc7
TM
143}
144
78bf26a5
TM
145/**
146* Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
147*
fc5c5b8b
TM
148* Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
149*
78bf26a5
TM
150* @package Sklad_HTML
151* @author Tomas Mudrunka
152*/
35916247 153class Sklad_HTML extends HTML { //TODO: Split into few more methods
fc5c5b8b 154 function header($title='') {
cdfce7c2
TM
155 $home = URL_HOME;
156 $script = $_SERVER['SCRIPT_NAME'];
d9384cb5 157 $search = htmlspecialchars(@trim($_GET['q']));
64f31c54 158 $message = strip_tags(@trim($_GET['message']),'<a><b><u><i>');
ac2ed3a1 159 $instance = INSTANCE_ID != '' ? '/'.INSTANCE_ID : '';
35916247 160 //$title = T($title); //TODO
ec106ddf
TM
161
162 $html = $this->head("SōkoMan$title");
163 $html .= <<<EOF
ac2ed3a1 164<h1><a href="$script/">SōkoMan</a><small>$instance$title</small></h1>
c9759229
TM
165
166<style type="text/css">
ac2ed3a1 167* { font-family: arial; }
933b760a
TM
168td,body { background-color: white; }
169table { background-color: orange; border: orange; }
d0e7939c 170a, a img { text-decoration:none; color: darkblue; border:none; }
933b760a 171li a, a:hover { text-decoration:underline; }
ac2ed3a1 172
7bcd6b42 173.menu li {
c9759229 174 float: left;
7bcd6b42
TM
175 padding: 0.2em;
176}
177
178.menu * li {
179 float: none;
c9759229
TM
180}
181
182.menu * menu {
183 position: absolute;
7bcd6b42 184 padding: 0.2em;
c9759229
TM
185}
186
187.menu, .menu * menu {
188 list-style: none;
189}
190
191.menu * menu {
7bcd6b42 192 border: 1px solid orange;
c9759229
TM
193 display: none;
194 margin: 0;
195}
196
7bcd6b42 197.menu li:hover menu, .menu li:hover {
c9759229 198 display: block;
7bcd6b42 199 background-color: yellow;
c9759229 200}
7bcd6b42 201
c9759229
TM
202</style>
203
cdfce7c2 204<div>
35916247
TM
205EOF;
206
207 $assistants=array();
208 foreach(scandir(DIR_ASSISTANTS) as $item) {
209 if($item == '.' || $item == '..') continue;
210 $item = preg_replace('/\.inc\.php$/','',$item);
211 $assistants[$item] = "assistant/$item";
212 }
213
214 $tables=array('item','model','category','producer','vendor','room','status');
215
216 foreach($tables as $table) {
217 $listable[$table] = $table;
218 $insertable[$table] = "$table/new";
219 }
220
221 $html .= $this->ul(array(
35916247 222 'Home' => '',
ec106ddf 223 'Logout' => '?logout',
35916247 224 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
ec106ddf
TM
225 1 => $this->ul($insertable,'menu',$this->link('New','#')),
226 2 => $this->ul($listable,'menu',$this->link('List','#'))
35916247
TM
227 ),'menu', '', 'menu');
228
229 $html .= '<div style="float: right;">';
230
231 $html .= $this->form("$script/assistant/go", 'GET', array(
81ab8aef 232 array('q','','text','smart id...', 'autofocus'),
35916247
TM
233 array(false,'go','submit')
234 ), 'style="float: left;"');
235
236 $html .= $this->form('?', 'GET', array(
237 array('q',$search,'text','regexp...'),
238 array(false,'filter','submit')
239 ), 'style="float: left;"');
240
241 $html .= '</div>';
242
243 $html .= <<<EOF
cdfce7c2 244</div>
c9759229 245<hr style="clear: both;" />
d9384cb5
TM
246<div style="background-color:#FFDDDD;">
247 <font color="red">$message</font>
248</div>
cdfce7c2 249EOF;
35916247
TM
250
251 return $html;
cdfce7c2
TM
252 }
253
d9384cb5
TM
254 function internal_url($link) {
255 return $_SERVER['SCRIPT_NAME'].'/'.$link;
256 }
257
cdfce7c2
TM
258 function table_add_images(&$table) {
259 $image = array('model_id');
260 foreach($table as $id => $row) {
261 foreach($image as $column) if(isset($table[$id][$column])) {
262 $type = @array_shift(preg_split('/_/', $column));
263 $src=URL_IMAGES."/$type/".$table[$id][$column].'.jpg';
264 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
265 }
266 }
267 }
268
81ab8aef
TM
269 function render_barcode($barcode,$opts=false) {
270 return $this->link($this->img($this->internal_url("barcode/$barcode"),$barcode,$opts),"barcode/$barcode",true,false);
271 }
272
273 function table_add_barcodes(&$table) {
274 $image = array('model_barcode', 'item_serial');
275 foreach($table as $id => $row) {
276 foreach($image as $column) if(isset($table[$id][$column])) {
277 $table[$id][$column]=$this->render_barcode($table[$id][$column]);
278 }
279 }
280 }
281
cdfce7c2
TM
282 function table_collapse(&$table) {
283 $collapse = array(
284 'item_id' => 'item_id',
285 'model_id' => 'model_name',
286 'category_id' => 'category_name',
287 'producer_id' => 'producer_name',
288 'vendor_id' => 'vendor_name',
289 'room_id' => 'room_name',
290 'status_id' => 'status_name',
291 );
292 foreach($table as $id => $row) {
293 foreach($collapse as $link => $title)
fff6ce40 294 if(isset($table[$id][$link]) && isset($row[$title])) {
cdfce7c2
TM
295 $type = @array_shift(preg_split('/_/', $link));
296 if($link != $title) unset($table[$id][$link]);
297 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
298 }
299 }
300 }
301
302 function table_sort(&$table) {
303 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
304 $table_sorted = array();
305 foreach($table as $id => $row) {
306 $table_sorted[$id] = array();
307 foreach($precedence as $column) if(isset($table[$id][$column])) {
326a9fc9 308 $table_sorted[$id][T($column)]=$table[$id][$column];
cdfce7c2
TM
309 unset($table[$id][$column]);
310 }
326a9fc9
TM
311 //$table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
312 foreach($table[$id] as $key => $val) $table_sorted[$id][T($key)] = $val; //array_merge with T() translating
cdfce7c2
TM
313 }
314 $table = $table_sorted;
315 }
316
fc5c5b8b 317 function render_item_table($table) {
cdfce7c2 318 $this->table_add_images($table);
81ab8aef 319 $this->table_add_barcodes($table);
cdfce7c2
TM
320 $this->table_collapse($table);
321 $this->table_sort($table);
fc5c5b8b 322 return $this->table($table);
cdfce7c2
TM
323 }
324
d0e7939c
TM
325 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
326 $html = '';
cdfce7c2 327 foreach($columns as $column) {
326a9fc9 328 $html.=T($class).':<b>'.T($column['Field']).'</b>: ';
7d20381f 329 $name="values[$class][".$column['Field'].'][]';
16261142 330 $val = $update && isset($current[$column['Field']]) ? $current[$column['Field']] : false;
cdfce7c2 331 switch(true) {
a084118b 332 case (preg_match('/auto_increment/', $column['Extra']) || in_array($column['Field'], $hidecols)):
e9cb8cea 333 if(!$val) $val = '';
fc5c5b8b
TM
334 $html.=$this->input($name, $val, 'hidden');
335 $html.=$val.'(AUTO)';
cdfce7c2
TM
336 break;
337 case isset($selectbox[$column['Field']]):
e9cb8cea 338 $html.=$this->select($name,$selectbox[$column['Field']],$val);
cdfce7c2
TM
339 break;
340 default:
fc5c5b8b 341 $html.=$this->input($name, $val);
cdfce7c2
TM
342 break;
343 }
fc5c5b8b 344 $html.='<br />';
cdfce7c2 345 }
d0e7939c
TM
346 return $html;
347 }
cdfce7c2 348
d0e7939c
TM
349 function render_insert_form_multi($array) {
350 $html = '';
351 $head=false;
352
353 foreach($array as $key => $args) {
354 $parts=array('inputs');
355 if(!$head) { $head = true;
356 $parts[]='head';
357 }
358 if(!isset($array[$key+1])) {
359 $parts[]='foot';
5b0075fa
TM
360 $hr = '';
361 } else $hr = '<hr />';
362 //$args[] = false;
d0e7939c
TM
363 $args[] = $parts;
364 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
5b0075fa 365 $html .= $hr;
d0e7939c
TM
366 }
367 return $html;
368 }
369
370 function render_insert_form($class, $columns, $selectbox=array(), $current=false, $hidecols=false, $action=false, $multi_insert=true, $parts=false) {
371 $html = '';
372 //print_r($parts);
373 //echo('<pre>'); print_r($selectbox);
374 //echo('<pre>'); print_r($current);
375 $update = false;
376 if(is_array($current)) {
377 $update = true;
378 $current = array_shift($current);
379 }
380
381 if(!is_array($hidecols)) $hidecols = array();
382 $hidecols = array_merge($hidecols, array('item_author', 'item_valid_from', 'item_valid_till')); //TODO Autodetect
383
384 if(!is_array($parts) || in_array('head', $parts)) {
385 $action = $action ? " action='$action'" : false;
386 $html.="<form$action method='POST'>"; //TODO: use $this->form()
5b0075fa 387 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
cdfce7c2
TM
388 }
389
d0e7939c
TM
390 if(!is_array($parts) || in_array('inputs', $parts))
391 $html.=$this->render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update);
392
393 if(!is_array($parts) || in_array('foot', $parts)) {
5b0075fa 394 $html .= '</div></span><br style="clear:both" />';
d0e7939c
TM
395 if($multi_insert) { //TODO, move to separate JS file
396 $html.=<<<EOF
d0e7939c
TM
397 <script>
398 function duplicate_element(what, where) {
399 var node = document.getElementsByName(what)[0];
400 node.parentNode.appendChild(node.cloneNode(true));
401 }
402 </script>
403 <a href='#' onClick="duplicate_element('input_set')">+</a>
404EOF;
405 }
406
407 $btn = is_array($current) ? 'UPDATE' : 'INSERT'; //TODO: $current may be set even when inserting...
408 $html.=$this->input(false, $btn, 'submit');
409 $html.='</form>';
410 }
fc5c5b8b 411 return $html;
cdfce7c2
TM
412 }
413}
414
78bf26a5
TM
415/**
416* Trida poskytuje rozhrani k databazi skladu
417*
418* @package Sklad_DB
419* @author Tomas Mudrunka
420*/
cdfce7c2
TM
421class Sklad_DB extends PDO {
422 function __construct() {
423 $this->lms = new Sklad_LMS();
424
425 parent::__construct(
426 DB_DSN, DB_USER, DB_PASS,
427 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") //Force UTF8 for MySQL
428 );
429 }
430
431 function escape($str) {
432 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
433 }
434
cb8a6861 435 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
2bedfdac 436 //Configuration
cdfce7c2
TM
437 $join = array(
438 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
439 'model' => array('category', 'producer')
9ea191cb 440 ); //TODO Autodetect using foreign keys?
cdfce7c2 441 $search_fields = array(
df4079a6 442 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name')
9ea191cb 443 ); //TODO Autodetect
2bedfdac
TM
444
445 //Escaping
446 $class = $this->escape($class);
447
448 //SELECT
cdfce7c2 449 $sql="SELECT * FROM $class\n";
2bedfdac 450 //JOIN
8fd613d6 451 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$suffix_id)\n";
2bedfdac 452 //WHERE/REGEXP
cdfce7c2
TM
453 if($search) {
454 $search = $this->quote($search);
326a9fc9 455 if(!isset($search_fields[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
5895162b
TM
456 $sql_search = '';
457 foreach($search_fields[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
458 $where[] = "FALSE $sql_search";
cb8a6861
TM
459 } elseif($id) $where[] = "$class$suffix_id = $id";
460 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
461
5895162b 462 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
117817be
TM
463 //ORDER
464 if(!$order) $order = $class.$suffix_id;
465 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
466 $sql .= "ORDER BY $order\n";
2bedfdac 467 //LIMIT/OFFSET
cdfce7c2
TM
468 if($limit) {
469 $limit = $this->escape((int)$limit);
470 $offset = $this->escape((int)$offset);
471 $sql .= "LIMIT $offset,$limit\n";
472 }
2bedfdac 473
cdfce7c2
TM
474 return $sql;
475 }
476
66b6f4d6 477 function safe_query($sql, $fatal=true) {
cdfce7c2
TM
478 $result = $this->query($sql);
479 if(!$result) {
2bedfdac 480 $error = $this->errorInfo();
66b6f4d6
TM
481 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>");
482 if($fatal) die();
cdfce7c2
TM
483 }
484 return $result;
485 }
486
326a9fc9
TM
487 function translate_query_results($result) {
488 $translate_cols = array('status_name', 'item_valid_till'); //TODO: Hardcoded
489 foreach($result as $key => $row) {
490 foreach($translate_cols as $col) if(isset($result[$key][$col])){
491 $result[$key][$col] = T($result[$key][$col]);
492 }
493 }
494 return $result;
495 }
496
497 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO::FETCH_ASSOC, $translate=true) {
498 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
499 if($translate) $result = $this->translate_query_results($result);
500 return $result;
501 }
502
503
cb8a6861
TM
504 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
505 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
326a9fc9 506 $result = $this->safe_query_fetch($sql);
cdfce7c2
TM
507 if(!$result || !is_array($indexed)) return $result;
508
509 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
510 return $indexed;
511 }
512
d0e7939c 513 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
cdfce7c2
TM
514 $class = $this->escape($class);
515 $sql = "SHOW COLUMNS FROM $class;";
d0e7939c
TM
516 $columns = $this->safe_query_fetch($sql);
517 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
518 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
519 }*/
520 return $columns;
cdfce7c2
TM
521 }
522
523 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
524 $selectbox=array();
525 foreach($columns as $column) {
66b6f4d6 526 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)!
cdfce7c2
TM
527 if($class && $column['Field'] == $class.$suffix_id) continue;
528 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
529 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
66b6f4d6 530
117817be 531 $history = $this->contains_history($table) ? " WHERE ${table}_valid_till=0" : '';
b4dcae05 532 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
326a9fc9 533 $result = $this->safe_query_fetch($sql, false);
66b6f4d6 534 if(!$result) continue;
cdfce7c2
TM
535 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
536 }
537 //echo('<pre>'); print_r($selectbox);
66b6f4d6 538 return array_filter($selectbox, 'ksort');
9ea191cb
TM
539 }
540
d0e7939c 541 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
16261142
TM
542 $history = $this->contains_history($table) ? " AND ${table}_valid_till=0" : '';
543 $value=$this->quote($value);
544 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
326a9fc9 545 $result = $this->safe_query_fetch($sql);
d0e7939c 546 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
16261142
TM
547 }
548
9ea191cb
TM
549 function contains_history($table) {
550 $history_tables = array('item'); //TODO Autodetect
551 return in_array($table, $history_tables);
cdfce7c2
TM
552 }
553
554 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
b66fadbb
TM
555 //Init
556 $history = $this->contains_history($table);
557
9ea191cb 558 //Escaping
cdfce7c2
TM
559 $table = $this->escape($table);
560
561 //Get list of POSTed columns
aa3fd0a8
TM
562 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
563 $columns = implode(',',$columns_array);
cdfce7c2 564
9fb856ba 565 //Build query
b66fadbb 566 $sql = '';
b66fadbb
TM
567 //echo('<pre>'); die(print_r($values));
568
569 if($history) {
570 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
571 if($history_update) {
572 $sql .= "UPDATE $table";
117817be
TM
573 $sql .= " SET ${table}_valid_till=NOW()";
574 $sql .= " WHERE ${table}_valid_till=0 AND (";
b66fadbb
TM
575 $or = '';
576 foreach($values as $row) {
5b0075fa 577 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
b66fadbb
TM
578 $or = ' OR';
579 }
580 $sql .= " );\n\n";
581 $replace = false;
582 }
583 }
584
cdfce7c2 585 //Insert into table (columns)
aa3fd0a8 586 $sql .= "INSERT INTO $table ($columns) VALUES ";
cdfce7c2
TM
587
588 //Values (a,b,c),(d,e,f)
589 $comma='';
590 foreach($values as $row) {
9fb856ba
TM
591 $row_quoted = array_map(array($this,'quote'), $row); //Check
592 if($history) {
b66fadbb
TM
593 foreach($row as $column => $value) {
594 switch($column) {
595 case $table.'_valid_from':
596 $row_quoted[$column] = 'NOW()';
597 break;
598 case $table.'_valid_till':
599 $row_quoted[$column] = '0';
600 break;
9fb856ba
TM
601 case $table.'_author':
602 $row_quoted[$column] = $this->lms->get_authorized_user_id();
b66fadbb
TM
603 //die($this->lms->get_authorized_user_id().'=USER');
604 break;
b66fadbb
TM
605 }
606 }
607 }
608 $sql .= $comma.'('.implode(',',$row_quoted).')';
cdfce7c2
TM
609 $comma = ',';
610 }
611
aa3fd0a8
TM
612 //On duplicate key
613 if($replace) {
614 foreach($columns_array as $col) {
615 if($col == $table.'_id' || $col == $table.'_valid_till') continue;
616 $on_duplicate[] = "$col=VALUES($col)";
617 }
618 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
619 }
620
cdfce7c2
TM
621 //Terminate
622 $sql .= ';';
623 return $sql;
624 }
625
b4dcae05
TM
626 function insert_or_update($table, $values, $replace=true) {
627 $sql = $this->build_query_insert($table, $values, $replace);
cdfce7c2
TM
628 $this->safe_query($sql);
629 return $this->lastInsertId();
630 }
631
b4dcae05 632 function insert_or_update_multitab($values, $replace=true) {
371a86f4 633 $last=false;
b4dcae05 634 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
371a86f4
TM
635 return $last;
636 }
637
cdfce7c2 638 function delete($table, $id, $suffix_id='_id') {
64f31c54 639 if($this->contains_history($table)) return false;
cdfce7c2
TM
640 $key = $this->escape($table.$suffix_id);
641 $table = $this->escape($table);
642 $id = $this->quote($id);
643 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
644 }
645}
646
0a027cc7
TM
647/**
648* Trida poskytuje high-level rozhrani k databazi skladu
649*
650* @package Sklad_DB_Abstract
651* @author Tomas Mudrunka
652*/
653class Sklad_DB_Abstract extends Sklad_DB {
654 //TODO Code
655}
656
78bf26a5
TM
657/**
658* Trida implementuje uzivatelske rozhrani skladu
659*
660* Example usage:
661* $sklad = new Sklad_UI();
662* $sklad->process_http_request();
663*
664* @package Sklad_UI
665* @author Tomas Mudrunka
666*/
cdfce7c2
TM
667class Sklad_UI {
668 function __construct() {
669 $this->db = new Sklad_DB();
670 $this->html = new Sklad_HTML();
671 }
672
cb8a6861
TM
673 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
674 return $this->html->render_item_table($this->db->get_listing($class, $id, $limit, $offset, $where, $search, $history, false));
cdfce7c2
TM
675 }
676
a25f85f8 677 function render_form_add($class) {
cdfce7c2
TM
678 $columns = $this->db->get_columns($class);
679 $selectbox = $this->db->columns_get_selectbox($columns, $class);
a25f85f8 680 return $this->html->render_insert_form($class, $columns, $selectbox);
cdfce7c2
TM
681 }
682
a25f85f8 683 function render_form_edit($class, $id) {
cdfce7c2
TM
684 $columns = $this->db->get_columns($class);
685 $selectbox = $this->db->columns_get_selectbox($columns, $class);
117817be 686 $current = $this->db->get_listing($class, $id, 1);
a25f85f8 687 return $this->html->render_insert_form($class, $columns, $selectbox, $current);
cdfce7c2
TM
688 }
689
a25f85f8 690 function render_single_record_details($class, $id) {
cdfce7c2
TM
691 $id_next = $id + 1;
692 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
693 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
a25f85f8
TM
694 $html='';
695 $html.= $this->html->link('<<', "$class/$id_prev/");
696 $html.= '-';
697 $html.= $this->html->link('>>', "$class/$id_next/");
698 $html.= '<br />';
54694117 699 $html.='<span style="float:right;">'.$this->html->render_barcode(BARCODE_PREFIX.strtoupper("$class/$id")).'</span>';
a25f85f8 700 $html.= $this->html->link('edit', "$class/$id/edit/");
9fb856ba 701 if($this->db->contains_history($class)) $html.= ' ][ '.$this->html->link('history', "$class/$id/history/");
a25f85f8 702 return $html;
cdfce7c2
TM
703 }
704
a25f85f8 705 function render_listing_navigation($class, $id, $limit, $offset) {
cdfce7c2
TM
706 $offset_next = $offset + $limit;
707 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
708 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
a25f85f8
TM
709 $html='';
710 $html.= $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
711 $html.= '-';
712 $html.= $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
713 $html.= '<br />';
714 $html.= $this->html->link('new', "$class/new/$get");
715 return $html;
cdfce7c2
TM
716 }
717
a25f85f8
TM
718 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
719 $html='';
cdfce7c2 720 if(is_numeric($id)) {
a25f85f8 721 $html.=$this->render_single_record_details($class, $id);
cdfce7c2 722 } else {
a25f85f8 723 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
cdfce7c2
TM
724 }
725 if($edit) {
a25f85f8 726 $html.= $this->render_form_edit($class, $id);
cdfce7c2 727 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
35916247
TM
728 $html.=$this->html->form($action,'POST',array(
729 array(false,'DELETE','submit'),
730 array('sure', false, 'checkbox', false, false, 'sure?')
731 ));
cdfce7c2 732 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
35916247
TM
733 $html.=$this->html->form($action,'POST',array(
734 array('image', false, 'file', false, 'size="30"'),
735 array(false, 'IMAGE', 'submit')
736 ), "enctype='multipart/form-data'");
cdfce7c2 737 }
a25f85f8 738 return $html;
cdfce7c2
TM
739 }
740
741 function check_auth() {
742 new HTTP_Auth('SkladovejSystem', true, array($this->db->lms,'check_auth'));
743 }
744
64f31c54 745 function post_redirect_get($location, $message='', $error=false) {
326a9fc9 746 $url_args = $message != '' ? '?message='.urlencode(T($message)) : '';
8acef003 747 $location = $this->html->internal_url($location).$url_args;
1f74892d 748 header('Location: '.$location);
64f31c54 749 if($error) trigger_error($message);
7efdf72a
TM
750 $location=htmlspecialchars($location);
751 die(
752 "<meta http-equiv='refresh' content='0; url=$location'>".
326a9fc9 753 T($message)."<br />Location: <a href='$location'>$location</a>"
7efdf72a 754 );
cdfce7c2
TM
755 }
756
623c65e2 757 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
64f31c54 758 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
3e6c412e 759 $filename="$dir/$name$ext";
64f31c54 760 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
623c65e2 761 foreach($vars as $var => $val) $$var=$val;
3e6c412e
TM
762 ob_start();
763 include($filename);
764 $out=ob_get_contents();
765 ob_end_clean();
766 return $out;
767 }
768
bda4a4be 769 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
cdfce7c2 770 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
1f74892d 771 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
cdfce7c2
TM
772
773 //SephirPOST:
371a86f4
TM
774
775 /* Tenhle foreach() prekopiruje promenne
7d20381f 776 * z: $_POST['values'][$table][$column][$id];
371a86f4
TM
777 * do: $values[$table][$id][$column]
778 */
7d20381f
TM
779 if(isset($_POST['values'])) {
780 $values=array();
781 foreach($_POST['values'] as $table => $columns) {
782 foreach($columns as $column => $ids) {
783 foreach($ids as $id => $val) $values[$table][$id][$column] = $val;
784 }
cdfce7c2 785 }
7d20381f 786 //die(print_r($values));
cdfce7c2
TM
787 }
788
789 if($action) switch($action) {
790 case 'new':
b4dcae05 791 $replace = false;
cdfce7c2 792 case 'edit':
b4dcae05 793 if(!isset($replace)) $replace = true;
64f31c54 794 $table = $class ? $class : 'item';
cdfce7c2 795 //print_r($values); //debug
b4dcae05 796 $last = $this->db->insert_or_update_multitab($values, $replace);
bda4a4be 797 $last = $force_redirect ? $force_redirect."?last=$last" : "$table/$last/";
d9384cb5 798 $next = "$table/new/";
bda4a4be
TM
799 $message = $force_redirect ? '' : 'Hotovo. Další záznam přidáte '.$this->html->link('zde', $next).'.';
800 $this->post_redirect_get($last, $message);
cdfce7c2
TM
801 break;
802 case 'delete':
64f31c54
TM
803 if(!isset($_POST['sure']) || !$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
804 $this->db->delete($class, $id) || $this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
1f74892d 805 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
cdfce7c2
TM
806 break;
807 case 'image':
808 $image_classes = array('model'); //TODO, use this more widely across the code
64f31c54 809 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
cdfce7c2 810 $image_destination = DIR_IMAGES."/$class/$id.jpg";
326a9fc9 811 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
cdfce7c2 812 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
1f74892d 813 chmod ($image_destination, 0664);
326a9fc9
TM
814 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
815 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
cdfce7c2
TM
816 break;
817 default:
326a9fc9 818 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
cdfce7c2
TM
819 break;
820 }
821
822 die('POSTed pyčo!');
823 }
824
825 function process_http_request() {
826 $this->check_auth();
827
828 @ini_set('magic_quotes_gpc' , 'off');
829 if(get_magic_quotes_gpc()) {
830 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
831 }
832
833 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
cdfce7c2 834 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
81ab8aef 835 //Sephirot:
cdfce7c2 836 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
81ab8aef
TM
837 if($_SERVER['REQUEST_METHOD'] != 'POST' && $PATH_CHUNKS[1]!='barcode') echo $this->html->header($PATH_INFO); //TODO: tyhle podminky naznacujou, ze je v navrhu nejaka drobna nedomyslenost...
838 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
cdfce7c2
TM
839 case 'test': //test
840 die('Tell me why you cry');
841 break;
3e6c412e 842 case 'assistant': //assistant
de77377e
TM
843 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ? trim($PATH_CHUNKS[3]) : false;
844 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
845 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
846 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
5ef6c52f 847 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
623c65e2 848 echo $this->safe_include(DIR_ASSISTANTS,$PATH_CHUNKS[2],$assistant_vars);
3e6c412e 849 break;
81ab8aef
TM
850 case 'barcode': //barcode
851 Barcode::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
852 break;
cdfce7c2
TM
853 default: //?
854 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
855 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
856 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
857 switch($PATH_CHUNKS[2]) {
858 case 'new': //?/new
859 $this->process_http_request_post($PATH_CHUNKS[2], $class);
a25f85f8 860 echo $this->render_form_add($class);
cdfce7c2
TM
861 break;
862 default: //?/?
863 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
864 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
865 $edit=false;
866 switch($PATH_CHUNKS[3]) {
867 case 'edit': //?/?/edit
9fb856ba
TM
868 case 'image': //?/?/image
869 case 'delete': //?/?/delete
cdfce7c2
TM
870 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
871 $edit=true;
872 default: //?/?/?
9fb856ba 873 $history = $PATH_CHUNKS[3] == 'history' ? true : false;
cdfce7c2
TM
874 $limit = (int) (isset($PATH_CHUNKS[3]) ? $PATH_CHUNKS[3] : '0');
875 $offset = (int) (isset($PATH_CHUNKS[4]) ? $PATH_CHUNKS[4] : '0');
cb8a6861
TM
876 $where = false; //TODO get from URL
877 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
a25f85f8 878 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
cdfce7c2
TM
879 //print_r(array("<pre>",$_SERVER));
880 break;
881 }
882 break;
883 }
884 break;
885 }
886 }
887}
888
889$sklad = new Sklad_UI();
890$sklad->process_http_request();
891
54694117 892echo('<br style="clear:both;" /><hr />');
This page took 0.852003 seconds and 4 git commands to generate.