BookCalAvailabilitiesListController::index()   F
last analyzed

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
    public function index(bool $executeActions = true): bool
53
    {
54
        global $conf;
55
        global $db;
56
        global $user;
57
        global $hookmanager;
58
        global $user;
59
        global $menumanager;
60
        global $langs;
61
62
// Load translation files required by the page
63
        $langs->loadLangs(["agenda", "other"]);
64
65
        $id = GETPOSTINT('id');
66
        $ref = GETPOST('ref', 'alpha');
67
68
        $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'add', 'create', 'edit', 'update', 'view', ...
69
        $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
70
        $show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ?
71
        $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
72
        $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
73
        $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
74
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)) . basename(__FILE__, '.php')); // To manage different context of search
75
        $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
76
        $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
77
        $mode = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)
78
79
// Load variable for pagination
80
        $limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit;
81
        $sortfield = GETPOST('sortfield', 'aZ09comma');
82
        $sortorder = GETPOST('sortorder', 'aZ09comma');
83
        $page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT("page");
84
        if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) {
85
            // If $page is not defined, or '' or -1 or if we click on clear filters
86
            $page = 0;
87
        }
88
        $offset = $limit * $page;
89
        $pageprev = $page - 1;
90
        $pagenext = $page + 1;
91
92
// Initialize technical objects
93
        $object = new Availabilities($db);
94
        $extrafields = new ExtraFields($db);
95
        $diroutputmassaction = $conf->bookcal->dir_output . '/temp/massgeneration/' . $user->id;
96
        $hookmanager->initHooks([$contextpage]); // Note that conf->hooks_modules contains array
97
98
// Fetch optionals attributes and labels
99
        $extrafields->fetch_name_optionals_label($object->table_element);
100
//$extrafields->fetch_name_optionals_label($object->table_element_line);
101
102
        $search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_');
103
104
// Default sort order (if not yet defined by previous GETPOST)
105
        if (!$sortfield) {
106
            reset($object->fields);                 // Reset is required to avoid key() to return null.
107
            $sortfield = "t." . key($object->fields); // Set here default search field. By default 1st field in definition.
108
        }
109
        if (!$sortorder) {
110
            $sortorder = "ASC";
111
        }
112
113
// Initialize array of search criteria
114
        $search_all = GETPOST('search_all', 'alphanohtml');
115
        $search = [];
116
        foreach ($object->fields as $key => $val) {
117
            if (GETPOST('search_' . $key, 'alpha') !== '') {
118
                $search[$key] = GETPOST('search_' . $key, 'alpha');
119
            }
120
            if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
121
                $search[$key . '_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_' . $key . '_dtstartmonth'), GETPOSTINT('search_' . $key . '_dtstartday'), GETPOSTINT('search_' . $key . '_dtstartyear'));
122
                $search[$key . '_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_' . $key . '_dtendmonth'), GETPOSTINT('search_' . $key . '_dtendday'), GETPOSTINT('search_' . $key . '_dtendyear'));
123
            }
124
        }
125
126
// List of fields to search into when doing a "search in all"
127
// $fieldstosearchall = array();
128
// foreach ($object->fields as $key => $val) {
129
//  if (!empty($val['searchall'])) {
130
//      $fieldstosearchall['t.'.$key] = $val['label'];
131
//  }
132
// }
133
// $parameters = array('fieldstosearchall'=>$fieldstosearchall);
134
// $reshook = $hookmanager->executeHooks('completeFieldsToSearchAll', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
135
// if ($reshook > 0) {
136
//  $fieldstosearchall = empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall'];
137
// } elseif ($reshook == 0) {
138
//  $fieldstosearchall = array_merge($fieldstosearchall, empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']);
139
// }
140
141
142
// $fieldstosearchall is supposedly defined further below, ensure that it is.
143
        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...
144
            $fieldstosearchall = [];
145
        }
146
        '
147
 @phan-var-force array<string,string> $fieldstosearchall
148
';
149
150
151
// Definition of array of fields for columns
152
        $arrayfields = Fields::getArrayFields($object->fields);
153
154
// Extra fields
155
        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
156
157
        $object->fields = dol_sort_array($object->fields, 'position');
158
//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right');
159
        $arrayfields = dol_sort_array($arrayfields, 'position');
160
161
// There is several ways to check permission.
162
// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
163
        $enablepermissioncheck = 0;
164
        if ($enablepermissioncheck) {
165
            $permissiontoread = $user->hasRight('bookcal', 'availabilities', 'read');
166
            $permissiontoadd = $user->hasRight('bookcal', 'availabilities', 'write');
167
            $permissiontodelete = $user->hasRight('bookcal', 'availabilities', 'delete');
168
        } else {
169
            $permissiontoread = 1;
170
            $permissiontoadd = 1;
171
            $permissiontodelete = 1;
172
        }
173
174
// Security check (enable the most restrictive one)
175
        if ($user->socid > 0) {
176
            accessforbidden();
177
        }
178
//if ($user->socid > 0) accessforbidden();
179
//$socid = 0; if ($user->socid > 0) $socid = $user->socid;
180
//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
181
//restrictedArea($user, $object->element, 0, $object->table_element, '', 'fk_soc', 'rowid', $isdraft);
182
        if (!isModEnabled('bookcal')) {
183
            accessforbidden('Module bookcal not enabled');
184
        }
185
        if (!$permissiontoread) {
186
            accessforbidden();
187
        }
188
189
190
        /*
191
         * Actions
192
         */
193
194
        if (GETPOST('cancel', 'alpha')) {
195
            $action = 'list';
196
            $massaction = '';
197
        }
198
        if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
199
            $massaction = '';
200
        }
201
202
        $parameters = [];
203
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
204
        if ($reshook < 0) {
205
            setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
206
        }
207
208
        if (empty($reshook)) {
209
            // Selection of new fields
210
            include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
211
212
            // Purge search criteria
213
            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
214
                foreach ($object->fields as $key => $val) {
215
                    $search[$key] = '';
216
                    if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
217
                        $search[$key . '_dtstart'] = '';
218
                        $search[$key . '_dtend'] = '';
219
                    }
220
                }
221
                $toselect = [];
222
                $search_array_options = [];
223
            }
224
            if (
225
                GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
226
                || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')
227
            ) {
228
                $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
229
            }
230
231
            // Mass actions
232
            $objectclass = 'Availabilities';
233
            $objectlabel = 'Availabilities';
234
            $uploaddir = $conf->bookcal->dir_output;
235
            include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
236
237
            // You can add more action here
238
            // if ($action == 'xxx' && $permissiontoxxx) ...
239
        }
240
241
242
        /*
243
         * View
244
         */
245
        require_once realpath(BASE_PATH . '/../Dolibarr/Modules/BookCal/Views/availabilities_list.php');
246
247
        $db->close();
248
249
        return true;
250
    }
251
}
252