Completed
Push — master ( 56a15a...550ab7 )
by Daniel
02:08
created

MySQLiAdvancedOutput::getFieldOutputDate()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 20
rs 9.4285
cc 2
eloc 15
nc 2
nop 2
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 DomComponentsByDanielGP,
40
        MySQLiByDanielGP;
41
42
    protected $advCache = null;
43
44
    /**
45
     * Establish Database and Table intended to work with
46
     * (in case the DB is ommited get the default one)
47
     *
48
     * @param string $tblSrc
49
     */
50
    private function establishDatabaseAndTable($tblSrc)
51
    {
52
        if (strpos($tblSrc, '.') === false) {
53
            if (!defined('MYSQL_DATABASE')) {
54
                define('MYSQL_DATABASE', 'information_schema');
55
            }
56
            return [$tblSrc, MYSQL_DATABASE];
57
        }
58
        return explode('.', str_replace('`', '', $tblSrc));
59
    }
60
61
    private function establishDefaultEnumSet($fldType)
62
    {
63
        $dfltArray = [
64
            'enum' => ['additional' => ['size' => 1], 'suffix' => ''],
65
            'set'  => ['additional' => ['size' => 5, 'multiselect'], 'suffix' => '[]'],
66
        ];
67
        return $dfltArray[$fldType];
68
    }
69
70
    private function fixTableSource($refTbl)
71
    {
72
        $outS = [];
73
        if (substr($refTbl, 0, 1) !== '`') {
74
            $outS[] = '`';
75
        }
76
        $psT = strpos($refTbl, '.`');
77
        if ($psT !== false) {
78
            $refTbl = substr($refTbl, $psT + 2, strlen($refTbl) - $psT);
79
        }
80
        $outS[] = $refTbl;
81
        if (substr($refTbl, -1) !== '`') {
82
            $outS[] = '`';
83
        }
84
        return implode('', $outS);
85
    }
86
87
    private function getFieldCompletionType($details)
88
    {
89
        $inputFeatures = ['display' => '***', 'ftrs' => ['title' => 'Mandatory', 'class' => 'inputMandatory']];
90
        if ($details['IS_NULLABLE'] == 'YES') {
91
            $inputFeatures = ['display' => '~', 'ftrs' => ['title' => 'Optional', 'class' => 'inputOptional']];
92
        }
93
        return $this->setStringIntoTag($inputFeatures['display'], 'span', $inputFeatures['ftrs']);
94
    }
95
96
    /**
97
     * Returns the name of a field for displaying
98
     *
99
     * @param array $details
100
     * @return string
101
     */
102
    private function getFieldNameForDisplay($details)
