Passed
Push — EXTRACT_CLASSES ( ae6b5c...83d77a )
by Rafael
60:14 queued 23:58
created

FormCardWebPortal::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* Copyright (C) 2023-2024  Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2023-2024	Lionel Vessiller		    <[email protected]>
5
 * Copyright (C) 2024		MDW							<[email protected]>
6
 * Copyright (C) 2024       Frédéric France             <[email protected]>
7
 * Copyright (C) 2024       Rafael San José             <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
22
23
namespace Dolibarr\Code\WebPortal\Classes;
24
25
use DoliDB;
26
27
/**
28
 * \file       htdocs/webportal/class/html.formlistwebportal.class.php
29
 * \ingroup    webportal
30
 * \brief      File of class with all html predefined components for WebPortal
31
 */
32
33
require_once constant('DOL_DOCUMENT_ROOT') . '/webportal/class/html.formwebportal.class.php';
34
35
/**
36
 *    Class to manage generation of HTML components
37
 *    Only common components for WebPortal must be here.
38
 *
39
 */
40
class FormCardWebPortal
41
{
42
    /**
43
     * @var string Action
44
     */
45
    public $action = '';
46
47
    /**
48
     * @var string Back to page
49
     */
50
    public $backtopage = '';
51
52
    /**
53
     * @var string Back to page for cancel
54
     */
55
    public $backtopageforcancel = '';
56
57
    /**
58
     * @var string Back to page for JS fields
59
     */
60
    public $backtopagejsfields = '';
61
62
    /**
63
     * @var string Cancel
64
     */
65
    public $cancel = '';
66
67
    /**
68
     * @var DoliDB Database
69
     */
70
    public $db;
71
72
    /**
73
     * @var string Element in english
74
     */
75
    public $elementEn = '';
76
77
    /**
78
     * @var Form  Instance of the Form
79
     */
80
    public $form;
81
82
    /**
83
     * @var int Id
84
     */
85
    public $id;
86
87
    /**
88
     * @var CommonObject Object
89
     */
90
    public $object;
91
92
    /**
93
     * @var int Permission to read
94
     */
95
    public $permissiontoread = 0;
96
97
    /**
98
     * @var int Permission to add
99
     */
100
    public $permissiontoadd = 0;
101
102
    /**
103
     * @var int Permission to delete
104
     */
105
    public $permissiontodelete = 0;
106
107
    /**
108
     * @var int Permission to note
109
     */
110
    public $permissionnote = 0;
111
112
    /**
113
     * @var int Permission to delete links
114
     */
115
    public $permissiondellink = 0;
116
117
    /**
118
     * @var string Ref
119
     */
120
    public $ref;
121
122
    /**
123
     * @var string Title key to translate
124
     */
125
    public $titleKey = '';
126
127
    /**
128
     * @var string Title desc key to translate
129
     */
130
    public $titleDescKey = '';
131
132
    /**
133
     * Constructor
134
     *
135
     * @param DoliDB $db Database handler
136
     */
137
    public function __construct($db)
138
    {
139
        $this->db = $db;
140
        $this->form = new FormWebPortal($this->db);
141
    }
142
143
    /**
144
     * Init
145
     *
146
     * @param   string  $elementEn              Element (english) : "member" (for adherent), "partnership"
147
     * @param   int     $id                     [=0] ID element
148
     * @param   int     $permissiontoread       [=0] Permission to read (0 : access forbidden by default)
149
     * @param   int     $permissiontoadd        [=0] Permission to add (0 : access forbidden by default), used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php
150
     * @param   int     $permissiontodelete     [=0] Permission to delete (0 : access forbidden by default)
151
     * @param   int     $permissionnote         [=0] Permission to note (0 : access forbidden by default)
152
     * @param   int     $permissiondellink      [=0] Permission to delete links (0 : access forbidden by default)
153
     * @return  void
154
     */
155
    public function init($elementEn, $id = 0, $permissiontoread = 0, $permissiontoadd = 0, $permissiontodelete = 0, $permissionnote = 0, $permissiondellink = 0)
156
    {
157
        global $hookmanager, $langs;
158
159
        $elementEnUpper = strtoupper($elementEn);
160
        $objectclass = 'WebPortal' . ucfirst($elementEn);
161
162
        $elementCardAccess = getDolGlobalString('WEBPORTAL_' . $elementEnUpper . '_CARD_ACCESS', 'hidden');
163
        if ($elementCardAccess == 'hidden' || $id <= 0) {
164
            accessforbidden();
165
        }
166
167
        // load module libraries
168
        dol_include_once('/webportal/class/webportal' . $elementEn . '.class.php');
169
170
        // Load translation files required by the page
171
        $langs->loadLangs(array('website', 'other'));
172
173
        // Get parameters
174
        //$id = $id > 0 ? $id : GETPOST('id', 'int');
175
        $ref = GETPOST('ref', 'alpha');
176
        $action = GETPOST('action', 'aZ09');
177
        $confirm = GETPOST('confirm', 'alpha');
178
        $cancel = GETPOST('cancel', 'aZ09');
179
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'webportal' . $elementEn . 'card'; // To manage different context of search
180
        $backtopage = GETPOST('backtopage', 'alpha');                    // if not set, a default page will be used
181
        $backtopageforcancel = GETPOST('backtopageforcancel', 'alpha');    // if not set, $backtopage will be used
182
        $backtopagejsfields = GETPOST('backtopagejsfields', 'alpha');
183
184
        // Initialize technical objects
185
        $object = new $objectclass($this->db);
186
        //$extrafields = new ExtraFields($db);
187
        $hookmanager->initHooks(array('webportal' . $elementEn . 'card', 'globalcard')); // Note that conf->hooks_modules contains array
188
189
        // Fetch optionals attributes and labels
190
        //$extrafields->fetch_name_optionals_label($object->table_element);
191
        //$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
192
193
        if (empty($action) && empty($id) && empty($ref)) {
194
            $action = 'view';
195
        }
196
197
        // Load object
198
        include DOL_DOCUMENT_ROOT . '/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
199
200
        // Security check (enable the most restrictive one)
201
        if (!isModEnabled('webportal')) {
202
            accessforbidden();
203
        }
204
        if (!$permissiontoread) {
205
            accessforbidden();
206
        }
207
208
        // set form card
209
        $this->action = $action;
210
        $this->backtopage = $backtopage;
0 ignored issues
show
Documentation Bug introduced by
It seems like $backtopage can also be of type array. However, the property $backtopage is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
211
        $this->backtopageforcancel = $backtopageforcancel;
0 ignored issues
show
Documentation Bug introduced by
It seems like $backtopageforcancel can also be of type array or array or array. However, the property $backtopageforcancel is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
212
        $this->backtopagejsfields = $backtopagejsfields;
0 ignored issues
show
Documentation Bug introduced by
It seems like $backtopagejsfields can also be of type array or array or array. However, the property $backtopagejsfields is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
213
        $this->cancel = $cancel;
0 ignored issues
show
Documentation Bug introduced by
It seems like $cancel can also be of type array or array or array. However, the property $cancel is declared as type string. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
214
        $this->elementEn = $elementEn;
215
        $this->id = $id;
216
        $this->object = $object;
217
        $this->permissiontoread = $permissiontoread;
218
        $this->permissiontoadd = $permissiontoadd;
219
        $this->permissiontodelete = $permissiontodelete;
220
        $this->permissionnote = $permissionnote;
221
        $this->permissiondellink = $permissiondellink;
222
        $this->titleKey = $objectclass . 'CardTitle';
223
        $this->ref = $ref;
224
    }
225
226
    /**
227
     * Do actions
228
     *
229
     * @return  void
230
     */
231
    public function doActions()
232
    {
233
        global $langs;
234
235
        // initialize
236
        $action = $this->action;
237
        $backtopage = $this->backtopage;
238
        $backtopageforcancel = $this->backtopageforcancel;
239
        $cancel = $this->cancel;
240
        $elementEn = $this->elementEn;
241
        $id = $this->id;
242
        $object = $this->object;
243
        //$permissiontoread = $this->permissiontoread;
244
        $permissiontoadd = $this->permissiontoadd;
245
246
        $error = 0;
247
248
        $context = Context::getInstance();
249
250
        $backurlforlist = $context->getControllerUrl('default');
251
        $noback = 1;
252
253
        if (empty($backtopage) || ($cancel && empty($id))) {
254
            if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) {
255
                $backtopage = $context->getControllerUrl($elementEn . 'card');
256
            }
257
        }
258
259
        // Action to cancel record
260
        if ($cancel) {
261
            if (!empty($backtopageforcancel)) {
262
                header("Location: " . $backtopageforcancel);
263
                exit;
264
            } elseif (!empty($backtopage)) {
265
                header("Location: " . $backtopage);
266
                exit;
267
            }
268
            $action = '';
269
        }
270
271
        // Action to update record
272
        if ($action == 'update' && !empty($permissiontoadd)) {
273
            foreach ($object->fields as $key => $val) {
274
                // Check if field was submitted to be edited
275
                if ($object->fields[$key]['type'] == 'duration') {
276
                    if (!GETPOSTISSET($key . 'hour') || !GETPOSTISSET($key . 'min')) {
277
                        continue; // The field was not submitted to be saved
278
                    }
279
                } elseif ($object->fields[$key]['type'] == 'boolean') {
280
                    if (!GETPOSTISSET($key)) {
281
                        $object->$key = 0; // use 0 instead null if the field is defined as not null
282
                        continue;
283
                    }
284
                } else {
285
                    if (!GETPOSTISSET($key) && !preg_match('/^chkbxlst:/', $object->fields[$key]['type']) && $object->fields[$key]['type'] !== 'checkbox') {
286
                        continue; // The field was not submitted to be saved
287
                    }
288
                }
289
                // Ignore special fields
290
                if (in_array($key, array('rowid', 'entity', 'import_key'))) {
291
                    continue;
292
                }
293
                if (in_array($key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
294
                    if (!in_array(abs($val['visible']), array(1, 3, 4))) {
295
                        continue; // Only 1 and 3 and 4, that are cases to update
296
                    }
297
                }
298
299
                // Set value to update
300
                if (preg_match('/^text/', $object->fields[$key]['type'])) {
301
                    $tmparray = explode(':', $object->fields[$key]['type']);
302
                    if (!empty($tmparray[1])) {
303
                        $value = GETPOST($key, $tmparray[1]);
304
                    } else {
305
                        $value = GETPOST($key, 'nohtml');
306
                    }
307
                } elseif (preg_match('/^html/', $object->fields[$key]['type'])) {
308
                    $tmparray = explode(':', $object->fields[$key]['type']);
309
                    if (!empty($tmparray[1])) {
310
                        $value = GETPOST($key, $tmparray[1]);
311
                    } else {
312
                        $value = GETPOST($key, 'restricthtml');
313
                    }
314
                } elseif (in_array($object->fields[$key]['type'], array('date', 'datetime'))) {
315
                    $postDate = GETPOST($key, 'alphanohtml');
316
                    // extract date YYYY-MM-DD for year, month and day
317
                    $dateArr = explode('-', $postDate);
318
                    $dateYear = 0;
319
                    $dateMonth = 0;
320
                    $dateDay = 0;
321
                    if (count($dateArr) == 3) {
322
                        $dateYear = (int) $dateArr[0];
323
                        $dateMonth = (int) $dateArr[1];
324
                        $dateDay = (int) $dateArr[2];
325
                    }
326
                    // extract time HH:ii:ss for hours, minutes and seconds
327
                    $postTime = GETPOST($key . '_time', 'alphanohtml');
328
                    $timeArr = explode(':', $postTime);
329
                    $timeHours = 12;
330
                    $timeMinutes = 0;
331
                    $timeSeconds = 0;
332
                    if (!empty($timeArr)) {
333
                        if (isset($timeArr[0])) {
334
                            $timeHours = (int) $timeArr[0];
335
                        }
336
                        if (isset($timeArr[1])) {
337
                            $timeMinutes = (int) $timeArr[1];
338
                        }
339
                        if (isset($timeArr[2])) {
340
                            $timeSeconds = (int) $timeArr[2];
341
                        }
342
                    }
343
                    $value = dol_mktime($timeHours, $timeMinutes, $timeSeconds, $dateMonth, $dateDay, $dateYear);
344
                } elseif ($object->fields[$key]['type'] == 'duration') {
345
                    if (GETPOSTINT($key . 'hour') != '' || GETPOSTINT($key . 'min') != '') {
346
                        $value = 60 * 60 * GETPOSTINT($key . 'hour') + 60 * GETPOSTINT($key . 'min');
347
                    } else {
348
                        $value = '';
349
                    }
350
                } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) {
351
                    $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup
352
                } elseif ($object->fields[$key]['type'] == 'boolean') {
353
                    $value = ((GETPOST($key, 'aZ09') == 'on' || GETPOST($key, 'aZ09') == '1') ? 1 : 0);
354
                    //}
355
                    //elseif ($object->fields[$key]['type'] == 'reference') {
356
                    //    $value = array_keys($object->param_list)[GETPOST($key)].','.GETPOST($key.'2');
357
                } elseif (preg_match('/^chkbxlst:/', $object->fields[$key]['type']) || $object->fields[$key]['type'] == 'checkbox') {
358
                    $value = '';
359
                    $values_arr = GETPOST($key, 'array');
360
                    if (!empty($values_arr)) {
361
                        $value = implode(',', $values_arr);
362
                    }
363
                } else {
364
                    if ($key == 'lang') {
365
                        $value = GETPOST($key, 'aZ09');
366
                    } else {
367
                        $value = GETPOST($key, 'alphanohtml');
368
                    }
369
                }
370
                if (preg_match('/^integer:/i', $object->fields[$key]['type']) && $value == '-1') {
371
                    $value = ''; // This is an implicit foreign key field
372
                }
373
                if (!empty($object->fields[$key]['foreignkey']) && $value == '-1') {
374
                    $value = ''; // This is an explicit foreign key field
375
                }
376
377
                $object->$key = $value;
378
                if (!empty($val['notnull']) && $val['notnull'] > 0 && $object->$key == '' && is_null($val['default'])) {
379
                    $error++;
380
                    $context->setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val['label'])), null, 'errors');
381
                }
