priprava na templaty
[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');
21require_once('Sklad_LMS-fake.class.php');
22require_once('HTTP_Auth.class.php');
23
78bf26a5
TM
24/**
25* Trida poskytuje podpurne funkce pro generovani HTML kodu specificke pro sklad
26*
27* @package Sklad_HTML
28* @author Tomas Mudrunka
29*/
cdfce7c2
TM
30class Sklad_HTML {
31 function header_print($title='') {
32 $home = URL_HOME;
33 $script = $_SERVER['SCRIPT_NAME'];
34 $search = @trim($_GET['q']);
35 echo <<<EOF
10562613 36<head>
37 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
38</head>
cdfce7c2
TM
39<h1><a href="$script/">SystémSklad</a><small>$title</small></h1>
40<div>
41 <menu>
42 <li><a href="?logout">Logout</a></li>
43 <li><a href="$script/">Home</a></li>
44 </menu>
45 <form action="?" method="GET">
46 <input type="text" name="q" placeholder="regexp..." value="$search" />
47 <input type="submit" value="filter" />
48 </form>
49 <!-- form action="$script/" method="GET">
50 <input type="text" name="q" placeholder="regexp..." value="$search" />
51 <input type="submit" value="search items" />
52 </form -->
53</div>
54EOF;
55 }
56
57 function row_print($row) {
58 echo('<tr>');
59 foreach($row as $var) {
60 if(trim($var) == '') $var = '&nbsp;';
61 echo("<td>$var</td>");
62 }
63 echo('</tr>');
64 }
65
66 function table_print(&$table, $params='border=1') {
67 echo("<table $params>");
68 $header=true;
69 foreach($table as $row) {
70 if($header) {
71 $this->row_print(array_keys($row));
72 $header=false;
73 }
74 $this->row_print($row);
75 }
76 echo('</table>');
77 }
78
79 function link($title='n/a', $link='#void', $internal=true) {
80 if($internal) $link = $_SERVER['SCRIPT_NAME'].'/'.$link;
81 return "<a href='$link'>$title</a>";
82 }
83
84 function img($src='#void', $title='img') {
85 return "<img src='$src' alt='$title' title='$title' width=64 />";
86 }
87
88 function table_add_images(&$table) {
89 $image = array('model_id');
90 foreach($table as $id => $row) {
91 foreach($image as $column) if(isset($table[$id][$column])) {
92 $type = @array_shift(preg_split('/_/', $column));
93 $src=URL_IMAGES."/$type/".$table[$id][$column].'.jpg';
94 $table[$id][$type.'_image']=$this->img($src, $table[$id][$column]);
95 }
96 }
97 }
98
99 function table_collapse(&$table) {
100 $collapse = array(
101 'item_id' => 'item_id',
102 'model_id' => 'model_name',
103 'category_id' => 'category_name',
104 'producer_id' => 'producer_name',
105 'vendor_id' => 'vendor_name',
106 'room_id' => 'room_name',
107 'status_id' => 'status_name',
108 );
109 foreach($table as $id => $row) {
110 foreach($collapse as $link => $title)
111 if(isset($table[$id][$link])) {
112 $type = @array_shift(preg_split('/_/', $link));
113 if($link != $title) unset($table[$id][$link]);
114 $table[$id][$title]=$this->link($row[$title], $type.'/'.$row[$link].'/');
115 }
116 }
117 }
118
119 function table_sort(&$table) {
120 $precedence = array('item_id', 'model_image', 'model_name','model_descript','category_name','status_name','room_name');
121 $table_sorted = array();
122 foreach($table as $id => $row) {
123 $table_sorted[$id] = array();
124 foreach($precedence as $column) if(isset($table[$id][$column])) {
125 $table_sorted[$id][$column]=$table[$id][$column];
126 unset($table[$id][$column]);
127 }
128 $table_sorted[$id]=array_merge($table_sorted[$id],$table[$id]);
129 }
130 $table = $table_sorted;
131 }
132
133 function print_item_table($table) {
134 $this->table_add_images($table);
135 $this->table_collapse($table);
136 $this->table_sort($table);
137 return $this->table_print($table);
138 }
139
140 function input($name=false, $value=false, $type='text', $placeholder=false, $options=false) {
141 $html = "<input type='$type' ";
142 if($name) $html.= "name='$name' ";
143 if(!is_bool($value)) $html.= "value='$value' ";
144 if($options) $html.= "$options ";
145 if($placeholder) $html.= "placeholder='$placeholder' ";
146 $html .= '/>';
147 return $html;
148 }
149
150 function select($name, $selectbox, $default=false) {
151 //echo('<pre>'); print_r($selectbox);
152 $html = "<select name='$name'>";
153
154 if($default) {
155 $value=$default; $title=$selectbox[$value];
156 $html .= "<option value='$value'>$value :: $title</option>";
157 unset($selectbox[$value]);
158 }
159 foreach($selectbox as $value => $title) {
160 $html .= "<option value='$value'>$value :: $title</option>";
161 }
162 $html .= "</select>";
163 return $html;
164 }
165
166 function print_insert_form($class, $columns, $selectbox=array(), $current=false, $multi_insert=true) {
167 //echo('<pre>'); print_r($selectbox);
168 //echo('<pre>'); print_r($current);
169 $update = false;
170 if(is_array($current)) {
171 $update = true;
172 $current = array_shift($current);
173 }
174
175 echo('<form method="POST">');
176 if($multi_insert) echo('<div name="input_set" style="float:left; border:1px solid grey;">');
177 echo $this->input('table', $class, 'hidden');
178 foreach($columns as $column) {
179 echo($column['Field'].': ');
180 $name='value:'.$column['Field'].'[]';
181 switch(true) {
182 case preg_match('/auto_increment/', $column['Extra']):
183 $val = $update ? $current[$column['Field']] : ''; //opakuje se (skoro) zbytecne
184 echo $this->input($name, $val, 'hidden');
185 echo($val.'(AUTO)');
186 break;
187 case isset($selectbox[$column['Field']]):
188 $val = $update ? $current[$column['Field']] : false;
189 echo $this->select($name,$selectbox[$column['Field']],$val); //opakuje se
190 break;
191 default:
192 $val = $update ? $current[$column['Field']] : false; //opakuje se
193 echo $this->input($name, $val);
194 break;
195 }
196 echo('<br />');
197 }
198
199 if($multi_insert) {
200 //TODO, move to separate JS file
201 echo <<<EOF
202 </div>
203 <span name="input_set_next"></span><br style="clear:both" />
204 <script>
205 function duplicate_element(what, where) {
206 document.getElementsByName(where)[0].outerHTML =
207 document.getElementsByName(what)[0].outerHTML
208 + document.getElementsByName(where)[0].outerHTML;
209 }
210 </script>
211 <a href='#' onClick="duplicate_element('input_set', 'input_set_next')">+</a>
212EOF;
213 }
214
215 $btn = is_array($current) ? 'UPDATE' : 'INSERT';
216 echo($this->input(false, $btn, 'submit'));
217 echo('</form>');
218 }
219}
220
78bf26a5
TM
221/**
222* Trida poskytuje rozhrani k databazi skladu
223*
224* @package Sklad_DB
225* @author Tomas Mudrunka
226*/
cdfce7c2
TM
227class Sklad_DB extends PDO {
228 function __construct() {
229 $this->lms = new Sklad_LMS();
230
231 parent::__construct(
232 DB_DSN, DB_USER, DB_PASS,
233 array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8") //Force UTF8 for MySQL
234 );
235 }
236
237 function escape($str) {
238 return preg_replace('(^.|.$)', '', $this->quote($str)); //TODO HACK
239 }
240
241 function build_query_select($class, $id=false, $limit=false, $offset=0, $search=false, $id_suffix='_id') {
242 $class = $this->escape($class);
243 $join = array(
244 'item' => array('model', 'category', 'producer', 'vendor', 'room', 'status'),
245 'model' => array('category', 'producer')
246 );
247 $search_fields = array(
248 'item' => array('item_id','model_name','model_barcode','model_descript','producer_name','vendor_name')
249 );
250 $sql="SELECT * FROM $class\n";
251 if(isset($join[$class])) foreach($join[$class] as $j) $sql .= "LEFT JOIN $j USING($j$id_suffix)\n";
252 if($search) {
253 $search = $this->quote($search);
254 if(!isset($search_fields[$class])) {
255 trigger_error("Ve tride $class zatim vyhledavat nemozno :-(");
256 die();
257 }
258 $sql .= 'WHERE FALSE ';
259 foreach($search_fields[$class] as $column) $sql .= "OR $column REGEXP $search ";
260 } elseif($id) $sql .= "WHERE $class$id_suffix = $id\n";
261 if($limit) {
262 $limit = $this->escape((int)$limit);
263 $offset = $this->escape((int)$offset);
264 $sql .= "LIMIT $offset,$limit\n";
265 }
266 return $sql;
267 }
268
269 function safe_query($sql) {
270 $result = $this->query($sql);
271 if(!$result) {
272 trigger_error('<font color=red><b>QUERY FAILED:</b><pre>'.$sql.'</pre></font>');
273 die();
274 }
275 return $result;
276 }
277
278 function get_listing($class, $id=false, $limit=false, $offset=0, $search=false, $indexed=array(), $suffix_id='_id') {
279 $sql = $this->build_query_select($class, $id, $limit, $offset, $search);
280 $result = $this->safe_query($sql)->fetchAll(PDO::FETCH_ASSOC);
281 if(!$result || !is_array($indexed)) return $result;
282
283 foreach($result as $key => $row) $indexed[$row[$class.$suffix_id]]=$row;
284 return $indexed;
285 }
286
287 function get_columns($class) {
288 $class = $this->escape($class);
289 $sql = "SHOW COLUMNS FROM $class;";
290 return $this->safe_query($sql)->fetchAll(PDO::FETCH_ASSOC);
291 }
292
293 function columns_get_selectbox($columns, $class=false, $suffix_id='_id', $suffix_name='_name') {
294 $selectbox=array();
295 foreach($columns as $column) {
296 if($class && $column['Field'] == $class.$suffix_id) continue;
297 if(!preg_match('/'.$suffix_id.'$/', $column['Field'])) continue;
298 $table=preg_replace('/'.$suffix_id.'$/','',$column['Field']);
299 $sql = "SELECT $table$suffix_id, $table$suffix_name FROM $table;";
300 $result=$this->safe_query($sql)->fetchAll(PDO::FETCH_ASSOC);
301 foreach($result as $row) $selectbox[$table.$suffix_id][$row[$table.$suffix_id]]=$row[$table.$suffix_name];
302 }
303 //echo('<pre>'); print_r($selectbox);
304 return $selectbox;
305 }
306
307 function build_query_insert($table, $values, $replace=true, $suffix_id='_id') {
308 $table = $this->escape($table);
309
310 //Get list of POSTed columns
311 $columns = implode(',',array_map(array($this,'escape'), array_keys($values[0])));
312
313 //Insert into table (columns)
314 $sql = 'INSERT';
315 if($replace) $sql = 'REPLACE';
316 $sql .= " INTO $table ($columns) VALUES ";
317
318 //Values (a,b,c),(d,e,f)
319 $comma='';
320 foreach($values as $row) {
321 $sql .= $comma.'('.implode(',',array_map(array($this,'quote'), $row)).')';
322 $comma = ',';
323 }
324
325 //Terminate
326 $sql .= ';';
327 return $sql;
328 }
329
330 function insert_or_update($table, $values) {
331 $sql = $this->build_query_insert($table, $values);
332 $this->safe_query($sql);
333 return $this->lastInsertId();
334 }
335
336 function delete($table, $id, $suffix_id='_id') {
337 $key = $this->escape($table.$suffix_id);
338 $table = $this->escape($table);
339 $id = $this->quote($id);
340 return $this->safe_query("DELETE FROM $table WHERE $key = $id LIMIT 1;");
341 }
342}
343
78bf26a5
TM
344/**
345* Trida implementuje uzivatelske rozhrani skladu
346*
347* Example usage:
348* $sklad = new Sklad_UI();
349* $sklad->process_http_request();
350*
351* @package Sklad_UI
352* @author Tomas Mudrunka
353*/
cdfce7c2
TM
354class Sklad_UI {
355 function __construct() {
356 $this->db = new Sklad_DB();
357 $this->html = new Sklad_HTML();
358 }
359
360 function show_items($class, $id=false, $limit=false, $offset=0, $search=false) {
361 $this->html->print_item_table($this->db->get_listing($class, $id, $limit, $offset, $search));
362 }
363
364 function show_form_add($class) {
365 $columns = $this->db->get_columns($class);
366 $selectbox = $this->db->columns_get_selectbox($columns, $class);
367 $this->html->print_insert_form($class, $columns, $selectbox);
368 }
369
370 function show_form_edit($class, $id) {
371 $columns = $this->db->get_columns($class);
372 $selectbox = $this->db->columns_get_selectbox($columns, $class);
373 $current = $this->db->get_listing($class, $id);
374 $this->html->print_insert_form($class, $columns, $selectbox, $current);
375 }
376
377 function show_single_record_details($class, $id) {
378 $id_next = $id + 1;
379 $id_prev = $id - 1 > 0 ? $id - 1 : 0;
380 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
381 echo $this->html->link('<<', "$class/$id_prev/");
382 echo '-';
383 echo $this->html->link('>>', "$class/$id_next/");
384 echo ('<br />');
385 echo $this->html->link('edit', "$class/$id/edit/");
386 }
387
388 function show_listing_navigation($class, $id, $limit, $offset) {
389 $offset_next = $offset + $limit;
390 $offset_prev = $offset - $limit > 0 ? $offset - $limit : 0;
391 $get = $_SERVER['QUERY_STRING'] != '' ? '?'.$_SERVER['QUERY_STRING'] : '';
392 echo $this->html->link('<<', "$class/$id/$limit/$offset_prev/$get");
393 echo '-';
394 echo $this->html->link('>>', "$class/$id/$limit/$offset_next/$get");
395 echo ('<br />');
396 echo $this->html->link('new', "$class/new/$get");
397 }
398
399 function show_listing_extensions($class, $id, $limit, $offset, $edit=false) {
400 if(is_numeric($id)) {
401 $this->show_single_record_details($class, $id);
402 } else {
403 $this->show_listing_navigation($class, '*', $limit, $offset);
404 }
405 if($edit) {
406 echo('<br />TODO UPDATE FORM!<br />');
407 $this->show_form_edit($class, $id);
408 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/delete";
409 echo("<form action='$action' method='POST'>");
410 echo $this->html->input(false, 'DELETE', 'submit');
411 echo 'sure?'.$this->html->input('sure', false, 'checkbox');
412 echo('</form>');
413 $action = $_SERVER['SCRIPT_NAME']."/$class/$id/image";
414 echo("<form action='$action' method='POST' enctype='multipart/form-data'>");
415 echo $this->html->input('image', false, 'file', false, 'size="30"');
416 echo $this->html->input(false, 'IMAGE', 'submit');
417 echo('</form>');
418 }
419 }
420
421 function check_auth() {
422 new HTTP_Auth('SkladovejSystem', true, array($this->db->lms,'check_auth'));
423 }
424
425 function post_redirect_get($last, $next) { //TODO prepracovat, tohle je uplna picovina...
426 //header('Location: '.$_SERVER['REQUEST_URI']); //TODO redirect (need templating system or ob_start() first!!!)
427 echo 'Hotovo. Poslední vložený záznam naleznete '.$this->html->link('zde', $last).'.<br />'.
428 'Další záznam přidáte '.$this->html->link('zde', $next).'.';
429 die();
430 }
431
432 function process_http_request_post($action=false, $class=false, $id=false) {
433 if($_SERVER['REQUEST_METHOD'] != 'POST') return;
434 echo('<pre>'); //DEBUG (maybe todo remove)
435
436 //SephirPOST:
437 $values=array();
438 foreach($_POST as $key => $value) {
439 $name = preg_split('/:/',$key);
440 if(isset($name[0])) switch($name[0]) {
441 case 'value':
442 foreach($value as $id => $val) $values[$id][$name[1]]=$value[$id];
443 break;
444 default:
445 break;
446 }
447 }
448
449 if($action) switch($action) {
450 case 'new':
451 case 'edit':
452 if(!isset($_POST['table'])) die(trigger_error("Jest nutno specifikovat tabulku voe!"));
453 $table=$_POST['table'];
454 //print_r($values); //debug
455 $last = $this->db->insert_or_update($table, $values);
456 $this->post_redirect_get("$table/$last/", "$table/new/");
457 break;
458 case 'delete':
459 if(!isset($_POST['sure']) || !$_POST['sure']) die(trigger_error('Sure user expected :-)'));
460 //$this->db->delete($class, $id);
461 die('Neco asi bylo smazano. Fnuk :\'-('); //TODO REDIRECT
462 break;
463 case 'image':
464 $image_classes = array('model'); //TODO, use this more widely across the code
465 if(!in_array($class, $image_classes)) die(trigger_error("Nekdo nechce k DB Tride '$class' prirazovat obrazky!"));
466 $image_destination = DIR_IMAGES."/$class/$id.jpg";
467 if($_FILES['image']['name'] == '') die(trigger_error('Kazde neco se musi nejak jmenovat!'));
468 if(move_uploaded_file($_FILES['image']['tmp_name'], $image_destination)) {
469 chmod ($image_destination, 0664);
470 die('Obrazek se naladoval :)'); //TODO REDIRECT
471 } else die(trigger_error('Soubor se nenahral :('));
472 break;
473 default:
474 trigger_error('Nothin\' to do here my cutie :-*');
475 break;
476 }
477
478 die('POSTed pyčo!');
479 }
480
481 function process_http_request() {
482 $this->check_auth();
483
484 @ini_set('magic_quotes_gpc' , 'off');
485 if(get_magic_quotes_gpc()) {
486 die(trigger_error("Error: magic_quotes_gpc needs to be disabled! F00K!"));
487 }
488
489 $PATH_INFO=@trim($_SERVER[PATH_INFO]);
490 $this->html->header_print($PATH_INFO);
491
492
493 //Sephirot:
494 $PATH_CHUNKS = preg_split('/\//', $PATH_INFO);
495 if(!isset($PATH_CHUNKS[1])) $PATH_CHUNKS[1]='';
496 switch($PATH_CHUNKS[1]) {
497 case 'test': //test
498 die('Tell me why you cry');
499 break;
500 default: //?
501 $search = (isset($_GET['q']) && trim($_GET['q']) != '') ? trim($_GET['q']) : false;
502 $class = (isset($PATH_CHUNKS[1]) && $PATH_CHUNKS[1] != '') ? $PATH_CHUNKS[1] : 'item';
503 if(!isset($PATH_CHUNKS[2])) $PATH_CHUNKS[2]='';
504 switch($PATH_CHUNKS[2]) {
505 case 'new': //?/new
506 $this->process_http_request_post($PATH_CHUNKS[2], $class);
507 $this->show_form_add($class);
508 break;
509 default: //?/?
510 $id = (isset($PATH_CHUNKS[2]) && is_numeric($PATH_CHUNKS[2]) ? (int) $PATH_CHUNKS[2] : false);
511 if(!isset($PATH_CHUNKS[3])) $PATH_CHUNKS[3]='';
512 $edit=false;
513 switch($PATH_CHUNKS[3]) {
514 case 'edit': //?/?/edit
515 case 'image': //?/image
516 case 'delete': //?/delete
517 $this->process_http_request_post($PATH_CHUNKS[3], $class, $id);
518 $edit=true;
519 default: //?/?/?
520 $limit = (int) (isset($PATH_CHUNKS[3]) ? $PATH_CHUNKS[3] : '0');
521 $offset = (int) (isset($PATH_CHUNKS[4]) ? $PATH_CHUNKS[4] : '0');
522 $this->show_items($class, $id, $limit, $offset, $search);
523 $this->show_listing_extensions($class, $id, $limit, $offset, $edit);
524 //print_r(array("<pre>",$_SERVER));
525 break;
526 }
527 break;
528 }
529 break;
530 }
531 }
532}
533
534$sklad = new Sklad_UI();
535$sklad->process_http_request();
536
537echo("<hr/>");
This page took 0.46677 seconds and 4 git commands to generate.