Passed
Push — main ( 9a81fe...875825 )
by Rafael
41:55
created

BookCalAvailabilitiesListController::index()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 198
Code Lines 102

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 102
nc 819200
nop 1
dl 0
loc 198
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* Copyright (C) 2007-2017  Laurent Destailleur     <[email protected]>
4
 * Copyright (C) 2022       Alice Adminson          <[email protected]>
5
 * Copyright (C) 2024       Rafael San José         <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace DoliModules\BookCal\Controller;
22
23
global $conf;
24
global $db;
25
global $user;
26
global $hookmanager;
27
global $user;
28
global $menumanager;
29
global $langs;
30
global $mysoc;
31
32
use DoliCore\Base\DolibarrController;
33
use DoliCore\Lib\ExtraFields;
34
use DoliCore\Lib\Fields;
35
use DoliModules\BookCal\Model\Availabilities;
36
37
/**
38
 *   \file       htdocs/bookcal/availabilities_list.php
39
 *   \ingroup    bookcal
40
 *   \brief      List page for availabilities
41
 */
42
43
// Load Dolibarr environment
44
require BASE_PATH . '/main.inc.php';
45
require_once BASE_PATH . '/../Dolibarr/Lib/Date.php';
46
require_once BASE_PATH . '/../Dolibarr/Lib/Company.php';
47
48
// for other modules
49
//dol_include_once('/othermodule/class/otherobject.class.php');
50
class BookCalAvailabilitiesListController extends DolibarrController
51
{
52
53
    public function index(bool $executeActions = true): bool
54
    {
55
        global $conf;
56
        global $db;
57
        global $user;
58
        global $hookmanager;
59
        global $user;
60
        global $menumanager;
61
        global $langs;
62
63
// Load translation files required by the page
64
        $langs->loadLangs(["agenda", "other"]);
65
66
        $id = GETPOSTINT('id');
67
        $ref = GETPOST('ref', 'alpha');
68
69
        $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
70
        $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
71
        $show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ?
72
        $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
73
        $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
74
        $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
75
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)) . basename(__FILE__, '.php')); // To manage different context of search
76
        $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
77
        $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
78
        $mode = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)
79
80
// Load variable for pagination
81
        $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
82
        $sortfield = GETPOST('sortfield', 'aZ09comma');
83
        $sortorder = GETPOST('sortorder', 'aZ09comma');
84
        $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
85
        if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
86
            // If $page is not defined, or '' or -1 or if we click on clear filters
87
            $page = 0;
88
        }
89
        $offset = $limit * $page;
90
        $pageprev = $page - 1;
91
        $pagenext = $page + 1;
92
93
// Initialize technical objects
94
        $object = new Availabilities($db);
95
        $extrafields = new ExtraFields($db);
96
        $diroutputmassaction = $conf->bookcal->dir_output . '/temp/massgeneration/' . $user->id;
97
        $hookmanager->initHooks([$contextpage]); // Note that conf->hooks_modules contains array
98
99
// Fetch optionals attributes and labels
100
        $extrafields->fetch_name_optionals_label($object->table_element);
101
//$extrafields->fetch_name_optionals_label($object->table_element_line);
102
103
        $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
104
105
// Default sort order (if not yet defined by previous GETPOST)
106
        if (!$sortfield) {
107
            reset($object->fields);                 // Reset is required to avoid key() to return null.
108
            $sortfield = "t." . key($object->fields); // Set here default search field. By default 1st field in definition.
109
        }
110
        if (!$sortorder) {
111
            $sortorder = "ASC";
112
        }
113
114
// Initialize array of search criteria
115
        $search_all = GETPOST('search_all', 'alphanohtml');
116
        $search = [];
117
        foreach ($object->fields as $key => $val) {
118
            if (GETPOST('search_' . $key, 'alpha') !== '') {
119
                $search[$key] = GETPOST('search_' . $key, 'alpha');
120
            }
121
            if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
122
                $search[$key . '_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_' . $key . '_dtstartmonth'), GETPOSTINT('search_' . $key . '_dtstartday'), GETPOSTINT('search_' . $key . '_dtstartyear'));