382
383
                // Validation of fields values
384
                if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 2 || getDolGlobalString('MAIN_ACTIVATE_VALIDATION_RESULT')) {
385
                    if (!$error && !empty($val['validate']) && is_callable(array($object, 'validateField'))) {
386
                        if (!$object->validateField($object->fields, $key, $value)) {
387
                            $error++;
388
                        }
389
                    }
390
                }
391
392
                if (isModEnabled('category')) {
393
                    $categories = GETPOST('categories', 'array');
394
                    if (method_exists($object, 'setCategories')) {
395
                        $object->setCategories($categories);
396
                    }
397
                }
398
            }
399
400
            // Fill array 'array_options' with data from add form
401
            //if (!$error) {
402
            //    $ret = $extrafields->setOptionalsFromPost(null, $object, '@GETPOSTISSET');
403
            //    if ($ret < 0) {
404
            //        $error++;
405
            //    }
406
            //}
407
408
            if (!$error) {
409
                $result = $object->update($context->logged_user);
410
                if ($result >= 0) {
411
                    $action = 'view';
412
                    $urltogo = $backtopage ? str_replace('__ID__', $result, $backtopage) : $backurlforlist;
413
                    $urltogo = preg_replace('/--IDFORBACKTOPAGE--/', (string) $object->id, $urltogo); // New method to autoselect project after a New on another form object creation
414
                    if ($urltogo && empty($noback)) {
415
                        header("Location: " . $urltogo);
416
                        exit;
417
                    }
418
                } else {
419
                    $error++;
420
                    // Creation KO
421
                    $context->setEventMessages($object->error, $object->errors, 'errors');
422
                    $action = 'edit';
423
                }
424
            } else {
425
                $action = 'edit';
426
            }
