Passed
Push — EXTRACT_CLASSES ( ff35ec...a2ff75 )
by Rafael
48:13
created

Opensurveysondage::fetch()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 58
Code Lines 48

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 48
nc 4
nop 2
dl 0
loc 58
rs 8.5123
c 0
b 0
f 0

How to fix   Long Method   

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) 2013-2014  Laurent Destailleur         <[email protected]>
4
 * Copyright (C) 2014       Marcos García	            <[email protected]>
5
 * Copyright (C) 2020-2024  Frédéric France		        <[email protected]>
6
 * Copyright (C) 2024		MDW							<[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\OpenSurvey\Classes;
24
25
use Dolibarr\Core\Base\CommonObject;
26
27
/**
28
 *  \file       htdocs/opensurvey/class/opensurveysondage.class.php
29
 *  \ingroup    opensurvey
30
 *  \brief      This file is an example for a CRUD class file (Create/Read/Update/Delete)
31
 *              Initially built by build_class_from_table on 2013-03-10 00:32
32
 */
33
34
/**
35
 *  Put here description of your class
36
 */
37
class Opensurveysondage extends CommonObject
38
{
39
    /**
40
     * @var string ID to identify managed object
41
     */
42
    public $element = 'opensurvey_sondage';
43
44
    /**
45
     * @var string Name of table without prefix where object is stored
46
     */
47
    public $table_element = 'opensurvey_sondage';
48
49
    /**
50
     * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
51
     */
52
    public $picto = 'poll';
53
54
    /**
55
     * @var string Description
56
     */
57
    public $description;
58
59
    /**
60
     * @var string Date last modification (same as tms)
61
     */
62
    public $date_m;
63
64
65
    /**
66
     *  'type' field format:
67
     *      'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
68
     *      'select' (list of values are in 'options'),
69
     *      'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]',
70
     *      'chkbxlst:...',
71
     *      'varchar(x)',
72
     *      'text', 'text:none', 'html',
73
     *      'double(24,8)', 'real', 'price',
74
     *      'date', 'datetime', 'timestamp', 'duration',
75
     *      'boolean', 'checkbox', 'radio', 'array',
76
     *      'mail', 'phone', 'url', 'password', 'ip'
77
     *      Note: Filter must be a Dolibarr Universal Filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)"
78
     *  'label' the translation key.
79
     *  'picto' is code of a picto to show before value in forms
80
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalInt("MY_SETUP_PARAM")' or 'isModEnabled("multicurrency")' ...)
81
     *  'position' is the sort order of field.
82
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
83
     *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
84
     *  'noteditable' says if field is not editable (1 or 0)
85
     *  'alwayseditable' says if field can be modified also when status is not draft ('1' or '0')
86
     *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
87
     *  'index' if we want an index in database.
88
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
89
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
90
     *  'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
91
     *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
92
     *  'help' and 'helplist' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
93
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
94
     *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
95
     *  'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
96
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
97
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
98
     *  'validate' is 1 if need to validate with $this->validateField()
99
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
100
     *
101
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
102
     */
103
104
    // BEGIN MODULEBUILDER PROPERTIES
105
    /**
106
     * @var array<string,array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string}>  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string,array{type:...ring>,comment?:string}> at position 16 could not be parsed: Expected '}' at position 16, but found 'int'.
Loading history...
107
     */
108
    public $fields = array(
109
        'id_sondage' => array('type' => 'varchar(16)', 'label' => 'Idsondage', 'enabled' => '1', 'position' => 10, 'notnull' => 1, 'visible' => -1,),
110
        'commentaires' => array('type' => 'mediumtext', 'label' => 'Comments', 'enabled' => '1', 'position' => 15, 'notnull' => 0, 'visible' => -1,),
111
        'mail_admin' => array('type' => 'varchar(128)', 'label' => 'Mailadmin', 'enabled' => '1', 'position' => 20, 'notnull' => 0, 'visible' => -1,),
112
        'nom_admin' => array('type' => 'varchar(64)', 'label' => 'Nomadmin', 'enabled' => '1', 'position' => 25, 'notnull' => 0, 'visible' => -1,),
113
        'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => '1', 'position' => 30, 'notnull' => 1, 'visible' => -2, 'css' => 'maxwidth500 widthcentpercentminusxx', 'csslist' => 'tdoverflowmax150',),
114
        'titre' => array('type' => 'mediumtext', 'label' => 'Title', 'enabled' => '1', 'position' => 35, 'notnull' => 1, 'visible' => -1,),
115
        'date_fin' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => '1', 'position' => 40, 'notnull' => 1, 'visible' => -1,),
116
        'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => '1', 'position' => 500, 'notnull' => 0, 'visible' => -1,),
117
        'format' => array('type' => 'varchar(2)', 'label' => 'Format', 'enabled' => '1', 'position' => 50, 'notnull' => 1, 'visible' => -1,),
118
        'mailsonde' => array('type' => 'integer', 'label' => 'Mailsonde', 'enabled' => '1', 'position' => 55, 'notnull' => 1, 'visible' => -1,),
119
        'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => '1', 'position' => 60, 'notnull' => 1, 'visible' => -1,),
120
        'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => '1', 'position' => 65, 'notnull' => 1, 'visible' => -2, 'default' => '1', 'index' => 1,),
121
        'allow_comments' => array('type' => 'integer', 'label' => 'Allowcomments', 'enabled' => '1', 'position' => 70, 'notnull' => 1, 'visible' => -1,),
122
        'allow_spy' => array('type' => 'integer', 'label' => 'Allowspy', 'enabled' => '1', 'position' => 75, 'notnull' => 1, 'visible' => -1,),
123
        'sujet' => array('type' => 'mediumtext', 'label' => 'Sujet', 'enabled' => '1', 'position' => 80, 'notnull' => 0, 'visible' => -1,),
124
        'id_sondage_admin' => array('type' => 'char(24)', 'label' => 'Idsondageadmin', 'enabled' => '1', 'position' => 85, 'notnull' => 0, 'visible' => -1,),
125
    );
126
127
    /**
128
     * @var string Id sondage not an int
129
     */
130
    public $id_sondage;
131
    /**
132
     * @var string      Description
133
     * @deprecated      Use $description instead
134
     */
135
    public $commentaires;
136
    public $mail_admin;
137
    public $nom_admin;
138
    public $fk_user_creat;
139
    public $title;
140
    public $date_fin = '';
141
    public $status;
142
    public $format;
143
    public $mailsonde;
144
    public $entity;
145
    /**
146
     * @var int     Allow comments on this poll
147
     */
148
    public $allow_comments;
149
150
    /**
151
     * @var int     Allow users see others vote
152
     */
153
    public $allow_spy;
154
155
    /**
156
     * @var string Subject
157
     */
158
    public $sujet;
159
160
    /**
161
     * @var string Id sondage admin not an int
162
     */
163
    public $id_sondage_admin;
164
    // END MODULEBUILDER PROPERTIES
165
166
    /**
167
     * Draft status (not used)
168
     */
169
    const STATUS_DRAFT = 0;
170
    /**
171
     * Validated/Opened status
172
     */
173
    const STATUS_VALIDATED = 1;
174
    /**
175
     * Closed
176
     */
177
    const STATUS_CLOSED = 2;
178
179
180
    /**
181
     *  Constructor
182
     *
183
     *  @param  DoliDB      $db      Database handler
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\OpenSurvey\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
184
     */
185
    public function __construct($db)
186
    {
187
        $this->db = $db;
188
    }
189
190
191
    /**
192
     *  Create object into database
193
     *
194
     *  @param  User    $user        User that creates
195
     *  @param  int     $notrigger   0=launch triggers after, 1=disable triggers
196
     *  @return int                  Return integer <0 if KO, Id of created object if OK
197
     */
198
    public function create(User $user, $notrigger = 0)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\OpenSurvey\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
199
    {
200
        global $conf;
201
202
        $error = 0;
203
204
        // Clean parameters
205
        $this->cleanParameters();
206
207
        // Check parameters
208
        if (!$this->date_fin > 0) {
209
            $this->error = 'BadValueForEndDate';
210
            dol_syslog(get_class($this) . "::create " . $this->error, LOG_ERR);
211
            return -1;
212
        }
213
214
        // Insert request
215
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "opensurvey_sondage(";
216
        $sql .= "id_sondage,";
217
        $sql .= "commentaires,";
218
        $sql .= "fk_user_creat,";
219
        $sql .= "titre,";
220
        $sql .= "date_fin,";
221
        $sql .= "status,";
222
        $sql .= "format,";
223
        $sql .= "mailsonde,";
224
        $sql .= "allow_comments,";
225
        $sql .= "allow_spy,";
226
        $sql .= "sujet,";
227
        $sql .= "entity";
228
        $sql .= ") VALUES (";
229
        $sql .= "'" . $this->db->escape($this->id_sondage) . "',";
230
        $sql .= " " . (empty($this->description) ? 'NULL' : "'" . $this->db->escape($this->description) . "'") . ",";
231
        $sql .= " " . (int) $user->id . ",";
232
        $sql .= " '" . $this->db->escape($this->title) . "',";
233
        $sql .= " '" . $this->db->idate($this->date_fin) . "',";
234
        $sql .= " " . (int) $this->status . ",";
235
        $sql .= " '" . $this->db->escape($this->format) . "',";
236
        $sql .= " " . ((int) $this->mailsonde) . ",";
237
        $sql .= " " . ((int) $this->allow_comments) . ",";
238
        $sql .= " " . ((int) $this->allow_spy) . ",";
239
        $sql .= " '" . $this->db->escape($this->sujet) . "',";
240
        $sql .= " " . ((int) $conf->entity);
241
        $sql .= ")";
242
243
        $this->db->begin();
244
245
        dol_syslog(get_class($this) . "::create", LOG_DEBUG);
246
        $resql = $this->db->query($sql);
247
        if (!$resql) {
248
            $error++;
249
            $this->errors[] = "Error " . $this->db->lasterror();
250
        }
251
252
        if (!$error && !$notrigger) {
253
            // Call trigger
254
            $result = $this->call_trigger('OPENSURVEY_CREATE', $user);
255
            if ($result < 0) {
256
                $error++;
257
            }
258
            // End call triggers
259
        }
260
261
        // Commit or rollback
262
        if ($error) {
263
            foreach ($this->errors as $errmsg) {
264
                dol_syslog(get_class($this) . "::create " . $errmsg, LOG_ERR);
265
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
266
            }
267
            $this->db->rollback();
268
            return -1 * $error;
269
        } else {
270
            $this->db->commit();
271
            return $this->id;
272
        }
273
    }
274
275
276
    /**
277
     *  Load object in memory from the database
278
     *
279
     *  @param  int     $id                 Id object
280
     *  @param  string  $numsurvey          Ref of survey (admin or not)
281
     *  @return int                         Return integer <0 if KO, >0 if OK
282
     */
283
    public function fetch($id, $numsurvey = '')
284
    {
285
        $sql = "SELECT";
286
        $sql .= " t.id_sondage,";
287
        $sql .= " t.titre as title,";
288
        $sql .= " t.commentaires as description,";
289
        $sql .= " t.mail_admin,";
290
        $sql .= " t.nom_admin,";
291
        $sql .= " t.fk_user_creat,";
292
        $sql .= " t.date_fin,";
293
        $sql .= " t.status,";
294
        $sql .= " t.format,";
295
        $sql .= " t.mailsonde,";
296
        $sql .= " t.allow_comments,";
297
        $sql .= " t.allow_spy,";
298
        $sql .= " t.sujet,";
299
        $sql .= " t.tms";
300
        $sql .= " FROM " . MAIN_DB_PREFIX . "opensurvey_sondage as t";
301
        $sql .= " WHERE t.id_sondage = '" . $this->db->escape($id ? $id : $numsurvey) . "'";
302
303
        dol_syslog(get_class($this) . "::fetch", LOG_DEBUG);
304
        $resql = $this->db->query($sql);
305
        if ($resql) {
306
            if ($this->db->num_rows($resql)) {
307
                $obj = $this->db->fetch_object($resql);
308
309
                $this->id_sondage = $obj->id_sondage;
310
                $this->ref = $this->id_sondage; //For compatibility
311
312
                $this->description = $obj->description;
313
                $this->mail_admin = $obj->mail_admin;
314
                $this->nom_admin = $obj->nom_admin;
315
                $this->title = $obj->title;
316
                $this->date_fin = $this->db->jdate($obj->date_fin);
317
                $this->status = $obj->status;
318
                $this->format = $obj->format;
319
                $this->mailsonde = $obj->mailsonde;
320
                $this->allow_comments = $obj->allow_comments;
321
                $this->allow_spy = $obj->allow_spy;
322
                $this->sujet = $obj->sujet;
323
                $this->fk_user_creat = $obj->fk_user_creat;
324
325
                $this->date_m = $this->db->jdate(!empty($obj->tms) ? $obj->tms : "");
326
                $ret = 1;
327
            } else {
328
                $sondage = ($id ? 'id=' . $id : 'sondageid=' . $numsurvey);
329
                $this->error = 'Fetch no poll found for ' . $sondage;
330
                dol_syslog($this->error, LOG_ERR);
331
                $ret = 0;
332
            }
333
334
            $this->db->free($resql);
335
        } else {
336
            $this->error = "Error " . $this->db->lasterror();
337
            $ret = -1;
338
        }
339
340
        return $ret;
341
    }
342
343
344
    /**
345
     *  Update object into database
346
     *
347
     *  @param  User    $user        User that modifies
348
     *  @param  int     $notrigger   0=launch triggers after, 1=disable triggers
349
     *  @return int                  Return integer <0 if KO, >0 if OK
350
     */
351
    public function update(User $user, $notrigger = 0)
352
    {
353
        $error = 0;
354
355
        // Clean parameters
356
        $this->cleanParameters();
357
358
        // Check parameters
359
        // Put here code to add a control on parameters values
360
361
        // Update request
362
        $sql = "UPDATE " . MAIN_DB_PREFIX . "opensurvey_sondage SET";
363
        $sql .= " id_sondage=" . (isset($this->id_sondage) ? "'" . $this->db->escape($this->id_sondage) . "'" : "null") . ",";
364
        $sql .= " commentaires=" . (isset($this->description) ? "'" . $this->db->escape($this->description) . "'" : "null") . ",";
365
        $sql .= " mail_admin=" . (isset($this->mail_admin) ? "'" . $this->db->escape($this->mail_admin) . "'" : "null") . ",";
366
        $sql .= " nom_admin=" . (isset($this->nom_admin) ? "'" . $this->db->escape($this->nom_admin) . "'" : "null") . ",";
367
        $sql .= " titre=" . (isset($this->title) ? "'" . $this->db->escape($this->title) . "'" : "null") . ",";
368
        $sql .= " date_fin=" . (dol_strlen($this->date_fin) != 0 ? "'" . $this->db->idate($this->date_fin) . "'" : 'null') . ",";
369
        $sql .= " status=" . (isset($this->status) ? "'" . $this->db->escape($this->status) . "'" : "null") . ",";
370
        $sql .= " format=" . (isset($this->format) ? "'" . $this->db->escape($this->format) . "'" : "null") . ",";
371
        $sql .= " mailsonde=" . (isset($this->mailsonde) ? ((int) $this->mailsonde) : "null") . ",";
372
        $sql .= " allow_comments=" . ((int) $this->allow_comments) . ",";
373
        $sql .= " allow_spy=" . ((int) $this->allow_spy);
374
        $sql .= " WHERE id_sondage='" . $this->db->escape($this->id_sondage) . "'";
375
376
        $this->db->begin();
377
378
        dol_syslog(get_class($this) . "::update", LOG_DEBUG);
379
        $resql = $this->db->query($sql);
380
        if (!$resql) {
381
            $error++;
382
            $this->errors[] = "Error " . $this->db->lasterror();
383
        }
384
385
        if (!$error && !$notrigger) {
386
            // Call trigger
387
            $result = $this->call_trigger('OPENSURVEY_MODIFY', $user);
388
            if ($result < 0) {
389
                $error++;
390
            }
391
            // End call triggers
392
        }
393
394
        // Commit or rollback
395
        if ($error) {
396
            foreach ($this->errors as $errmsg) {
397
                dol_syslog(get_class($this) . "::update " . $errmsg, LOG_ERR);
398
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
399
            }
400
            $this->db->rollback();
401
            return -1 * $error;
402
        } else {
403
            $this->db->commit();
404
            return 1;
405
        }
406
    }
407
408
    /**
409
     *  Delete object in database
410
     *
411
     *  @param  User    $user               User that deletes
412
     *  @param  int     $notrigger          0=launch triggers after, 1=disable triggers
413
     *  @param  string  $numsondage         Num sondage admin to delete
414
     *  @return int                         Return integer <0 if KO, >0 if OK
415
     */
416
    public function delete(User $user, $notrigger = 0, $numsondage = '')
417
    {
418
        global $conf, $langs;
419
        $error = 0;
420
421
        if (empty($numsondage)) {
422
            $numsondage = $this->id_sondage;
423
        }
424
425
        $this->db->begin();
426
427
        if (!$error && !$notrigger) {
428
            // Call trigger
429
            $result = $this->call_trigger('OPENSURVEY_DELETE', $user);
430
            if ($result < 0) {
431
                $error++;
432
            }
433
            // End call triggers
434
        }
435
436
        if (!$error) {
437
            $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . "opensurvey_comments WHERE id_sondage = '" . $this->db->escape($numsondage) . "'";
438
            dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
439
            $resql = $this->db->query($sql);
440
            $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . "opensurvey_user_studs WHERE id_sondage = '" . $this->db->escape($numsondage) . "'";
441
            dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
442
            $resql = $this->db->query($sql);
443
444
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "opensurvey_sondage";
445
            $sql .= " WHERE id_sondage = '" . $this->db->escape($numsondage) . "'";
446
447
            dol_syslog(get_class($this) . "::delete", LOG_DEBUG);
448
            $resql = $this->db->query($sql);
449
            if (!$resql) {
450
                $error++;
451
                $this->errors[] = "Error " . $this->db->lasterror();
452
            }
453
        }
454
455
        // Commit or rollback
456
        if ($error) {
457
            foreach ($this->errors as $errmsg) {
458
                dol_syslog(get_class($this) . "::delete " . $errmsg, LOG_ERR);
459
                $this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
460
            }
461
            $this->db->rollback();
462
            return -1 * $error;
463
        } else {
464
            $this->db->commit();
465
            return 1;
466
        }
467
    }
468
469
    /**
470
     * getTooltipContentArray
471
     *
472
     * @param array $params ex option, infologin
473
     * @since v18
474
     * @return array
475
     */
476
    public function getTooltipContentArray($params)
477
    {
478
        global $conf, $langs;
479
480
        $langs->load('opensurvey');
481
482
        $datas = [];
483
        $datas['picto'] = img_picto('', $this->picto) . ' <u>' . $langs->trans("ShowSurvey") . '</u>';
484
        if (isset($this->status)) {
485
            $datas['picto'] .= ' ' . $this->getLibStatut(5);
486
        }
487
        $datas['ref'] = '<br><b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;
488
        if (!empty($this->date_fin)) {
489
            $datas['expire_date'] = '<br><b>' . $langs->trans('ExpireDate') . ':</b> ' . dol_print_date($this->date_fin, 'day');
490
            if ($this->date_fin && $this->date_fin < dol_now() && $this->status == Opensurveysondage::STATUS_VALIDATED) {
491
                $datas['expire_date'] .= img_warning($langs->trans("Expired"));
492
            }
493
        }
494
        $datas['title'] = '<br><b>' . $langs->trans('Title') . ':</b> ' . $this->title;
495
        if (!empty($this->description)) {
496
            $datas['description'] = '<br><b>' . $langs->trans('Description') . ':</b> ' . $this->description;
497
        }
498
499
        return $datas;
500
    }
501
502
    /**
503
     *  Return a link to the object card (with optionally the picto)
504
     *
505
     *  @param  int     $withpicto                  Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
506
     *  @param  int     $notooltip                  1=Disable tooltip
507
     *  @param  string  $morecss                    Add more css on link
508
     *  @param  int     $save_lastsearch_value      -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
509
     *  @return string                              String with URL
510
     */
511
    public function getNomUrl($withpicto = 0, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
512
    {
513
        global $conf, $hookmanager, $langs;
514
515
        if (!empty($conf->dol_no_mouse_hover)) {
516
            $notooltip = 1; // Force disable tooltips
517
        }
518
519
        $result = '';
520
        $params = [
521
            'id' => $this->id,
522
            'objecttype' => $this->element,
523
        ];
524
        $classfortooltip = 'classfortooltip';
525
        $dataparams = '';
526
        if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
527
            $classfortooltip = 'classforajaxtooltip';
528
            $dataparams = ' data-params="' . dol_escape_htmltag(json_encode($params)) . '"';
529
            $label = '';
530
        } else {
531
            $label = implode($this->getTooltipContentArray($params));
532
        }
533
534
        $url = constant('BASE_URL') . '/opensurvey/card.php?id=' . $this->id;
535
536
        // Add param to save lastsearch_values or not
537
        $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
538
        if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
539
            $add_save_lastsearch_values = 1;
540
        }
541
        if ($add_save_lastsearch_values) {
542
            $url .= '&save_lastsearch_values=1';
543
        }
544
545
        $linkclose = '';
546
        if (empty($notooltip)) {
547
            if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
548
                $label = $langs->trans("ShowMyObject");
549
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
550
            }
551
            $linkclose .= ($label ? ' title="' . dol_escape_htmltag($label, 1) . '"' : ' title="tocomplete"');
552
            $linkclose .= $dataparams . ' class="' . $classfortooltip . ($morecss ? ' ' . $morecss : '') . '"';
553
        } else {
554
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
555
        }
