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