Completed
Push — master ( 46b52a...5bdb41 )
by Daniel
04:16 queued 42s
created

MySQLiAdvancedOutput::setNeededField()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 8
Bugs 0 Features 1
Metric Value
c 8
b 0
f 1
dl 0
loc 13
rs 9.2
cc 4
eloc 8
nc 5
nop 3
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * usefull functions to get quick results
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiAdvancedOutput
37
{
38
39
    use MySQLiByDanielGP;
40
41
    protected $advCache = null;
42
43
    /**
44
     * Establish Database and Table intended to work with
45
     * (in case the DB is ommited get the default one)
46
     *
47
     * @param string $tblSrc
48
     */
49
    private function establishDatabaseAndTable($tblSrc)
50
    {
51
        if (strpos($tblSrc, '.') === false) {
52
            if (!defined('MYSQL_DATABASE')) {
53
                define('MYSQL_DATABASE', 'information_schema');
54
            }
55
            return [$tblSrc, MYSQL_DATABASE];
56
        }
57
        return explode('.', str_replace('`', '', $tblSrc));
58
    }
59
60
    private function establishDefaultEnumSet($fldType)
61
    {
62
        $dfltArray = [
63
            'enum' => ['additional' => ['size' => 1], 'suffix' => ''],
64
            'set'  => ['additional' => ['size' => 5, 'multiselect'], 'suffix' => '[]'],
65
        ];
66
        return $dfltArray[$fldType];
67
    }
68
69
    private function fixTableSource($refTbl)
70
    {
71
        $outS = [];
72
        if (substr($refTbl, 0, 1) !== '`') {
73
            $outS[] = '`';
74
        }
75
        $psT = strpos($refTbl, '.`');
76
        if ($psT !== false) {
77
            $refTbl = substr($refTbl, $psT + 2, strlen($refTbl) - $psT);
78
        }
79
        $outS[] = $refTbl;
80
        if (substr($refTbl, -1) !== '`') {
81
            $outS[] = '`';
82
        }
83
        return implode('', $outS);
84
    }
85
86
    private function getFieldCompletionType($details)
87
    {
88
        $inputFeatures = ['display' => '***', 'ftrs' => ['title' => 'Mandatory', 'class' => 'inputMandatory']];
89
        if ($details['IS_NULLABLE'] == 'YES') {
90
            $inputFeatures = ['display' => '~', 'ftrs' => ['title' => 'Optional', 'class' => 'inputOptional']];
91
        }
92
        return $this->setStringIntoTag($inputFeatures['display'], 'span', $inputFeatures['ftrs']);
93
    }
94
95
    /**
96
     * Returns the name of a field for displaying
97
     *
98
     * @param array $details
99
     * @return string
100
     */
101
    private function getFieldNameForDisplay($details)
102
    {
103
        $tableUniqueId = $details['TABLE_SCHEMA'] . '.' . $details['TABLE_NAME'];
104
        if ($details['COLUMN_COMMENT'] != '') {
105
            return $details['COLUMN_COMMENT'];
106
        } elseif (isset($this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']])) {
107
            return $this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']];
108
        }
109
        return $details['COLUMN_NAME'];
110
    }
111
112
    /**
113
     * Returns a Date field 2 use in a form
114
     *
115
     * @param array $value
116
     * @return string
117
     */
118
    private function getFieldOutputDate($value)
119
    {
120
        $defaultValue = $this->getFieldValue($value);
121
        if (is_null($defaultValue)) {
122
            $defaultValue = date('Y-m-d');
123
        }
124
        $inA = [
125
            'type'      => 'text',
126
            'name'      => $value['Field'],
127
            'id'        => $value['Field'],
128
            'value'     => $defaultValue,
129
            'size'      => 10,
130
            'maxlength' => 10,
131
            'onfocus'   => implode('', [
132
                'javascript:NewCssCal(\'' . $value['Field'],
133
                '\',\'yyyyMMdd\',\'dropdown\',false,\'24\',false);',
134
            ]),
135
        ];
136
        return $this->setStringIntoShortTag('input', $inA) . $this->setCalendarControl($value['Field']);
137
    }
138
139
    /**
140
     * Returns a Enum or Set field to use in form
141
     *
142
     * @param string $tblSrc
143
     * @param string $fldType
144
     * @param array $val
145
     * @param array $iar
146
     * @return string
147
     */
148
    private function getFieldOutputEnumSet($tblSrc, $fldType, $val, $iar = [])
149
    {
150
        $adnlThings = $this->establishDefaultEnumSet($fldType);
151
        if (array_key_exists('readonly', $val)) {
152
            return $this->getFieldOutputEnumSetReadOnly($val, $adnlThings);
153
        }
154
        $inAdtnl = $adnlThings['additional'];
155
        if ($iar !== []) {
156
            $inAdtnl = array_merge($inAdtnl, $iar);
157
        }
158
        $vlSlct    = explode(',', $this->getFieldValue($val));
159
        $slctOptns = $this->getSetOrEnum2Array($tblSrc, $val['COLUMN_NAME']);
160
        return $this->setArrayToSelect($slctOptns, $vlSlct, $val['COLUMN_NAME'] . $adnlThings['suffix'], $inAdtnl);
161
    }
162
163
    private function getFieldOutputEnumSetReadOnly($val, $adnlThings)
164
    {
165
        $inputFeatures = [
166
            'name'     => $val['COLUMN_NAME'] . $adnlThings['suffix'],
167
            'id'       => $val['COLUMN_NAME'],
168
            'readonly' => 'readonly',
169
            'class'    => 'input_readonly',
170
            'size'     => 50,
171
            'value'    => $this->getFieldValue($val),
172
        ];
173
        return $this->setStringIntoShortTag('input', $inputFeatures);
174
    }
175
176
    /**
177
     * Returns a Numeric field 2 use in a form
178
     *
179
     * @param string $tblSrc
180
     * @param array $value
181
     * @param array $iar
182
     * @return string
183
     */
184
    private function getFieldOutputNumeric($tblSrc, $value, $iar = [])
185
    {
186
        if ($value['EXTRA'] == 'auto_increment') {
187
            return $this->getFieldOutputNumericAI($value, $iar);
188
        }
189
        $fkArray = $this->getForeignKeysToArray($this->advCache['workingDatabase'], $tblSrc, $value['COLUMN_NAME']);
190
        if (is_null($fkArray)) {
191
            $fldNos = $this->setFieldNumbers($value);
192
            return $this->getFieldOutputTT($value, min(50, $fldNos['l']), $iar);
193
        }
194
        return $this->getFieldOutputNumericNonFK($fkArray, $value, $iar);
195
    }
196
197
    private function getFieldOutputNumericAI($value, $iar = [])
198
    {
199
        if ($this->getFieldValue($value) == '') {
200
            $spF = ['id' => $value['COLUMN_NAME'], 'style' => 'font-style:italic;'];
201
            return $this->setStringIntoTag('auto-numar', 'span', $spF);
202
        }
203
        $inAdtnl = [
204
            'type'  => 'hidden',
205
            'name'  => $value['COLUMN_NAME'],
206
            'id'    => $value['COLUMN_NAME'],
207
            'value' => $this->getFieldValue($value),
208
        ];
209
        if ($iar !== []) {
210
            $inAdtnl = array_merge($inAdtnl, $iar);
211
        }
212
        return '<b>' . $this->getFieldValue($value) . '</b>' . $this->setStringIntoShortTag('input', $inAdtnl);
213
    }
214
215
    private function getFieldOutputNumericNonFK($fkArray, $value, $iar = [])
216
    {
217
        $query         = $this->sQueryGenericSelectKeyValue([
218
            $fkArray[$value['COLUMN_NAME']][1],
219
            $fkArray[$value['COLUMN_NAME']][2],
220
            $fkArray[$value['COLUMN_NAME']][0],
221
        ]);
222
        $selectOptions = $this->setMySQLquery2Server($query, 'array_key_value')['result'];
223
        $selectValue   = $this->getFieldValue($value);
224
        $inAdtnl       = ['size' => 1];
225
        if ($value['IS_NULLABLE'] == 'YES') {
226
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
227
        }
228
        if ($iar !== []) {
229
            $inAdtnl = array_merge($inAdtnl, $iar);
230
        }
231
        return $this->setArrayToSelect($selectOptions, $selectValue, $value['COLUMN_NAME'], $inAdtnl);
232
    }
233
234
    /**
235
     * Returns a Char field 2 use in a form
236
     *
237
     * @param string $tbl
238
     * @param string $fieldType
239
     * @param array $value
240
     * @param array $iar
241
     * @return string
242
     */
243
    private function getFieldOutputText($tbl, $fieldType, $value, $iar = [])
244
    {
245
        if (!in_array($fieldType, ['char', 'tinytext', 'varchar'])) {
246
            return '';
247
        }
248
        $foreignKeysArray = $this->getFieldOutputTextPrerequisites($tbl, $value);
249
        if (is_null($foreignKeysArray)) {
250
            return $this->getFieldOutputTextFK($foreignKeysArray, $value, $iar);
251
        }
252
        return $this->getFieldOutputTextNonFK($value, $iar);
253
    }
254
255
    private function getFieldOutputTextFK($foreignKeysArray, $value, $iar)
256
    {
257
        $query   = $this->sQueryGenericSelectKeyValue([
258
            $foreignKeysArray[$value['COLUMN_NAME']][1],
259
            $foreignKeysArray[$value['COLUMN_NAME']][2],
260
            $foreignKeysArray[$value['COLUMN_NAME']][0]
261
        ]);
262
        $inAdtnl = ['size' => 1];
263
        if ($value['IS_NULLABLE'] == 'YES') {
264
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
265
        }
266
        if ($iar !== []) {
267
            $inAdtnl = array_merge($inAdtnl, $iar);
268
        }
269
        $slct = [
270
            'Options' => $this->setMySQLquery2Server($query, 'array_key_value'),
271
            'Value'   => $this->getFieldValue($value),
272
        ];
273
        return $this->setArrayToSelect($slct['Options'], $slct['Value'], $value['COLUMN_NAME'], $inAdtnl);
274
    }
275
276
    /**
277
     * Returns a Text field 2 use in a form
278
     *
279
     * @param string $fieldType
280
     * @param array $value
281
     * @param array $iar
282
     * @return string
283
     */
284
    private function getFieldOutputTextLarge($fieldType, $value, $iar = [])
285
    {
286
        if (!in_array($fieldType, ['blob', 'text'])) {
287
            return '';
288
        }
289
        $inAdtnl = [
290
            'name' => $value['COLUMN_NAME'],
291
            'id'   => $value['COLUMN_NAME'],
292
            'rows' => 4,
293
            'cols' => 55,
294
        ];
295
        if ($iar !== []) {
296
            $inAdtnl = array_merge($inAdtnl, $iar);
297
        }
298
        return $this->setStringIntoTag($this->getFieldValue($value), 'textarea', $inAdtnl);
299
    }
300
301
    private function getFieldOutputTextNonFK($value, $iar)
302
    {
303
        $fldNos  = $this->setFieldNumbers($value);
304
        $inAdtnl = [
305
            'type'      => ($value['COLUMN_NAME'] == 'password' ? 'password' : 'text'),
306
            'name'      => $value['COLUMN_NAME'],
307
            'id'        => $value['COLUMN_NAME'],
308
            'size'      => min(30, $fldNos['l']),
309
            'maxlength' => min(255, $fldNos['l']),
310
            'value'     => $this->getFieldValue($value),
311
        ];
312
        if ($iar !== []) {
313
            $inAdtnl = array_merge($inAdtnl, $iar);
314
        }
315
        return $this->setStringIntoShortTag('input', $inAdtnl);
316
    }
317
318
    private function getFieldOutputTextPrerequisites($tbl, $value)
319
    {
320
        $foreignKeysArray = null;
321
        if (($tbl != 'user_rights') && ($value['COLUMN_NAME'] != 'eid')) {
322
            $database = $this->advCache['workingDatabase'];
323
            if (strpos($tbl, '`.`')) {
324
                $database = substr($tbl, 0, strpos($tbl, '`.`'));
325
            }
326
            $foreignKeysArray = $this->getForeignKeysToArray($database, $tbl, $value['COLUMN_NAME']);
327
        }
328
        return $foreignKeysArray;
329
    }
330
331
    private function getFieldOutputTT($value, $szN, $iar = [])
332
    {
333
        $inAdtnl = [
334
            'id'        => $value['COLUMN_NAME'],
335
            'maxlength' => $szN,
336
            'name'      => $value['COLUMN_NAME'],
337
            'size'      => $szN,
338
            'type'      => 'text',
339
            'value'     => $this->getFieldValue($value),
340
        ];
341
        if ($iar !== []) {
342
            $inAdtnl = array_merge($inAdtnl, $iar);
343
        }
344
        return $this->setStringIntoShortTag('input', $inAdtnl);
345
    }
346
347
    /**
348
     * Returns a Time field 2 use in a form
349
     *
350
     * @param array $value
351
     * @param array $iar
352
     * @return string
353
     */
354
    private function getFieldOutputTime($value, $iar = [])
355
    {
356
        return $this->getFieldOutputTT($value, 8, $iar);
357
    }
358
359
    /**
360
     * Returns a Timestamp field 2 use in a form
361
     *
362
     * @param array $value
363
     * @param array $iar
364
     * @return string
365
     */
366
    private function getFieldOutputTimestamp($value, $iar = [])
367
    {
368
        if (($dtl['COLUMN_DEFAULT'] == 'CURRENT_TIMESTAMP') || ($dtl['EXTRA'] == 'on update CURRENT_TIMESTAMP')) {
369
            return $this->getTimestamping($dtl);
0 ignored issues
show
Bug introduced by
The variable $dtl does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
370
        }
371
        $input = $this->getFieldOutputTT($value, 19, $iar);
372
        if (!array_key_exists('readonly', $iar)) {
373
            $input .= $this->setCalendarControlWithTime($value['COLUMN_NAME']);
374
        }
375
        return $input;
376
    }
377
378
    /**
379
     * Returns a Year field 2 use in a form
380
     *
381
     * @param array $details
382
     * @param array $iar
383
     * @return string
384
     */
385
    private function getFieldOutputYear($tblName, $details, $iar)
386
    {
387
        $listOfValues = [];
388
        for ($cntr = 1901; $cntr <= 2155; $cntr++) {
389
            $listOfValues[$cntr] = $cntr;
390
        }
391
        if ($iar == []) {
392
            $slDflt = $this->getFieldValue($details);
393
            return $this->setArrayToSelect($listOfValues, $slDflt, $details['COLUMN_NAME'], ['size' => 1]);
394
        }
395
        return $this->getFieldOutputText($tblName, 'varchar', $details, $iar);
396
    }
397
398
    /**
399
     * Returns given value for a field from REQUEST global variable
400
     *
401
     * @param array $details
402
     * @return string
403
     */
404
    private function getFieldValue($details)
405
    {
406
        $this->initializeSprGlbAndSession();
407
        $rqCN = $this->tCmnRequest->request->get($details['COLUMN_NAME']);
408
        if (!is_null($rqCN)) {
409
            if (($details['IS_NULLABLE'] == 'YES') && ($rqCN == '')) {
410
                return 'NULL';
411
            }
412
            return $rqCN;
413
        }
414
        return $this->getFieldValueWithoutUserInput($details);
415
    }
416
417
    /**
418
     * Handles field value ignoring any input from the user
419
     *
420
     * @param array $details
421
     * @return string
422
     */
423
    private function getFieldValueWithoutUserInput($details)
424
    {
425
        if ($details['COLUMN_DEFAULT'] === null) {
426
            if ($details['IS_NULLABLE'] == 'YES') {
427
                return 'NULL';
428
            }
429
            return '';
430
        }
431
        return $details['COLUMN_DEFAULT'];
432
    }
433
434
    private function getForeignKeysQuery($value)
435
    {
436
        $flt = [
437
            'TABLE_SCHEMA' => $value['REFERENCED_TABLE_SCHEMA'],
438
            'TABLE_NAME'   => $value['REFERENCED_TABLE_NAME'],
439
            'DATA_TYPE'    => ['char', 'varchar', 'text'],
440
        ];
441
        return $this->sQueryMySqlColumns($flt);
442
    }
443
444
    /**
445
     * Returns an array with fields referenced by a Foreign key
446
     *
447
     * @param string $database
448
     * @param string $tblName
449
     * @param string|array $onlyCol
450
     * @return array
451
     */
452
    private function getForeignKeysToArray($database, $tblName, $onlyCol = '')
453
    {
454
        $this->setTableForeginKeyCache($database, $this->fixTableSource($tblName));
455
        $array2return = null;
456
        if (isset($this->advCache['tableFKs'][$database][$tblName])) {
457
            foreach ($this->advCache['tableFKs'][$database][$tblName] as $value) {
458
                if ($value['COLUMN_NAME'] == $onlyCol) {
459
                    $query                  = $this->getForeignKeysQuery($value);
460
                    $targetTblTxtFlds       = $this->setMySQLquery2Server($query, 'full_array_key_numbered')['result'];
461
                    $array2return[$onlyCol] = [
462
                        $this->glueDbTb($value['REFERENCED_TABLE_SCHEMA'], $value['REFERENCED_TABLE_NAME']),
463
                        $value['REFERENCED_COLUMN_NAME'],
464
                        '`' . $targetTblTxtFlds[0]['COLUMN_NAME'] . '`',
465
                    ];
466
                }
467
            }
468
        }
469
        return $array2return;
470
    }
471
472
    private function getLabel($details)
473
    {
474
        return $this->setStringIntoTag($this->getFieldNameForDisplay($details), 'span', ['class' => 'fake_label']);
475
    }
476
477
    /**
478
     * Returns an array with possible values of a SET or ENUM column
479
     *
480
     * @param string $refTbl
481
     * @param string $refCol
482
     * @return array
483
     */
484
    protected function getSetOrEnum2Array($refTbl, $refCol)
485
    {
486
        $dat = $this->establishDatabaseAndTable($this->fixTableSource($refTbl));
487
        foreach ($this->advCache['tableStructureCache'][$dat[0]][$dat[1]] as $value) {
488
            if ($value['COLUMN_NAME'] == $refCol) {
489
                $clndVls = explode(',', str_replace([$value['DATA_TYPE'], '(', "'", ')'], '', $value['COLUMN_TYPE']));
490
                $enmVls  = array_combine($clndVls, $clndVls);
491
                if ($value['IS_NULLABLE'] == 'YES') {
492
                    $enmVls['NULL'] = '';
493
                }
494
            }
495
        }
496
        ksort($enmVls);
497
        return $enmVls;
498
    }
499
500
    /**
501
     * Returns a timestamp field value
502
     *
503
     * @param array $dtl
504
     * @return array
505
     */
506
    private function getTimestamping($dtl)
507
    {
508
        $inM = $this->setStringIntoTag($this->getFieldValue($dtl), 'span');
509
        if (in_array($this->getFieldValue($dtl), ['', 'CURRENT_TIMESTAMP', 'NULL'])) {
510
            $mCN = [
511
                'InsertDateTime'        => 'data/timpul ad. informatiei',
512
                'ModificationDateTime'  => 'data/timpul modificarii inf.',
513
                'modification_datetime' => 'data/timpul modificarii inf.',
514
            ];
515
            if (array_key_exists($dtl['COLUMN_NAME'], $mCN)) {
516
                $inM = $this->setStringIntoTag($mCN[$dtl['COLUMN_NAME']], 'span', ['style' => 'font-style:italic;']);
517
            }
518
        }
519
        return ['label' => $this->getLabel($dtl), 'input' => $inM];
520
    }
521
522
    private function glueDbTb($dbName, $tbName)
523
    {
524
        return '`' . $dbName . '`.`' . $tbName . '`';
525
    }
526
527
    /**
528
     * Manages features flag
529
     *
530
     * @param string $fieldName
531
     * @param array $features
532
     * @return string
533
     */
534
    private function handleFeatures($fieldName, $features)
535
    {
536
        $rOly  = $this->handleFeaturesSingle($fieldName, $features, 'readonly');
537
        $rDbld = $this->handleFeaturesSingle($fieldName, $features, 'disabled');
538
        $rNl   = [];
539
        if (isset($features['include_null']) && in_array($fieldName, $features['include_null'])) {
540
            $rNl = ['include_null'];
541
        }
542
        return array_merge([], $rOly, $rDbld, $rNl);
543
    }
544
545
    private function handleFeaturesSingle($fieldName, $features, $featureKey)
546
    {
547
        $fMap    = [
548
            'readonly' => ['readonly', 'class', 'input_readonly'],
549
            'disabled' => ['disabled']
550
        ];
551
        $aReturn = [];
552
        if (array_key_exists($featureKey, $features)) {
553
            if (array_key_exists($fieldName, $features[$featureKey])) {
554
                $aReturn[$featureKey][$fMap[$featureKey][0]] = $fMap[$featureKey][0];
555
                if (count($fMap[$featureKey]) > 1) {
556
                    $aReturn[$featureKey][$fMap[$featureKey][1]] = $fMap[$featureKey][2];
557
                }
558
            }
559
        }
560
        return $aReturn;
561
    }
562
563
    private function setField($tableSource, $dtl, $features, $fieldLabel)
564
    {
565
        if ($dtl['COLUMN_NAME'] == 'host') {
566
            $inVl = gethostbyaddr($this->tCmnRequest->server->get('REMOTE_ADDR'));
567
            return [
568
                'label' => '<label for="' . $dtl['COLUMN_NAME'] . '">Numele calculatorului</label>',
569
                'input' => '<input type="text" name="host" size="15" readonly value="' . $inVl . '" />',
570
            ];
571
        }
572
        $result = $this->setFieldInput($tableSource, $dtl, $features);
573
        return ['label' => $this->setFieldLabel($dtl, $features, $fieldLabel), 'input' => $result];
574
    }
575
576
    private function setFieldInput($tableSource, $dtl, $features)
577
    {
578
        if ($dtl['COLUMN_NAME'] == 'ChoiceId') {
579
            return '<input type="text" name="ChoiceId" value="'
580
                    . $this->tCmnRequest->request->get($dtl['COLUMN_NAME']) . '" />';
581
        }
582
        return $this->setNeededFieldByType($tableSource, $dtl, $features);
583
    }
584
585
    private function setFieldLabel($details, $features, $fieldLabel)
586
    {
587
        $aLabel = ['for' => $details['COLUMN_NAME'], 'id' => $details['COLUMN_NAME'] . '_label'];
588
        if (isset($features['disabled'])) {
589
            if (in_array($details['COLUMN_NAME'], $features['disabled'])) {
590
                $aLabel = array_merge($aLabel, ['style' => 'color: grey;']);
591
            }
592
        }
593
        return $this->setStringIntoTag($fieldLabel, 'label', $aLabel);
594
    }
595
596
    private function setFormButtons($feat, $hiddenInfo)
597
    {
598
        $btn   = [];
599
        $btn[] = '<input type="submit" id="submit" style="margin-left:220px;" value="'
600
                . $this->lclMsgCmn('i18n_Form_ButtonSave') . '" />';
601
        if (isset($feat['insertAndUpdate'])) {
602
            $btn[] = '<input type="hidden" id="insertAndUpdate" name="insertAndUpdate" value="insertAndUpdate" />';
603
        }
604
        if (is_array($hiddenInfo)) {
605
            foreach ($hiddenInfo as $key => $value) {
606
                $btn[] = '<input type="hidden" id="' . $key . '" name="' . $key . '" value="' . $value . '" />';
607
            }
608
        }
609
        return '<div>' . implode('', $btn) . '</div>';
610
    }
611
612
    private function setFormJavascriptFinal($frmId)
613
    {
614
        $cnt = implode('', [
615
            '$(document).ready(function(){',
616
            '$("form#' . $frmId . '").submit(function(){',
617
            '$("input").attr("readonly", true);',
618
            '$("input[type=submit]").attr("disabled", "disabled");',
619
            '$("input[type=submit]").attr("value", "' . $this->lclMsgCmn('i18n_Form_ButtonSaving') . '");',
620
            '});',
621
            '});',
622
        ]);
623
        return $this->setJavascriptContent($cnt);
624
    }
625
626
    /**
627
     * Returns a generic form based on a given table
628
     *
629
     * @param string $tblSrc Table Source
630
     * @param array $feat
631
     * @param string|array $hdnInf List of hidden fields
632
     *
633
     * @return string Form to add/modify detail for a single row within a table
634
     */
635
    protected function setFormGenericSingleRecord($tblSrc, $feat, $hdnInf = '')
636
    {
637
        echo $this->setStringIntoTag('', 'div', ['id' => 'loading']);
638
        if (strpos($tblSrc, '.') !== false) {
639
            $tblSrc = explode('.', str_replace('`', '', $tblSrc))[1];
640
        }
641
        $this->setTableCache($tblSrc);
642
        $sReturn = [];
643
        if (count($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc]) != 0) {
644
            foreach ($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc] as $value) {
645
                $sReturn[] = $this->setNeededField($tblSrc, $value, $feat);
646
            }
647
        }
648
        $frmFtrs = ['id' => $feat['id'], 'action' => $feat['action'], 'method' => $feat['method']];
649
        return $this->setStringIntoTag(implode('', $sReturn) . $this->setFormButtons($feat, $hdnInf), 'form', $frmFtrs)
650
                . $this->setFormJavascriptFinal($feat['id']);
651
    }