556
557
        $linkstart = '<a href="' . $url . '"';
558
        $linkstart .= $linkclose . '>';
559
        $linkend = '</a>';
560
561
        $result .= $linkstart;
562
        if ($withpicto) {
563
            $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
564
        }
565
        if ($withpicto != 2) {
566
            $result .= $this->ref;
567
        }
568
        $result .= $linkend;
569
570
        global $action;
571
        $hookmanager->initHooks(array($this->element . 'dao'));
572
        $parameters = array('id' => $this->id, 'getnomurl' => &$result);
573
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
574
        if ($reshook > 0) {
575
            $result = $hookmanager->resPrint;
576
        } else {
577
            $result .= $hookmanager->resPrint;
578
        }
579
580
        return $result;
581
    }
582
583
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
584
    /**
585
     * Return array of lines
586
     *
587
     * @return  int     Return integer <0 if KO, >0 if OK
588
     */
589
    public function fetch_lines()
590
    {
591
		// phpcs:enable
592
        $this->lines = array();
593
594
        $sql = "SELECT id_users, nom as name, reponses";
595
        $sql .= " FROM " . MAIN_DB_PREFIX . "opensurvey_user_studs";
596
        $sql .= " WHERE id_sondage = '" . $this->db->escape($this->id_sondage) . "'";
597
598
        $resql = $this->db->query($sql);
599
600
        if ($resql) {
601
            $num = $this->db->num_rows($resql);
602
            $i = 0;
603
            while ($i < $num) {
604
                $obj = $this->db->fetch_object($resql);
605
                $tmp = array('id_users' => $obj->id_users, 'nom' => $obj->name, 'reponses' => $obj->reponses);
606
607
                $this->lines[] = $tmp;
608
                $i++;
609
            }
610
        } else {
611
            dol_print_error($this->db);
612
        }
613
614
        return count($this->lines);
615
    }