123
                $search[$key . '_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_' . $key . '_dtendmonth'), GETPOSTINT('search_' . $key . '_dtendday'), GETPOSTINT('search_' . $key . '_dtendyear'));
124
            }
125
        }
126
127
// List of fields to search into when doing a "search in all"
128
// $fieldstosearchall = array();
129
// foreach ($object->fields as $key => $val) {
130
//  if (!empty($val['searchall'])) {
131
//      $fieldstosearchall['t.'.$key] = $val['label'];
132
//  }
133
// }
134
// $parameters = array('fieldstosearchall'=>$fieldstosearchall);
135
// $reshook = $hookmanager->executeHooks('completeFieldsToSearchAll', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
136
// if ($reshook > 0) {
137
//  $fieldstosearchall = empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall'];
138
// } elseif ($reshook == 0) {
139
//  $fieldstosearchall = array_merge($fieldstosearchall, empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']);
140
// }
141
142
143
// $fieldstosearchall is supposedly defined further below, ensure that it is.
144
        if (!isset($fieldstosearchall) || !is_array($fieldstosearchall)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $fieldstosearchall seems to never exist and therefore isset should always be false.
Loading history...
145
            $fieldstosearchall = [];
146
        }
147
        '
148
 @phan-var-force array<string,string> $fieldstosearchall
149
';
150
151
152
// Definition of array of fields for columns
153
        $arrayfields = Fields::getArrayFields($object->fields);
154
155
// Extra fields
156
        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
157
158
        $object->fields = dol_sort_array($object->fields, 'position');
159
//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right');
160
        $arrayfields = dol_sort_array($arrayfields, 'position');
161
162
// There is several ways to check permission.
163
// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
164
        $enablepermissioncheck = 0;
165
        if ($enablepermissioncheck) {
166
            $permissiontoread = $user->hasRight('bookcal', 'availabilities', 'read');
167
            $permissiontoadd = $user->hasRight('bookcal', 'availabilities', 'write');
168
            $permissiontodelete = $user->hasRight('bookcal', 'availabilities', 'delete');
169
        } else {
170
            $permissiontoread = 1;
171
            $permissiontoadd = 1;
172
            $permissiontodelete = 1;
173
        }
174
175
// Security check (enable the most restrictive one)
176
        if ($user->socid > 0) {
177
            accessforbidden();
178
        }
179
//if ($user->socid > 0) accessforbidden();
180
//$socid = 0; if ($user->socid > 0) $socid = $user->socid;
181
//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
182
//restrictedArea($user, $object->element, 0, $object->table_element, '', 'fk_soc', 'rowid', $isdraft);
183
        if (!isModEnabled('bookcal')) {
184
            accessforbidden('Module bookcal not enabled');
185
        }
186
        if (!$permissiontoread) {
187
            accessforbidden();
188
        }
189
190
191
        /*
192
         * Actions
193
         */
194
195
        if (GETPOST('cancel', 'alpha')) {
196
            $action = 'list';
197
            $massaction = '';
198
        }
199
        if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
200
            $massaction = '';
201
        }
202
203
        $parameters = [];
204
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
205
        if ($reshook < 0) {
206
            setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
207
        }
208
209
        if (empty($reshook)) {
210
            // Selection of new fields
211
            include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
212
213
            // Purge search criteria
214
            if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers
215
                foreach ($object->fields as $key => $val) {
216
                    $search[$key] = '';
217
                    if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
218
                        $search[$key . '_dtstart'] = '';
219
                        $search[$key . '_dtend'] = '';
220
                    }
221
                }
222
                $toselect = [];
223
                $search_array_options = [];
224
            }
225
            if (
226
                GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
227
                || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')
228
            ) {
229
                $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
230
            }
231
232
            // Mass actions
233
            $objectclass = 'Availabilities';
234
            $objectlabel = 'Availabilities';
235
            $uploaddir = $conf->bookcal->dir_output;
236
            include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
237
238
            // You can add more action here
239
            // if ($action == 'xxx' && $permissiontoxxx) ...
240
        }
241
242
243
        /*
244
         * View
245
         */
246
        require_once realpath(BASE_PATH . '/../Dolibarr/Modules/BookCal/Views/availabilities_list.php');
247
248
        $db->close();
249
250
        return true;
251
    }
252
}
253