tbrehm
2012-05-21 7d9225b2cfa096605d5c338b68384815c86ff2e8
commit | author | age
2dadd2 1 <?php
T 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 /**
32 * Formularbehandlung
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)
d7ef36 43 *        - DATE (Date format, converts from and to UNIX timestamps automatically)
2dadd2 44 *
T 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 eoarately.
58 *
59 */
60
61 class tform {
62
63         /**
64         * Table definition (array)
65         * @var tableDef
66         */
67         var $tableDef;
68
69         /**
70         * Private
71         * @var action
72         */
73         var $action;
74
75         /**
76         * Table name (String)
77         * @var table_name
78         */
79         var $table_name;
80
81         /**
82         * Enable debigging
83         * @var debug
84         */
85         var $debug = 0;
86
87         /**
88         * name of the primary field of the datbase table (string)
89         * @var table_index
90         */
91         var $table_index;
92
93         /**
94         * contains the error message
95         * @var errorMessage
96         */
97         var $errorMessage = '';
98
99         var $dateformat = "d.m.Y";
100         var $formDef;
101         var $wordbook;
102         var $module;
103         var $primary_id;
104         var $diffrec = array();
105
106         /**
107         * Loading of the table definition
108         *
109         * @param file: path to the form definition file
110         * @return true
111         */
112         /*
113         function loadTableDef($file) {
114                 global $app,$conf;
115
116                 include_once($file);
117                 $this->tableDef = $table;
118                 $this->table_name = $table_name;
119                 $this->table_index = $table_index;
120                 return true;
121         }
122         */
123
124     function loadFormDef($file,$module = '') {
125                 global $app,$conf;
126
127                 include_once($file);
128                 $this->formDef = $form;
129
130                 $this->module = $module;
131                 $wb = array();
132                 
133                 include_once(ISPC_ROOT_PATH.'/lib/lang/'.$_SESSION['s']['language'].'.lng');
40dd9f 134                 
T 135                 if(is_array($wb)) $wb_global = $wb;
136                 
2dadd2 137                 if($module == '') {
T 138                     $lng_file = "lib/lang/".$_SESSION["s"]["language"]."_".$this->formDef["name"].".lng";
139                     if(!file_exists($lng_file)) $lng_file = "lib/lang/en_".$this->formDef["name"].".lng";
140                     include($lng_file);
141                 } else {
142                     $lng_file = "../$module/lib/lang/".$_SESSION["s"]["language"]."_".$this->formDef["name"].".lng";
143                     if(!file_exists($lng_file)) $lng_file = "../$module/lib/lang/en_".$this->formDef["name"].".lng";
144                     include($lng_file);
145                 }
b5a0dc 146
40dd9f 147                 if(is_array($wb_global)) {
5bbfc1 148                     $wb = $app->functions->array_merge($wb_global,$wb);
40dd9f 149                 }
T 150                 if(isset($wb_global)) unset($wb_global);
151                 
2dadd2 152                 $this->wordbook = $wb;
b2673a 153                 
F 154                 $this->dateformat = $app->lng('conf_format_dateshort');
2dadd2 155
T 156                 return true;
157         }
158
159
160         /**
161         * Converts the data in the array to human readable format
162         * Datatype conversion e.g. to show the data in lists
163         *
164         * @param record
165         * @return record
166         */
167         function decode($record,$tab) {
1ca823 168                 global $conf, $app;
T 169                 if(!is_array($this->formDef['tabs'][$tab])) $app->error("Tab does not exist or the tab is empty (TAB: $tab).");
2dadd2 170                 $new_record = '';
f9c7f3 171                 $table_idx = $this->formDef['db_table_idx'];
T 172                 if(isset($record[$table_idx])) $new_record[$table_idx] = intval($record[$table_idx ]);
173                 
2dadd2 174                 if(is_array($record)) {
T 175                         foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
176                                 switch ($field['datatype']) {
177                                 case 'VARCHAR':
8f7333 178                                         $new_record[$key] = $record[$key];
2dadd2 179                                 break;
T 180
181                                 case 'TEXT':
8f7333 182                                         $new_record[$key] = $record[$key];
2dadd2 183                                 break;
T 184
57540e 185                                 case 'DATETSTAMP':
2dadd2 186                                         if($record[$key] > 0) {
T 187                                                 $new_record[$key] = date($this->dateformat,$record[$key]);
57540e 188                                         }
T 189                                 break;
190                                 
191                                 case 'DATE':
192                                         if($record[$key] != '' && $record[$key] != '0000-00-00') {
193                                                 $tmp = explode('-',$record[$key]);
194                                                 $new_record[$key] = date($this->dateformat,mktime(0, 0, 0, $tmp[1]  , $tmp[2], $tmp[0]));
2dadd2 195                                         }
T 196                                 break;
197
198                                 case 'INTEGER':
199                                         $new_record[$key] = intval($record[$key]);
200                                 break;
201
202                                 case 'DOUBLE':
203                                         $new_record[$key] = $record[$key];
204                                 break;
205
206                                 case 'CURRENCY':
1ca823 207                                         $new_record[$key] = $app->functions->currency_format($record[$key]);
2dadd2 208                                 break;
T 209
210                                 default:
8f7333 211                                         $new_record[$key] = $record[$key];
2dadd2 212                                 }
T 213                         }
214
215                 }
216                 
217         return $new_record;
218         }
219
220         /**
221         * Get the key => value array of a form filed from a datasource definitiom
222         *
223         * @param field = array with field definition
224         * @param record = Dataset as array
225         * @return key => value array for the value field of a form
226         */
227
228         function getDatasourceData($field, $record) {
229                 global $app;
230
231                 $values = array();
232
233                 if($field["datasource"]["type"] == 'SQL') {
234
235                         // Preparing SQL string. We will replace some
236                         // common placeholders
237                         $querystring = $field["datasource"]["querystring"];
238                         $querystring = str_replace("{USERID}",$_SESSION["s"]["user"]["userid"],$querystring);
239                         $querystring = str_replace("{GROUPID}",$_SESSION["s"]["user"]["default_group"],$querystring);
240                         $querystring = str_replace("{GROUPS}",$_SESSION["s"]["user"]["groups"],$querystring);
241                         $table_idx = $this->formDef['db_table_idx'];
242                         
243                         $tmp_recordid = (isset($record[$table_idx]))?$record[$table_idx]:0;
f9c7f3 244                         //$tmp_recordid = intval($this->primary_id);
2dadd2 245                         $querystring = str_replace("{RECORDID}",$tmp_recordid,$querystring);
T 246                         unset($tmp_recordid);
247                         
248                         $querystring = str_replace("{AUTHSQL}",$this->getAuthSQL('r'),$querystring);
f9c7f3 249                         
2dadd2 250                         // Getting the records
T 251                         $tmp_records = $app->db->queryAllRecords($querystring);
252                         if($app->db->errorMessage != '') die($app->db->errorMessage);
253                         if(is_array($tmp_records)) {
254                                 $key_field = $field["datasource"]["keyfield"];
255                                 $value_field = $field["datasource"]["valuefield"];
256                                 foreach($tmp_records as $tmp_rec) {
257                                         $tmp_id = $tmp_rec[$key_field];
258                                         $values[$tmp_id] = $tmp_rec[$value_field];
259                                 }
260                         }
261                 }
262
263                 if($field["datasource"]["type"] == 'CUSTOM') {
264                         // Calls a custom class to validate this record
265                         if($field["datasource"]['class'] != '' and $field["datasource"]['function'] != '') {
266                                 $datasource_class = $field["datasource"]['class'];
267                                 $datasource_function = $field["datasource"]['function'];
268                                 $app->uses($datasource_class);
269                                 $values = $app->$datasource_class->$datasource_function($field, $record);
270                         } else {
271                                 $this->errorMessage .= "Custom datasource class or function is empty<br />\r\n";
272                         }
273                 }
274
275                 return $values;
276
277         }
278         
279         //* If the parameter 'valuelimit' is set
280         function applyValueLimit($limit,$values) {
281             
282             global $app;
283             
284             $limit_parts = explode(':',$limit);
285             
286             //* values are limited to a comma separated list
287             if($limit_parts[0] == 'list') {
288                 $allowed = explode(',',$limit_parts[1]);
289             }
290             
291             //* values are limited to a field in the client settings
292             if($limit_parts[0] == 'client') {
293                 if($_SESSION["s"]["user"]["typ"] == 'admin') {
294                     return $values;
295                 } else {
296                     $client_group_id = $_SESSION["s"]["user"]["default_group"];
297                     $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");
298                     $allowed = explode(',',$client['lm']);
299                 }
300             }
301             
67c4b3 302             //* values are limited to a field in the reseller settings
T 303             if($limit_parts[0] == 'reseller') {
304                 if($_SESSION["s"]["user"]["typ"] == 'admin') {
305                     return $values;
306                 } else {
307                     //* Get the limits of the client that is currently logged in
308                     $client_group_id = $_SESSION["s"]["user"]["default_group"];
309                     $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");
310                     //echo "SELECT parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id";
311                     //* If the client belongs to a reseller, we will check against the reseller Limit too
312                     if($client['parent_client_id'] != 0) {
313                 
314                         //* first we need to know the groups of this reseller
315                         $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ".$client['parent_client_id']);
316                         $reseller_groups = $tmp["groups"];
317                         $reseller_userid = $tmp["userid"];
318                 
319                         // Get the limits of the reseller of the logged in client
320                         $client_group_id = $_SESSION["s"]["user"]["default_group"];
321                         $reseller = $app->db->queryOneRecord("SELECT ".$limit_parts[1]." as lm FROM client WHERE client_id = ".$client['parent_client_id']);
322                         $allowed = explode(',',$reseller['lm']);
323                     } else {
324                         return $values;
325                     }
326                 } // end if admin
327             } // end if reseller
328             
2dadd2 329             //* values are limited to a field in the system settings
T 330             if($limit_parts[0] == 'system') {
331                 $app->uses('getconf');
332                 $tmp_conf = $app->getconf->get_global_config($limit_parts[1]);
333                 $tmp_key = $limit_parts[2];
334                 $allowed = $tmp_conf[$tmp_key];
335             }
336             
337             $values_new = array();
338             foreach($values as $key => $val) {
339                 if(in_array($key,$allowed)) $values_new[$key] = $val;
340             }
341             
342             return $values_new;
343         }
344
345
346         /**
347         * Prepare the data record to show the data in a form.
348         *
349         * @param record = Datensatz als Array
350         * @param action = NEW oder EDIT
351         * @return record
352         */
353         function getHTML($record, $tab, $action = 'NEW') {
354
355                 global $app;
356
357                 $this->action = $action;
358
359                 if(!is_array($this->formDef)) $app->error("No form definition found.");
360                 if(!is_array($this->formDef['tabs'][$tab])) $app->error("The tab is empty or does not exist (TAB: $tab).");
361
362                 $new_record = array();
363                 if($action == 'EDIT') {
364                         $record = $this->decode($record,$tab);
365                         if(is_array($record)) {
366                                 foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
cd9d38 367                                 
T 368                                         if(isset($record[$key])) {
369                                             $val = $record[$key];
370                                         } else {
371                                             $val = '';
372                                         }
2dadd2 373
T 374                                         // If Datasource is set, get the data from there
375                                         if(isset($field['datasource']) && is_array($field['datasource'])) {
418623 376                                                 if(is_array($field["value"])) {
9f56bd 377                                                     //$field["value"] = array_merge($field["value"],$this->getDatasourceData($field, $record));
5bbfc1 378                                                     $field["value"] = $app->functions->array_merge($field["value"],$this->getDatasourceData($field, $record));
418623 379                                                 } else {
T 380                                                     $field["value"] = $this->getDatasourceData($field, $record);
381                                                 }
2dadd2 382                                         }
T 383                                         
384                                         // If a limitation for the values is set
385                                         if(isset($field['valuelimit']) && is_array($field["value"])) {
386                                             $field["value"] = $this->applyValueLimit($field['valuelimit'],$field["value"]);
387                                         }
388
389                                         switch ($field['formtype']) {
390                                         case 'SELECT':
391                                                 $out = '';
392                                                 if(is_array($field['value'])) {
393                                                         foreach($field['value'] as $k => $v) {
394                                                                 $selected = ($k == $val)?' SELECTED':'';
9539ce 395                                                                 if(!empty($this->wordbook[$v]))
F 396                                                                     $v = $this->wordbook[$v];
2dadd2 397                                                                 $out .= "<option value='$k'$selected>$v</option>\r\n";
T 398                                                         }
399                                                 }
400                                                 $new_record[$key] = $out;
401                                         break;
402                                         case 'MULTIPLE':
403                                                 if(is_array($field['value'])) {
404
405                                                         // Split
406                                                         $vals = explode($field['separator'],$val);
407
408                                                         // write HTML
409                                                         $out = '';
410                                                         foreach($field['value'] as $k => $v) {
411
412                                                                 $selected = '';
413                                                                 foreach($vals as $tvl) {
414                                                                         if(trim($tvl) == trim($k)) $selected = ' SELECTED';
415                                                                 }
416
417                                                                 $out .= "<option value='$k'$selected>$v</option>\r\n";
418                                                         }
419                                                 }
420                                                 $new_record[$key] = $out;
421                                         break;
422
423                                         case 'PASSWORD':
424                                                 $new_record[$key] = '';
425                                         break;
426
427                                         case 'CHECKBOX':
428                                                 $checked = ($val == $field['value'][1])?' CHECKED':'';
429                                                 $new_record[$key] = "<input name=\"".$key."\" id=\"".$key."\" value=\"".$field['value'][1]."\" type=\"checkbox\" $checked />\r\n";
430                                         break;
431
432                                         case 'CHECKBOXARRAY':
433                                                 if(is_array($field['value'])) {
434
435                                                         // aufsplitten ergebnisse
436                                                         $vals = explode($field['separator'],$val);
437
438                                                         // HTML schreiben
439                                                         $out = '';
5d0a76 440                                                         $elementNo = 0;
2dadd2 441                                                         foreach($field['value'] as $k => $v) {
T 442
443                                                                 $checked = '';
444                                                                 foreach($vals as $tvl) {
445                                                                         if(trim($tvl) == trim($k)) $checked = ' CHECKED';
446                                                                 }
447                                                                 // $out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"checkbox\" $checked /> $v</label>\r\n";
5d0a76 448                                                                 $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"checkbox\" $checked /> $v</label><br/>\r\n";
M 449                                                                 $elementNo++;
2dadd2 450                                                         }
T 451                                                 }
452                                                 $new_record[$key] = $out;
453                                         break;
454
455                                         case 'RADIO':
456                                                 if(is_array($field['value'])) {
457
458                                                         // HTML schreiben
459                                                         $out = '';
5d0a76 460                                                         $elementNo = 0;
2dadd2 461                                                         foreach($field['value'] as $k => $v) {
T 462                                                                 $checked = ($k == $val)?' CHECKED':'';
463                                                                 //$out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
5d0a76 464                                                                 $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"radio\" $checked/> $v </label>\r\n";
M 465                                                                 $elementNo++;
2dadd2 466                                                         }
T 467                                                 }
468                                                 $new_record[$key] = $out;
469                                         break;
75ae20 470                                         
W 471                                         case 'DATETIME':
472                                                 if (strtotime($val) !== false) {
473                                                     $dt_value = $val;
474                                                 } elseif ( isset($field['default']) && (strtotime($field['default']) !== false) ) {
475                                                     $dt_value = $field['default'];
476                                                 } else {
477                                                     $dt_value = 0;
478                                                 }
479                                                 
480                                                 $display_seconds = (isset($field['display_seconds']) && $field['display_seconds'] == true) ? true : false;
481                                       
482                                                 $new_record[$key] = $this->_getDateTimeHTML($key, $dt_value, $display_seconds);
483                                         break;
2dadd2 484
T 485                                         default:
cd9d38 486                                             if(isset($record[$key])) {
2dadd2 487                                                 $new_record[$key] = htmlspecialchars($record[$key]);
cd9d38 488                                             } else {
T 489                                                 $new_record[$key] = '';
490                                             }
2dadd2 491                                         }
T 492                                 }
493                         }
494                 } else {
495                         // Action: NEW
496                         foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
497
498                                 // If Datasource is set, get the data from there
499                                 if(@is_array($field['datasource'])) {
418623 500                                     if(is_array($field["value"])) {
5bbfc1 501                                         $field["value"] = $app->functions->array_merge($field["value"],$this->getDatasourceData($field, $record));
418623 502                                     } else {
T 503                                         $field["value"] = $this->getDatasourceData($field, $record);
504                                     }
2dadd2 505                                 }
T 506                                 
507                                 // If a limitation for the values is set
508                                 if(isset($field['valuelimit']) && is_array($field["value"])) {
509                                     $field["value"] = $this->applyValueLimit($field['valuelimit'],$field["value"]);
510                                 }
511
512                                 switch ($field['formtype']) {
513                                 case 'SELECT':
514                                         if(is_array($field['value'])) {
515                                                 $out = '';
516                                                 foreach($field['value'] as $k => $v) {
a47108 517                                                     $selected = ($k == $field["default"])?' SELECTED':'';
b5a0dc 518                                                     $out .= "<option value='$k'$selected>".$this->lng($v)."</option>\r\n";
2dadd2 519                                                 }
T 520                                         }
521                                         if(isset($out)) $new_record[$key] = $out;
522                                 break;
523                                 case 'MULTIPLE':
524                                                 if(is_array($field['value'])) {
525
526                                                         // aufsplitten ergebnisse
527                                                         $vals = explode($field['separator'],$val);
528
529                                                         // HTML schreiben
530                                                         $out = '';
531                                                         foreach($field['value'] as $k => $v) {
532
533                                                                 $out .= "<option value='$k'>$v</option>\r\n";
534                                                         }
535                                                 }
536                                                 $new_record[$key] = $out;
537                                         break;
538
539                                 case 'PASSWORD':
540                                         $new_record[$key] = '';
541                                 break;
542
543                                 case 'CHECKBOX':
544                                         // $checked = (empty($field["default"]))?'':' CHECKED';
545                                                             $checked = ($field["default"] == $field['value'][1])?' CHECKED':'';
546                                         $new_record[$key] = "<input name=\"".$key."\" id=\"".$key."\" value=\"".$field['value'][1]."\" type=\"checkbox\" $checked />\r\n"; 
547                                 break;
548
549                                 case 'CHECKBOXARRAY':
550                                         if(is_array($field['value'])) {
551
552                                                 // aufsplitten ergebnisse
553                                                 $vals = explode($field['separator'],$field["default"]);
554
555                                                 // HTML schreiben
556                                                 $out = '';
5d0a76 557                                                 $elementNo = 0;
2dadd2 558                                                 foreach($field['value'] as $k => $v) {
T 559
560                                                         $checked = '';
561                                                         foreach($vals as $tvl) {
562                                                                 if(trim($tvl) == trim($k)) $checked = ' CHECKED';
563                                                         }
564                                                         // $out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"checkbox\" $checked /> $v</label>\r\n";
5d0a76 565                                                         $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"checkbox\" $checked /> $v</label> &nbsp;\r\n";
M 566                                                         $elementNo++;
2dadd2 567                                                 }
T 568                                         }
569                                         $new_record[$key] = $out;
570                                 break;
571
572                                 case 'RADIO':
573                                         if(is_array($field['value'])) {
574
575                                                 // HTML schreiben
576                                                 $out = '';
5d0a76 577                                                 $elementNo = 0;
2dadd2 578                                                 foreach($field['value'] as $k => $v) {
T 579                                                         $checked = ($k == $field["default"])?' CHECKED':'';
580                                                         //$out .= "<label for=\"".$key."[]\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key."[]\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
5d0a76 581                                                         $out .= "<label for=\"".$key.$elementNo."\" class=\"inlineLabel\"><input name=\"".$key."[]\" id=\"".$key.$elementNo."\" value=\"$k\" type=\"radio\" $checked/> $v</label>\r\n";
M 582                                                         $elementNo++;
2dadd2 583                                                 }
T 584                                         }
585                                         $new_record[$key] = $out;
586                                 break;
75ae20 587                                 
W 588                                 case 'DATETIME':
589                                         $dt_value = (isset($field['default'])) ? $field['default'] : 0;
590                                         $display_seconds = (isset($field['display_seconds']) && $field['display_seconds'] == true) ? true : false;
591                               
592                                         $new_record[$key] = $this->_getDateTimeHTML($key, $dt_value, $display_seconds);
593                                 break;
2dadd2 594
T 595                                 default:
596                                         $new_record[$key] = htmlspecialchars($field['default']);
597                                 }
598                         }
599
600                 }
601
602                 if($this->debug == 1) $this->dbg($new_record);
603
604                 return $new_record;
605         }
606
607         /**
608         * Rewrite the record data to be stored in the database
609         * and check values with regular expressions.
610         *
611         * @param record = Datensatz als Array
612         * @return record
613         */
2b81b8 614         function encode($record,$tab,$dbencode = true) {
2dadd2 615             global $app;
T 616             
617                 if(!is_array($this->formDef['tabs'][$tab])) $app->error("Tab is empty or does not exist (TAB: $tab).");
618                 //$this->errorMessage = '';
619
620                 if(is_array($record)) {
621                         foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
622
623                                 if(isset($field['validators']) && is_array($field['validators'])) $this->validateField($key, (isset($record[$key]))?$record[$key]:'', $field['validators']);
624
625                                 switch ($field['datatype']) {
626                                 case 'VARCHAR':
627                                         if(!@is_array($record[$key])) {
2b81b8 628                                                 $new_record[$key] = (isset($record[$key]))?$record[$key]:'';
2dadd2 629                                         } else {
T 630                                                 $new_record[$key] = implode($field['separator'],$record[$key]);
631                                         }
632                                 break;
633                                 case 'TEXT':
634                                         if(!is_array($record[$key])) {
2b81b8 635                                                 $new_record[$key] = $record[$key];
2dadd2 636                                         } else {
T 637                                                 $new_record[$key] = implode($field['separator'],$record[$key]);
638                                         }
639                                 break;
57540e 640                                 case 'DATETSTAMP':
2dadd2 641                                         if($record[$key] > 0) {
T 642                                                 list($tag,$monat,$jahr) = explode('.',$record[$key]);
643                                                 $new_record[$key] = mktime(0,0,0,$monat,$tag,$jahr);
644                                         } else {
645                                             $new_record[$key] = 0;
646                                         }
647                                 break;
57540e 648                                 case 'DATE':
T 649                                         if($record[$key] != '' && $record[$key] != '0000-00-00') {
1ca823 650                                                 if(function_exists('date_parse_from_format')) {
T 651                                                     $date_parts = date_parse_from_format($this->dateformat,$record[$key]);
652                                                     //list($tag,$monat,$jahr) = explode('.',$record[$key]);
653                                                     $new_record[$key] = $date_parts['year'].'-'.$date_parts['month'].'-'.$date_parts['day'];
654                                                     //$tmp = strptime($record[$key],$this->dateformat);
655                                                     //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday'];
656                                                 } else {
657                                                     //$tmp = strptime($record[$key],$this->dateformat);
658                                                     //$new_record[$key] = ($tmp['tm_year']+1900).'-'.($tmp['tm_mon']+1).'-'.$tmp['tm_mday'];
659                                                     $tmp = strtotime($record[$key]);
660                                                     $new_record[$key] = date('Y-m-d',$tmp);
661                                                 }
57540e 662                                         } else {
T 663                                             $new_record[$key] = '0000-00-00';
664                                         }
665                                 break;
2dadd2 666                                 case 'INTEGER':
T 667                                         $new_record[$key] = (isset($record[$key]))?$record[$key]:0;
668                                         //if($new_record[$key] != $record[$key]) $new_record[$key] = $field['default'];
669                                         //if($key == 'refresh') die($record[$key]);
670                                 break;
671                                 case 'DOUBLE':
2b81b8 672                                         $new_record[$key] = $record[$key];
2dadd2 673                                 break;
T 674                                 case 'CURRENCY':
675                                         $new_record[$key] = str_replace(",",".",$record[$key]);
75ae20 676                                 break;
W 677                                 
678                                 case 'DATETIME':
679                                         if (is_array($record[$key]))
680                                         {
681                                             $filtered_values = array_map(create_function('$item','return (int)$item;'), $record[$key]);
682                                             extract($filtered_values, EXTR_PREFIX_ALL, '_dt');
683                                             
684                                             if ($_dt_day != 0 && $_dt_month != 0 && $_dt_year != 0) {
685                                                 $new_record[$key] = date( 'Y-m-d H:i:s', mktime($_dt_hour, $_dt_minute, $_dt_second, $_dt_month, $_dt_day, $_dt_year) );
686                                             }
687                                         }
2dadd2 688                                 break;
T 689                                 }
690
691                                 // The use of the field value is deprecated, use validators instead
692                                 if(isset($field['regex']) && $field['regex'] != '') {
693                                         // Enable that "." matches also newlines
694                                         $field['regex'] .= 's';
695                                         if(!preg_match($field['regex'], $record[$key])) {
696                                                 $errmsg = $field['errmsg'];
697                                                 $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
698                                         }
699                                 }
2b81b8 700                                 
T 701                                 //* Add slashes to all records, when we encode data which shall be inserted into mysql.
702                                 if($dbencode == true) $new_record[$key] = $app->db->quote($new_record[$key]);
2dadd2 703                         }
T 704                 }
705                 return $new_record;
706         }
707
708         /**
709         * process the validators for a given field.
710         *
711         * @param field_name = Name of the field
712         * @param field_value = value of the field
713         * @param validatoors = Array of validators
714         * @return record
715         */
716
717         function validateField($field_name, $field_value, $validators) {
718
719                 global $app;
720                 
721                 $escape = '`';
722                 
723                 // loop trough the validators
724                 foreach($validators as $validator) {
725
726                         switch ($validator['type']) {
727                                 case 'REGEX':
728                                         $validator['regex'] .= 's';
729                                         if(!preg_match($validator['regex'], $field_value)) {
730                                                 $errmsg = $validator['errmsg'];
731                                                 if(isset($this->wordbook[$errmsg])) {
732                                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
733                                                 } else {
734                                                     $this->errorMessage .= $errmsg."<br />\r\n";
735                                                 }
736                                         }
737                                 break;
738                                 case 'UNIQUE':
739                                         if($this->action == 'NEW') {
740                                                 $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."'");
741                                                 if($num_rec["number"] > 0) {
742                                                         $errmsg = $validator['errmsg'];
743                                                         if(isset($this->wordbook[$errmsg])) {
744                                                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
745                                                         } else {
746                                                             $this->errorMessage .= $errmsg."<br />\r\n";
747                                                         }
748                                                 }
749                                         } else {
750                                                 $num_rec = $app->db->queryOneRecord("SELECT count(*) as number FROM ".$escape.$this->formDef['db_table'].$escape. " WHERE $field_name = '".$app->db->quote($field_value)."' AND ".$this->formDef['db_table_idx']." != ".$this->primary_id);
751                                                 if($num_rec["number"] > 0) {
752                                                         $errmsg = $validator['errmsg'];
753                                                         if(isset($this->wordbook[$errmsg])) {
754                                                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
755                                                         } else {
756                                                             $this->errorMessage .= $errmsg."<br />\r\n";
757                                                         }
758                                                 }
759                                         }
760                                 break;
761                                 case 'NOTEMPTY':
762                                         if(empty($field_value)) {
763                                                 $errmsg = $validator['errmsg'];
764                                                 if(isset($this->wordbook[$errmsg])) {
765                                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
766                                                 } else {
767                                                     $this->errorMessage .= $errmsg."<br />\r\n";
768                                                 }
769                                         }
770                                 break;
771                                 case 'ISEMAIL':
04620b 772                                         if(!preg_match("/^\w+[\w\.\-\+]*\w{0,}@\w+[\w.-]*\w+\.[a-zA-Z0-9\-]{2,30}$/i", $field_value)) {
2dadd2 773                                                 $errmsg = $validator['errmsg'];
T 774                                                 if(isset($this->wordbook[$errmsg])) {
775                                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
776                                                 } else {
777                                                     $this->errorMessage .= $errmsg."<br />\r\n";
778                                                 }
779                                         }
780                                 break;
781                                 case 'ISINT':
782                                         $tmpval = intval($field_value);
783                                         if($tmpval === 0 and !empty($field_value)) {
784                                                 $errmsg = $validator['errmsg'];
785                                                 if(isset($this->wordbook[$errmsg])) {
786                                                     $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
787                                                 } else {
788                                                     $this->errorMessage .= $errmsg."<br />\r\n";
789                                                 }
790                                         }
791                                 break;
792                                 case 'ISPOSITIVE':
793                                         if(!is_numeric($field_value) || $field_value <= 0){
794                                           $errmsg = $validator['errmsg'];
795                                           if(isset($this->wordbook[$errmsg])) {
796                                              $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
797                                           } else {
798                                              $this->errorMessage .= $errmsg."<br />\r\n";
799                                           }
800                                         }
801                                 break;
802                                 case 'ISIPV4':
803                                 $vip=1;
804                                 if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){
805                                 $groups=explode(".",$field_value);
806                                 foreach($groups as $group){
807                                     if($group<0 OR $group>255)
808                                     $vip=0;
809                                 }
810                                 }else{$vip=0;}
811                                         if($vip==0) {
812                                         $errmsg = $validator['errmsg'];
813                                           if(isset($this->wordbook[$errmsg])) {
814                                              $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
815                                           } else {
816                                              $this->errorMessage .= $errmsg."<br />\r\n";
817                                           }
818                                         }
819                                 break;
a70698 820                                 case 'ISIP':
T 821                                 //* Check if its a IPv4 or IPv6 address
822                                 if(function_exists('filter_var')) {
823                                     if(!filter_var($field_value,FILTER_VALIDATE_IP)) {
824                                         $errmsg = $validator['errmsg'];
825                                         if(isset($this->wordbook[$errmsg])) {
826                                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
827                                         } else {
828                                             $this->errorMessage .= $errmsg."<br />\r\n";
829                                         }
830                                     }
831                                 } else {
832                                     //* Check content with regex, if we use php < 5.2
833                                     $ip_ok = 0;
834                                     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)){
835                                         $ip_ok = 1;
836                                     }
837                                     if(preg_match("/^[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}(\.)[0-9]{1,3}$/", $field_value)){
838                                         $ip_ok = 1;
839                                     }
840                                     if($ip_ok == 0) {
841                                         $errmsg = $validator['errmsg'];
842                                         if(isset($this->wordbook[$errmsg])) {
843                                             $this->errorMessage .= $this->wordbook[$errmsg]."<br />\r\n";
844                                         } else {
845                                             $this->errorMessage .= $errmsg."<br />\r\n";
846                                         }
847                                     }
848                                 }
849                                 break;
2dadd2 850                                 case 'CUSTOM':
T 851                                         // Calls a custom class to validate this record
852                                         if($validator['class'] != '' and $validator['function'] != '') {
853                                                 $validator_class = $validator['class'];
854                                                 $validator_function = $validator['function'];
855                                                 $app->uses($validator_class);
856                                                 $this->errorMessage .= $app->$validator_class->$validator_function($field_name, $field_value, $validator);
857                                         } else {
858                                                 $this->errorMessage .= "Custom validator class or function is empty<br />\r\n";
859                                         }
860                                 break;
861                                 default:
862                                     $this->errorMessage .= "Unknown Validator: ".$validator['type'];
863                                 break;
864                         }
865
866
867                 }
868
869                 return true;
870         }
871
872         /**
873         * Create the SQL staement.
874         *
875         * @param record = Datensatz als Array
876         * @param action = INSERT oder UPDATE
877         * @param primary_id
878         * @return record
879         */
880         function getSQL($record, $tab, $action = 'INSERT', $primary_id = 0, $sql_ext_where = '') {
881
882                 global $app;
883
884                 // If there are no data records on the tab, return empty sql string
885                 if(count($this->formDef['tabs'][$tab]['fields']) == 0) return '';
886
887                 // checking permissions
888                 if($this->formDef['auth'] == 'yes' && $_SESSION["s"]["user"]["typ"] != 'admin') {
889                         if($action == "INSERT") {
890                                 if(!$this->checkPerm($primary_id,'i')) $this->errorMessage .= "Insert denied.<br />\r\n";
891                         } else {
892                                 if(!$this->checkPerm($primary_id,'u')) $this->errorMessage .= "Update denied.<br />\r\n";
893                         }
894                 }
895
896                 $this->action = $action;
897                 $this->primary_id = $primary_id;
898
7d9225 899                 $record = $this->encode($record,$tab,true);
2dadd2 900                 $sql_insert_key = '';
T 901                 $sql_insert_val = '';
902                 $sql_update = '';
903
904                 if(!is_array($this->formDef)) $app->error("Form definition not found.");
905                 if(!is_array($this->formDef['tabs'][$tab])) $app->error("The tab is empty or does not exist (TAB: $tab).");
906
907                 // go trough all fields of the tab
908                 if(is_array($record)) {
909                 foreach($this->formDef['tabs'][$tab]['fields'] as $key => $field) {
910                                 // Wenn es kein leeres Passwortfeld ist
911                                 if (!($field['formtype'] == 'PASSWORD' and $record[$key] == '')) {
912                                         // Erzeuge Insert oder Update Quelltext
913                                         if($action == "INSERT") {
914                                                 if($field['formtype'] == 'PASSWORD') {
915                                                         $sql_insert_key .= "`$key`, ";
916                                                         if($field['encryption'] == 'CRYPT') {
c614f1 917                                                                 $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
2dadd2 918                                                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
T 919                                                         } elseif ($field['encryption'] == 'MYSQL') {
920                                                                 $sql_insert_val .= "PASSWORD('".$app->db->quote($record[$key])."'), ";
921                                                         } elseif ($field['encryption'] == 'CLEARTEXT') {
922                                                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
923                                                         } else {
04620b 924                                                                 $record[$key] = md5(stripslashes($record[$key]));
2dadd2 925                                                                 $sql_insert_val .= "'".$app->db->quote($record[$key])."', ";
T 926                                                         }
927                                                         
928                                                 } elseif ($field['formtype'] == 'CHECKBOX') {
929                                                         $sql_insert_key .= "`$key`, ";
930                                                         if($record[$key] == '') {
931                                                             // if a checkbox is not set, we set it to the unchecked value
932                                                             $sql_insert_val .= "'".$field['value'][0]."', ";
933                                                             $record[$key] = $field['value'][0];
934                                                         } else {
935                                                             $sql_insert_val .= "'".$record[$key]."', ";
936                                                         }
937                                                 } else {
938                                                         $sql_insert_key .= "`$key`, ";
939                                                         $sql_insert_val .= "'".$record[$key]."', ";
940                                                 }
941                                         } else {
942                                                 if($field['formtype'] == 'PASSWORD') {
943                                                         if(isset($field['encryption']) && $field['encryption'] == 'CRYPT') {
c614f1 944                                                                 $record[$key] = $app->auth->crypt_password(stripslashes($record[$key]));
2dadd2 945                                                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
T 946                                                         } elseif (isset($field['encryption']) && $field['encryption'] == 'MYSQL') {
947                                                                 $sql_update .= "`$key` = PASSWORD('".$app->db->quote($record[$key])."'), ";
948                                                         } elseif (isset($field['encryption']) && $field['encryption'] == 'CLEARTEXT') {
949                                                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
950                                                         } else {
04620b 951                                                                 $record[$key] = md5(stripslashes($record[$key]));
2dadd2 952                                                                 $sql_update .= "`$key` = '".$app->db->quote($record[$key])."', ";
T 953                                                         }
954                                                         
955                                                 } elseif ($field['formtype'] == 'CHECKBOX') {
956                                                         if($record[$key] == '') {
957                                                             // if a checkbox is not set, we set it to the unchecked value
958                                                             $sql_update .= "`$key` = '".$field['value'][0]."', ";
959                                                             $record[$key] = $field['value'][0];
960                                                         } else {
961                                                             $sql_update .= "`$key` = '".$record[$key]."', ";
962                                                         }
963                                                 } else {
964                                                         $sql_update .= "`$key` = '".$record[$key]."', ";
965                                                 }
966                                         }
967                                 } else {
968                                     // we unset the password filed, if empty to tell the datalog function 
969                                     // that the password has not been changed
970                                     unset($record[$key]);
971                                 }
972                         }
973         }
974
975
976                 // Add backticks for incomplete table names
977                 if(stristr($this->formDef['db_table'],'.')) {
978                         $escape = '';
979                 } else {
980                         $escape = '`';
981                 }
982
983
984                 if($action == "INSERT") {
985                         if($this->formDef['auth'] == 'yes') {
986                                 // Set user and group
987                                 $sql_insert_key .= "`sys_userid`, ";
988                                 $sql_insert_val .= ($this->formDef["auth_preset"]["userid"] > 0)?"'".$this->formDef["auth_preset"]["userid"]."', ":"'".$_SESSION["s"]["user"]["userid"]."', ";
989                                 $sql_insert_key .= "`sys_groupid`, ";
990                                 $sql_insert_val .= ($this->formDef["auth_preset"]["groupid"] > 0)?"'".$this->formDef["auth_preset"]["groupid"]."', ":"'".$_SESSION["s"]["user"]["default_group"]."', ";
991                                 $sql_insert_key .= "`sys_perm_user`, ";
992                                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_user"]."', ";
993                                 $sql_insert_key .= "`sys_perm_group`, ";
994                                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_group"]."', ";
995                                 $sql_insert_key .= "`sys_perm_other`, ";
996                                 $sql_insert_val .= "'".$this->formDef["auth_preset"]["perm_other"]."', ";
997                         }
998                         $sql_insert_key = substr($sql_insert_key,0,-2);
999                         $sql_insert_val = substr($sql_insert_val,0,-2);
1000                         $sql = "INSERT INTO ".$escape.$this->formDef['db_table'].$escape." ($sql_insert_key) VALUES ($sql_insert_val)";
1001                 } else {
1002                     if($this->formDef['auth'] == 'yes') {
1003                         if($primary_id != 0) {
1004                                 $sql_update = substr($sql_update,0,-2);
1005                                 $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->getAuthSQL('u')." AND ".$this->formDef['db_table_idx']." = ".$primary_id;
1006                                 if($sql_ext_where != '') $sql .= " and ".$sql_ext_where;
1007                         } else {
1008                                 $app->error("Primary ID fehlt!");
1009                         }
1010                     } else {
1011                         if($primary_id != 0) {
1012                                 $sql_update = substr($sql_update,0,-2);
1013                                 $sql = "UPDATE ".$escape.$this->formDef['db_table'].$escape." SET ".$sql_update." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id;
1014                                 if($sql_ext_where != '') $sql .= " and ".$sql_ext_where;
1015                         } else {
1016                                 $app->error("Primary ID fehlt!");
1017                         }
1018                     }
1019                     //* return a empty string if there is nothing to update
1020                     if(trim($sql_update) == '') $sql = '';
1021                 }
7d9225 1022
2dadd2 1023                 return $sql;
T 1024         }
1025
1026         /**
1027         * Debugging arrays.
1028         *
1029         * @param array_data
1030         */
1031         function dbg($array_data) {
1032
1033                 echo "<pre>";
1034                 print_r($array_data);
1035                 echo "</pre>";
1036
1037         }
1038
1039
1040     function showForm() {
1041             global $app,$conf;
1042
1043         if(!is_array($this->formDef)) die("Form Definition wurde nicht geladen.");
1044
1045                 $active_tab = $this->getNextTab();
1046
1047         // go trough the tabs
1048         foreach( $this->formDef["tabs"] as $key => $tab) {
1049
1050             $tab['name'] = $key;
40dd9f 1051             // Translate the title of the tab
T 1052             $tab['title'] = $this->lng($tab['title']);
1053             
2dadd2 1054             if($tab['name'] == $active_tab) {
T 1055
1056                 // If module is set, then set the template path relative to the module..
1057                 if($this->module != '') $tab["template"] = "../".$this->module."/".$tab["template"];
1058
1059                 // Generate the template if it does not exist yet.
1060                 
40dd9f 1061                 
2dadd2 1062                                 
T 1063                 if(!is_file($tab["template"])) {
1064                      $app->uses('tform_tpl_generator');
1065                      $app->tform_tpl_generator->buildHTML($this->formDef,$tab['name']);
1066                 }
1067
1068                 $app->tpl->setInclude('content_tpl',$tab["template"]);
1069                 $tab["active"] = 1;
1070                 $_SESSION["s"]["form"]["tab"] = $tab['name'];
1071             } else {
1072                     $tab["active"] = 0;
1073             }
1074
1075                         // Unset unused variables.
1076                         unset($tab["fields"]);
1077                         unset($tab["plugins"]);
1078
1079             $frmTab[] = $tab;
1080         }
1081
1082         // setting form tabs
1083         $app->tpl->setLoop("formTab", $frmTab);
1084
1085                 // Set form action
1086                 $app->tpl->setVar('form_action',$this->formDef["action"]);
1087                 $app->tpl->setVar('form_active_tab',$active_tab);
1088
1089                 // Set form title
1090                 $form_hint = $this->lng($this->formDef["title"]);
1091                 if($this->formDef["description"] != '') $form_hint .= '<div class="pageForm_description">'.$this->lng($this->formDef["description"]).'</div>';
1092                 $app->tpl->setVar('form_hint',$form_hint);
1093
1094                 // Set Wordbook for this form
1095
1096                 $app->tpl->setVar($this->wordbook);
1097         }
1098
1099         function getDataRecord($primary_id) {
1100             global $app;
1101             $escape = '`';
1102             $sql = "SELECT * FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id;
1103             return $app->db->queryOneRecord($sql);
1104         }
1105         
1106
1107         function datalogSave($action,$primary_id, $record_old, $record_new) {
1108                 global $app,$conf;
74829e 1109                 
T 1110                 $app->db->datalogSave($this->formDef['db_table'], $action, $this->formDef['db_table_idx'], $primary_id, $record_old, $record_new);
1111                 return true;
1112                 
1113                 /*
2dadd2 1114                 // Add backticks for incomplete table names.
T 1115                 if(stristr($this->formDef['db_table'],'.')) {
1116                         $escape = '';
1117                 } else {
1118                         $escape = '`';
1119                 }
1120
1121                 $this->diffrec = array();
1122                 
1123                 // Full diff records for ISPConfig, they have a different format then the simple diffrec
1124                 $diffrec_full = array();
1125
1126                 if(is_array($record_old) && count($record_old) > 0) {
1127                         foreach($record_old as $key => $val) {
1128                                 //if(isset($record_new[$key]) && $record_new[$key] != $val) {
1129                                 if(!isset($record_new[$key]) || $record_new[$key] != $val) {
1130                                     // Record has changed
1131                                     $diffrec_full['old'][$key] = $val;
1132                                     $diffrec_full['new'][$key] = $record_new[$key];
1133                                     $this->diffrec[$key] = array(    'new' => $record_new[$key],
1134                                                                        'old' => $val);
1135                                 } else {
1136                                     $diffrec_full['old'][$key] = $val;
1137                                     $diffrec_full['new'][$key] = $val;
1138                                 }
1139                         }
1140                 } elseif(is_array($record_new)) {
1141                         foreach($record_new as $key => $val) {
1142                                 if(isset($record_new[$key]) && $record_old[$key] != $val) {
1143                                     // Record has changed
1144                                     $diffrec_full['new'][$key] = $val;
1145                                     $diffrec_full['old'][$key] = $record_old[$key];
1146                                     $this->diffrec[$key] = array(    'old' => @$record_old[$key],
1147                                                                        'new' => $val);
1148                                 } else {
1149                                     $diffrec_full['new'][$key] = $val;
1150                                     $diffrec_full['old'][$key] = $val;
1151                                 }
1152                         }
1153                 }
1154                 
1155                 //$this->diffrec = $diffrec;
1156                 // Insert the server_id, if the record has a server_id
1157                 $server_id = (isset($record_old["server_id"]) && $record_old["server_id"] > 0)?$record_old["server_id"]:0;
1158                 if(isset($record_new["server_id"])) $server_id = $record_new["server_id"];
1159
1160                 if(count($this->diffrec) > 0) {
1161                         $diffstr = addslashes(serialize($diffrec_full));
1162                         $username = $app->db->quote($_SESSION["s"]["user"]["username"]);
1163                         $dbidx = $this->formDef['db_table_idx'].":".$primary_id;
1164                         // $action = ($action == 'INSERT')?'i':'u';
1165                         
1166                         if($action == 'INSERT') $action = 'i';
1167                         if($action == 'UPDATE') $action = 'u';
1168                         if($action == 'DELETE') $action = 'd';
1169                         $sql = "INSERT INTO sys_datalog (dbtable,dbidx,server_id,action,tstamp,user,data) VALUES ('".$this->formDef['db_table']."','$dbidx','$server_id','$action','".time()."','$username','$diffstr')";
1170                         $app->db->query($sql);
1171                 }
1172
1173                 return true;
74829e 1174                 */
2dadd2 1175
T 1176         }
1177
24f38b 1178         function getAuthSQL($perm, $table = '') {
2dadd2 1179                 if($_SESSION["s"]["user"]["typ"] == 'admin') {
T 1180                     return '1';
1181                 } else {
24f38b 1182                     if ($table != ''){
V 1183                         $table = ' ' . $table . '.';
1184                     }
2dadd2 1185                     $groups = ( $_SESSION["s"]["user"]["groups"] ) ? $_SESSION["s"]["user"]["groups"] : 0;
T 1186                     $sql = '(';
24f38b 1187                     $sql .= "(" . $table . "sys_userid = ".$_SESSION["s"]["user"]["userid"]." AND " . $table . "sys_perm_user like '%$perm%') OR  ";
V 1188                     $sql .= "(" . $table . "sys_groupid IN (".$groups.") AND " . $table ."sys_perm_group like '%$perm%') OR ";
1189                     $sql .= $table . "sys_perm_other like '%$perm%'";
2dadd2 1190                     $sql .= ')';
T 1191
1192                     return $sql;
1193                 }
1194         }
1195
1196         /*
1197         This function checks if a user has the parmissions $perm for the data record with the ID $record_id
1198         If record_id = 0, the the permissions are tested against the defaults of the form file.
1199         */
1200         function checkPerm($record_id,$perm) {
1201                 global $app;
1202
1203                 if($record_id > 0) {
1204                         // Add backticks for incomplete table names.
1205                         if(stristr($this->formDef['db_table'],'.')) {
1206                                 $escape = '';
1207                         } else {
1208                                 $escape = '`';
1209                         }
1210
1211                         $sql = "SELECT ".$this->formDef['db_table_idx']." FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$record_id." AND ".$this->getAuthSQL($perm);
1212                         if($record = $app->db->queryOneRecord($sql)) {
1213                                 return true;
1214                         } else {
1215                                 return false;
1216                         }
1217                 } else {
1218                         $result = false;
1219                         if(@$this->formDef["auth_preset"]["userid"] == $_SESSION["s"]["user"]["userid"] && stristr($perm,$this->formDef["auth_preset"]["perm_user"])) $result = true;
1220                         if(@$this->formDef["auth_preset"]["groupid"] == $_SESSION["s"]["user"]["groupid"] && stristr($perm,$this->formDef["auth_preset"]["perm_group"])) $result = true;
1221                         if(@stristr($this->formDef["auth_preset"]["perm_other"],$perm)) $result = true;
1222
1223                         // if preset == 0, everyone can insert a record of this type
1224                         if($this->formDef["auth_preset"]["userid"] == 0 AND $this->formDef["auth_preset"]["groupid"] == 0 AND (@stristr($this->formDef["auth_preset"]["perm_user"],$perm) OR @stristr($this->formDef["auth_preset"]["perm_group"],$perm))) $result = true;
1225
1226                         return $result;
1227
1228                 }
1229
1230         }
1231
1232         function getNextTab() {
1233                 // Which tab is shown
1234                 if($this->errorMessage == '') {
1235                     // If there is no error
1236                     if(isset($_REQUEST["next_tab"]) && $_REQUEST["next_tab"] != '') {
1237                                 // If the next tab is known
1238                                 $active_tab = $_REQUEST["next_tab"];
1239                     } else {
1240                         // else use the default tab
1241                         $active_tab = $this->formDef['tab_default'];
1242                     }
1243                 } else {
1244                     // Show the same tab again in case of an error
1245                     $active_tab = $_SESSION["s"]["form"]["tab"];
1246                 }
1247
1248                 return $active_tab;
1249         }
1250
1251         function getCurrentTab() {
1252                 return $_SESSION["s"]["form"]["tab"];
1253         }
1254         
1255         function isReadonlyTab($tab, $primary_id) {
1256             global $app, $conf;
1257             
1258             // Add backticks for incomplete table names.
1259             if(stristr($this->formDef['db_table'],'.')) {
1260                 $escape = '';
1261             } else {
1262                 $escape = '`';
1263             }
1264             
1265             $sql = "SELECT sys_userid FROM ".$escape.$this->formDef['db_table'].$escape." WHERE ".$this->formDef['db_table_idx']." = ".$primary_id;
1266             $record = $app->db->queryOneRecord($sql);
1267             
1268             // return true if the readonly flag of the form is set and the current loggedin user is not the owner of the record.
1269             if(isset($this->formDef['tabs'][$tab]['readonly']) && $this->formDef['tabs'][$tab]['readonly'] == true && $record['sys_userid'] != $_SESSION["s"]["user"]["userid"]) {
1270                 return true;
1271             } else {
1272                 return false;
1273             }
1274         }
1275         
1276         
1277         // translation function for forms, tries the form wordbook first and if this fails, it tries the global wordbook
1278         function lng($msg) {
8d0c6b 1279             global $app,$conf;
2dadd2 1280             
T 1281             if(isset($this->wordbook[$msg])) {
1282                 return $this->wordbook[$msg];
1283             } else {
1284                 return $app->lng($msg);
1285             }
1286             
1287         }
3cebc3 1288         
T 1289         function checkClientLimit($limit_name,$sql_where = '') {
1290             global $app;
1291             
1292             $check_passed = true;
1293             $limit_name = $app->db->quote($limit_name);
1294             if($limit_name == '') $app->error('Limit name missing in function checkClientLimit.');
1295             
1296             // Get the limits of the client that is currently logged in
1297             $client_group_id = $_SESSION["s"]["user"]["default_group"];
1298             $client = $app->db->queryOneRecord("SELECT $limit_name as number, parent_client_id FROM sys_group, client WHERE sys_group.client_id = client.client_id and sys_group.groupid = $client_group_id");
1299             
1300             // Check if the user may add another item
1301             if($client["number"] >= 0) {
1302                 $sql = "SELECT count(".$this->formDef['db_table_idx'].") as number FROM ".$this->formDef['db_table']." WHERE ".$this->getAuthSQL('u');
1303                 if($sql_where != '') $sql .= ' and '.$sql_where;
1304                 $tmp = $app->db->queryOneRecord($sql);
1305                 if($tmp["number"] >= $client["number"]) $check_passed = false;
1306             }
1307             
1308             return $check_passed;
1309         }
1310         
1311         function checkResellerLimit($limit_name,$sql_where = '') {
1312             global $app;
1313             
1314             $check_passed = true;
1315             $limit_name = $app->db->quote($limit_name);
1316             if($limit_name == '') $app->error('Limit name missing in function checkClientLimit.');
1317             
1318             // Get the limits of the client that is currently logged in
1319             $client_group_id = $_SESSION["s"]["user"]["default_group"];
1320             $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");
1321             
1322             //* If the client belongs to a reseller, we will check against the reseller Limit too
1323             if($client['parent_client_id'] != 0) {
1324                 
1325                 //* first we need to know the groups of this reseller
1326                 $tmp = $app->db->queryOneRecord("SELECT userid, groups FROM sys_user WHERE client_id = ".$client['parent_client_id']);
1327                 $reseller_groups = $tmp["groups"];
1328                 $reseller_userid = $tmp["userid"];
1329                 
1330                 // Get the limits of the reseller of the logged in client
1331                 $client_group_id = $_SESSION["s"]["user"]["default_group"];
1332                 $reseller = $app->db->queryOneRecord("SELECT $limit_name as number FROM client WHERE client_id = ".$client['parent_client_id']);
1333             
1334                 // Check if the user may add another item
1335                 if($reseller["number"] >= 0) {
1336                     $sql = "SELECT count(".$this->formDef['db_table_idx'].") as number FROM ".$this->formDef['db_table']." WHERE (sys_groupid IN (".$reseller_groups.") or sys_userid = ".$reseller_userid.")";
1337                     if($sql_where != '') $sql .= ' and '.$sql_where;
1338                     $tmp = $app->db->queryOneRecord($sql);
1339                     if($tmp["number"] >= $reseller["number"]) $check_passed = false;
1340                 }
1341             }
1342             
1343             return $check_passed;
1344         }
11b3da 1345         
T 1346         //* get the difference record of two arrays
1347         function getDiffRecord($record_old,$record_new) {
1348             
1349             if(is_array($record_new) && count($record_new) > 0) {
1350             foreach($record_new as $key => $val) {
1351                 if(@$record_old[$key] != $val) {
1352                     // Record has changed
1353                     $diffrec[$key] = array(    'old' => @$record_old[$key],
1354                                             'new' => $val);
1355                     }
1356                 }
1357             } elseif(is_array($record_old)) {
1358                 foreach($record_old as $key => $val) {
1359                     if($record_new[$key] != $val) {
1360                         // Record has changed
1361                         $diffrec[$key] = array(    'new' => $record_new[$key],
1362                                                 'old' => $val);
1363                         }
1364                     }
1365                 }
1366             return $diffrec;
1367         
1368         }
75ae20 1369         
W 1370         /**
1371          * Generate HTML for DATETIME fields.
1372          * 
1373          * @access private
1374          * @param string $form_element Name of the form element.
1375          * @param string $default_value Selected value for fields.
1376          * @param bool $display_secons Include seconds selection.
1377          * @return string HTML    
1378          */
1379         function _getDateTimeHTML($form_element, $default_value, $display_seconds=false)
1380         {
1381             $_datetime = strtotime($default_value);
1382             $_showdate = ($_datetime === false) ? false : true;
2dadd2 1383
75ae20 1384             $dselect = array('day','month','year','hour','minute');
W 1385             if ($display_seconds === true) {
1386                  $dselect[] = 'second';
1387             }
1388              
1389             $out = '';
1390              
1391             foreach ($dselect as $dt_element)
1392             {
1393                  $dt_options = array();
1394                  $dt_space = 1;
1395                  
1396                  switch ($dt_element) {
1397                      case 'day':
1398                          for ($i = 1; $i <= 31; $i++) {
1399                             $dt_options[] = array('name' =>  sprintf('%02d', $i),
1400                                                   'value' => sprintf('%d', $i));
1401                         }
1402                         $selected_value = date('d', $_datetime);
1403                          break;
1404                          
1405                      case 'month':
1406                          for ($i = 1; $i <= 12; $i++) {
1407                             $dt_options[] = array('name' => strftime('%b', mktime(0, 0, 0, $i, 1, 2000)),
1408                                                   'value' => strftime('%m', mktime(0, 0, 0, $i, 1, 2000)));
1409                         }
1410                         $selected_value = date('n', $_datetime);
1411                          break;
1412                          
1413                      case 'year':
1414                          $start_year = strftime("%Y");
1415                         $years = range((int)$start_year, (int)($start_year+3));
1416                         
1417                         foreach ($years as $year) {
1418                             $dt_options[] = array('name' => $year,
1419                                                  'value' => $year);
1420                         }
1421                         $selected_value = date('Y', $_datetime);
1422                         $dt_space = 2;
1423                          break;
1424                          
1425                      case 'hour':
1426                          foreach(range(0, 23) as $hour) {
1427                              $dt_options[] = array('name' =>  sprintf('%02d', $hour),
1428                                                   'value' => sprintf('%d', $hour));
1429                          }
1430                          $selected_value = date('G', $_datetime);
1431                          break;
1432                          
1433                      case 'minute':
1434                          foreach(range(0, 59) as $minute) {
1435                              if (($minute % 5) == 0) {
1436                                  $dt_options[] = array('name' =>  sprintf('%02d', $minute),
1437                                                       'value' => sprintf('%d', $minute));
1438                              }
1439                          }
1440                          $selected_value = (int)floor(date('i', $_datetime));
1441                          break;
1442                          
1443                      case 'second':    
1444                          foreach(range(0, 59) as $second) {
1445                              $dt_options[] = array('name' =>  sprintf('%02d', $second),
1446                                                     'value' => sprintf('%d', $second));
1447                          }
1448                          $selected_value = (int)floor(date('s', $_datetime));
1449                          break;
1450                  }
1451                          
1452                 $out .= "<select name=\"".$form_element."[$dt_element]\" id=\"".$form_element."_$dt_element\" class=\"selectInput\" style=\"width: auto; float: none;\">";
1453                 if (!$_showdate) {
1454                     $out .= "<option value=\"-\" selected=\"selected\">--</option>" . PHP_EOL;
1455                 } else {
1456                     $out .= "<option value=\"-\">--</option>" . PHP_EOL;
1457                 }
1458                  
1459                 foreach ($dt_options as $dt_opt) {
1460                     if ( $_showdate && ($selected_value == $dt_opt['value']) ) {
1461                         $out .= "<option value=\"{$dt_opt['value']}\" selected=\"selected\">{$dt_opt['name']}</option>" . PHP_EOL;
1462                     } else {
1463                         $out .= "<option value=\"{$dt_opt['value']}\">{$dt_opt['name']}</option>" . PHP_EOL;
1464                     }
1465                 }
1466                                                         
1467                 $out .= '</select>' . str_repeat('&nbsp;', $dt_space);
1468             }
1469             
1470             return $out;
1471         }
2dadd2 1472 }
T 1473
d7ef36 1474 ?>