Marius Cramer
2015-08-06 37b29231e47a0c4458dc1c15d98588f16f07e1e2
commit | author | age
5bff39 1 <?php
M 2
3 /*
4 Copyright (c) 2007, Till Brehm, projektfarm Gmbh
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without modification,
8 are permitted provided that the following conditions are met:
9
10     * Redistributions of source code must retain the above copyright notice,
11       this list of conditions and the following disclaimer.
12     * Redistributions in binary form must reproduce the above copyright notice,
13       this list of conditions and the following disclaimer in the documentation
14       and/or other materials provided with the distribution.
15     * Neither the name of ISPConfig nor the names of its contributors
16       may be used to endorse or promote products derived from this software without
17       specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
20 ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
21 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
23 INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
24 BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
26 OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
27 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
28 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 /**
b1a6a5 32  * Formularbehandlung
MC 33  *
34  * Functions to validate, display and save form values
35  *
36  *        Database table field definitions
37  *
38  *        Datatypes:
39  *        - INTEGER (Converts data to int automatically)
40  *        - DOUBLE
41  *        - CURRENCY (Formats digits in currency notation)
42  *        - VARCHAR (No format check)
43  *        - DATE (Date format, converts from and to UNIX timestamps automatically)
44  *
45  *        Formtype:
46  *        - TEXT (Normal text field)
47  *        - PASSWORD (password field, the content will not be displayed again to the user)
48  *        - SELECT (Option fiield)
49  *        - MULTIPLE (Allows selection of multiple values)
50  *
51  *        VALUE:
52  *        - Value or array
53  *
54  *        SEPARATOR
55  *        - separator char used for fileds with multiple values
56  *
57  *        Hint: The auto increment (ID) filed of the table has not be be definied separately.
58  *
59  */
60
5bff39 61
M 62 class tform_base {
63
b1a6a5 64     /**
MC 65      * Definition of the database table (array)
66      * @var tableDef
67      */
68     var $tableDef;
5bff39 69
b1a6a5 70     /**
MC 71      * Private
72      * @var action
73      */
74     var $action;
5bff39 75
b1a6a5 76     /**
MC 77      * Table name (String)
78      * @var table_name
79      */
80     var $table_name;
5bff39 81
b1a6a5 82     /**
MC 83      * Debug Variable
84      * @var debug
85      */
86     var $debug = 0;
5bff39 87
b1a6a5 88     /**
MC 89      * name of the primary field of the database table (string)
90      * @var table_index
91      */
92     var $table_index;
5bff39 93
b1a6a5 94     /**
MC 95      * contains the error messages
96      * @var errorMessage
97      */
98     var $errorMessage = '';
5bff39 99
b1a6a5 100     var $dateformat = "d.m.Y";
43e5b6 101     var $datetimeformat = 'd.m.Y H:i';
b1a6a5 102     var $formDef = array();
MC 103     var $wordbook;
104     var $module;
105     var $primary_id;
106     var $diffrec = array();
5bff39 107
b1a6a5 108     /**
MC 109      * Loading of the table definition
110      *
111      * @param file: path to the form definition file
112      * @return true
113      */
114     /*
5bff39 115         function loadTableDef($file) {
M 116                 global $app,$conf;
117
118                 include_once($file);
119                 $this->tableDef = $table;
120                 $this->table_name = $table_name;
121                 $this->table_index = $table_index;
122                 return true;
123         }
124         */
125
b1a6a5 126     function loadFormDef($file, $module = '') {
MC 127         global $app, $conf;
5bff39 128
b1a6a5 129         include $file;
MC 130         $this->formDef = $form;
5bff39 131
b1a6a5 132         $this->module = $module;
MC 133         $wb = array();
5bff39 134
b1a6a5 135         include_once ISPC_ROOT_PATH.'/lib/lang/'.$_SESSION['s']['language'].'.lng';
5bff39 136
b1a6a5 137         if(is_array($wb)) $wb_global = $wb;
5bff39 138
b1a6a5 139         if($module == '') {
MC 140             $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_".$this->formDef["name"].".lng";
141             if(!file_exists($lng_file)) $lng_file = "lib/lang/en_".$this->formDef["name"].".lng";
142             include $lng_file;
143         } else {
144             $lng_file = "../$module/lib/lang/".$_SESSION["s"]["language"]."_".$this->formDef["name"].".lng";
145             if(!file_exists($lng_file)) $lng_file = "../$module/lib/lang/en_".$this->formDef["name"].".lng";
146             include $lng_file;
5bff39 147         }
M 148
b1a6a5 149         if(is_array($wb_global)) {
MC 150             $wb = $app->functions->array_merge($wb_global, $wb);
151         }
152         if(isset($wb_global)) unset($wb_global);
153
154         $this->wordbook = $wb;
155
156         $this->dateformat = $app->lng('conf_format_dateshort');
43e5b6 157         $this->datetimeformat = $app->lng('conf_format_datetime');
b1a6a5 158
MC 159         return true;
160     }
161
162     /*
5bff39 163         * Converts the data in the array to human readable format
M 164         * Datatype conversion e.g. to show the data in lists
165         *
166         * @param record
167         * @param tab
168         * @param apply_filters
169         * @return record
170         */
b1a6a5 171     protected function _decode($record, $tab = '', $api = false) {
MC 172         global $app;
173         $new_record = '';
174         if($api == false) {
175             $table_idx = $this->formDef['db_table_idx'];
176             if(isset($record[$table_idx])) $new_record[$table_idx] = $app->functions->intval($record[$table_idx ]);
177             $fields = &$this->formDef['tabs'][$tab]['fields'];
178         } else {
179             $fields = &$this->formDef['fields'];
180         }
181
182         if(is_array($record)) {
183             foreach($fields as $key => $field) {
184
185                 //* Apply filter to record value.
186                 if($api == false && isset($field['filters']) && is_array($field['filters'])) {
187                     $record[$key] = $this->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SHOW');
5bff39 188                 }
M 189
b1a6a5 190                 switch ($field['datatype']) {
MC 191                 case 'VARCHAR':
192                     $new_record[$key] = ($api == true ? stripslashes($record[$key]) : $record[$key]);
193                     break;
5bff39 194
b1a6a5 195                 case 'TEXT':
MC 196                     $new_record[$key] = ($api == true ? stripslashes($record[$key]) : $record[$key]);
197                     break;
5bff39 198
b1a6a5 199                 case 'DATETSTAMP':
MC 200                     if($record[$key] > 0) {
201                         $new_record[$key] = date($this->dateformat, $record[$key]);
202                     }
203                     break;
5bff39 204
b1a6a5 205                 case 'DATE':
MC 206                     if($record[$key] != '' && $record[$key] != '0000-00-00') {
207                         $tmp = explode('-', $record[$key]);
208                         $new_record[$key] = date($this->dateformat, mktime(0, 0, 0, $tmp[1]  , $tmp[2], $tmp[0]));
209                     }
210                     break;
5bff39 211
b1a6a5 212                 case 'INTEGER':
MC 213                     $new_record[$key] = $app->functions->intval($record[$key]);
214                     break;
5bff39 215
b1a6a5 216                 case 'DOUBLE':
MC 217                     $new_record[$key] = $record[$key];
218                     break;
5bff39 219
b1a6a5 220                 case 'CURRENCY':
MC 221                     $new_record[$key] = $app->functions->currency_format($record[$key]);
222                     break;
5bff39 223
b1a6a5 224                 default:
MC 225                     $new_record[$key] = ($api == true ? stripslashes($record[$key]) : $record[$key]);
5bff39 226                 }
b1a6a5 227             }
MC 228
229         }
5bff39 230
M 231         return $new_record;
b1a6a5 232     }
MC 233
234
235     /**
236      * Converts the data in the array to human readable format
237      * Datatype conversion e.g. to show the data in lists
238      *
239      * @param record
240      * @return record
241      */
242     function decode($record, $tab) {
243         global $conf, $app;
244         if(!is_array($this->formDef['tabs'][$tab])) $app->error("Tab does not exist or the tab is empty (TAB: $tab).");
245         return $this->_decode($record, $tab, false);
246     }
247
248     /**
249      * Get the key => value array of a form filled from a datasource definitiom
250      *
251      * @param field = array with field definition
252      * @param record = Dataset as array
253      * @return key => value array for the value field of a form
254      */
255     protected function _getDatasourceData($field, $record, $api = false) {
256         global $app;
257
258         $values = array();
259
260         if($field["datasource"]["type"] == 'SQL') {
261
262             // Preparing SQL string. We will replace some
263             // common placeholders
264             $querystring = $field["datasource"]["querystring"];
265             $querystring = str_replace("{USERID}", $_SESSION["s"]["user"]["userid"], $querystring);
266             $querystring = str_replace("{GROUPID}", $_SESSION["s"]["user"]["default_group"], $querystring);
267             $querystring = str_replace("{GROUPS}", $_SESSION["s"]["user"]["groups"], $querystring);
268             $table_idx = $this->formDef['db_table_idx'];
269
270             $tmp_recordid = (isset($record[$table_idx]))?$record[$table_idx]:0;
271             $querystring = str_replace("{RECORDID}", $tmp_recordid, $querystring);
272             unset($tmp_recordid);
273
274             $querystring = str_replace("{AUTHSQL}", $this->getAuthSQL('r'), $querystring);
797215 275             $querystring = preg_replace_callback('@{AUTHSQL::(.+?)}@', create_function('$matches','global $app; $tmp = $app->tform->getAuthSQL("r", $matches[1]); return $tmp;'), $querystring);
b1a6a5 276
MC 277             // Getting the records
278             $tmp_records = $app->db->queryAllRecords($querystring);
279             if($app->db->errorMessage != '') die($app->db->errorMessage);
280             if(is_array($tmp_records)) {
281                 $key_field = $field["datasource"]["keyfield"];
282                 $value_field = $field["datasource"]["valuefield"];
283                 foreach($tmp_records as $tmp_rec) {
284                     $tmp_id = $tmp_rec[$key_field];
285                     $values[$tmp_id] = $tmp_rec[$value_field];
286                 }
287             }
5bff39 288         }
M 289
b1a6a5 290         if($field["datasource"]["type"] == 'CUSTOM') {
MC 291             // Calls a custom class to validate this record
292             if($field["datasource"]['class'] != '' and $field["datasource"]['function'] != '') {
293                 $datasource_class = $field["datasource"]['class'];
294                 $datasource_function = $field["datasource"]['function'];
295                 $app->uses($datasource_class);
296                 $values = $app->$datasource_class->$datasource_function($field, $record);
297             } else {
298                 $this->errorMessage .= "Custom datasource class or function is empty<br />\r\n";
299             }
5bff39 300         }
M 301
b1a6a5 302         if($api == false && isset($field['filters']) && is_array($field['filters'])) {
MC 303             $new_values = array();
304             foreach($values as $index => $value) {
305                 $new_index = $this->filterField($index, $index, $field['filters'], 'SHOW');
306                 $new_values[$new_index] = $this->filterField($index, (isset($values[$index]))?$values[$index]:'', $field['filters'], 'SHOW');
307             }
308             $values = $new_values;
309             unset($new_values);
310             unset($new_index);
311         }
5bff39 312
b1a6a5 313         return $values;
5bff39 314
b1a6a5 315     }
5bff39 316
797215 317     /*
cce3c1 318     function table_auth_sql($matches){
MC 319         return $this->getAuthSQL('r', $matches[1]);
320     }
797215 321     */
MC 322     
b1a6a5 323     /**
MC 324      * Get the key => value array of a form filled from a datasource definitiom
325      *
326      * @param field = array with field definition
327      * @param record = Dataset as array
328      * @return key => value array for the value field of a form
329      */
330     function getDatasourceData($field, $record) {
331         return $this->_getDatasourceData($field, $record, false);
332     }
5bff39 333
b1a6a5 334     //* If the parameter 'valuelimit' is set
MC 335     function applyValueLimit($limit, $values) {
5bff39 336
b1a6a5 337         global $app;
5bff39 338
b1a6a5 339         $limit_parts = explode(':', $limit);
5bff39 340
b1a6a5 341         //* values are limited to a comma separated list
MC 342         if($limit_parts[0] == 'list') {
343             $allowed = explode(',', $limit_parts[1]);
344         }
5bff39 345
b1a6a5 346         //* values are limited to a field in the client settings
MC 347         if($limit_parts[0] == 'client') {
348             if($_SESSION["s"]["user"]["typ"] == 'admin') {
5bff39 349                 return $values;
b1a6a5 350             } else {
MC 351                 $client_group_id = $_SESSION["s"]["user"]["default_group"];
cc7a82 352                 $client = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $client_group_id);
b1a6a5 353                 $allowed = explode(',', $client['lm']);
MC 354             }
5bff39 355         }
M 356
b1a6a5 357         //* values are limited to a field in the reseller settings
MC 358         if($limit_parts[0] == 'reseller') {
359             if($_SESSION["s"]["user"]["typ"] == 'admin') {
360                 return $values;
361             } else {
362                 //* Get the limits of the client that is currently logged in
363                 $client_group_id = $_SESSION["s"]["user"]["default_group"];
cc7a82 364                 $client = $app->db->queryOneRecord("SELECT parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = ?", $client_group_id);
b1a6a5 365                 //echo "SELECT parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id";
MC 366                 //* If the client belongs to a reseller, we will check against the reseller Limit too
367                 if($client['parent_client_id'] != 0) {
5bff39 368
b1a6a5 369                     //* first we need to know the groups of this reseller
2af58c 370                     $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ?", $client['parent_client_id']);
b1a6a5 371                     $reseller_groups = $tmp["groups"];
MC 372                     $reseller_userid = $tmp["userid"];
5bff39 373
b1a6a5 374                     // Get the limits of the reseller of the logged in client
5bff39 375                     $client_group_id = $_SESSION["s"]["user"]["default_group"];
2af58c 376                     $reseller = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM client WHERE client_id = ?", $client['parent_client_id']);
b1a6a5 377                     $allowed = explode(',', $reseller['lm']);
MC 378                 } else {
379                     return $values;
5bff39 380                 }
b1a6a5 381             } // end if admin
MC 382         } // end if reseller
5bff39 383
b1a6a5 384         //* values are limited to a field in the system settings
MC 385         if($limit_parts[0] == 'system') {
386             $app->uses('getconf');
387             $tmp_conf = $app->getconf->get_global_config($limit_parts[1]);
388             $tmp_key = $limit_parts[2];
389             $allowed = $tmp_conf[$tmp_key];
390         }
5bff39 391
b1a6a5 392         $values_new = array();
MC 393         foreach($values as $key => $val) {
394             if(in_array($key, $allowed)) $values_new[$key] = $val;
395         }
5bff39 396
b1a6a5 397         return $values_new;
MC 398     }
399
400
401     /**
402      * Prepare the data record to show the data in a form.
403      *
404      * @param record = Datensatz als Array
405      * @param action = NEW oder EDIT
406      * @return record
407      */
408     function getHTML($record, $tab, $action = 'NEW') {
409
410         global $app;
411
412         $this->action = $action;
413
414         if(!is_array($this->formDef)) $app->error("No form definition found.");
415         if(!is_array($this->formDef['tabs'][$tab])) $app->error("The tab is empty or does not exist (TAB: $tab).");
416
985390 417         /* CSRF PROTECTION */
MC 418         // generate csrf protection id and key
8cb6f8 419         $csrf_token = $app->auth->csrf_token_get($this->formDef['name']);
MC 420         $_csrf_id = $csrf_token['csrf_id'];
421         $_csrf_value = $csrf_token['csrf_key'];
422         
985390 423         $this->formDef['tabs'][$tab]['fields']['_csrf_id'] = array(
MC 424             'datatype' => 'VARCHAR',
425             'formtype' => 'TEXT',
426             'default' => $_csrf_id,
427             'value' => $_csrf_id
428         );
429         $this->formDef['tabs'][$tab]['fields']['_csrf_key'] = array(
430             'datatype' => 'VARCHAR',
431             'formtype' => 'TEXT',
432             'default' => $_csrf_value,
433             'value' => $_csrf_value
434         );
435         $record['_csrf_id'] = $_csrf_id;
436         $record['_csrf_key'] = $_csrf_value;
437         /* CSRF PROTECTION */
438         
b1a6a5 439         $new_record = array();
MC 440         if($action == 'EDIT') {
441             $record = $this->decode($record, $tab);
442             if(is_array($record)) {
443                 foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
444
445                     if(isset($record[$key])) {
446                         $val = $record[$key];
5bff39 447                     } else {
b1a6a5 448                         $val = '';
5bff39 449                     }
M 450
b1a6a5 451                     // If Datasource is set, get the data from there
MC 452                     if(isset($field['datasource']) && is_array($field['datasource'])) {
453                         if(is_array($field["value"])) {
454                             //$field["value"] = array_merge($field["value"],$this->getDatasourceData($field, $record));
455                             $field["value"] = $app->functions->array_merge($field["value"], $this->getDatasourceData($field, $record));
456                         } else {
457                             $field["value"] = $this->getDatasourceData($field, $record);
5bff39 458                         }
M 459                     }
460
b1a6a5 461                     // If a limitation for the values is set
MC 462                     if(isset($field['valuelimit']) && is_array($field["value"])) {
463                         $field["value"] = $this->applyValueLimit($field['valuelimit'], $field["value"]);
464                     }
5bff39 465
b1a6a5 466                     switch ($field['formtype']) {
MC 467                     case 'SELECT':
468                         $out = '';
469                         if(is_array($field['value'])) {
470                             foreach($field['value'] as $k => $v) {
471                                 $selected = ($k == $val)?' SELECTED':'';
86e699 472                                 if(isset($this->wordbook[$v]))
b1a6a5 473                                     $v = $this->wordbook[$v];
MC 474                                 $out .= "<option value='$k'$selected>".$this->lng($v)."</option>\r\n";
5bff39 475                             }
b1a6a5 476                         }
MC 477                         $new_record[$key] = $out;
478                         break;
479                     case 'MULTIPLE':
480                         if(is_array($field['value'])) {
481
482                             // Split
483                             $vals = explode($field['separator'], $val);
484
485                             // write HTML
486                             $out = '';
487                             foreach($field['value'] as $k => $v) {
488
489                                 $selected = '';
490                                 foreach($vals as $tvl) {
491                                     if(trim($tvl) == trim($k)) $selected = ' SELECTED';
492                                 }
493
494                                 $out .= "<option value='$k'$selected>$v</option>\r\n";
495                             }
496                         }
497                         $new_record[$key] = $out;
498                         break;
499
500                     case 'PASSWORD':
501                         $new_record[$key] = '';
502                         break;
503
504                     case 'CHECKBOX':
505                         $checked = ($val == $field['value'][1])?' CHECKED':'';
506                         $new_record[$key] = "<input name=\"".$key."\" id=\"".$key."\" value=\"".$field['value'][1]."\" type=\"checkbox\" $checked />\r\n";
507                         break;
508
509                     case 'CHECKBOXARRAY':
510                         if(is_array($field['value'])) {
511
512                             // aufsplitten ergebnisse
513                             $vals = explode($field['separator'], $val);
514
515                             // HTML schreiben
516                             $out = '';
517                             $elementNo = 0;
518                             foreach($field['value'] as $k => $v) {
519
520                                 $checked = '';
521                                 foreach($vals as $tvl) {
522                                     if(trim($tvl) == trim($k)) $checked = ' CHECKED';
523                                 }
524                                 // $out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"checkbox\" $checked /> $v</label>\r\n";
525                                 $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"checkbox\" $checked /> $v</label><br/>\r\n";
526                                 $elementNo++;
527                             }
528                         }
529                         $new_record[$key] = $out;
530                         break;
531
532                     case 'RADIO':
533                         if(is_array($field['value'])) {
534
535                             // HTML schreiben
536                             $out = '';
537                             $elementNo = 0;
538                             foreach($field['value'] as $k => $v) {
539                                 $checked = ($k == $val)?' CHECKED':'';
540                                 //$out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
541                                 $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"radio\" $checked/> $v </label>\r\n";
542                                 $elementNo++;
543                             }
544                         }
545                         $new_record[$key] = $out;
546                         break;
547
548                     case 'DATETIME':
549                         if (strtotime($val) !== false) {
550                             $dt_value = $val;
551                         } elseif ( isset($field['default']) && (strtotime($field['default']) !== false) ) {
552                             $dt_value = $field['default'];
553                         } else {
554                             $dt_value = 0;
555                         }
556
557                         $display_seconds = (isset($field['display_seconds']) && $field['display_seconds'] == true) ? true : false;
558
559                         $new_record[$key] = $this->_getDateTimeHTML($key, $dt_value, $display_seconds);
560                         break;
561
562                     default:
563                         if(isset($record[$key])) {
564                             $new_record[$key] = htmlspecialchars($record[$key]);
565                         } else {
566                             $new_record[$key] = '';
567                         }
568                     }
569                 }
570             }
571         } else {
572             // Action: NEW
573             foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
574
575                 // If Datasource is set, get the data from there
576                 if(@is_array($field['datasource'])) {
577                     if(is_array($field["value"])) {
578                         $field["value"] = $app->functions->array_merge($field["value"], $this->getDatasourceData($field, $record));
5bff39 579                     } else {
b1a6a5 580                         $field["value"] = $this->getDatasourceData($field, $record);
5bff39 581                     }
b1a6a5 582                 }
MC 583
584                 // If a limitation for the values is set
585                 if(isset($field['valuelimit']) && is_array($field["value"])) {
586                     $field["value"] = $this->applyValueLimit($field['valuelimit'], $field["value"]);
587                 }
588
589                 switch ($field['formtype']) {
590                 case 'SELECT':
591                     if(is_array($field['value'])) {
592                         $out = '';
593                         foreach($field['value'] as $k => $v) {
594                             $selected = ($k == $field["default"])?' SELECTED':'';
595                             $out .= "<option value='$k'$selected>".$this->lng($v)."</option>\r\n";
596                         }
5bff39 597                     }
b1a6a5 598                     if(isset($out)) $new_record[$key] = $out;
MC 599                     break;
600                 case 'MULTIPLE':
601                     if(is_array($field['value'])) {
602
603                         // aufsplitten ergebnisse
604                         $vals = explode($field['separator'], $val);
605
606                         // HTML schreiben
607                         $out = '';
608                         foreach($field['value'] as $k => $v) {
609
610                             $out .= "<option value='$k'>$v</option>\r\n";
611                         }
5bff39 612                     }
b1a6a5 613                     $new_record[$key] = $out;
MC 614                     break;
615
616                 case 'PASSWORD':
617                     //$new_record[$key] = '';
618                     $new_record[$key] = htmlspecialchars($field['default']);
619                     break;
620
621                 case 'CHECKBOX':
622                     // $checked = (empty($field["default"]))?'':' CHECKED';
623                     $checked = ($field["default"] == $field['value'][1])?' CHECKED':'';
624                     $new_record[$key] = "<input name=\"".$key."\" id=\"".$key."\" value=\"".$field['value'][1]."\" type=\"checkbox\" $checked />\r\n";
625                     break;
626
627                 case 'CHECKBOXARRAY':
628                     if(is_array($field['value'])) {
629
630                         // aufsplitten ergebnisse
631                         $vals = explode($field['separator'], $field["default"]);
632
633                         // HTML schreiben
634                         $out = '';
635                         $elementNo = 0;
636                         foreach($field['value'] as $k => $v) {
637
638                             $checked = '';
639                             foreach($vals as $tvl) {
640                                 if(trim($tvl) == trim($k)) $checked = ' CHECKED';
641                             }
642                             // $out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"checkbox\" $checked /> $v</label>\r\n";
643                             $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"checkbox\" $checked /> $v</label> &nbsp;\r\n";
644                             $elementNo++;
645                         }
5bff39 646                     }
b1a6a5 647                     $new_record[$key] = $out;
MC 648                     break;
649
650                 case 'RADIO':
651                     if(is_array($field['value'])) {
652
653                         // HTML schreiben
654                         $out = '';
655                         $elementNo = 0;
656                         foreach($field['value'] as $k => $v) {
657                             $checked = ($k == $field["default"])?' CHECKED':'';
658                             //$out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
659                             $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
660                             $elementNo++;
661                         }
5bff39 662                     }
b1a6a5 663                     $new_record[$key] = $out;
MC 664                     break;
665
666                 case 'DATETIME':
667                     $dt_value = (isset($field['default'])) ? $field['default'] : 0;
668                     $display_seconds = (isset($field['display_seconds']) && $field['display_seconds'] == true) ? true : false;
669
670                     $new_record[$key] = $this->_getDateTimeHTML($key, $dt_value, $display_seconds);
671                     break;
672
673                 default:
674                     $new_record[$key] = htmlspecialchars($field['default']);
675                 }
676             }
677
678         }
679
680         if($this->debug == 1) $this->dbg($new_record);
681
682         return $new_record;
683     }
684
685     /**
686      * Rewrite the record data to be stored in the database
687      * and check values with regular expressions.
688      *
689      * @param record = Datensatz als Array
690      * @return record
691      */
692     protected function _encode($record, $tab, $dbencode = true, $api = false) {
693         global $app;
985390 694         if($api == true) {
MC 695             $fields = &$this->formDef['fields'];
696         } else {
697             $fields = &$this->formDef['tabs'][$tab]['fields'];
698             /* CSRF PROTECTION */
699             if(isset($_POST) && is_array($_POST)) {
700                 $_csrf_valid = false;
701                 if(isset($_POST['_csrf_id']) && isset($_POST['_csrf_key'])) {
702                     $_csrf_id = trim($_POST['_csrf_id']);
703                     $_csrf_key = trim($_POST['_csrf_key']);
704                     if(isset($_SESSION['_csrf']) && isset($_SESSION['_csrf'][$_csrf_id]) && isset($_SESSION['_csrf_timeout']) && isset($_SESSION['_csrf_timeout'][$_csrf_id])) {
705                         if($_SESSION['_csrf'][$_csrf_id] === $_csrf_key && $_SESSION['_csrf_timeout'] >= time()) $_csrf_valid = true;
706                     }
707                 }
708                 if($_csrf_valid !== true) {
709                     $app->log('CSRF attempt blocked. Referer: ' . (isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : 'unknown'), LOGLEVEL_WARN);
352477 710                     $errmsg = 'err_csrf_attempt_blocked';
MC 711                     $this->errorMessage .= ($api == true ? $errmsg : $this->wordbook[$errmsg]."<br />") . "\r\n";
985390 712                     unset($_POST);
MC 713                     unset($record);
714                 }
715                 
716                 if(isset($_SESSION['_csrf_timeout']) && is_array($_SESSION['_csrf_timeout'])) {
717                     $to_unset = array();
718                     foreach($_SESSION['_csrf_timeout'] as $_csrf_id => $timeout) {
719                         if($timeout < time()) $to_unset[] = $_csrf_id;
720                     }
721                     foreach($to_unset as $_csrf_id) {
c8b685 722                         $_SESSION['_csrf'][$_csrf_id] = null;
MC 723                         $_SESSION['_csrf_timeout'][$_csrf_id] = null;
985390 724                         unset($_SESSION['_csrf'][$_csrf_id]);
MC 725                         unset($_SESSION['_csrf_timeout'][$_csrf_id]);
726                     }
727                     unset($to_unset);
728                 }
729             }
730             /* CSRF PROTECTION */
731         }
732         
733         $new_record = array();
b1a6a5 734         if(is_array($record)) {
MC 735             foreach($fields as $key => $field) {
736
737                 //* Apply filter to record value
738                 if(isset($field['filters']) && is_array($field['filters'])) {
739                     $record[$key] = $this->filterField($key, (isset($record[$key]))?$record[$key]:'', $field['filters'], 'SAVE');
740                 }
741                 //* Validate record value
742                 if(isset($field['validators']) && is_array($field['validators'])) {
743                     $this->validateField($key, (isset($record[$key]))?$record[$key]:'', $field['validators']);
744                 }
745
746                 switch ($field['datatype']) {
747                 case 'VARCHAR':
748                     if(!@is_array($record[$key])) {
749                         $new_record[$key] = (isset($record[$key]))?$record[$key]:'';
750                     } else {
751                         $new_record[$key] = implode($field['separator'], $record[$key]);
752                     }
753                     break;
754                 case 'TEXT':
755                     if(!is_array($record[$key])) {
756                         $new_record[$key] = $record[$key];
757                     } else {
758                         $new_record[$key] = implode($field['separator'], $record[$key]);
759                     }
760                     break;
761                 case 'DATETSTAMP':
762                     if($record[$key] > 0) {
763                         list($tag, $monat, $jahr) = explode('.', $record[$key]);
764                         $new_record[$key] = mktime(0, 0, 0, $monat, $tag, $jahr);
765                     } else {
766                         $new_record[$key] = 0;
767                     }
768                     break;
769                 case 'DATE':
770                     if($record[$key] != '' && $record[$key] != '0000-00-00') {
771                         if(function_exists('date_parse_from_format')) {
772                             $date_parts = date_parse_from_format($this->dateformat, $record[$key]);
86bc65 773                             $new_record[$key] = $date_parts['year'].'-'.str_pad($date_parts['month'], 2, "0", STR_PAD_LEFT).'-'.str_pad($date_parts['day'], 2, "0", STR_PAD_LEFT);
b1a6a5 774                         } else {
MC 775                             $tmp = strtotime($record[$key]);
776                             $new_record[$key] = date('Y-m-d', $tmp);
777                         }
778                     } else {
779                         $new_record[$key] = '0000-00-00';
780                     }
781                     break;
782                 case 'INTEGER':
783                     $new_record[$key] = (isset($record[$key]))?$app->functions->intval($record[$key]):0;
784                     break;
785                 case 'DOUBLE':
786                     $new_record[$key] = $record[$key];
787                     break;
788                 case 'CURRENCY':
789                     $new_record[$key] = str_replace(",", ".", $record[$key]);
790                     break;
791
792                 case 'DATETIME':
43e5b6 793                     /*if (is_array($record[$key]))
b1a6a5 794                     {
MC 795                         $filtered_values = array_map(create_function('$item', 'return (int)$item;'), $record[$key]);
796                         extract($filtered_values, EXTR_PREFIX_ALL, '_dt');
797
798                         if ($_dt_day != 0 && $_dt_month != 0 && $_dt_year != 0) {
799                             $new_record[$key] = date( 'Y-m-d H:i:s', mktime($_dt_hour, $_dt_minute, $_dt_second, $_dt_month, $_dt_day, $_dt_year) );
800                         }
43e5b6 801                     } else {*/
MC 802                         if($record[$key] != '' && $record[$key] != '0000-00-00 00:00:00') {
803                             $tmp = strtotime($record[$key]);
804                             $new_record[$key] = date($this->datetimeformat, $tmp);
805                         } else {
806                             $new_record[$key] = '0000-00-00 00:00:00';
807                         }
808                     /*}*/
b1a6a5 809                     break;
MC 810                 }
811
812                 // The use of the field value is deprecated, use validators instead
813                 if(isset($field['regex']) && $field['regex'] != '') {
814                     // Enable that "." matches also newlines
815                     $field['regex'] .= 's';
816                     if(!preg_match($field['regex'], $record[$key])) {
817                         $errmsg = $field['errmsg'];
818                         $this->errorMessage .= ($api == true ? $errmsg : $this->wordbook[$errmsg]."<br />") . "\r\n";
819                     }
820                 }
821
822                 //* Add slashes to all records, when we encode data which shall be inserted into mysql.
823                 if($dbencode == true) $new_record[$key] = $app->db->quote($new_record[$key]);
824             }
825         }
826         return $new_record;
827     }
828
829
830     /**
831      * Rewrite the record data to be stored in the database
832      * and check values with regular expressions.
833      *
834      * @param record = Datensatz als Array
835      * @return record
836      */
837     function encode($record, $tab, $dbencode = true) {
838         global $app;
839
840         if(!is_array($this->formDef['tabs'][$tab])) $app->error("Tab is empty or does not exist (TAB: $tab).");
841         return $this->_encode($record, $tab, $dbencode, false);
842     }
843
844
845     /**
846      * process the filters for a given field.
847      *
848      * @param field_name = Name of the field
849      * @param field_value = value of the field
850      * @param filters = Array of filters
851      * @param filter_event = 'SAVE'or 'SHOW'
852      * @return record
853      */
854     function filterField($field_name, $field_value, $filters, $filter_event) {
855
856         global $app;
857         $returnval = $field_value;
858
859         //* Loop trough all filters
860         foreach($filters as $filter) {
861             if($filter['event'] == $filter_event) {
862                 switch ($filter['type']) {
863                 case 'TOLOWER':
864                     $returnval = strtolower($returnval);
865                     break;
866                 case 'TOUPPER':
867                     $returnval = strtoupper($returnval);
868                     break;
869                 case 'IDNTOASCII':
870                     $returnval = $app->functions->idn_encode($returnval);
871                     break;
872                 case 'IDNTOUTF8':
873                     $returnval = $app->functions->idn_decode($returnval);
874                     break;
61f1f5 875                 case 'TRIM':
MC 876                     $returnval = trim($returnval);
877                     break;
b1a6a5 878                 default:
MC 879                     $this->errorMessage .= "Unknown Filter: ".$filter['type'];
880                     break;
881                 }
882             }
883         }
884         return $returnval;
885     }
886
887
888     /**
889      * process the validators for a given field.
890      *
891      * @param field_name = Name of the field
892      * @param field_value = value of the field
893      * @param validatoors = Array of validators
894      * @return record
895      */
896     function validateField($field_name, $field_value, $validators) {
897
898         global $app;
899
900         $escape = '`';
901
902         // loop trough the validators
903         foreach($validators as $validator) {
904
905             switch ($validator['type']) {
906             case 'REGEX':
907                 $validator['regex'] .= 's';
908                 if(!preg_match($validator['regex'], $field_value)) {
909                     $errmsg = $validator['errmsg'];
910                     if(isset($this->wordbook[$errmsg])) {
911                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
912                     } else {
5bff39 913                         $this->errorMessage .= $errmsg."<br />\r\n";
M 914                     }
b1a6a5 915                 }
5bff39 916                 break;
b1a6a5 917             case 'UNIQUE':
MC 918                 if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n';
919                 if($validator['allowempty'] == 'n' || ($validator['allowempty'] == 'y' && $field_value != '')){
920                     if($this->action == 'NEW') {
2af58c 921                         $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ?? WHERE ?? = ?", $this->formDef['db_table'], $field_name, $field_value);
b1a6a5 922                         if($num_rec["number"] > 0) {
MC 923                             $errmsg = $validator['errmsg'];
924                             if(isset($this->wordbook[$errmsg])) {
925                                 $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
926                             } else {
927                                 $this->errorMessage .= $errmsg."<br />\r\n";
928                             }
5bff39 929                         }
M 930                     } else {
2af58c 931                         $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ?? WHERE ?? = ? AND ?? != ?", $this->formDef['db_table'], $field_name, $field_value, $this->formDef['db_table_idx'], $this->primary_id);
b1a6a5 932                         if($num_rec["number"] > 0) {
MC 933                             $errmsg = $validator['errmsg'];
934                             if(isset($this->wordbook[$errmsg])) {
935                                 $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
936                             } else {
937                                 $this->errorMessage .= $errmsg."<br />\r\n";
938                             }
5bff39 939                         }
M 940                     }
941                 }
b1a6a5 942                 break;
MC 943             case 'NOTEMPTY':
86e699 944                 if(!isset($field_value) || $field_value === '') {
b1a6a5 945                     $errmsg = $validator['errmsg'];
MC 946                     if(isset($this->wordbook[$errmsg])) {
947                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
948                     } else {
949                         $this->errorMessage .= $errmsg."<br />\r\n";
950                     }
951                 }
952                 break;
bd8b72 953             case 'ISASCII':
MC 954                 if(preg_match("/[^\x20-\x7F]/", $field_value)) {
955                     $errmsg = $validator['errmsg'];
956                     if(isset($this->wordbook[$errmsg])) {
957                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
958                     } else {
959                         $this->errorMessage .= $errmsg."<br />\r\n";
960                     }
961                 }
b1a6a5 962             case 'ISEMAIL':
MC 963                 if(function_exists('filter_var')) {
964                     if(filter_var($field_value, FILTER_VALIDATE_EMAIL) === false) {
965                         $errmsg = $validator['errmsg'];
966                         if(isset($this->wordbook[$errmsg])) {
967                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
5bff39 968                         } else {
b1a6a5 969                             $this->errorMessage .= $errmsg."<br />\r\n";
5bff39 970                         }
b1a6a5 971                     }
MC 972                 } else {
973                     if(!preg_match("/^\w+[\w\.\-\+]*\w{0,}@\w+[\w.-]*\w+\.[a-zA-Z0-9\-]{2,30}$/i", $field_value)) {
974                         $errmsg = $validator['errmsg'];
975                         if(isset($this->wordbook[$errmsg])) {
976                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
977                         } else {
978                             $this->errorMessage .= $errmsg."<br />\r\n";
979                         }
980                     }
5bff39 981                 }
b1a6a5 982                 break;
MC 983             case 'ISINT':
984                 if(function_exists('filter_var') && $field_value < 2147483647) {
985                     if($field_value != '' && filter_var($field_value, FILTER_VALIDATE_INT) === false) {
986                         $errmsg = $validator['errmsg'];
987                         if(isset($this->wordbook[$errmsg])) {
988                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
989                         } else {
990                             $this->errorMessage .= $errmsg."<br />\r\n";
991                         }
992                     }
993                 } else {
994                     $tmpval = $app->functions->intval($field_value);
995                     if($tmpval === 0 and !empty($field_value)) {
996                         $errmsg = $validator['errmsg'];
997                         if(isset($this->wordbook[$errmsg])) {
998                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
999                         } else {
1000                             $this->errorMessage .= $errmsg."<br />\r\n";
1001                         }
1002                     }
1003                 }
1004                 break;
1005             case 'ISPOSITIVE':
1006                 if(!is_numeric($field_value) || $field_value <= 0){
1007                     $errmsg = $validator['errmsg'];
1008                     if(isset($this->wordbook[$errmsg])) {
1009                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1010                     } else {
1011                         $this->errorMessage .= $errmsg."<br />\r\n";
1012                     }
1013                 }
1014                 break;
fbeb11 1015             case 'V6PREFIXEND':
FS 1016                 $explode_field_value = explode(':',$field_value);
1017 //                if ($explode_field_value[count($explode_field_value)-1]=='' && $explode_field_value[count($explode_field_value)-2]=='' ){ }
1018                 if (!$explode_field_value[count($explode_field_value)-1]=='' && $explode_field_value[count($explode_field_value)-2]!='' ) {
1019                     $errmsg = $validator['errmsg'];
1020                     if(isset($this->wordbook[$errmsg])) {
1021                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1022                     } else {
1023                         $this->errorMessage .= $errmsg."<br />\r\n";
1024                     }
1025                 }
1026                 break;
1027             case 'V6PREFIXLENGTH':
1028                 // find shortes ipv6 subnet can`t be longer
1029                 $sql_v6 = $app->db->queryOneRecord("SELECT ip_address FROM server_ip WHERE ip_type = 'IPv6' AND virtualhost = 'y' ORDER BY CHAR_LENGTH(ip_address) ASC LIMIT 0,1;");
1030                 $sql_v6_explode=explode(':',$sql_v6['ip_address']);
1031                 $explode_field_value = explode(':',$field_value);
1032                 if (count($sql_v6_explode) < count($explode_field_value) && isset($sql_v6['ip_address'])) {
1033                     $errmsg = $validator['errmsg'];
1034                     if(isset($this->wordbook[$errmsg])) {
1035                         $this->errorMessage .= $this->wordbook[$errmsg].$sql_v6[ip_address]."<br />\r\n";
1036                     } else {
1037                         $this->errorMessage .= $errmsg."<br />\r\n";
1038                     }
1039                 }
1040                 break;
b1a6a5 1041             case 'ISV6PREFIX':
fbeb11 1042                 $v6_prefix_ok=0;
FS 1043                 $explode_field_value = explode(':',$field_value);
b1a6a5 1044                 if ($explode_field_value[count($explode_field_value)-1]=='' && $explode_field_value[count($explode_field_value)-2]=='' ){
MC 1045                     if ( count($explode_field_value) <= 9 ) {
fbeb11 1046                         if (filter_var(substr($field_value,0,strlen($field_value)-2),FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) or filter_var(substr($field_value,0,strlen($field_value)-2).'::0',FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) or filter_var(substr($field_value,0,strlen($field_value)-2).':0',FILTER_VALIDATE_IP,FILTER_FLAG_IPV6) ) {
b1a6a5 1047                             $v6_prefix_ok = 1;
MC 1048                         }
1049                     }
1050                 }
fbeb11 1051                 if($v6_prefix_ok <> 1) {
b1a6a5 1052                     $errmsg = $validator['errmsg'];
fbeb11 1053                     if(isset($this->wordbook[$errmsg])) {
FS 1054                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1055                     } else {
1056                         $this->errorMessage .= $errmsg."<br />\r\n";
1057                     }
b1a6a5 1058                 }
MC 1059                 break;
fbeb11 1060
FS 1061
1062
b1a6a5 1063             case 'ISIPV4':
MC 1064                 $vip=1;
1065                 if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){
1066                     $groups=explode(".", $field_value);
1067                     foreach($groups as $group){
1068                         if($group<0 or $group>255)
1069                             $vip=0;
1070                     }
1071                 }else{$vip=0;}
1072                 if($vip==0) {
1073                     $errmsg = $validator['errmsg'];
1074                     if(isset($this->wordbook[$errmsg])) {
1075                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1076                     } else {
1077                         $this->errorMessage .= $errmsg."<br />\r\n";
1078                     }
1079                 }
1080                 break;
1081             case 'ISIP':
1082                 if($validator['allowempty'] != 'y') $validator['allowempty'] = 'n';
1083                 if($validator['allowempty'] == 'y' && $field_value == '') {
1084                     //* Do nothing
1085                 } else {
1086                     //* Check if its a IPv4 or IPv6 address
1087                     if(isset($validator['separator']) && $validator['separator'] != '') {
1088                         //* When the field may contain several IP addresses, split them by the char defined as separator
1089                         $field_value_array = explode($validator['separator'], $field_value);
1090                     } else {
1091                         $field_value_array[] = $field_value;
1092                     }
1093                     foreach($field_value_array as $field_value) {
1094                         $field_value = trim($field_value);
1095                         if(function_exists('filter_var')) {
1096                             if(!filter_var($field_value, FILTER_VALIDATE_IP)) {
1097                                 $errmsg = $validator['errmsg'];
1098                                 if(isset($this->wordbook[$errmsg])) {
1099                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1100                                 } else {
1101                                     $this->errorMessage .= $errmsg."<br />\r\n";
1102                                 }
1103                             }
1104                         } else {
1105                             //* Check content with regex, if we use php < 5.2
1106                             $ip_ok = 0;
1107                             if(preg_match("/^(\:\:([a-f0-9]{1,4}\:){0,6}?[a-f0-9]{0,4}|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){0,6}?\:\:|[a-f0-9]{1,4}(\:[a-f0-9]{1,4}){1,6}?\:\:([a-f0-9]{1,4}\:){1,6}?[a-f0-9]{1,4})(\/\d{1,3})?$/i", $field_value)){
1108                                 $ip_ok = 1;
1109                             }
1110                             if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){
1111                                 $ip_ok = 1;
1112                             }
1113                             if($ip_ok == 0) {
1114                                 $errmsg = $validator['errmsg'];
1115                                 if(isset($this->wordbook[$errmsg])) {
1116                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1117                                 } else {
1118                                     $this->errorMessage .= $errmsg."<br />\r\n";
1119                                 }
1120                             }
1121                         }
1122                     }
1123                 }
1124                 break;
1125             case 'RANGE':
1126                 //* Checks if the value is within the given range or above / below a value
1127                 //* Range examples: < 10 = ":10", between 2 and 10 = "2:10", above 5 = "5:".
1128                 $range_parts = explode(':', trim($validator['range']));
1129                 $ok = true;
1130                 if($range_parts[0] != '' && $field_value < $range_parts[0]) {
1131                     $ok = false;
1132                 }
1133                 if($range_parts[1] != '' && $field_value > $range_parts[1]) {
1134                     $ok = false;
1135                 }
1136                 if($ok != true) {
1137                     $errmsg = $validator['errmsg'];
1138                     if(isset($this->wordbook[$errmsg])) {
1139                         $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
1140                     } else {
1141                         $this->errorMessage .= $errmsg."<br />\r\n";
1142                     }
1143                 }
1144                 unset($range_parts);
1145                 break;
1146             case 'CUSTOM':
1147                 // Calls a custom class to validate this record
1148                 if($validator['class'] != '' and $validator['function'] != '') {
1149                     $validator_class = $validator['class'];
1150                     $validator_function = $validator['function'];
1151                     $app->uses($validator_class);
1152                     $this->errorMessage .= $app->$validator_class->$validator_function($field_name, $field_value, $validator);
1153                 } else {
1154                     $this->errorMessage .= "Custom validator class or function is empty<br />\r\n";
1155                 }
1156                 break;
1157             default:
1158                 $this->errorMessage .= "Unknown Validator: ".$validator['type'];
1159                 break;
1160             }
5bff39 1161
M 1162
1163         }
b1a6a5 1164
MC 1165         return true;
1166     }
1167
1168     /**
1169      * Create SQL statement
1170      *
1171      * @param record = Datensatz als Array
1172      * @param action = INSERT oder UPDATE
1173      * @param primary_id
1174      * @return record
1175      */
3a11d2 1176      /* TODO: check for double quoting */
b1a6a5 1177     protected function _getSQL($record, $tab, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '', $api = false) {
MC 1178
1179         global $app;
1180
1181         $this->action = $action;
1182         $this->primary_id = $primary_id;
1183
1184
1185         $record = $this->encode($record, $tab, true);
1186         $sql_insert_key = '';
1187         $sql_insert_val = '';
1188         $sql_update = '';
1189
1190         if($api == true) $fields = &$this->formDef['fields'];
1191         else $fields = &$this->formDef['tabs'][$tab]['fields'];
1192
1193         // go trough all fields of the tab
1194         if(is_array($record)) {
1195             foreach($fields as $key => $field) {
1196                 // Wenn es kein leeres Passwortfeld ist
1197                 if (!($field['formtype'] == 'PASSWORD' and $record[$key] == '')) {
1198                     // Erzeuge Insert oder Update Quelltext
1199                     if($action == "INSERT") {
1200                         if($field['formtype'] == 'PASSWORD') {
1201                             $sql_insert_key .= "`$key`, ";
1202                             if ((isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') || (isset($record['_ispconfig_pw_crypted']) && $record['_ispconfig_pw_crypted'] == 1)) {
1203                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1204                             } elseif(isset($field['encryption']) && $field['encryption'] == 'CRYPT') {
1205                                 $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
1206                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1207                             } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
2af58c 1208                                 $tmp = $app->db->queryOneRecord("SELECT PASSWORD(?) as `crypted`", stripslashes($record[$key]));
b1a6a5 1209                                 $record[$key] = $tmp['crypted'];
MC 1210                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1211                             } else {
1212                                 $record[$key] = md5(stripslashes($record[$key]));
1213                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
1214                             }
1215                         } elseif ($field['formtype'] == 'CHECKBOX') {
1216                             $sql_insert_key .= "`$key`, ";
1217                             if($record[$key] == '') {
1218                                 // if a checkbox is not set, we set it to the unchecked value
1219                                 $sql_insert_val .= "'".$field['value'][0]."', ";
1220                                 $record[$key] = $field['value'][0];
1221                             } else {
1222                                 $sql_insert_val .= "'".$record[$key]."', ";
1223                             }
1224                         } else {
1225                             $sql_insert_key .= "`$key`, ";
1226                             $sql_insert_val .= "'".$record[$key]."', ";
1227                         }
1228                     } else {
1229                         if($field['formtype'] == 'PASSWORD') {
1230                             if ((isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') || (isset($record['_ispconfig_pw_crypted']) && $record['_ispconfig_pw_crypted'] == 1)) {
1231                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1232                             } elseif(isset($field['encryption']) && $field['encryption'] == 'CRYPT') {
1233                                 $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
1234                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1235                             } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
2af58c 1236                                 $tmp = $app->db->queryOneRecord("SELECT PASSWORD(?) as `crypted`", stripslashes($record[$key]));
b1a6a5 1237                                 $record[$key] = $tmp['crypted'];
MC 1238                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1239                             } else {
1240                                 $record[$key] = md5(stripslashes($record[$key]));
1241                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
1242                             }
1243
1244                         } elseif ($field['formtype'] == 'CHECKBOX') {
1245                             if($record[$key] == '') {
1246                                 // if a checkbox is not set, we set it to the unchecked value
1247                                 $sql_update .= "`$key` = '".$field['value'][0]."', ";
1248                                 $record[$key] = $field['value'][0];
1249                             } else {
1250                                 $sql_update .= "`$key` = '".$record[$key]."', ";
1251                             }
1252                         } else {
1253                             $sql_update .= "`$key` = '".$record[$key]."', ";
1254                         }
1255                     }
1256                 } else {
1257                     // we unset the password filed, if empty to tell the datalog function
1258                     // that the password has not been changed
1259                     unset($record[$key]);
1260                 }
1261             }
1262         }
1263
1264
1265         // Add backticks for incomplete table names
1266         if(stristr($this->formDef['db_table'], '.')) {
1267             $escape = '';
1268         } else {
1269             $escape = '`';
1270         }
1271
1272
1273         if($action == "INSERT") {
1274             if($this->formDef['auth'] == 'yes') {
1275                 // Set user and group
1276                 $sql_insert_key .= "`sys_userid`, ";
1277                 $sql_insert_val .= ($this->formDef["auth_preset"]["userid"] > 0)?"'".$this->formDef["auth_preset"]["userid"]."', ":"'".$_SESSION["s"]["user"]["userid"]."', ";
1278                 $sql_insert_key .= "`sys_groupid`, ";
1279                 $sql_insert_val .= ($this->formDef["auth_preset"]["groupid"] > 0)?"'".$this->formDef["auth_preset"]["groupid"]."', ":"'".$_SESSION["s"]["user"]["default_group"]."', ";
1280                 $sql_insert_key .= "`sys_perm_user`, ";
1281                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_user"]."', ";
1282                 $sql_insert_key .= "`sys_perm_group`, ";
1283                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_group"]."', ";
1284                 $sql_insert_key .= "`sys_perm_other`, ";
1285                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_other"]."', ";
1286             }
1287             $sql_insert_key = substr($sql_insert_key, 0, -2);
1288             $sql_insert_val = substr($sql_insert_val, 0, -2);
1289             $sql = "INSERT INTO ".$escape.$this->formDef['db_table'].$escape." ($sql_insert_key) VALUES ($sql_insert_val)";
1290         } else {
1291             if($this->formDef['auth'] == 'yes') {
1292                 if($primary_id != 0) {
1293                     if($api == true && $_SESSION["s"]["user"]["client_id"] > 0 && $_SESSION["s"]["user"]["iserid"] > 0 && $_SESSION["s"]["user"]["default_group"] > 0) {
1294                         $sql_update .= '`sys_userid` = '.$this->sys_userid.', ';
1295                         $sql_update .= '`sys_groupid` = '.$this->sys_default_group.', ';
1296                     }
1297
1298                     $sql_update = substr($sql_update, 0, -2);
1299                     $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->getAuthSQL('u')." AND ".$this->formDef['db_table_idx']." = ".$primary_id;
1300                     if($sql_ext_where != '') $sql .= " and ".$sql_ext_where;
1301                 } else {
1302                     $app->error("Primary ID fehlt!");
1303                 }
1304             } else {
1305                 if($primary_id != 0) {
1306                     $sql_update = substr($sql_update, 0, -2);
1307                     $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id;
1308                     if($sql_ext_where != '') $sql .= " and ".$sql_ext_where;
1309                 } else {
1310                     $app->error("Primary ID fehlt!");
1311                 }
1312             }
1313             //* return a empty string if there is nothing to update
1314             if(trim($sql_update) == '') $sql = '';
1315         }
1316
1317         return $sql;
1318     }
1319
1320
1321     /**
1322      * Create SQL statement
1323      *
1324      * @param record = Datensatz als Array
1325      * @param action = INSERT oder UPDATE
1326      * @param primary_id
1327      * @return record
1328      */
1329     function getSQL($record, $tab, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '') {
1330
1331         global $app;
1332
1333         // If there are no data records on the tab, return empty sql string
1334         if(count($this->formDef['tabs'][$tab]['fields']) == 0) return '';
1335
1336         // checking permissions
1337         if($this->formDef['auth'] == 'yes' && $_SESSION["s"]["user"]["typ"] != 'admin') {
1338             if($action == "INSERT") {
1339                 if(!$this->checkPerm($primary_id, 'i')) $this->errorMessage .= "Insert denied.<br />\r\n";
1340             } else {
1341                 if(!$this->checkPerm($primary_id, 'u')) $this->errorMessage .= "Update denied.<br />\r\n";
1342             }
1343         }
1344
1345         if(!is_array($this->formDef)) $app->error("Form definition not found.");
1346         if(!is_array($this->formDef['tabs'][$tab])) $app->error("The tab is empty or does not exist (TAB: $tab).");
1347
1348         return $this->_getSQL($record, $tab, $action, $primary_id, $sql_ext_where, false);
1349     }
1350
1351
1352     /**
1353      * Debugging arrays.
1354      *
1355      * @param array_data
1356      */
1357     function dbg($array_data) {
1358
1359         echo "<pre>";
1360         print_r($array_data);
1361         echo "</pre>";
1362
1363     }
5bff39 1364
M 1365
1366     function showForm() {
b1a6a5 1367         global $app, $conf;
5bff39 1368
M 1369         if(!is_array($this->formDef)) die("Form Definition wurde nicht geladen.");
1370
b1a6a5 1371         $active_tab = $this->getNextTab();
5bff39 1372
M 1373         // go trough the tabs
1374         foreach( $this->formDef["tabs"] as $key => $tab) {
1375
1376             $tab['name'] = $key;
1377             // Translate the title of the tab
1378             $tab['title'] = $this->lng($tab['title']);
1379
1380             if($tab['name'] == $active_tab) {
1381
1382                 // If module is set, then set the template path relative to the module..
1383                 if($this->module != '') $tab["template"] = "../".$this->module."/".$tab["template"];
1384
1385                 // Generate the template if it does not exist yet.
1386
1387
1388
1389                 if(!is_file($tab["template"])) {
b1a6a5 1390                     $app->uses('tform_tpl_generator');
MC 1391                     $app->tform_tpl_generator->buildHTML($this->formDef, $tab['name']);
5bff39 1392                 }
M 1393                 $app->tpl->setVar('readonly_tab', (isset($tab['readonly']) && $tab['readonly'] == true));
b1a6a5 1394                 $app->tpl->setInclude('content_tpl', $tab["template"]);
5bff39 1395                 $tab["active"] = 1;
M 1396                 $_SESSION["s"]["form"]["tab"] = $tab['name'];
1397             } else {
b1a6a5 1398                 $tab["active"] = 0;
5bff39 1399             }
M 1400
b1a6a5 1401             // Unset unused variables.
MC 1402             unset($tab["fields"]);
1403             unset($tab["plugins"]);
5bff39 1404
M 1405             $frmTab[] = $tab;
1406         }
1407
1408         // setting form tabs
1409         $app->tpl->setLoop("formTab", $frmTab);
1410
b1a6a5 1411         // Set form action
MC 1412         $app->tpl->setVar('form_action', $this->formDef["action"]);
1413         $app->tpl->setVar('form_active_tab', $active_tab);
5bff39 1414
b1a6a5 1415         // Set form title
MC 1416         $form_hint = $this->lng($this->formDef["title"]);
1417         if($this->formDef["description"] != '') $form_hint .= '<div class="pageForm_description">'.$this->lng($this->formDef["description"]).'</div>';
1418         $app->tpl->setVar('form_hint', $form_hint);
5bff39 1419
b1a6a5 1420         // Set Wordbook for this form
5bff39 1421
b1a6a5 1422         $app->tpl->setVar($this->wordbook);
MC 1423     }
1424
1425     function getDataRecord($primary_id) {
1426         global $app;
1427         $escape = '`';
2af58c 1428         $sql = "SELECT * FROM ?? WHERE ?? = ? AND ".$this->getAuthSQL('r', $this->formDef['db_table']);
MC 1429         return $app->db->queryOneRecord($sql, $this->formDef['db_table'], $this->formDef['db_table_idx'], $primary_id);
b1a6a5 1430     }
MC 1431
1432
1433     function datalogSave($action, $primary_id, $record_old, $record_new) {
1434         global $app, $conf;
1435
1436         $app->db->datalogSave($this->formDef['db_table'], $action, $this->formDef['db_table_idx'], $primary_id, $record_old, $record_new);
1437         return true;
1438     }
1439
1440     function getAuthSQL($perm, $table = '') {
ebbe63 1441         if($_SESSION["s"]["user"]["typ"] == 'admin' || $_SESSION['s']['user']['mailuser_id'] > 0) {
b1a6a5 1442             return '1';
MC 1443         } else {
1444             if ($table != ''){
1445                 $table = ' ' . $table . '.';
1446             }
1447             $groups = ( $_SESSION["s"]["user"]["groups"] ) ? $_SESSION["s"]["user"]["groups"] : 0;
1448             $sql = '(';
1449             $sql .= "(" . $table . "sys_userid = ".$_SESSION["s"]["user"]["userid"]." AND " . $table . "sys_perm_user like '%$perm%') OR  ";
1450             $sql .= "(" . $table . "sys_groupid IN (".$groups.") AND " . $table ."sys_perm_group like '%$perm%') OR ";
1451             $sql .= $table . "sys_perm_other like '%$perm%'";
1452             $sql .= ')';
1453
1454             return $sql;
5bff39 1455         }
b1a6a5 1456     }
5bff39 1457
M 1458 }
1459
1460 ?>