427
        }
428
429
        $this->object = $object;
430
        $this->action = $action;
431
    }
432
433
    /**
434
     * Html for header
435
     *
436
     * @param   Context $context    Context object
437
     * @return  string
438
     */
439
    protected function header($context)
440
    {
441
        global $langs;
442
443
        $html = '';
444
445
        // initialize
446
        $object = $this->object;
447
        $addgendertxt = '';
448
        //if (property_exists($object, 'gender') && !empty($object->gender)) {
449
        //    switch ($object->gender) {
450
        //        case 'man':
451
        //            $addgendertxt .= '<i class="fas fa-mars"></i>';
452
        //            break;
453
        //        case 'woman':
454
        //            $addgendertxt .= '<i class="fas fa-venus"></i>';
455
        //            break;
456
        //        case 'other':
457
        //            $addgendertxt .= '<i class="fas fa-transgender"></i>';
458
        //            break;
459
        //    }
460
        //}
461
462
        $html .= '<!-- html.formcardwebportal.class.php -->';
463
        $html .= '<header>';
464
465
        // Left block - begin
466
        $html .= '<div class="header-card-left-block inline-block" style="width: 75%;">';
467
        $html .= '<div>';
468
469
        // logo or photo
470
        $form = new Form($this->db);
471
        $html .= '<div class="inline-block floatleft valignmiddle">';
472
        $html .= '<div class="floatleft inline-block valignmiddle divphotoref">';
473
        $html .= $form->showphoto('memberphoto', $object, 0, 0, 0, 'photowithmargin photoref', 'small', 1, 0, 1);
474
        //include DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';
475
        //$html .= getImagePublicURLOfObject($object, 1, '_small');
476
        $html .= '</div>';
477
        $html .= '</div>';
478
479
        // main information - begin
480
        $html .= '<div class="header-card-main-information inline-block valignmiddle">';
481
        // ref
482
        $html .= '<div><strong>' . $langs->trans("Ref") . ' : ' . dol_escape_htmltag($object->ref) . '</strong></div>';
483
        // full name
484
        $fullname = '';
485
        if (method_exists($object, 'getFullName')) {
486
            $fullname = $object->getFullName($langs);
487
        }
488
        $html .= '<div><strong>';
489
        if ($object->element == 'member') {
490
            if ($object->morphy == 'mor' && !empty($object->societe)) {
491
                $html .= dol_htmlentities($object->societe);
492
                $html .= (!empty($fullname) && $object->societe != $fullname) ? ' (' . dol_htmlentities($fullname) . $addgendertxt . ')' : '';
493
            } else {
494
                $html .= dol_htmlentities($fullname) . $addgendertxt;
495
                if (empty($object->fk_soc)) {
496
                    $html .= (!empty($object->societe) && $object->societe != $fullname) ? ' (' . dol_htmlentities($object->societe) . ')' : '';
497
                }
498
            }
499
        } else {
500
            $html .= dol_htmlentities(!empty($object->ref) ? $object->ref : '');
501
        }
502
        $html .= '</strong></div>';
503
        // address
504
        if (method_exists($object, 'getBannerAddressForWebPortal')) {
505
            $moreaddress = $object->getBannerAddressForWebPortal('refaddress');
506
            if ($moreaddress) {
507
                $html .= '<div class="refidno refaddress">';
508
                $html .= $moreaddress;
509
                $html .= '</div>';
510
            }
511
        }
512
        $html .= '</div>';
513
        // main information - end
514
515
        $html .= '</div>';
516
        $html .= '</div>';
517
        // Left block - end
518
519
        // Right block - begin
520
        $html .= '<div class="header-card-right-block inline-block" style="width: 24%;">';
521
        // show status
522
        $htmlStatus = $object->getLibStatut(6);
523
        if (empty($htmlStatus) || $htmlStatus == $object->getLibStatut(3)) {
524
            $htmlStatus = $object->getLibStatut(5);
525
        }
526
        $html .= $htmlStatus;
527
        $html .= '</div>';
528
        // Right block - end
529
530
        $html .= '</header>';
531
532
        return $html;
533
    }