652
653
    /**
654
     * Analyse the field and returns the proper line 2 use in forms
655
     *
656
     * @param string $tableSource
657
     * @param array $details
658
     * @param array $features
659
     * @return string|array
660
     */
661
    private function setNeededField($tableSource, $details, $features)
662
    {
663
        if (isset($features['hidden'])) {
664
            if (in_array($details['COLUMN_NAME'], $features['hidden'])) {
665
                return null;
666
            }
667
        }
668
        $fieldLabel = $this->getFieldNameForDisplay($details);
669
        if ($fieldLabel == 'hidden') {
670
            return null;
671
        }
672
        return $this->setNeededFieldFinal($tableSource, $details, $features, $fieldLabel);
673
    }
674
675
    /**
676
     * Analyse the field type and returns the proper lines 2 use in forms
677
     *
678
     * @param string $tblName
679
     * @param array $dtls
680
     * @param array $features
681
     * @return string|array
682
     */
683
    private function setNeededFieldByType($tblName, $dtls, $features)
684
    {
685
        if (isset($features['special']) && isset($features['special'][$dtls['COLUMN_NAME']])) {
686
            $sOpt = $this->setMySQLquery2Server($features['special'][$dtls['COLUMN_NAME']], 'array_key_value');
687
            return $this->setArrayToSelect($sOpt, $this->getFieldValue($dtls), $dtls['COLUMN_NAME'], ['size' => 1]);
688
        }
689
        return $this->setNeededFieldKnown($tblName, $dtls, $features);
690
    }