616
617
    /**
618
     *  Initialise object with example values
619
     *  Id must be 0 if object instance is a specimen
620
     *
621
     *  @return int
622
     */
623
    public function initAsSpecimen()
624
    {
625
        $this->id = 0;
626
627
        $this->id_sondage = 'a12d5g';
628
        $this->description = 'Description of the specimen survey';
629
        $this->mail_admin = '[email protected]';
630
        $this->nom_admin = 'surveyadmin';
631
        $this->title = 'This is a specimen survey';
632
        $this->date_fin = dol_now() + 3600 * 24 * 10;
633
        $this->status = 1;
634
        $this->format = 'classic';
635
        $this->mailsonde = 0;
636
637
        return 1;
638
    }
639
640
    /**
641
     * Returns all comments for the current opensurvey poll
642
     *
643
     * @return Object[]
644
     */
645
    public function getComments()
646
    {
647
        $comments = array();
648
649
        $sql = 'SELECT id_comment, usercomment, comment';
650
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'opensurvey_comments';
651
        $sql .= " WHERE id_sondage='" . $this->db->escape($this->id_sondage) . "'";
652
        $sql .= " ORDER BY id_comment";
653
        $resql = $this->db->query($sql);
654
655
        if ($resql) {
656
            $num_rows = $this->db->num_rows($resql);
657
658
            if ($num_rows > 0) {
659
                while ($obj = $this->db->fetch_object($resql)) {
660
                    $comments[] = $obj;
661
                }
662
            }
663
        }
664
665
        return $comments;
666
    }