534
535
    /**
536
     * Html for body (view mode)
537
     * @param   string  $keyforbreak    [=''] Key for break left block
538
     * @return  string  Html for body
539
     */
540
    protected function bodyView($keyforbreak = '')
541
    {
542
        global $langs;
543
544
        $html = '';
545
546
        // initialize
547
        $object = $this->object;
548
549
        $object->fields = dol_sort_array($object->fields, 'position');
550
551
        // separate fields to show on the left and on the right
552
        $fieldShowList = array();
553
        foreach ($object->fields as $key => $val) {
554
            // discard if it's a hidden field on form
555
            if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4 && abs($val['visible']) != 5) {
556
                continue;
557
            }
558
559
            if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) {
560
                continue; // we don't want this field
561
            }
562
563
            if (!empty($val['showonheader'])) {
564
                continue; // already on header
565
            }
566
567
            $fieldShowList[$key] = $val;
568
        }
569
570
        $nbFieldShow = count($fieldShowList);
571
        $lastKeyFieldLeft = $keyforbreak;
572
        $lastNumFieldLeft = 0;
573
        if ($lastKeyFieldLeft == '') {
574
            $lastNumFieldLeft = ceil($nbFieldShow / 2);
575
        }
576
        $numField = 0;
577
        $html .= '<div class="grid">';
