Passed
Pull Request — dev (#8)
by Rafael
58:47
created

InfoBox::listBoxes()   F

Complexity

Conditions 33
Paths > 20000

Size

Total Lines 118
Code Lines 76

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 33
eloc 76
nc 204825
nop 6
dl 0
loc 118
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) 2003       Rodolphe Quiedeville        <[email protected]>
4
 * Copyright (C) 2004-2012	Laurent Destailleur		    <[email protected]>
5
 * Copyright (C) 2005-2012	Regis Houssin			    <[email protected]>
6
 * Copyright (C) 2019		Nicolas ZABOURI			    <[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\Core\Classes;
24
25
use DoliDB;
26
27
/**
28
 *  \file       htdocs/core/class/infobox.class.php
29
 *  \brief      File of class to manage widget boxes
30
 */
31
32
/**
33
 *  Class to manage boxes on pages. This is an utility class (all is static)
34
 */
35
class InfoBox
36
{
37
    /**
38
     * Name of positions (See below)
39
     *
40
     * @return  string[]        Array with list of zones
41
     */
42
    public static function getListOfPagesForBoxes()
43
    {
44
        global $conf;
45
46
        if (getDolGlobalInt('MAIN_FEATURES_LEVEL') < 2) {
47
            return array(
48
                0 => 'Home',
49
                1 => 'UsersHome',
50
                2 => 'MembersHome',
51
                3 => 'ThirdpartiesHome',
52
                11 => 'TicketsHome',
53
                27 => 'AccountancyHome'
54
            );
55
        } else {
56
            return array(
57
                0 => 'Home',
58
                1 => 'UsersHome',
59
                2 => 'MembersHome',
60
                3 => 'ThirdpartiesHome',
61
                4 => 'productindex',
62
                5 => 'productindex',
63
                6 => 'mrpindex',
64
                7 => 'commercialindex',
65
                8 => 'projectsindex',
66
                9 => 'invoiceindex',
67
                10 => 'hrmindex',
68
                11 => 'TicketsHome',
69
                12 => 'stockindex',
70
                13 => 'sendingindex',
71
                14 => 'receptionindex',
72
                15 => 'activityindex',
73
                16 => 'proposalindex',
74
                17 => 'ordersindex',
75
                18 => 'orderssuppliersindex',
76
                19 => 'contractindex',
77
                20 => 'interventionindex',
78
                21 => 'suppliersproposalsindex',
79
                22 => 'donationindex',
80
                23 => 'specialexpensesindex',
81
                24 => 'expensereportindex',
82
                25 => 'mailingindex',
83
                26 => 'opensurveyindex',
84
                27 => 'AccountancyHome'
85
            );
86
        }
87
    }
88
89
    /**
90
     *  Return array of boxes qualified for area and user
91
     *
92
     *  @param  DoliDB      $dbs            Database handler
93
     *  @param  string      $mode           'available' or 'activated'
94
     *  @param  int         $zone           Name or area (-1 for all, 0 for Homepage, 1 for Accountancy, 2 for xxx, ...)
95
     *  @param  User|null   $user           Object user to filter
96
     *  @param  array       $excludelist    Array of box id (box.box_id = boxes_def.rowid) to exclude
97
     *  @param  int         $includehidden  Include also hidden boxes
98
     *  @return array                       Array of boxes
99
     */
100
    public static function listBoxes($dbs, $mode, $zone, $user = null, $excludelist = array(), $includehidden = 1)
101
    {
102
        global $conf;
103
104
        $boxes = array();
105
106
        if ($mode == 'activated') { // activated
107
            $sql = "SELECT b.rowid, b.position, b.box_order, b.fk_user,";
108
            $sql .= " d.rowid as box_id, d.file, d.note, d.tms";
109
            $sql .= " FROM " . $dbs->prefix() . "boxes as b, " . $dbs->prefix() . "boxes_def as d";
110
            $sql .= " WHERE b.box_id = d.rowid";
111
            $sql .= " AND b.entity IN (0," . $conf->entity . ")";
112
            if ($zone >= 0) {
113
                $sql .= " AND b.position = " . ((int) $zone);
114
            }
115
            if (is_object($user)) {
116
                $sql .= " AND b.fk_user IN (0," . $user->id . ")";
117
            } else {
118
                $sql .= " AND b.fk_user = 0";
119
            }
120
            $sql .= " ORDER BY b.box_order";
121
        } else { // available
122
            $sql = "SELECT d.rowid as box_id, d.file, d.note, d.tms";
123
            $sql .= " FROM " . $dbs->prefix() . "boxes_def as d";
124
            $sql .= " WHERE d.entity IN (0, " . $conf->entity . ")";
125
        }
126
127
        dol_syslog(self::class . "::listBoxes get default box list for mode=" . $mode . " userid=" . (is_object($user) ? $user->id : ''), LOG_DEBUG);
128
        $resql = $dbs->query($sql);
129
        if ($resql) {
130
            $num = $dbs->num_rows($resql);
131
            $j = 0;
132
            while ($j < $num) {
133
                $obj = $dbs->fetch_object($resql);
134
135
                if (!in_array($obj->box_id, $excludelist)) {
136
                    $regs = array();
137
                    if (preg_match('/^([^@]+)@([^@]+)$/i', $obj->file, $regs)) {
138
                        $boxname = preg_replace('/\.php$/i', '', $regs[1]);
139
                        $module = $regs[2];
140
                        $relsourcefile = "/" . $module . "/core/boxes/" . $boxname . ".php";
141
                    } else {
142
                        $boxname = preg_replace('/\.php$/i', '', $obj->file);
143
                        $relsourcefile = "/core/boxes/" . $boxname . ".php";
144
                    }
145
146
                    //print $obj->box_id.'-'.$boxname.'-'.$relsourcefile.'<br>';
147
148
                    // TODO PERF Do not make "dol_include_once" here, nor "new" later. This means, we must store a 'depends' field to store modules list, then
149
                    // the "enabled" condition for modules forbidden for external users and the depends condition can be done.
150
                    // Goal is to avoid making a "new" done for each boxes returned by select.
151
                    dol_include_once($relsourcefile);
152
                    if (class_exists($boxname)) {
153
                        $box = new $boxname($dbs, $obj->note); // Constructor may set properties like box->enabled. obj->note is note into box def, not user params.
154
                        //$box=new stdClass();
155
156
                        // box properties
157
                        $box->rowid = (empty($obj->rowid) ? '' : $obj->rowid);
158
                        $box->id = (empty($obj->box_id) ? '' : $obj->box_id);
159
                        $box->position = ((isset($obj->position) && $obj->position == '') ? '' : (isset($obj->position) ? $obj->position : '')); // '0' must stay '0'
160
                        $box->box_order = (empty($obj->box_order) ? '' : $obj->box_order);
161
                        $box->fk_user = (empty($obj->fk_user) ? 0 : $obj->fk_user);
162
                        $box->sourcefile = $relsourcefile;
163
                        $box->class = $boxname;
164
165
                        if ($mode == 'activated' && !is_object($user)) {    // List of activated box was not yet personalized into database
166
                            if (is_numeric($box->box_order)) {
167
                                if ($box->box_order % 2 == 1) {
168
                                    $box->box_order = 'A' . $box->box_order;
169
                                } elseif ($box->box_order % 2 == 0) {
170
                                    $box->box_order = 'B' . $box->box_order;
171
                                }
172
                            }
173
                        }
174
                        // box_def properties
175
                        $box->box_id = (empty($obj->box_id) ? '' : $obj->box_id);
176
                        $box->note = (empty($obj->note) ? '' : $obj->note);
177
178
                        // Filter on box->enabled (used for example by box_comptes)
179
                        // Filter also on box->depends. Example: array("product|service") or array("contrat", "service")
180
                        $enabled = $box->enabled;
181
                        if (isset($box->depends) && count($box->depends) > 0) {
182
                            foreach ($box->depends as $moduleelem) {
183
                                $arrayelem = explode('|', $moduleelem);
184
                                $tmpenabled = 0; // $tmpenabled is used for the '|' test (OR)
185
                                foreach ($arrayelem as $module) {
186
                                    $tmpmodule = preg_replace('/@[^@]+/', '', $module);
187
                                    if (!empty($conf->$tmpmodule->enabled)) {
188
                                        $tmpenabled = 1;
189
                                    }
190
                                    //print $boxname.'-'.$module.'-module enabled='.(empty($conf->$tmpmodule->enabled)?0:1).'<br>';
191
                                }
192
                                if (empty($tmpenabled)) {   // We found at least one module required that is disabled
193
                                    $enabled = 0;
194
                                    break;
195
                                }
196
                            }
197
                        }
198
                        //print '=>'.$boxname.'-enabled='.$enabled.'<br>';
199
200
                        //print 'xx module='.$module.' enabled='.$enabled;
201
                        if ($enabled && ($includehidden || empty($box->hidden))) {
202
                            $boxes[] = $box;
203
                        } else {
204
                            unset($box);
205
                        }
206
                    } else {
207
                        dol_syslog("Failed to load box '" . $boxname . "' into file '" . $relsourcefile . "'", LOG_WARNING);
208
                    }
209
                }
210
                $j++;
211
            }
212
        } else {
213
            dol_syslog($dbs->lasterror(), LOG_ERR);
214
            return array('error' => $dbs->lasterror());
215
        }
216
217
        return $boxes;
218
    }
219
220
221
    /**
222
     *  Save order of boxes for area and user
223
     *
224
     *  @param  DoliDB  $dbs            Database handler
225
     *  @param  int     $zone           Name of area (0 for Homepage, ...)
226
     *  @param  string  $boxorder       List of boxes with correct order 'A:123,456,...-B:789,321...'
227
     *  @param  int     $userid         Id of user
228
     *  @return int                     Return integer <0 if KO, 0=Nothing done, > 0 if OK
229
     */
230
    public static function saveboxorder($dbs, $zone, $boxorder, $userid = 0)
231
    {
232
        global $conf;
233
234
        $error = 0;
235
236
        require_once constant('DOL_DOCUMENT_ROOT') . '/core/lib/functions2.lib.php';
237
238
        dol_syslog(get_class() . "::saveboxorder zone=" . $zone . " userid=" . $userid);
239
240
        if (!$userid || $userid == 0) {
241
            return 0;
242
        }
243
244
        $user = new User($dbs);
245
        $user->id = $userid;
246
247
        $dbs->begin();
248
249
        // Save parameters to say user has a dedicated setup
250
        $tab = array();
251
        $confuserzone = 'MAIN_BOXES_' . $zone;
252
        $tab[$confuserzone] = 1;
253
        if (dol_set_user_param($dbs, $conf, $user, $tab) < 0) {
254
            $error = $dbs->lasterror();
255
            $dbs->rollback();
256
            return -3;
257
        }
258
259
        // Delete all lines
260
        $sql = "DELETE FROM " . $dbs->prefix() . "boxes";
261
        $sql .= " WHERE entity = " . $conf->entity;
262
        $sql .= " AND fk_user = " . ((int) $userid);
263
        $sql .= " AND position = " . ((int) $zone);
264
265
        dol_syslog(get_class() . "::saveboxorder", LOG_DEBUG);
266
        $result = $dbs->query($sql);
267
        if ($result) {
268
            $colonnes = explode('-', $boxorder);
269
            foreach ($colonnes as $collist) {
270
                $part = explode(':', $collist);
271
                $colonne = $part[0];
272
                $list = $part[1];
273
                dol_syslog(get_class() . "::saveboxorder column=" . $colonne . ' list=' . $list);
274
275
                $i = 0;
276
                $listarray = explode(',', $list);
277
                foreach ($listarray as $id) {
278
                    if (is_numeric($id)) {
279
                        //dol_syslog("aaaaa".count($listarray));
280
                        $i++;
281
                        $ii = sprintf('%02d', $i);
282
283
                        $sql = "INSERT INTO " . $dbs->prefix() . "boxes";
284
                        $sql .= "(box_id, position, box_order, fk_user, entity)";
285
                        $sql .= " values (";
286
                        $sql .= " " . ((int) $id) . ",";
287
                        $sql .= " " . ((int) $zone) . ",";
288
                        $sql .= " '" . $dbs->escape($colonne . $ii) . "',";
289
                        $sql .= " " . ((int) $userid) . ",";
290
                        $sql .= " " . ((int) $conf->entity);
291
                        $sql .= ")";
292
293
                        $result = $dbs->query($sql);
294
                        if ($result < 0) {
295
                            $error++;
296
                            break;
297
                        }
298
                    }
299
                }
300
            }
301
        } else {
302
            $error++;
303
        }
304
305
        if ($error) {
306
            $dbs->rollback();
307
            return -2;
308
        } else {
309
            $dbs->commit();
310
            return 1;
311
        }
312
    }
313
}
314