Pridano nacitani WHERE z URL
[mirrors/SokoMan.git] / index.php
... / ...
CommitLineData
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
20require_once('sklad.conf.php');
21set_include_path(DIR_LIB.PATH_SEPARATOR.get_include_path());
22
23require_once('Sklad_LMS-fake.class.php');
24require_once('HTTP_Auth.class.php');
25require_once('Locale.class.php');
26require_once('Barcode.class.php');
27
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 {
37 function row($row,$type=false) {
38 $html = '';
39 if($type) $html.="<$type>";
40 $html.='<tr>';
41 $td = $type == 'thead' ? 'th' : 'td';
42 foreach($row as $var) {
43 if(trim($var) == '') $var = '&nbsp;';
44 $html.="<$td>$var</$td>";
45 }
46 $html.='</tr>';
47 if($type) $html.="</$type>";
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) {
56 $html.=$this->row(array_keys($row),'thead');
57 $header=false;
58 }
59 $html.=$this->row($row);
60 }
61 $html.='</table>';
62 return $html;
63 }
64
65 function link($title='n/a', $link='#void', $internal=true, $translate=true) {
66 if($internal && (!isset($link[0]) || $link[0] != '#')) $link = $this->internal_url($link);
67 if($translate) $title = T($title);
68 return "<a href='$link'>".$title."</a>";
69 }
70
71 function img($src='#void', $title='img', $options='width=64') {
72 $options = $options ? " $options" : '';
73 return "<img src='$src' alt='$title' title='$title'$options; />";
74 }
75
76 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false, $prefix='') {
77 $html = T($prefix)."<input type='$type' ";
78 if($name) $html.= "name='$name' ";
79 if(!is_bool($value)) {
80 if($type == 'submit') $value = T($value);
81 $html.= "value='$value' ";
82 }
83 if($options) $html.= "$options ";
84 if($placeholder) $html.= "placeholder='$placeholder' ";
85 $html .= '/>';
86 return $html;
87 }
88
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
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 }
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 }
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 }
143}
144
145/**
146* Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
147*
148* Tato trida by nemela sama nic vypisovat (vyjma chybovych a debugovacich hlasek)!
149*
150* @package Sklad_HTML
151* @author Tomas Mudrunka
152*/
153class Sklad_HTML extends HTML { //TODO: Split into few more methods
154 function header($title='') {
155 $home = URL_HOME;
156 $script = $_SERVER['SCRIPT_NAME'];
157 $search = htmlspecialchars(@trim($_GET['q']));
158 $message = strip_tags(@trim($_GET['message']),'<a><b><u><i>');
159 $instance = INSTANCE_ID != '' ? '/'.INSTANCE_ID : '';
160 //$title = T($title); //TODO
161
162 $html = $this->head("SōkoMan$title");
163 $html .= <<<EOF
164<h1><a href="$script/">SōkoMan</a><small>$instance$title</small></h1>
165
166<style type="text/css">
167* { font-family: arial; }
168td,body { background-color: white; }
169table { background-color: orange; border: orange; }
170a, a img { text-decoration:none; color: darkblue; border:none; }
171li a, a:hover { text-decoration:underline; }
172
173.menu li {
174 float: left;
175 padding: 0.2em;
176}
177
178.menu * li {
179 float: none;
180}
181
182.menu * menu {
183 position: absolute;
184 padding: 0.2em;
185}
186
187.menu, .menu * menu {
188 list-style: none;
189}
190
191.menu * menu {
192 border: 1px solid orange;
193 display: none;
194 margin: 0;
195}
196
197.menu li:hover menu, .menu li:hover {
198 display: block;
199 background-color: yellow;
200}
201
202</style>
203
204<div>
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(
222 'Home' => '',
223 'Logout' => '?logout',
224 0 => $this->ul($assistants,'menu',$this->link('Assistants','#')),
225 1 => $this->ul($insertable,'menu',$this->link('New','#')),
226 2 => $this->ul($listable,'menu',$this->link('List','#'))
227 ),'menu', '', 'menu');
228
229 $html .= '<div style="float: right;">';
230
231 $html .= $this->form("$script/assistant/go", 'GET', array(
232 array('q','','text','smart id...', 'autofocus'),
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
244</div>
245<hr style="clear: both;" />
246<div style="background-color:#FFDDDD;">
247 <font color="red">$message</font>
248</div>
249EOF;
250
251 return $html;
252 }
253
254 function internal_url($link) {
255 return $_SERVER['SCRIPT_NAME'].'/'.$link;
256 }
257
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
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
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)
294 if(isset($table[$id][$link]) && isset($row[$title])) {
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])) {
308 $table_sorted[$id][T($column)]=$table[$id][$column];
309 unset($table[$id][$column]);
310 }
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
313 }
314 $table = $table_sorted;
315 }
316
317 function render_item_table($table) {
318 $this->table_add_images($table);
319 $this->table_add_barcodes($table);
320 $this->table_collapse($table);
321 $this->table_sort($table);
322 return $this->table($table);
323 }
324
325 function render_insert_inputs($class,$columns,$selectbox,$current,$hidecols,$update) {
326 $html = '';
327 foreach($columns as $column) {
328 $html.=T($class).':<b>'.T($column['Field']).'</b>: ';
329 $name="values[$class][".$column['Field'].'][]';
330 $val = $update && isset($current[$column['Field']]) ? $current[$column['Field']] : false;
331 switch(true) {
332 case (preg_match('/auto_increment/', $column['Extra']) || in_array($column['Field'], $hidecols)):
333 if(!$val) $val = '';
334 $html.=$this->input($name, $val, 'hidden');
335 $html.=$val.'(AUTO)';
336 break;
337 case isset($selectbox[$column['Field']]):
338 $html.=$this->select($name,$selectbox[$column['Field']],$val);
339 break;
340 default:
341 $html.=$this->input($name, $val);
342 break;
343 }
344 $html.='<br />';
345 }
346 return $html;
347 }
348
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';
360 $hr = '';
361 } else $hr = '<hr />';
362 //$args[] = false;
363 $args[] = $parts;
364 $html .= call_user_func_array(array($this, 'render_insert_form'), $args);
365 $html .= $hr;
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()
387 $html.='<span><div name="input_set" style="float:left; border:1px solid grey; padding: 1px; margin: 1px;">';
388 }
389
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)) {
394 $html .= '</div></span><br style="clear:both" />';
395 if($multi_insert) { //TODO, move to separate JS file
396 $html.=<<<EOF
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 }
411 return $html;
412 }
413}
414
415/**
416* Trida poskytuje rozhrani k databazi skladu
417*
418* @package Sklad_DB
419* @author Tomas Mudrunka
420*/
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
435 function build_query_select($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $order=false, $suffix_id='_id') {
436 //Configuration
437 $join = array(
438 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
439 'model' => array('category', 'producer')
440 ); //TODO Autodetect using foreign keys?
441 $search_fields = array(
442 'item' => array('item_id','item_serial','model_name','model_barcode','model_descript','producer_name','vendor_name')
443 ); //TODO Autodetect
444
445 //Init
446 if(is_array($where)) foreach($where as $key => $value) $where[$key] = $key.' '.$value; //TODO: escape SQLi!!!
447
448 //Escaping
449 $class = $this->escape($class);
450
451 //SELECT
452 $sql="SELECT * FROM $class\n";
453 //JOIN
454 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$suffix_id)\n";
455 //WHERE/REGEXP
456 if($search) {
457 $search = $this->quote($search);
458 if(!isset($search_fields[$class])) die(trigger_error(T("Can't search in $class table yet :-("))); //TODO: post_redirect_get
459 $sql_search = '';
460 foreach($search_fields[$class] as $column) $sql_search .= "OR $column REGEXP $search ";
461 $where[] = "FALSE $sql_search";
462 } elseif($id) $where[] = "$class$suffix_id = $id";
463 if(!$history && $this->contains_history($class)) $where[] = $class.'_valid_till=0';
464
465 if($where) $sql .= 'WHERE ('.implode(') AND (', $where).")\n";
466 //ORDER
467 if(!$order) $order = $class.$suffix_id;
468 if($this->contains_history($class)) $order .= ",${class}_valid_from DESC";
469 $sql .= "ORDER BY $order\n";
470 //LIMIT/OFFSET
471 if($limit) {
472 $limit = $this->escape((int)$limit);
473 $offset = $this->escape((int)$offset);
474 $sql .= "LIMIT $offset,$limit\n";
475 }
476
477 return $sql;
478 }
479
480 function safe_query($sql, $fatal=true) {
481 $result = $this->query($sql);
482 if(!$result) {
483 $error = $this->errorInfo();
484 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>");
485 if($fatal) die();
486 }
487 return $result;
488 }
489
490 function translate_query_results($result) {
491 $translate_cols = array('status_name', 'item_valid_till'); //TODO: Hardcoded
492 foreach($result as $key => $row) {
493 foreach($translate_cols as $col) if(isset($result[$key][$col])){
494 $result[$key][$col] = T($result[$key][$col]);
495 }
496 }
497 return $result;
498 }
499
500 function safe_query_fetch($sql, $fatal=true, $fetch_flags = PDO::FETCH_ASSOC, $translate=true) {
501 $result = $this->safe_query($sql, $fatal)->fetchAll($fetch_flags);
502 if($translate) $result = $this->translate_query_results($result);
503 return $result;
504 }
505
506
507 function get_listing($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false, $indexed=array(), $suffix_id='_id') {
508 $sql = $this->build_query_select($class, $id, $limit, $offset, $where, $search, $history);
509 $result = $this->safe_query_fetch($sql);
510 if(!$result || !is_array($indexed)) return $result;
511
512 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
513 return $indexed;
514 }
515
516 function get_columns($class,$disable_cols=array()) { //TODO: Not sure if compatible with non-MySQL DBs
517 $class = $this->escape($class);
518 $sql = "SHOW COLUMNS FROM $class;";
519 $columns = $this->safe_query_fetch($sql);
520 /*foreach($columns as $colk => $col) foreach($col as $key => $val) {
521 if(in_array($col['Field'],$disable_cols)) $columns[$colk]['Extra']='auto_increment';
522 }*/
523 return $columns;
524 }
525
526 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
527 $selectbox=array();
528 foreach($columns as $column) {
529 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)!
530 if($class && $column['Field'] == $class.$suffix_id) continue;
531 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
532 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
533
534 $history = $this->contains_history($table) ? " WHERE ${table}_valid_till=0" : '';
535 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table$history;"; //TODO use build_query_select()!!!
536 $result = $this->safe_query_fetch($sql, false);
537 if(!$result) continue;
538 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
539 }
540 //echo('<pre>'); print_r($selectbox);
541 return array_filter($selectbox, 'ksort');
542 }
543
544 function map_unique($key, $value, $select, $table, $fatal=true) { //TODO: Guess $select and $table if not passed
545 $history = $this->contains_history($table) ? " AND ${table}_valid_till=0" : '';
546 $value=$this->quote($value);
547 $sql = "SELECT $select FROM $table WHERE $key=$value$history LIMIT 1;"; //TODO use build_query_select()!!!
548 $result = $this->safe_query_fetch($sql);
549 if(isset($result[0][$select])) return $result[0][$select]; else if($fatal) die(trigger_error(T('Record not found!'))); //TODO post_redirect_get...
550 }
551
552 function contains_history($table) {
553 $history_tables = array('item'); //TODO Autodetect
554 return in_array($table, $history_tables);
555 }
556
557 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
558 //Init
559 $history = $this->contains_history($table);
560
561 //Escaping
562 $table = $this->escape($table);
563
564 //Get list of POSTed columns
565 $columns_array = array_map(array($this,'escape'), array_keys($values[0]));
566 $columns = implode(',',$columns_array);
567
568 //Build query
569 $sql = '';
570 //echo('<pre>'); die(print_r($values));
571
572 if($history) {
573 $history_update=false; foreach($values as $row) if(is_numeric($row[$table.'_id'])) $history_update=true;
574 if($history_update) {
575 $sql .= "UPDATE $table";
576 $sql .= " SET ${table}_valid_till=NOW()";
577 $sql .= " WHERE ${table}_valid_till=0 AND (";
578 $or = '';
579 foreach($values as $row) {
580 $sql .= $or.' '.$table.'_id='.$this->quote($row[$table.'_id']);
581 $or = ' OR';
582 }
583 $sql .= " );\n\n";
584 $replace = false;
585 }
586 }
587
588 //Insert into table (columns)
589 $sql .= "INSERT INTO $table ($columns) VALUES ";
590
591 //Values (a,b,c),(d,e,f)
592 $comma='';
593 foreach($values as $row) {
594 $row_quoted = array_map(array($this,'quote'), $row); //Check
595 if($history) {
596 foreach($row as $column => $value) {
597 switch($column) {
598 case $table.'_valid_from':
599 $row_quoted[$column] = 'NOW()';
600 break;
601 case $table.'_valid_till':
602 $row_quoted[$column] = '0';
603 break;
604 case $table.'_author':
605 $row_quoted[$column] = $this->lms->get_authorized_user_id();
606 //die($this->lms->get_authorized_user_id().'=USER');
607 break;
608 }
609 }
610 }
611 $sql .= $comma.'('.implode(',',$row_quoted).')';
612 $comma = ',';
613 }
614
615 //On duplicate key
616 if($replace) {
617 foreach($columns_array as $col) {
618 if($col == $table.'_id' || $col == $table.'_valid_till') continue;
619 $on_duplicate[] = "$col=VALUES($col)";
620 }
621 $sql .= "\nON DUPLICATE KEY UPDATE ".implode(',', $on_duplicate);
622 }
623
624 //Terminate
625 $sql .= ';';
626 return $sql;
627 }
628
629 function insert_or_update($table, $values, $replace=true) {
630 $sql = $this->build_query_insert($table, $values, $replace);
631 $this->safe_query($sql);
632 return $this->lastInsertId();
633 }
634
635 function insert_or_update_multitab($values, $replace=true) {
636 $last=false;
637 foreach($values as $table => $rows) $last = $this->insert_or_update($table, $rows, $replace);
638 return $last;
639 }
640
641 function delete($table, $id, $suffix_id='_id') {
642 if($this->contains_history($table)) return false;
643 $key = $this->escape($table.$suffix_id);
644 $table = $this->escape($table);
645 $id = $this->quote($id);
646 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
647 }
648}
649
650/**
651* Trida poskytuje high-level rozhrani k databazi skladu
652*
653* @package Sklad_DB_Abstract
654* @author Tomas Mudrunka
655*/
656class Sklad_DB_Abstract extends Sklad_DB {
657 //TODO Code
658}
659
660/**
661* Trida implementuje uzivatelske rozhrani skladu
662*
663* Example usage:
664* $sklad = new Sklad_UI();
665* $sklad->process_http_request();
666*
667* @package Sklad_UI
668* @author Tomas Mudrunka
669*/
670class Sklad_UI {
671 function __construct() {
672 $this->db = new Sklad_DB();
673 $this->html = new Sklad_HTML();
674 }
675
676 function render_items($class, $id=false, $limit=false, $offset=0, $where=false, $search=false, $history=false) {
677 return $this->html->render_item_table($this->db->get_listing($class, $id, $limit, $offset, $where, $search, $history, false));
678 }
679
680 function render_form_add($class) {
681 $columns = $this->db->get_columns($class);
682 $selectbox = $this->db->columns_get_selectbox($columns, $class);
683 return $this->html->render_insert_form($class, $columns, $selectbox);
684 }
685
686 function render_form_edit($class, $id) {
687 $columns = $this->db->get_columns($class);
688 $selectbox = $this->db->columns_get_selectbox($columns, $class);
689 $current = $this->db->get_listing($class, $id, 1);
690 return $this->html->render_insert_form($class, $columns, $selectbox, $current);
691 }
692
693 function render_single_record_details($class, $id) {
694 $id_next = $id + 1;
695 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
696 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
697 $html='';
698 $html.= $this->html->link('<<', "$class/$id_prev/");
699 $html.= '-';
700 $html.= $this->html->link('>>', "$class/$id_next/");
701 $html.= '<br />';
702 $html.='<span style="float:right;">'.$this->html->render_barcode(BARCODE_PREFIX.strtoupper("$class/$id")).'</span>';
703 $html.= $this->html->link('edit', "$class/$id/edit/");
704 if($this->db->contains_history($class)) $html.= ' ][ '.$this->html->link('history', "$class/$id/history/");
705 return $html;
706 }
707
708 function render_listing_navigation($class, $id, $limit, $offset) {
709 $offset_next = $offset + $limit;
710 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
711 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
712 $html='';
713 $html.= $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
714 $html.= '-';
715 $html.= $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
716 $html.= '<br />';
717 $html.= $this->html->link('new', "$class/new/$get");
718 return $html;
719 }
720
721 function render_listing_extensions($class, $id, $limit, $offset, $edit=false) {
722 $html='';
723 if(is_numeric($id)) {
724 $html.=$this->render_single_record_details($class, $id);
725 } else {
726 $html.=$this->render_listing_navigation($class, '*', $limit, $offset);
727 }
728 if($edit) {
729 $html.= $this->render_form_edit($class, $id);
730 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
731 $html.=$this->html->form($action,'POST',array(
732 array(false,'DELETE','submit'),
733 array('sure', false, 'checkbox', false, false, 'sure?')
734 ));
735 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
736 $html.=$this->html->form($action,'POST',array(
737 array('image', false, 'file', false, 'size="30"'),
738 array(false, 'IMAGE', 'submit')
739 ), "enctype='multipart/form-data'");
740 }
741 return $html;
742 }
743
744 function check_auth() {
745 new HTTP_Auth('SkladovejSystem', true, array($this->db->lms,'check_auth'));
746 }
747
748 function post_redirect_get($location, $message='', $error=false) {
749 $url_args = $message != '' ? '?message='.urlencode(T($message)) : '';
750 $location = $this->html->internal_url($location).$url_args;
751 header('Location: '.$location);
752 if($error) trigger_error($message);
753 $location=htmlspecialchars($location);
754 die(
755 "<meta http-equiv='refresh' content='0; url=$location'>".
756 T($message)."<br />Location: <a href='$location'>$location</a>"
757 );
758 }
759
760 function safe_include($dir,$name,$vars=array(),$ext='.inc.php') {
761 if(preg_match('/[^a-zA-Z0-9-]/',$name)) $this->post_redirect_get('', 'SAFE INCLUDE: Securityfuck.', true);
762 $filename="$dir/$name$ext";
763 if(!is_file($filename)) $this->post_redirect_get('', 'SAFE INCLUDE: Fuckfound.', true);
764 foreach($vars as $var => $val) $$var=$val;
765 ob_start();
766 include($filename);
767 $out=ob_get_contents();
768 ob_end_clean();
769 return $out;
770 }
771
772 function process_http_request_post($action=false, $class=false, $id=false, $force_redirect=false) {
773 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
774 //echo('<pre>'); //DEBUG (maybe todo remove), HEADERS ALREADY SENT!!!!
775
776 //SephirPOST:
777
778 /* Tenhle foreach() prekopiruje promenne
779 * z: $_POST['values'][$table][$column][$id];
780 * do: $values[$table][$id][$column]
781 */
782 if(isset($_POST['values'])) {
783 $values=array();
784 foreach($_POST['values'] as $table => $columns) {
785 foreach($columns as $column => $ids) {
786 foreach($ids as $id => $val) $values[$table][$id][$column] = $val;
787 }
788 }
789 //die(print_r($values));
790 }
791
792 if($action) switch($action) {
793 case 'new':
794 $replace = false;
795 case 'edit':
796 if(!isset($replace)) $replace = true;
797 $table = $class ? $class : 'item';
798 //print_r($values); //debug
799 $last = $this->db->insert_or_update_multitab($values, $replace);
800 $last = $force_redirect ? $force_redirect."?last=$last" : "$table/$last/";
801 $next = "$table/new/";
802 $message = $force_redirect ? '' : 'Hotovo. Další záznam přidáte '.$this->html->link('zde', $next).'.';
803 $this->post_redirect_get($last, $message);
804 break;
805 case 'delete':
806 if(!isset($_POST['sure']) || !$_POST['sure']) $this->post_redirect_get("$class/$id/edit", 'Sure user expected :-)');
807 $this->db->delete($class, $id) || $this->post_redirect_get("$class/$id/edit", "V tabulce $class jentak neco mazat nebudes chlapecku :-P");
808 $this->post_redirect_get("$class", "Neco (pravdepodobne /$class/$id) bylo asi smazano. Fnuk :'-(");
809 break;
810 case 'image':
811 $image_classes = array('model'); //TODO, use this more widely across the code
812 if(!in_array($class, $image_classes)) $this->post_redirect_get("$class/$id/edit", "Nekdo nechce k DB Tride '$class' prirazovat obrazky!");
813 $image_destination = DIR_IMAGES."/$class/$id.jpg";
814 if($_FILES['image']['name'] == '') $this->post_redirect_get("$class/$id/edit", 'Everything has to be called somehow!', true);
815 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
816 chmod ($image_destination, 0664);
817 $this->post_redirect_get("$class/$id", 'Image has been upbloated successfully :)');
818 } else $this->post_redirect_get("$class/$id/edit", 'File upload failed :(', true);
819 break;
820 default:
821 $this->post_redirect_get('', 'Nothin\' to do here my cutie :-*');
822 break;
823 }
824
825 die('POSTed pyčo!');
826 }
827
828 function process_http_request() {
829 $this->check_auth();
830
831 @ini_set('magic_quotes_gpc' , 'off');
832 if(get_magic_quotes_gpc()) {
833 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
834 }
835
836 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
837 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
838 //Sephirot:
839 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
840 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...
841 switch($PATH_CHUNKS[1]) { //TODO: Move some branches to plugins if possible
842 case 'test': //test
843 die('Tell me why you cry');
844 break;
845 case 'assistant': //assistant
846 $PATH_CHUNKS[3] = isset($PATH_CHUNKS[3]) ? trim($PATH_CHUNKS[3]) : false;
847 $assistant_vars['SUBPATH'] = array_slice($PATH_CHUNKS, 3);
848 $assistant_vars['URL_INTERNAL'] = 'assistant/'.$PATH_CHUNKS[2];
849 $assistant_vars['URL'] = $_SERVER['SCRIPT_NAME'].'/'.$assistant_vars['URL_INTERNAL'];
850 $assistant_vars['ASSISTANT'] = $PATH_CHUNKS[2];
851 echo $this->safe_include(DIR_ASSISTANTS,$PATH_CHUNKS[2],$assistant_vars);
852 break;
853 case 'barcode': //barcode
854 Barcode::download_barcode(implode('/',array_slice($PATH_CHUNKS, 2)));
855 break;
856 default: //?
857 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
858 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
859 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
860 switch($PATH_CHUNKS[2]) {
861 case 'new': //?/new
862 $this->process_http_request_post($PATH_CHUNKS[2], $class);
863 echo $this->render_form_add($class);
864 break;
865 default: //?/?
866 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
867 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
868 $edit=false;
869 switch($PATH_CHUNKS[3]) {
870 case 'edit': //?/?/edit
871 case 'image': //?/?/image
872 case 'delete': //?/?/delete
873 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
874 $edit=true;
875 default: //?/?/?
876 $history = $PATH_CHUNKS[3] == 'history' ? true : false;
877 $limit = (int) (isset($PATH_CHUNKS[3]) ? $PATH_CHUNKS[3] : '0');
878 $offset = (int) (isset($PATH_CHUNKS[4]) ? $PATH_CHUNKS[4] : '0');
879 $where = @is_array($_GET['where']) ? $_GET['where'] : false;
880 echo $this->render_items($class, $id, $limit, $offset, $where, $search, $history);
881 echo $this->render_listing_extensions($class, $id, $limit, $offset, $edit);
882 //print_r(array("<pre>",$_SERVER));
883 break;
884 }
885 break;
886 }
887 break;
888 }
889 }
890}
891
892$sklad = new Sklad_UI();
893$sklad->process_http_request();
894
895echo('<br style="clear:both;" /><hr />');
This page took 0.201107 seconds and 4 git commands to generate.