667
668
    /**
669
     * Adds a comment to the poll
670
     *
671
     * @param string $comment Comment content
672
     * @param string $comment_user Comment author
673
     * @param string $user_ip Comment author IP
674
     * @return boolean False in case of the query fails, true if it was successful
675
     */
676
    public function addComment($comment, $comment_user, $user_ip = '')
677
    {
678
        $now = dol_now();
679
        $sql = "INSERT INTO " . MAIN_DB_PREFIX . "opensurvey_comments (id_sondage, comment, usercomment, date_creation, ip)";
680
        $sql .= " VALUES ('" . $this->db->escape($this->id_sondage) . "','" . $this->db->escape($comment) . "','" . $this->db->escape($comment_user) . "','" . $this->db->idate($now) . "'" . ($user_ip ? ",'" . $this->db->escape($user_ip) . "'" : '') . ")";
681
        $resql = $this->db->query($sql);
682
683
        if (!$resql) {
684
            return false;
685
        }
686
687
        return true;
688
    }
689
690
    /**
691
     * Deletes a comment of the poll
692
     *
693
     * @param int $id_comment Id of the comment
694
     * @return boolean False in case of the query fails, true if it was successful
695
     */
696
    public function deleteComment($id_comment)
697
    {
698
        $sql = 'DELETE FROM ' . MAIN_DB_PREFIX . 'opensurvey_comments WHERE id_comment = ' . ((int) $id_comment) . ' AND id_sondage = "' . $this->db->escape($this->id_sondage) . '"';
699
        $resql = $this->db->query($sql);
700
701
        if (!$resql) {
702
            return false;
703
        }
704
705
        return true;
706
    }