103
    {
104
        $tableUniqueId = $details['TABLE_SCHEMA'] . '.' . $details['TABLE_NAME'];
105
        if ($details['COLUMN_COMMENT'] != '') {
106
            return $details['COLUMN_COMMENT'];
107
        } elseif (isset($this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']])) {
108
            return $this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']];
109
        }
110
        return $details['COLUMN_NAME'];
111
    }
112
113
    /**
114
     * Returns a Date field 2 use in a form
115
     *
116
     * @param string $fldType
117
     * @param array $value
118
     * @return array
119
     */
120
    private function getFieldOutputDate($fldType, $value)
0 ignored issues
show
Unused Code introduced by
The parameter $fldType is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
121
    {
122
        $defaultValue = $this->getFieldValue($value);
123
        if (is_null($defaultValue)) {
124
            $defaultValue = date('Y-m-d');
125
        }
126
        $inA = [
127
            'type'      => 'text',
128
            'name'      => $value['Field'],
129
            'id'        => $value['Field'],
130
            'value'     => $defaultValue,
131
            'size'      => 10,
132
            'maxlength' => 10,
133
            'onfocus'   => implode('', [
134
                'javascript:NewCssCal(\'' . $value['Field'],
135
                '\',\'yyyyMMdd\',\'dropdown\',false,\'24\',false);',
136
            ]),
137
        ];
138
        return $this->setStringIntoShortTag('input', $inA) . $this->setCalendarControl($value['Field']);
139
    }
140
141
    /**
142
     * Returns a Enum or Set field to use in form
143
     *
144
     * @param string $tblSrc
145
     * @param string $fldType
146
     * @param array $val
147
     * @param array $iar
148
     * @return string
149
     */
150
    private function getFieldOutputEnumSet($tblSrc, $fldType, $val, $iar = [])
151
    {
152
        $adnlThings = $this->establishDefaultEnumSet($fldType);
153
        if (array_key_exists('readonly', $val)) {
154
            return $this->getFieldOutputEnumSetReadOnly($val, $adnlThings);
155
        }
156
        $inAdtnl = $adnlThings['additional'];
157
        if ($iar !== []) {
158
            $inAdtnl = array_merge($inAdtnl, $iar);
159
        }
160
        $vlSlct    = explode(',', $this->getFieldValue($val));
161
        $slctOptns = $this->getSetOrEnum2Array($tblSrc, $val['COLUMN_NAME']);
162
        return $this->setArrayToSelect($slctOptns, $vlSlct, $val['COLUMN_NAME'] . $adnlThings['suffix'], $inAdtnl);
163
    }
164
165
    private function getFieldOutputEnumSetReadOnly($val, $adnlThings)
166
    {
167
        $inputFeatures = [
168
            'name'     => $val['COLUMN_NAME'] . $adnlThings['suffix'],
169
            'id'       => $val['COLUMN_NAME'],
170
            'readonly' => 'readonly',
171
            'class'    => 'input_readonly',
172
            'size'     => 50,
173
            'value'    => $this->getFieldValue($val),
174
        ];
175
        return $this->setStringIntoShortTag('input', $inputFeatures);
176
    }
177
178
    /**
179
     * Returns a Numeric field 2 use in a form
180
     *
181
     * @param string $tblSrc
182
     * @param array $value
183
     * @param array $iar
184
     * @return string
185
     */
186
    private function getFieldOutputNumeric($tblSrc, $value, $iar = [])
187
    {
188
        if ($value['EXTRA'] == 'auto_increment') {
189
            if ($this->getFieldValue($value) == '') {
190
                return $this->setStringIntoTag('auto-numar', 'span', [
191
                            'id'    => $value['COLUMN_NAME'],
192
                            'style' => 'font-style:italic;',
193
                ]);
194
            }
195
            $inAdtnl = [
196
                'type'  => 'hidden',
197
                'name'  => $value['COLUMN_NAME'],
198
                'id'    => $value['COLUMN_NAME'],
199
                'value' => $this->getFieldValue($value),
200
            ];
201
            if ($iar !== []) {
202
                $inAdtnl = array_merge($inAdtnl, $iar);
203
            }
204
            return $this->setStringIntoTag($this->getFieldValue($value), 'b')
205
                    . $this->setStringIntoShortTag('input', $inAdtnl);
206
        }
207
        $database = $this->advCache['workingDatabase'];
208
        $fkArray  = $this->getForeignKeysToArray($database, $tblSrc, $value['COLUMN_NAME']);
209
        if (is_null($fkArray)) {
210
            $fldNos  = $this->setFieldNumbers($value);
211
            $inAdtnl = [
212
                'type'      => 'text',
213
                'name'      => $value['COLUMN_NAME'],
214
                'id'        => $value['COLUMN_NAME'],
215
                'value'     => $this->getFieldValue($value),
216
                'size'      => min(50, $fldNos['l']),
217
                'maxlength' => min(50, $fldNos['l'])
218
            ];
219
            if ($iar !== []) {
220
                $inAdtnl = array_merge($inAdtnl, $iar);
221
            }
222
            return $this->setStringIntoShortTag('input', $inAdtnl);
223
        }
224
        $query         = $this->sQueryGenericSelectKeyValue([
225
            $fkArray[$value['COLUMN_NAME']][1],
226
            $fkArray[$value['COLUMN_NAME']][2],
227
            $fkArray[$value['COLUMN_NAME']][0]
228
        ]);
229
        $selectOptions = $this->setMySQLquery2Server($query, 'array_key_value')['result'];
230
        $selectValue   = $this->getFieldValue($value);
231
        $inAdtnl       = ['size' => 1];
232
        if ($value['IS_NULLABLE'] == 'YES') {
233
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
234
        }
235
        if ($iar !== []) {
236
            $inAdtnl = array_merge($inAdtnl, $iar);
237
        }
238
        return $this->setArrayToSelect($selectOptions, $selectValue, $value['COLUMN_NAME'], $inAdtnl);
239
    }
240
241
    /**
242
     * Returns a Char field 2 use in a form
243
     *
244
     * @param string $tbl
245
     * @param string $fieldType
246
     * @param array $value
247
     * @param array $iar
248
     * @return string
249
     */
250
    private function getFieldOutputText($tbl, $fieldType, $value, $iar = [])
251
    {
252
        if (!in_array($fieldType, ['char', 'tinytext', 'varchar'])) {
253
            return '';
254
        }
255
        $foreignKeysArray = $this->getFieldOutputTextPrerequisites($tbl, $value);
256
        if (is_null($foreignKeysArray)) {
257
            return $this->getFieldOutputTextFK($foreignKeysArray, $value, $iar);
258
        }
259
        return $this->getFieldOutputTextNonFK($value, $iar);
260
    }
261
262
    private function getFieldOutputTextFK($foreignKeysArray, $value, $iar)
263
    {
264
        $query   = $this->sQueryGenericSelectKeyValue([
265
            $foreignKeysArray[$value['COLUMN_NAME']][1],
266
            $foreignKeysArray[$value['COLUMN_NAME']][2],
267
            $foreignKeysArray[$value['COLUMN_NAME']][0]
268
        ]);
269
        $inAdtnl = ['size' => 1];
270
        if ($value['IS_NULLABLE'] == 'YES') {
271
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
272
        }
273
        if ($iar !== []) {
274
            $inAdtnl = array_merge($inAdtnl, $iar);
275
        }
276
        $slct = [
277
            'Options' => $this->setMySQLquery2Server($query, 'array_key_value'),
278
            'Value'   => $this->getFieldValue($value),
279
        ];
280
        return $this->setArrayToSelect($slct['Options'], $slct['Value'], $value['COLUMN_NAME'], $inAdtnl);
281
    }
282
283
    /**
284
     * Returns a Text field 2 use in a form
285
     *
286
     * @param string $fieldType
287
     * @param array $value
288
     * @param array $iar
289
     * @return string
290
     */
291
    private function getFieldOutputTextLarge($fieldType, $value, $iar = [])
292
    {
293
        if (!in_array($fieldType, ['blob', 'text'])) {
294
            return '';
295
        }
296
        $inAdtnl = [
297
            'name' => $value['COLUMN_NAME'],
298
            'id'   => $value['COLUMN_NAME'],
299
            'rows' => 4,
300
            'cols' => 55,
301
        ];
302
        if ($iar !== []) {
303
            $inAdtnl = array_merge($inAdtnl, $iar);
304
        }
305
        return $this->setStringIntoTag($this->getFieldValue($value), 'textarea', $inAdtnl);
306
    }
307
308
    private function getFieldOutputTextNonFK($value, $iar)
309
    {
310
        $fldNos  = $this->setFieldNumbers($value);
311
        $inAdtnl = [
312
            'type'      => ($value['COLUMN_NAME'] == 'password' ? 'password' : 'text'),
313
            'name'      => $value['COLUMN_NAME'],
314
            'id'        => $value['COLUMN_NAME'],
315
            'size'      => min(30, $fldNos['l']),
316
            'maxlength' => min(255, $fldNos['l']),
317
            'value'     => $this->getFieldValue($value),
318
        ];
319
        if ($iar !== []) {
320
            $inAdtnl = array_merge($inAdtnl, $iar);
321
        }
322
        return $this->setStringIntoShortTag('input', $inAdtnl);
323
    }
324
325
    private function getFieldOutputTextPrerequisites($tbl, $value)
326
    {
327
        $foreignKeysArray = null;
328
        if (($tbl != 'user_rights') && ($value['COLUMN_NAME'] != 'eid')) {
329
            $database = $this->advCache['workingDatabase'];
330
            if (strpos($tbl, '`.`')) {
331
                $database = substr($tbl, 0, strpos($tbl, '`.`'));
332
            }
333
            $foreignKeysArray = $this->getForeignKeysToArray($database, $tbl, $value['COLUMN_NAME']);
334
        }
335
        return $foreignKeysArray;
336
    }
337
338
    private function getFieldOutputTT($value, $szN, $iar = [])
339
    {
340
        $inAdtnl = [
341
            'id'        => $value['COLUMN_NAME'],
342
            'maxlength' => $szN,
343
            'name'      => $value['COLUMN_NAME'],
344
            'size'      => $szN,
345
            'type'      => 'text',
346
            'value'     => $this->getFieldValue($value),
347
        ];
348
        if ($iar !== []) {
349
            $inAdtnl = array_merge($inAdtnl, $iar);
350
        }
351
        return $this->setStringIntoShortTag('input', $inAdtnl);
352
    }
353
354
    /**
355
     * Returns a Time field 2 use in a form
356
     *
357
     * @param array $value
358
     * @param array $iar
359
     * @return string
360
     */
361
    private function getFieldOutputTime($value, $iar = [])
362
    {
363
        return $this->getFieldOutputTT($value, 8, $iar);
364
    }
365
366
    /**
367
     * Returns a Timestamp field 2 use in a form
368
     *
369
     * @param array $value
370
     * @param array $iar
371
     * @return string
372
     */
373
    private function getFieldOutputTimestamp($value, $iar = [])
374
    {
375
        $input = $this->getFieldOutputTT($value, 19, $iar);
376
        if (!array_key_exists('readonly', $iar)) {
377
            $input .= $this->setCalendarControlWithTime($value['COLUMN_NAME']);
378
        }
379
        return $input;
380
    }
381
382
    /**
383
     * Returns a Year field 2 use in a form
384
     *
385
     * @param array $details
386
     * @param array $iar
387
     * @return string
388
     */
389
    private function getFieldOutputYear($tblName, $details, $iar)
390
    {
391
        $listOfValues = [];
392
        for ($cntr = 1901; $cntr <= 2155; $cntr++) {
393
            $listOfValues[$cntr] = $cntr;
394
        }
395
        if ($iar == []) {
396
            $slDflt = $this->getFieldValue($details);
397
            return $this->setArrayToSelect($listOfValues, $slDflt, $details['COLUMN_NAME'], ['size' => 1]);
398
        }
399
        return $this->getFieldOutputText($tblName, 'varchar', $details, $iar);
400
    }
401
402
    /**
403
     * Returns given value for a field from $_REQUEST
404
     *
405
     * @param array $details
406
     * @return string
407
     */
408
    private function getFieldValue($details)
409
    {
410
        $this->initializeSprGlbAndSession();
411
        $rqCN = $this->tCmnRequest->request->get($details['COLUMN_NAME']);
412
        if (!is_null($rqCN)) {
413
            if (($details['IS_NULLABLE'] == 'YES') && ($rqCN == '')) {
414
                return 'NULL';
415
            }
416
            return $rqCN;
417
        }
418
        return $this->getFieldValueWithoutUserInput($details);
419
    }
420
421
    /**
422
     * Handles field value ignoring any input from the user
423
     *
424
     * @param array $details
425
     * @return string
426
     */
427
    private function getFieldValueWithoutUserInput($details)
428
    {
429
        if ($details['COLUMN_DEFAULT'] === null) {
430
            if ($details['IS_NULLABLE'] == 'YES') {
431
                return 'NULL';
432
            }
433
            return '';
434
        }
435
        return $details['COLUMN_DEFAULT'];
436
    }
437
438
    private function getForeignKeysQuery($value)
439
    {
440
        $flt = [
441
            'TABLE_SCHEMA' => $value['REFERENCED_TABLE_SCHEMA'],
442
            'TABLE_NAME'   => $value['REFERENCED_TABLE_NAME'],
443
            'DATA_TYPE'    => ['char', 'varchar', 'text'],
444
        ];
445
        return $this->sQueryMySqlColumns($flt);
446
    }
447
448
    /**
449
     * Returns an array with fields referenced by a Foreign key
450
     *
451
     * @param string $database
452
     * @param string $tblName
453
     * @param string|array $onlyCol
454
     * @return array
455
     */
456
    private function getForeignKeysToArray($database, $tblName, $onlyCol = '')
457
    {
458
        $this->setTableForeginKeyCache($database, $this->fixTableSource($tblName));
459
        $array2return = null;
460
        if (isset($this->advCache['tableFKs'][$database][$tblName])) {
461
            foreach ($this->advCache['tableFKs'][$database][$tblName] as $value) {
462
                if ($value['COLUMN_NAME'] == $onlyCol) {
463
                    $query                  = $this->getForeignKeysQuery($value);
464
                    $targetTblTxtFlds       = $this->setMySQLquery2Server($query, 'full_array_key_numbered')['result'];
465
                    $array2return[$onlyCol] = [
466
                        $this->glueDbTb($value['REFERENCED_TABLE_SCHEMA'], $value['REFERENCED_TABLE_NAME']),
467
                        $value['REFERENCED_COLUMN_NAME'],
468
                        '`' . $targetTblTxtFlds[0]['COLUMN_NAME'] . '`',
469
                    ];
470
                }
471
            }
472
        }
473
        return $array2return;
474
    }
475
476
    private function getLabel($details)
477
    {
478
        return $this->setStringIntoTag($this->getFieldNameForDisplay($details), 'span', ['class' => 'fake_label']);
479
    }
480
481
    /**
482
     * Returns an array with possible values of a SET or ENUM column
483
     *
484
     * @param string $refTbl
485
     * @param string $refCol
486
     * @return array
487
     */
488
    protected function getSetOrEnum2Array($refTbl, $refCol)
489
    {
490
        $dat = $this->establishDatabaseAndTable($this->fixTableSource($refTbl));
491
        foreach ($this->advCache['tableStructureCache'][$dat[0]][$dat[1]] as $value) {
492
            if ($value['COLUMN_NAME'] == $refCol) {
493
                $clndVls = explode(',', str_replace([$value['DATA_TYPE'], '(', "'", ')'], '', $value['COLUMN_TYPE']));
494
                $enmVls  = array_combine($clndVls, $clndVls);
495
                if ($value['IS_NULLABLE'] == 'YES') {
496
                    $enmVls['NULL'] = '';
497
                }
498
            }
499
        }
500
        ksort($enmVls);
501
        return $enmVls;
502
    }
503
504
    /**
505
     * Returns a timestamp field value
506
     *
507
     * @param array $dtl
508
     * @return array
509
     */
510
    private function getTimestamping($dtl)
511
    {
512
        $inM = $this->setStringIntoTag($this->getFieldValue($dtl), 'span');
513
        if (in_array($this->getFieldValue($dtl), ['', 'CURRENT_TIMESTAMP', 'NULL'])) {
514
            $mCN = [
515
                'InsertDateTime'        => 'data/timpul ad. informatiei',
516
                'ModificationDateTime'  => 'data/timpul modificarii inf.',
517
                'modification_datetime' => 'data/timpul modificarii inf.',
518
            ];
519
            if (array_key_exists($dtl['COLUMN_NAME'], $mCN)) {
520
                $inM = $this->setStringIntoTag($mCN[$dtl['COLUMN_NAME']], 'span', ['style' => 'font-style:italic;']);
521
            }
522
        }
523
        return ['label' => $this->getLabel($dtl), 'input' => $inM];
524
    }
525
526
    private function glueDbTb($dbName, $tbName)
527
    {
528
        return '`' . $dbName . '`.`' . $tbName . '`';
529
    }
530
531
    /**
532
     * Manages features flag
533
     *
534
     * @param string $fieldName
535
     * @param array $features
536
     * @return string
537
     */
538
    private function handleFeatures($fieldName, $features)
539
    {
540
        $rOly  = $this->handleFeaturesSingle($fieldName, $features, 'readonly');
541
        $rDbld = $this->handleFeaturesSingle($fieldName, $features, 'disabled');
542
        $rNl   = [];
543
        if (isset($features['include_null']) && in_array($fieldName, $features['include_null'])) {
544
            $rNl = ['include_null'];
545
        }
546
        return array_merge([], $rOly, $rDbld, $rNl);
547
    }
548
549
    private function handleFeaturesSingle($fieldName, $features, $featureKey)
550
    {
551
        $fMap    = [
552
            'readonly' => ['readonly', 'class', 'input_readonly'],
553
            'disabled' => ['disabled']
554
        ];
555
        $aReturn = [];
556
        if (array_key_exists($featureKey, $features)) {
557
            if (array_key_exists($fieldName, $features[$featureKey])) {
558
                $aReturn[$featureKey][$fMap[$featureKey][0]] = $fMap[$featureKey][0];
559
                if (count($fMap[$featureKey]) > 1) {
560
                    $aReturn[$featureKey][$fMap[$featureKey][1]] = $fMap[$featureKey][2];
561
                }
562
            }
563
        }
564
        return $aReturn;
565
    }
566
567
    /**
568
     * Returns a generic form based on a given table
569
     *
570
     * @param string $tblSrc Table Source
571
     * @param array $feat
572
     * @param string|array $hiddenInfo List of hidden fields
573
     *
574
     * @return string Form to add/modify detail for a single row within a table
575
     */
576
    protected function setFormGenericSingleRecord($tblSrc, $feat, $hiddenInfo = '')
577
    {
578
        echo $this->setStringIntoTag('', 'div', [
579
            'id' => 'loading'
580
        ]); // Ajax container
581
        if (strpos($tblSrc, '.') !== false) {
582
            $tblSrc = explode('.', str_replace('`', '', $tblSrc))[1];
583
        }
584
        $this->setTableCache($tblSrc);
585
        $sReturn = [];
586
        if (count($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc]) != 0) {
587
            foreach ($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc] as $value) {
588
                $sReturn[] = $this->setNeededField($tblSrc, $value, $feat);
589
            }
590
        }