691
692
    private function setNeededFieldKnown($tblName, $dtls, $features)
693
    {
694
        $iar      = $this->handleFeatures($dtls['COLUMN_NAME'], $features);
695
        $sReturn  = '';
696
        $numTypes = ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'float', 'double', 'decimal', 'numeric'];
697
        if (in_array($dtls['DATA_TYPE'], $numTypes)) {
698
            $sReturn = $this->getFieldOutputNumeric($tblName, $dtls, $iar);
699
        } elseif (in_array($dtls['DATA_TYPE'], ['char', 'tinytext', 'varchar', 'enum', 'set', 'text', 'blob'])) {
700
            $sReturn = $this->setNeededFieldTextRelated($tblName, $dtls, $iar);
701
        } elseif (in_array($dtls['DATA_TYPE'], ['date', 'datetime', 'time', 'timestamp', 'year'])) {
702
            $sReturn = $this->setNeededFieldSingleType($tblName, $dtls, $iar);
703
        }
704
        return $this->getFieldCompletionType($dtls) . $sReturn;
705
    }
706
707
    private function setNeededFieldFinal($tableSource, $details, $features, $fieldLabel)
708
    {
709
        $sReturn     = $this->setField($tableSource, $details, $features, $fieldLabel);
710
        $finalReturn = $sReturn['label'] . $this->setStringIntoTag($sReturn['input'], 'span', ['class' => 'labell']);
711
        $wrkDb       = $this->advCache['workingDatabase'];
712
        if (isset($this->advCache['tableFKs'][$wrkDb][$tableSource])) {
713
            if (in_array($details['COLUMN_NAME'], $this->advCache['FKcol'][$wrkDb][$tableSource])) {
714
                $finalReturn .= $this->setFieldNumbers($details);
715
            }
716
        }
717
        return '<div>' . $finalReturn . '</div>';
718
    }