578
        $html .= '<div class="card-left">';
579
        foreach ($object->fields as $key => $val) {
580
            if (!array_key_exists($key, $fieldShowList)) {
581
                continue; // not to show
582
            }
583
584
            $value = $object->$key;
585
586
            $html .= '<div class="grid field_' . $key . '">';
587
588
            $html .= '<div class="' . (empty($val['tdcss']) ? '' : $val['tdcss']) . ' fieldname_' . $key;
589
            $html .= '">';
590
            $labeltoshow = '';
591
            $labeltoshow .= '<strong>' . $langs->trans($val['label']) . '</strong>';
592
            $html .= $labeltoshow;
593
            $html .= '</div>';
594
595
            $html .= '<div class="valuefield fieldname_' . $key;
596
            if (!empty($val['cssview'])) {
597
                $html .= ' ' . $val['cssview'];
598
            }
599
            $html .= '">';
600
            if ($key == 'lang') {
601
                $langs->load('languages');
602
                $labellang = ($value ? $langs->trans('Language_' . $value) : '');
603
                //$html .= picto_from_langcode($value, 'class="paddingrightonly saturatemedium opacitylow"');
604
                $html .= $labellang;
605
            } else {
606
                $html .= $this->form->showOutputFieldForObject($object, $val, $key, $value, '', '', '', 0);
607
            }
608
            $html .= '</div>';
609
610
            $html .= '</div>';
611
612
            $numField++;
613
614
            // fields on the right
615
            $cardRight = false;
616
            if ($keyforbreak != '') {
617
                if ($key == $keyforbreak) {
618
                    $cardRight = true;
619
                }
620
            } else {
621
                if ($numField == $lastNumFieldLeft) {
622
                    $cardRight = true;
623
                }
624
            }
625
            if ($cardRight === true) {
626
                $html .= '</div>';
627
                $html .= '<div class="card-right">';
628
            }
629
        }