591
        $btn                  = [];
592
        $btn[]                = $this->setStringIntoShortTag('input', [
593
            'type'  => 'submit',
594
            'id'    => 'submit',
595
            'style' => 'margin-left:220px;',
596
            'value' => $this->lclMsgCmn('i18n_Form_ButtonSave'),
597
        ]);
598
        $adtnlScriptAfterForm = $this->setJavascriptContent(implode('', [
599
            '$(document).ready(function(){',
600
            '$("form#' . $feat['id'] . '").submit(function(){',
601
            '$("input").attr("readonly", true);',
602
            '$("input[type=submit]").attr("disabled", "disabled");',
603
            '$("input[type=submit]").attr("value", "' . $this->lclMsgCmn('i18n_Form_ButtonSaving') . '");',
604
            '});',
605
            '});',
606
        ]));
607
        if (isset($feat['insertAndUpdate'])) {
608
            $btn[] = $this->setStringIntoShortTag('input', [
609
                'type'  => 'hidden',
610
                'id'    => 'insertAndUpdate',
611
                'name'  => 'insertAndUpdate',
612
                'value' => 'insertAndUpdate'
613
            ]);
614
        }
615
        $sReturn[] = $this->setStringIntoTag(implode('', $btn), 'div');
616
        if (isset($hiddenInfo)) {
617
            if (is_array($hiddenInfo)) {
618
                foreach ($hiddenInfo as $key => $value) {
619
                    $hiddenInput = $this->setStringIntoShortTag('input', [
620
                        'type'  => 'hidden',
621
                        'name'  => $key,
622
                        'id'    => $key,
623
                        'value' => $value,
624
                    ]);
625
                    $sReturn[]   = $this->setStringIntoTag($hiddenInput, 'div');
626
                }
627
            }
628
        }