707
708
    /**
709
     * Cleans all the class variables before doing an update or an insert
710
     *
711
     * @return void
712
     */
713
    private function cleanParameters()
714
    {
715
        $this->id_sondage = trim($this->id_sondage);
716
        $this->description = trim($this->description);
717
        $this->mail_admin = trim($this->mail_admin);
718
        $this->nom_admin = trim($this->nom_admin);
719
        $this->title = trim($this->title);
720
        $this->status = (int) $this->status;
721
        $this->format = trim($this->format);
722
        $this->mailsonde = ($this->mailsonde ? 1 : 0);
723
        $this->allow_comments = ($this->allow_comments ? 1 : 0);
724
        $this->allow_spy = ($this->allow_spy ? 1 : 0);
725
        $this->sujet = trim($this->sujet);
726
    }
727
728
729
    /**
730
     *  Return status label of Order
731
     *
732
     *  @param  int     $mode           0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
733
     *  @return string                  Label if status
734
     */
735
    public function getLibStatut($mode)
736
    {
737
        return $this->LibStatut($this->status, $mode);
738
    }
739
740
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
741
    /**
742
     *  Return label of status
743
     *
744
     *  @param  int     $status         Id status
745
     *  @param  int     $mode           0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
746
     *  @return string                  Label of status
747
     */