719
720
    private function setNeededFieldSingleType($tblName, $dtls, $iar)
721
    {
722
        if ($dtls['DATA_TYPE'] == 'date') {
723
            return $this->getFieldOutputDate($dtls);
724
        } elseif ($dtls['DATA_TYPE'] == 'time') {
725
            return $this->getFieldOutputTime($dtls, $iar);
726
        } elseif (in_array($dtls['DATA_TYPE'], ['datetime', 'timestamp'])) {
727
            return $this->getFieldOutputTimestamp($dtls, $iar);
728
        }
729
        return $this->getFieldOutputYear($tblName, $dtls, $iar);
730
    }
731
732
    private function setNeededFieldTextRelated($tblName, $dtls, $iar)
733
    {
734
        if (in_array($dtls['DATA_TYPE'], ['char', 'tinytext', 'varchar'])) {
735
            return $this->getFieldOutputText($tblName, $dtls['DATA_TYPE'], $dtls, $iar);
736
        } elseif (in_array($dtls['DATA_TYPE'], ['text', 'blob'])) {
737
            return $this->getFieldOutputTextLarge($dtls['DATA_TYPE'], $dtls, $iar);
738
        }
739
        return $this->getFieldOutputEnumSet($tblName, $dtls['DATA_TYPE'], $dtls, $iar);
740
    }
