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

BookCalCalendarListController::index()   F

Complexity

Conditions 37
Paths > 20000

Size

Total Lines 196
Code Lines 102

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 37
eloc 102
nc 819200
nop 1
dl 0
loc 196
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) 2023       Alice Adminson          <[email protected]>
5
 * Copyright (C) 2024       Frédéric France         <[email protected]>
6
 * Copyright (C) 2024       Rafael San José         <[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20
 */
21
22
namespace DoliModules\BookCal\Controller;
23
24
global $conf;
25
global $db;
26
global $user;
27
global $hookmanager;
28
global $user;
29
global $menumanager;
30
global $langs;
31
global $mysoc;
32
33
use DoliCore\Base\DolibarrController;
34
use DoliCore\Lib\ExtraFields;
35
use DoliCore\Lib\Fields;
36
use DoliModules\BookCal\Model\Calendar;
37
38
/**
39
 *      \file       htdocs/bookcal/calendar_list.php
40
 *      \ingroup    bookcal
41
 *      \brief      List page for calendar
42
 */
43
44
// Load Dolibarr environment
45
require BASE_PATH . '/main.inc.php';
46
require_once BASE_PATH . '/../Dolibarr/Lib/Date.php';
47
require_once BASE_PATH . '/../Dolibarr/Lib/Company.php';
48
49
class BookCalCalendarListController extends DolibarrController
50
{
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
        $action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'create'/'add', 'edit'/'update', 'view', ...
66
        $massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists)
67
        $show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ?
68
        $confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation
69
        $cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button
70
        $toselect = GETPOST('toselect', 'array'); // Array of ids of elements selected into a list
71
        $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)) . basename(__FILE__, '.php')); // To manage different context of search
72
        $backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page
73
        $optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print')
74
        $mode = GETPOST('mode', 'aZ'); // The output mode ('list', 'kanban', 'hierarchy', 'calendar', ...)
75
76
        $id = GETPOSTINT('id');
77
        $ref = GETPOST('ref', 'alpha');
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 Calendar($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 of activated contexes
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
// $fieldstosearchall is supposedly defined further below, ensure that it is.
142
        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...
143
            $fieldstosearchall = [];
144
        }
145
        '
146
 @phan-var-force array<string,string> $fieldstosearchall
147
';
148
149
// Definition of array of fields for columns
150
        $arrayfields = Fields::getArrayFields($object->fields);
151
152
// Extra fields
153
        include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_list_array_fields.tpl.php';
154
155
        $object->fields = dol_sort_array($object->fields, 'position');
156
//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right');
157
        $arrayfields = dol_sort_array($arrayfields, 'position');
158
159
// There is several ways to check permission.
160
// Set $enablepermissioncheck to 1 to enable a minimum low level of checks
161
        $enablepermissioncheck = 0;
162
        if ($enablepermissioncheck) {
163
            $permissiontoread = $user->hasRight('bookcal', 'calendar', 'read');
164
            $permissiontoadd = $user->hasRight('bookcal', 'calendar', 'write');
165
            $permissiontodelete = $user->hasRight('bookcal', 'calendar', 'delete');
166
        } else {
167
            $permissiontoread = 1;
168
            $permissiontoadd = 1;
169
            $permissiontodelete = 1;
170
        }
171
172
// Security check (enable the most restrictive one)
173
        if ($user->socid > 0) {
174
            accessforbidden();
175
        }
176
//if ($user->socid > 0) accessforbidden();
177
//$socid = 0; if ($user->socid > 0) $socid = $user->socid;
178
//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0);
179
//restrictedArea($user, $object->module, 0, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft);
180
        if (!isModEnabled("bookcal")) {
181
            accessforbidden('Module bookcal not enabled');
182
        }
183
        if (!$permissiontoread) {
184
            accessforbidden();
185
        }
186
187
188
        /*
189
         * Actions
190
         */
191
192
        if (GETPOST('cancel', 'alpha')) {
193
            $action = 'list';
194
            $massaction = '';
195
        }
196
        if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') {
197
            $massaction = '';
198
        }
199
200
        $parameters = [];
201
        $reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
202
        if ($reshook < 0) {
203
            setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
204
        }
205
206
        if (empty($reshook)) {
207
            // Selection of new fields
208
            include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
209
210
            // Purge search criteria
211
            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
212
                foreach ($object->fields as $key => $val) {
213
                    $search[$key] = '';
214
                    if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) {
215
                        $search[$key . '_dtstart'] = '';
216
                        $search[$key . '_dtend'] = '';
217
                    }
218
                }
219
                $toselect = [];
220
                $search_array_options = [];
221
            }
222
            if (
223
                GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')
224
                || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')
225
            ) {
226
                $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation
227
            }
228
229
            // Mass actions
230
            $objectclass = 'Calendar';
231
            $objectlabel = 'Calendar';
232
            $uploaddir = $conf->bookcal->dir_output;
233
            include DOL_DOCUMENT_ROOT . '/core/actions_massactions.inc.php';
234
235
            // You can add more action here
236
            // if ($action == 'xxx' && $permissiontoxxx) ...
237
        }
238
239
240
        /*
241
         * View
242
         */
243
        require_once realpath(BASE_PATH . '/../Dolibarr/Modules/BookCal/Views/calendar_list.php');
244
245
        $db->close();
246
247
        return true;
248
    }
249
}
250