748
    public function LibStatut($status, $mode)
749
    {
750
		// phpcs:enable
751
        global $langs, $conf;
752
753
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
754
            global $langs;
755
            //$langs->load("mymodule");
756
            $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
757
            $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Opened');
758
            $this->labelStatus[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('Closed');
759
            $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
760
            $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Opened');
761
            $this->labelStatusShort[self::STATUS_CLOSED] = $langs->transnoentitiesnoconv('Closed');
762
        }
763
764
        $statusType = 'status' . $status;
765
        if ($status == self::STATUS_VALIDATED) {
766
            if (0) {
767
                $statusType = 'status1';
768
            } else {
769
                $statusType = 'status4';
770
            }
771
        }
772
        if ($status == self::STATUS_CLOSED) {
773
            $statusType = 'status6';
774
        }
775
776
        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
777
    }
778
779
780
    /**
781
     *  Return number of votes done for this survey.
782
     *
783
     *  @return     int         Number of votes
784
     */
785
    public function countVotes()
786
    {
787
        $result = 0;
788
789
        $sql = " SELECT COUNT(id_users) as nb FROM " . MAIN_DB_PREFIX . "opensurvey_user_studs";
790
        $sql .= " WHERE id_sondage = '" . $this->db->escape($this->ref) . "'";
791
792
        $resql = $this->db->query($sql);
793
        if ($resql) {
794
            $obj = $this->db->fetch_object($resql);
795
            if ($obj) {
796
                $result = $obj->nb;
797
            }
798
        } else {
799
            $this->error = $this->db->lasterror();
800
            $this->errors[] = $this->error;
801
        }
802
803
        return $result;
804
    }