630
        $html .= '</div>';
631
        $html .= '</div>';
632
633
        return $html;
634
    }
635
636
    /**
637
     *  Html for body (edit mode)
638
     *
639
     * @return  string
640
     */
641
    protected function bodyEdit()
642
    {
643
        global $langs;
644
645
        $html = '';
646
647
        // initialize
648
        $object = $this->object;
649
650
        $object->fields = dol_sort_array($object->fields, 'position');
651
652
        foreach ($object->fields as $key => $val) {
653
            // Discard if filed is a hidden field on form
654
            if (abs($val['visible']) != 1 && abs($val['visible']) != 3 && abs($val['visible']) != 4) {
655
                continue;
656
            }
657
658
            if (array_key_exists('enabled', $val) && isset($val['enabled']) && !verifCond($val['enabled'])) {
659
                continue; // We don't want this field
660
            }
661
662
            $html .= '<div class="grid field_' . $key . '">';
663
            $html .= '<div class="titlefieldcreate';
664
            if (isset($val['notnull']) && $val['notnull'] > 0) {
665
                $html .= ' required';
666
            }
667
            $html .= '">';
668
            $html .= $langs->trans($val['label']);
669
            $html .= '</div>';
670
671
            $html .= '<div class="valuefieldcreate">';
672
            if (in_array($val['type'], array('int', 'integer'))) {
673
                $value = GETPOSTISSET($key) ? GETPOSTINT($key) : $object->$key;
674
            } elseif ($val['type'] == 'double') {
675
                $value = GETPOSTISSET($key) ? price2num(GETPOST($key, 'alphanohtml')) : $object->$key;
676
            } elseif (preg_match('/^text/', $val['type'])) {
677
                $tmparray = explode(':', $val['type']);
678
                if (!empty($tmparray[1])) {
679
                    $check = $tmparray[1];
680
                } else {
681
                    $check = 'nohtml';
682
                }
683
                $value = GETPOSTISSET($key) ? GETPOST($key, $check) : $object->$key;
684
            } elseif (preg_match('/^html/', $val['type'])) {
685
                $tmparray = explode(':', $val['type']);
686
                if (!empty($tmparray[1])) {
687
                    $check = $tmparray[1];
688
                } else {
689
                    $check = 'restricthtml';
690
                }
691
                $value = GETPOSTISSET($key) ? GETPOST($key, $check) : $object->$key;
692
            } elseif (in_array($val['type'], array('date', 'datetime'))) {
693
                $isPostDate = GETPOSTISSET($key);
694
                $isPostTime = GETPOSTISSET($key . '_time');
695
                if ($isPostDate) {
696
                    $postDate = GETPOST($key, 'alphanohtml');
697
                    if ($isPostTime) {
698
                        $postTime = GETPOST($key . '_time', 'alphanohtml') . ':00';
699
                    } else {
700
                        $postTime = '00:00:00';
701
                    }
702
                    $valueDateTimeStr = $postDate . ' ' . $postTime;
703
                } else {
704
                    // format date timestamp to YYYY-MM-DD HH:ii:ss
705
                    $valueDateTimeStr = dol_print_date($object->$key, '%Y-%m-%d %H:%M:%S');
706
                }
707
708
                $value = $valueDateTimeStr;
709
            } elseif ($val['type'] == 'price') {
710
                $value = GETPOSTISSET($key) ? price2num(GETPOST($key)) : price2num($object->$key);
711
            } elseif ($key == 'lang') {
712
                $value = GETPOSTISSET($key) ? GETPOST($key, 'aZ09') : $object->lang;
713
            } else {
714
                $value = GETPOSTISSET($key) ? GETPOST($key, 'alphanohtml') : $object->$key;
715
            }
716
717
            if (!empty($val['noteditable'])) {
718
                $html .= $this->form->showOutputFieldForObject($object, $val, $key, $value, '', '', '', 0);
719
            } else {
720
                $html .= $this->form->showInputField($val, $key, $value, '', '', '', '');
721
            }
722
            $html .= '</div>';
723
            $html .= '</div>';
724
        }
725
726
        return $html;
727
    }