741
742
    /**
743
     * create a Cache for given table to use it in many places
744
     *
745
     * @param type $tblSrc
746
     */
747
    private function setTableCache($tblSrc)
748
    {
749
        $dat = $this->establishDatabaseAndTable($this->fixTableSource($tblSrc));
750
        if (!isset($this->advCache['tableStructureCache'][$dat[0]][$dat[1]])) {
751
            $this->advCache['workingDatabase'] = $dat[0];
752
            if ($dat[1] == 'user_rights') {
753
                $this->advCache['workingDatabase'] = 'usefull_security';
754
            }
755
            $this->advCache['tableStructureCache'][$dat[0]][$dat[1]] = $this->getMySQLlistColumns([
756
                'TABLE_SCHEMA' => $dat[0],
757
                'TABLE_NAME'   => $dat[1],
758
            ]);
759
            $this->setTableForeginKeyCache($dat[0], $dat[1]);
760
        }
761
    }
762
763
    private function setTableForeginKeyCache($dbName, $tblName)
764
    {
765
        $frgnKs = $this->getMySQLlistIndexes([
766
            'TABLE_SCHEMA'          => $dbName,
767
            'TABLE_NAME'            => $tblName,
768
            'REFERENCED_TABLE_NAME' => 'NOT NULL',
769
        ]);
770
        if (!is_null($frgnKs)) {
771
            $this->advCache['tableFKs'][$dbName][$tblName] = $frgnKs;
772
            $this->advCache['FKcol'][$dbName][$tblName]    = array_column($frgnKs, 'COLUMN_NAME', 'CONSTRAINT_NAME');
773
        }
774
    }
775
}
776