629
        return $this->setStringIntoTag(implode('', $sReturn), 'form', [
630
                    'id'     => $feat['id'],
631
                    'action' => $feat['action'],
632
                    'method' => $feat['method']
633
                ])
634
                . $adtnlScriptAfterForm;
635
    }
636
637
    protected function setTableLocaleFields($localizationStrings)
638
    {
639
        $this->advCache['tableStructureLocales'] = $localizationStrings;
640
    }
641
642
    /**
643
     * Analyse the field and returns the proper line 2 use in forms
644
     *
645
     * @param string $tableSource
646
     * @param array $details
647
     * @param array $features
648
     * @return string|array
649
     */
650
    private function setNeededField($tableSource, $details, $features)
0 ignored issues
show
Coding Style introduced by
setNeededField uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
setNeededField uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
651
    {
652
        if (isset($features['hidden'])) {
653
            if (in_array($details['COLUMN_NAME'], $features['hidden'])) {
654
                return null;
655
            }
656
        }
657
        $fieldLabel = $this->getFieldNameForDisplay($details);
658
        if ($fieldLabel == 'hidden') {
659
            return null;
660
        }
661
        $sReturn = [];
662
        switch ($details['COLUMN_NAME']) {
663
            case 'host':
664
                $sReturn['label'] = $this->setStringIntoTag('Numele calculatorului', 'label', [
665
                    'for' => $details['COLUMN_NAME']
666
                ]);
667
                $sReturn['input'] = $this->setStringIntoShortTag('input', [
668
                    'type'     => 'input',
669
                    'size'     => 15,
670
                    'readonly' => 'readonly',
671
                    'value'    => gethostbyaddr($_SERVER['REMOTE_ADDR'])
672
                ]);
673
                break;
674
            case 'InsertDateTime':
675
            case 'modification_datetime':
676
            case 'ModificationDateTime':
677
                $sReturn          = call_user_func_array([$this, 'getTimestamping'], [$details]);
678
                break;
679
            default:
680
                $aLabel           = [
681
                    'for' => $details['COLUMN_NAME'],
682
                    'id'  => $details['COLUMN_NAME'] . '_label'
683
                ];
684
                if (isset($features['disabled'])) {
685
                    if (in_array($details['COLUMN_NAME'], $features['disabled'])) {
686
                        $aLabel = array_merge($aLabel, ['style' => 'color: grey;']);
687
                    }
688
                }
689
                $sReturn['label'] = $this->setStringIntoTag($fieldLabel, 'label', $aLabel);
690
                $result           = $this->setNeededFieldByType($tableSource, $details, $features);
691
                if ($details['COLUMN_NAME'] == 'ChoiceId') {
692
                    $result = $this->setStringIntoShortTag('input', [
693
                        'type'  => 'text',
694
                        'name'  => $details['COLUMN_NAME'],
695
                        'value' => $_REQUEST[$details['COLUMN_NAME']]
696
                    ]);
697
                }
698
                $sReturn['input'] = $result;
699
                break;
700
        }
701
        $finalReturn   = [];
702
        $finalReturn[] = $sReturn['label'];
703
        $finalReturn[] = $this->setStringIntoTag($sReturn['input'], 'span', ['class' => 'labell']);
704
        $wrkDb         = $this->advCache['workingDatabase'];
705
        if (isset($this->tableFKsCache[$wrkDb][$tableSource])) {
0 ignored issues
show
Bug introduced by
The property tableFKsCache does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
706
            if (in_array($details['COLUMN_NAME'], $this->advCache['FKcol'][$wrkDb][$tableSource])) {
707
                $finalReturn[] = $this->setFieldNumbers($details);
708
            }
709
        }
710
        return $this->setStringIntoTag(implode('', $finalReturn), 'div');
711
    }