805
806
    /**
807
     * Load list of objects in memory from the database.
808
     *
809
     * @param  string       $sortorder      Sort Order
810
     * @param  string       $sortfield      Sort field
811
     * @param  int          $limit          limit
812
     * @param  int          $offset         Offset
813
     * @param  string       $filter         Filter as an Universal Search string.
814
     *                                      Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
815
     * @param  string       $filtermode     No more used
816
     * @return array|int                    int <0 if KO, array of pages if OK
817
     */
818
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
819
    {
820
        dol_syslog(__METHOD__, LOG_DEBUG);
821
822
        $records = array();
823
824
        $sql = 'SELECT ';
825
        $sql .= $this->getFieldList();
826
        $sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t';
827
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
828
            $sql .= ' WHERE t.entity IN (' . getEntity($this->element) . ')';
829
        } else {
830
            $sql .= ' WHERE 1 = 1';
831
        }
832
833
        // Manage filter
834
        $errormessage = '';
835
        $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
836
        if ($errormessage) {
837
            $this->errors[] = $errormessage;
838
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
839
            return -1;
840
        }
841
842
        if (!empty($sortfield)) {
843
            $sql .= $this->db->order($sortfield, $sortorder);
844
        }
845
        if (!empty($limit)) {
846
            $sql .= $this->db->plimit($limit, $offset);
847
        }
848
849
        $resql = $this->db->query($sql);
850
        if ($resql) {
851
            $num = $this->db->num_rows($resql);
852
            $i = 0;
853
            while ($i < ($limit ? min($limit, $num) : $num)) {
854
                $obj = $this->db->fetch_object($resql);
855
856
                $record = new self($this->db);
857
                $record->setVarsFromFetchObj($obj);
858
859
                $records[$record->id_sondage] = $record;
860
861
                $i++;
862
            }
863
            $this->db->free($resql);
864
865
            return $records;
866
        } else {
867
            $this->errors[] = 'Error ' . $this->db->lasterror();
868
            dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR);
869
870
            return -1;
871
        }
872
    }
873
}
874