728
729
    /**
730
     * Html for footer
731
     *
732
     * @return  string
733
     */
734
    protected function footer()
735
    {
736
        $html = '';
737
        $html .= '<footer>';
738
        $html .= '</footer>';
739
740
        return $html;
741
    }
742
743
    /**
744
     * Card for an element in the page context
745
     *
746
     * @param   Context     $context    Context object
747
     * @return  string      Html output
748
     */
749
    public function elementCard($context)
750
    {
751
        global $hookmanager, $langs;
752
753
        $html = '<!-- elementCard -->';
754
755
        // initialize
756
        $action = $this->action;
757
        $backtopage = $this->backtopage;
758
        $backtopageforcancel = $this->backtopageforcancel;
759
        //$backtopagejsfields = $this->backtopagejsfields;
760
        //$elementEn = $this->elementEn;
761
        $id = $this->id;
762
        $object = $this->object;
763
        //$permissiontoread = $this->permissiontoread;
764
        $permissiontoadd = $this->permissiontoadd;
765
        $ref = $this->ref;
766
        $titleKey = $this->titleKey;
767
        $title = $langs->trans($titleKey);
768
769
        // Part to edit record
770
        if (($id || $ref) && $action == 'edit') {
771
            $html .= '<article>';
772
            //$html .= load_fiche_titre($title, '', 'object_'.$object->picto);
773
            $html .= '<header>';
774
            $html .= '<h2>' . $title . '</h2>';
775
            $html .= '</header>';
776
777
            $url_file = $context->getControllerUrl($context->controller, '', false);
778
            $html .= '<form method="POST" action="' . $url_file . '">';
779
            $html .= $context->getFormToken();
780
            $html .= '<input type="hidden" name="action" value="update">';
781
            $html .= '<input type="hidden" name="id" value="' . $object->id . '">';
782
            if ($backtopage) {
783
                $html .= '<input type="hidden" name="backtopage" value="' . $backtopage . '">';
784
            }
785
            if ($backtopageforcancel) {
786
                $html .= '<input type="hidden" name="backtopageforcancel" value="' . $backtopageforcancel . '">';
787
            }
788
789
            //$html .= '<table>'."\n";
790
            // Common attributes
791
            //include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php';
792
            $html .= $this->bodyEdit();
793
794
            // Other attributes
795
            //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php';
796
            //$html  .= '</table>';
797
798
            // Save and Cancel buttons
799
            $html .= '<div class="grid">';
800
            $html .= '<div><input type="submit" name="save" role="button" value="' . dol_escape_htmltag($langs->trans('Save')) . '" /></div>';
801
            $html .= '<div><input type="submit" name="cancel" role="button" value="' . dol_escape_htmltag($langs->trans('Cancel')) . '" /></div>';
802
            $html .= '</div>';
803
804
            $html .= '</form>';
805
            $html .= '</article>';
806
        }
807
808
        // Part to show record
809
        if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) {
810
            $html .= '<article>';
811
812
            $formconfirm = '';
813
814
            // Call Hook formConfirm
815
            $parameters = array('formConfirm' => $formconfirm);
816
            $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
817
            if (empty($reshook)) {
818
                $formconfirm .= $hookmanager->resPrint;
819
            } elseif ($reshook > 0) {
820
                $formconfirm = $hookmanager->resPrint;
821
            }
822
823
            // Print form confirm
824
            $html .= $formconfirm;
825
826
            // Object card
827
            // ------------------------------------------------------------
828
            $html .= $this->header($context);
829
830
            // Common attributes
831
            $keyforbreak = '';
832
            $html .= $this->bodyView($keyforbreak);
833
834
            // Other attributes. Fields from hook formObjectOptions and Extrafields.
835
            //include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
836
837
            //$html .= $this->footer();
838
            $html .= '</article>';
839
840
            // Buttons for actions
841
            if ($action != 'presend' && $action != 'editline') {
842
                $html .= '<div>' . "\n";
843
                $parameters = array();
844
                $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
845
                if ($reshook < 0) {
846
                    $context->setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
847
                }
848
849
                if (empty($reshook)) {
850
                    if ($permissiontoadd) {
851
                        $url_file = $context->getControllerUrl($context->controller, '', false);
852
                        $html .= '<a href="' . $url_file . '&id=' . $object->id . '&action=edit" role="button">' . $langs->trans('Modify') . '</a>';
853
                    }
854
                }
855
                $html .= '</div>' . "\n";
856
            }
857
        }
858
859
        return $html;
860
    }
861
}
862