712
713
    /**
714
     * Analyse the field type and returns the proper lines 2 use in forms
715
     *
716
     * @param string $tblName
717
     * @param array $details
718
     * @param array $features
719
     * @return string|array
720
     */
721
    private function setNeededFieldByType($tblName, $details, $features)
722
    {
723
        $sReturn = null;
724
        if (isset($features['special']) && isset($features['special'][$details['COLUMN_NAME']])) {
725
            $slctOpt = $this->setMySQLquery2Server($features['special'][$details['COLUMN_NAME']], 'array_key_value');
726
            $sReturn = $this->setArrayToSelect($slctOpt, $this->getFieldValue($details), $details['COLUMN_NAME'], [
727
                'size' => 1
728
            ]);
729
        } else {
730
            $iar = $this->handleFeatures($details['COLUMN_NAME'], $features);
731
            switch ($details['DATA_TYPE']) {
732
                case 'bigint':
733
                case 'int':
734
                case 'mediumint':
735
                case 'smallint':
736
                case 'tinyint':
737
                case 'float':
738
                case 'double':
739
                case 'decimal':
740
                case 'numeric':
741
                    $sReturn = $this->getFieldOutputNumeric($tblName, $details, $iar);
742
                    break;
743
                case 'char':
744
                case 'tinytext':
745
                case 'varchar':
746
                    $sReturn = $this->getFieldOutputText($tblName, $details['DATA_TYPE'], $details, $iar);
747
                    break;
748
                case 'date':
749
                    $sReturn = $this->getFieldOutputDate($details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Unused Code introduced by
The call to MySQLiAdvancedOutput::getFieldOutputDate() has too many arguments starting with $iar.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
750
                    break;
751
                case 'datetime':
752
                case 'timestamp':
753
                    $sReturn = $this->getFieldOutputTimestamp($details, $iar);
754
                    break;
755
                case 'enum':
756
                case 'set':
757
                    $sReturn = $this->getFieldOutputEnumSet($tblName, $details['DATA_TYPE'], $details, $iar);
758
                    break;
759
                case 'text':
760
                case 'blob':
761
                    $sReturn = $this->getFieldOutputTextLarge($details['DATA_TYPE'], $details, $iar);
762
                    break;
763
                case 'time':
764
                    $sReturn = $this->getFieldOutputTime($details, $iar);
765
                    break;
766
                case 'year':
767
                    $sReturn = $this->getFieldOutputYear($tblName, $details, $iar);
768
                    break;
769
            }
770
        }
771
        return $this->getFieldCompletionType($details) . $sReturn;
772
    }
773
774
    /**
775
     * create a Cache for given table to use it in many places
776
     *
777
     * @param type $tblSrc
778
     */
779
    private function setTableCache($tblSrc)
780
    {
781
        $dat = $this->establishDatabaseAndTable($this->fixTableSource($tblSrc));
782
        if (!isset($this->advCache['tableStructureCache'][$dat[0]][$dat[1]])) {
783
            switch ($dat[1]) {
784
                case 'user_rights':
785
                    $this->advCache['workingDatabase'] = 'usefull_security';
786
                    break;
787
                default:
788
                    $this->advCache['workingDatabase'] = $dat[0];
789
                    break;
790
            }
791
            $this->advCache['tableStructureCache'][$dat[0]][$dat[1]] = $this->getMySQLlistColumns([
792
                'TABLE_SCHEMA' => $dat[0],
793
                'TABLE_NAME'   => $dat[1],
794
            ]);
795
            $this->setTableForeginKeyCache($dat[0], $dat[1]);
796
        }
797
    }
798
799
    private function setTableForeginKeyCache($dbName, $tblName)
800
    {
801
        $frgnKs = $this->getMySQLlistIndexes([
802
            'TABLE_SCHEMA'          => $dbName,
803
            'TABLE_NAME'            => $tblName,
804
            'REFERENCED_TABLE_NAME' => 'NOT NULL',
805
        ]);
806
        if (!is_null($frgnKs)) {
807
            $this->advCache['tableFKs'][$dbName][$tblName] = $frgnKs;
808
            $this->advCache['FKcol'][$dbName][$tblName]    = array_column($frgnKs, 'COLUMN_NAME', 'CONSTRAINT_NAME');
809
        }
810
    }
811
812
    private function setViewDeleteFeedbacks()
813
    {
814
        return [
815
            'Confirmation' => $this->lclMsgCmn('i18n_Action_Confirmation'),
816
            'Failed'       => $this->lclMsgCmn('i18n_ActionDelete_Failed'),
817
            'Impossible'   => $this->lclMsgCmn('i18n_ActionDelete_Impossible'),
818
            'Success'      => $this->lclMsgCmn('i18n_ActionDelete_Success'),
819
        ];
820
    }
821
822
    private function setViewDeletePackedFinal($sReturn)
823
    {
824
        $finalJavascript = $this->setJavascriptContent(implode('', [
825
            '$("#DeleteFeedback").fadeOut(4000, function() {',
826
            '$(this).remove();',
827
            '});',
828
        ]));
829
        return '<div id="DeleteFeedback">' . $sReturn . '</div>' . $finalJavascript;
830
    }
831
832
    /**
833
     * Automatic handler for Record deletion
834
     *
835
     * @param string $tbl
836
     * @param string $idn
837
     * @return string
838
     */
839
    protected function setViewModernDelete($tbl, $idn)
0 ignored issues
show
Coding Style introduced by
setViewModernDelete uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
840
    {
841
        $tMsg = $this->setViewDeleteFeedbacks();
842
        if ($tbl == '') {
843
            $sReturn = $this->setFeedbackModern('error', $tMsg['Confirmation'], $tMsg['Impossible']);
844
        } else {
845
            $this->setMySQLquery2Server($this->sQueryToDeleteSingleIdentifier([$tbl, $idn, $_REQUEST[$idn]]));
846
            $sReturn = $this->setFeedbackModern('error', $tMsg['Confirmation'], $tMsg['Failed'])
847
                    . '(' . $this->mySQLconnection->error . ')';
848
            if ($this->mySQLconnection->affected_rows > 0) {
849
                $sReturn = $this->setFeedbackModern('check', $tMsg['Confirmation'], $tMsg['Success']);
850
            }
851
        }
852
        return $this->setViewDeletePackedFinal($sReturn);
853
    }
854
}
855