Completed
Branch develop (45fc57)
by
unknown
27:54
created

Setup::getPaymentTerms()   C

Complexity

Conditions 8
Paths 19

Size

Total Lines 44
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 25
nc 19
nop 6
dl 0
loc 44
rs 5.3846
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2016   Xebax Christy           <[email protected]>
3
 * Copyright (C) 2016	Laurent Destailleur		<[email protected]>
4
 * Copyright (C) 2017	Regis Houssin	<[email protected]>
5
 * Copyright (C) 2017	Neil Orley	<[email protected]>
6
 *
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 <http://www.gnu.org/licenses/>.
20
 */
21
22
use Luracast\Restler\RestException;
23
24
require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
25
require_once DOL_DOCUMENT_ROOT.'/core/class/ccountry.class.php';
26
27
/**
28
 * API class for dictionaries
29
 *
30
 * @access protected
31
 * @class DolibarrApiAccess {@requires user,external}
32
 */
33
class Setup extends DolibarrApi
34
{
35
    private $translations = null;
36
37
    /**
38
     * Constructor
39
     */
40
    function __construct()
41
    {
42
        global $db;
43
        $this->db = $db;
44
    }
45
46
    /**
47
     * Get the list of payments types.
48
     *
49
     * @param string    $sortfield  Sort field
50
     * @param string    $sortorder  Sort order
51
     * @param int       $limit      Number of items per page
52
     * @param int       $page       Page number {@min 0}
53
     * @param int       $active     Payment type is active or not {@min 0} {@max 1}
54
     * @param string    $sqlfilters SQL criteria to filter with. Syntax example "(t.code:=:'CHQ')"
55
     *
56
     * @url     GET dictionary/payment_types
57
     *
58
     * @return array [List of payment types]
59
     *
60
     * @throws 400 RestException
61
     * @throws 200 OK
62
     */
63
    function getPaymentTypes($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
64
    {
65
        $list = array();
66
67
        $sql = "SELECT id, code, type, libelle as label, module";
68
        $sql.= " FROM ".MAIN_DB_PREFIX."c_paiement as t";
69
        $sql.= " WHERE t.active = ".$active;
70
        // Add sql filters
71
        if ($sqlfilters)
72
        {
73
            if (! DolibarrApi::_checkFilters($sqlfilters))
74
            {
75
                throw new RestException(400, 'error when validating parameter sqlfilters '.$sqlfilters);
76
            }
77
	          $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
78
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
79
        }
80
81
82
        $sql.= $this->db->order($sortfield, $sortorder);
83
84
        if ($limit) {
85
            if ($page < 0) {
86
                $page = 0;
87
            }
88
            $offset = $limit * $page;
89
90
            $sql .= $this->db->plimit($limit, $offset);
91
        }
92
93
        $result = $this->db->query($sql);
94
95
        if ($result) {
96
            $num = $this->db->num_rows($result);
97
            $min = min($num, ($limit <= 0 ? $num : $limit));
98
            for ($i = 0; $i < $min; $i++) {
99
                $list[] = $this->db->fetch_object($result);
100
            }
101
        } else {
102
            throw new RestException(400, $this->db->lasterror());
103
        }
104
105
        return $list;
106
    }
107
108
    /**
109
     * Get the list of countries.
110
     *
111
     * The names of the countries will be translated to the given language if
112
     * the $lang parameter is provided. The value of $lang must be a language
113
     * code supported by Dolibarr, for example 'en_US' or 'fr_FR'.
114
     * The returned list is sorted by country ID.
115
     *
116
     * @param string    $sortfield  Sort field
117
     * @param string    $sortorder  Sort order
118
     * @param int       $limit      Number of items per page
119
     * @param int       $page       Page number (starting from zero)
120
     * @param string    $filter     To filter the countries by name
121
     * @param string    $lang       Code of the language the label of the countries must be translated to
122
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
123
     * @return List of countries
124
     *
125
     * @url     GET dictionary/countries
126
     *
127
     * @throws RestException
128
     */
129
    function getListOfCountries($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $filter = '', $lang = '', $sqlfilters = '')
130
    {
131
        $list = array();
132
133
        // Note: The filter is not applied in the SQL request because it must
134
        // be applied to the translated names, not to the names in database.
135
        $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."c_country as t";
136
        $sql.=" WHERE 1 = 1";
137
        // Add sql filters
138
        if ($sqlfilters)
139
        {
140
            if (! DolibarrApi::_checkFilters($sqlfilters))
141
            {
142
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
143
            }
144
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
145
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
146
        }
147
148
        $sql.= $this->db->order($sortfield, $sortorder);
149
150
        if ($limit) {
151
            if ($page < 0) {
152
                $page = 0;
153
            }
154
            $offset = $limit * $page;
155
156
            $sql .= $this->db->plimit($limit, $offset);
157
        }
158
159
        $result = $this->db->query($sql);
160
161
        if ($result) {
162
            $num = $this->db->num_rows($result);
163
            $min = min($num, ($limit <= 0 ? $num : $limit));
164
            for ($i = 0; $i < $min; $i++) {
165
                $obj = $this->db->fetch_object($result);
166
                $country = new Ccountry($this->db);
167
                if ($country->fetch($obj->rowid) > 0) {
168
                    // Translate the name of the country if needed
169
                    // and then apply the filter if there is one.
170
                    $this->translateLabel($country, $lang);
171
172
                    if (empty($filter) || stripos($country->label, $filter) !== FALSE) {
173
                        $list[] = $this->_cleanObjectDatas($country);
174
                    }
175
                }
176
            }
177
        } else {
178
            throw new RestException(503, 'Error when retrieving list of countries : '.$country->error);
179
        }
180
181
        return $list;
182
    }
183
184
    /**
185
     * Get country by ID.
186
     *
187
     * @param int       $id        ID of country
188
     * @param string    $lang      Code of the language the name of the
189
     *                             country must be translated to
190
     *
191
     * @url     GET dictionary/countries/{id}
192
     *
193
     * @throws RestException
194
     */
195
    function getCountryByID($id, $lang = '')
196
    {
197
        $country = new Ccountry($this->db);
198
199
        if ($country->fetch($id) < 0) {
200
            throw new RestException(503, 'Error when retrieving country : '.$country->error);
201
        }
202
        else if ($country->fetch($id) == 0) {
203
            throw new RestException(404, 'country not found');
204
        }
205
206
        $this->translateLabel($country, $lang);
207
208
        return $this->_cleanObjectDatas($country);
209
    }
210
211
    /**
212
     * Clean sensible object datas
213
     *
214
     * @param object    $object    Object to clean
215
     * @return array 				Array of cleaned object properties
216
     */
217
    function _cleanObjectDatas($object)
218
    {
219
        $object = parent::_cleanObjectDatas($object);
220
221
        unset($object->error);
222
        unset($object->errors);
223
224
        return $object;
225
    }
226
227
    /**
228
     * Translate the name of the country to the given language.
229
     *
230
     * @param Ccountry $country   Country
231
     * @param string   $lang      Code of the language the name of the
232
     *                            country must be translated to
233
     */
234
    private function translateLabel($country, $lang)
235
    {
236
        if (!empty($lang)) {
237
            // Load the translations if this is a new language.
238
            if ($this->translations == null || $this->translations->getDefaultLang() !== $lang) {
239
                global $conf;
240
                $this->translations = new Translate('', $conf);
241
                $this->translations->setDefaultLang($lang);
242
                $this->translations->load('dict');
243
            }
244
            if ($country->code) {
245
                $key = 'Country'.$country->code;
246
                $translation = $this->translations->trans($key);
247
                if ($translation != $key) {
248
                    $country->label = html_entity_decode($translation);
249
                }
250
            }
251
        }
252
    }
253
254
    /**
255
     * Get the list of events types.
256
     *
257
     * @param string    $sortfield  Sort field
258
     * @param string    $sortorder  Sort order
259
     * @param int       $limit      Number of items per page
260
     * @param int       $page       Page number (starting from zero)
261
     * @param string    $type       To filter on type of event
262
     * @param string    $module     To filter on module events
263
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
264
     * @return List of events types
265
     *
266
     * @url     GET dictionary/event_types
267
     *
268
     * @throws RestException
269
     */
270
    function getListOfEvents($sortfield = "code", $sortorder = 'ASC', $limit = 100, $page = 0, $type = '', $module = '', $sqlfilters = '')
271
    {
272
        $list = array();
273
274
        $sql = "SELECT id, code, type, libelle as label, module";
275
        $sql.= " FROM ".MAIN_DB_PREFIX."c_actioncomm as t";
276
        $sql.= " WHERE t.active = 1";
277
        if ($type) $sql.=" AND t.type LIKE '%" . $this->db->escape($type) . "%'";
278
        if ($module)    $sql.=" AND t.module LIKE '%" . $this->db->escape($module) . "%'";
279
        // Add sql filters
280
        if ($sqlfilters)
281
        {
282
            if (! DolibarrApi::_checkFilters($sqlfilters))
283
            {
284
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
285
            }
286
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
287
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
288
        }
289
290
291
        $sql.= $this->db->order($sortfield, $sortorder);
292
293
        if ($limit) {
294
            if ($page < 0) {
295
                $page = 0;
296
            }
297
            $offset = $limit * $page;
298
299
            $sql .= $this->db->plimit($limit, $offset);
300
        }
301
302
        $result = $this->db->query($sql);
303
304
        if ($result) {
305
            $num = $this->db->num_rows($result);
306
            $min = min($num, ($limit <= 0 ? $num : $limit));
307
            for ($i = 0; $i < $min; $i++) {
308
                $list[] = $this->db->fetch_object($result);
309
            }
310
        } else {
311
            throw new RestException(503, 'Error when retrieving list of events types : '.$this->db->lasterror());
312
        }
313
314
        return $list;
315
    }
316
317
318
    /**
319
     * Get the list of extra fields.
320
     *
321
     * @param string	$sortfield	Sort field
322
     * @param string	$sortorder	Sort order
323
     * @param string    $type       Type of element ('adherent', 'commande', 'thirdparty', 'facture', 'propal', 'product', ...)
324
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.label:like:'SO-%')"
325
     * @return List of events types
326
     *
327
     * @url     GET extrafields
328
     *
329
     * @throws RestException
330
     */
331
    function getListOfExtrafields($sortfield = "t.pos", $sortorder = 'ASC', $type = '', $sqlfilters = '')
332
    {
333
        $list = array();
334
335
        if ($type == 'thirdparty') $type='societe';
336
        if ($type == 'contact') $type='socpeople';
337
338
        $sql = "SELECT t.rowid, t.name, t.label, t.type, t.size, t.elementtype, t.fieldunique, t.fieldrequired, t.param, t.pos, t.alwayseditable, t.perms, t.list, t.fielddefault, t.fieldcomputed";
339
        $sql.= " FROM ".MAIN_DB_PREFIX."extrafields as t";
340
        $sql.= " WHERE t.entity IN (".getEntity('extrafields').")";
341
        if (! empty($type)) $sql.= " AND t.elementtype = '".$this->db->escape($type)."'";
342
        // Add sql filters
343
        if ($sqlfilters)
344
        {
345
        	if (! DolibarrApi::_checkFilters($sqlfilters))
346
        	{
347
        		throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
348
        	}
349
        	$regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
350
        	$sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
351
        }
352
353
        $sql.= $this->db->order($sortfield, $sortorder);
354
355
        $resql=$this->db->query($sql);
356
        if ($resql)
357
        {
358
        	if ($this->db->num_rows($resql))
359
        	{
360
        		while ($tab = $this->db->fetch_object($resql))
361
        		{
362
        			// New usage
363
        			$list[$tab->elementtype][$tab->name]['type']=$tab->type;
364
        			$list[$tab->elementtype][$tab->name]['label']=$tab->label;
365
        			$list[$tab->elementtype][$tab->name]['size']=$tab->size;
366
        			$list[$tab->elementtype][$tab->name]['elementtype']=$tab->elementtype;
367
        			$list[$tab->elementtype][$tab->name]['default']=$tab->fielddefault;
368
        			$list[$tab->elementtype][$tab->name]['computed']=$tab->fieldcomputed;
369
        			$list[$tab->elementtype][$tab->name]['unique']=$tab->fieldunique;
370
        			$list[$tab->elementtype][$tab->name]['required']=$tab->fieldrequired;
371
        			$list[$tab->elementtype][$tab->name]['param']=($tab->param ? unserialize($tab->param) : '');
372
        			$list[$tab->elementtype][$tab->name]['pos']=$tab->pos;
373
        			$list[$tab->elementtype][$tab->name]['alwayseditable']=$tab->alwayseditable;
374
        			$list[$tab->elementtype][$tab->name]['perms']=$tab->perms;
375
        			$list[$tab->elementtype][$tab->name]['list']=$tab->list;
376
        		}
377
        	}
378
        }
379
        else
380
        {
381
            throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror());
382
        }
383
384
        if (! count($list))
385
        {
386
        	throw new RestException(404, 'No extrafield found');
387
        }
388
389
        return $list;
390
    }
391
392
393
    /**
394
     * Get the list of towns.
395
     *
396
     * @param string    $sortfield  Sort field
397
     * @param string    $sortorder  Sort order
398
     * @param int       $limit      Number of items per page
399
     * @param int       $page       Page number (starting from zero)
400
     * @param string    $zipcode    To filter on zipcode
401
     * @param string    $town       To filter on city name
402
     * @param string    $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(t.code:like:'A%') and (t.active:>=:0)"
403
     * @return List of towns
404
     *
405
     * @url     GET dictionary/towns
406
     *
407
     * @throws RestException
408
     */
409
    function getListOfTowns($sortfield = "zip,town", $sortorder = 'ASC', $limit = 100, $page = 0, $zipcode = '', $town = '', $sqlfilters = '')
410
    {
411
        $list = array();
412
413
        $sql = "SELECT rowid AS id, zip, town, fk_county, fk_pays AS fk_country";
414
        $sql.= " FROM ".MAIN_DB_PREFIX."c_ziptown as t";
415
        $sql.= " WHERE t.active = 1";
416
        if ($zipcode) $sql.=" AND t.zip LIKE '%" . $this->db->escape($zipcode) . "%'";
417
        if ($town)    $sql.=" AND t.town LIKE '%" . $this->db->escape($town) . "%'";
418
        // Add sql filters
419
        if ($sqlfilters)
420
        {
421
            if (! DolibarrApi::_checkFilters($sqlfilters))
422
            {
423
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
424
            }
425
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
426
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
427
        }
428
429
430
        $sql.= $this->db->order($sortfield, $sortorder);
431
432
        if ($limit) {
433
            if ($page < 0) {
434
                $page = 0;
435
            }
436
            $offset = $limit * $page;
437
438
            $sql .= $this->db->plimit($limit, $offset);
439
        }
440
441
        $result = $this->db->query($sql);
442
443
        if ($result) {
444
            $num = $this->db->num_rows($result);
445
            $min = min($num, ($limit <= 0 ? $num : $limit));
446
            for ($i = 0; $i < $min; $i++) {
447
                $list[] = $this->db->fetch_object($result);
448
            }
449
        } else {
450
            throw new RestException(503, 'Error when retrieving list of towns : '.$this->db->lasterror());
451
        }
452
453
        return $list;
454
    }
455
456
    /**
457
     * Get the list of payments terms.
458
     *
459
     * @param string    $sortfield  Sort field
460
     * @param string    $sortorder  Sort order
461
     * @param int       $limit      Number of items per page
462
     * @param int       $page       Page number {@min 0}
463
     * @param int       $active     Payment term is active or not {@min 0} {@max 1}
464
     * @param string    $sqlfilters SQL criteria to filter. Syntax example "(t.code:=:'CHQ')"
465
     *
466
     * @url     GET dictionary/payment_terms
467
     *
468
     * @return array List of payment terms
469
     *
470
     * @throws 400 RestException
471
     * @throws 200 OK
472
     */
473
    function getPaymentTerms($sortfield = "sortorder", $sortorder = 'ASC', $limit = 100, $page = 0, $active = 1, $sqlfilters = '')
474
    {
475
        $list = array();
476
477
        $sql = "SELECT rowid as id, code, sortorder, libelle as label, libelle_facture as descr, type_cdr, nbjour, decalage, module";
478
        $sql.= " FROM ".MAIN_DB_PREFIX."c_payment_term as t";
479
        $sql.= " WHERE t.active = ".$active;
480
        // Add sql filters
481
        if ($sqlfilters)
482
        {
483
            if (! DolibarrApi::_checkFilters($sqlfilters))
484
            {
485
                throw new RestException(400, 'Error when validating parameter sqlfilters '.$sqlfilters);
486
            }
487
                $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
488
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
489
        }
490
491
492
        $sql.= $this->db->order($sortfield, $sortorder);
493
494
        if ($limit) {
495
            if ($page < 0) {
496
                $page = 0;
497
            }
498
            $offset = $limit * $page;
499
500
            $sql .= $this->db->plimit($limit, $offset);
501
        }
502
503
        $result = $this->db->query($sql);
504
505
        if ($result) {
506
            $num = $this->db->num_rows($result);
507
            $min = min($num, ($limit <= 0 ? $num : $limit));
508
            for ($i = 0; $i < $min; $i++) {
509
                $list[] = $this->db->fetch_object($result);
510
            }
511
        } else {
512
            throw new RestException(400, $this->db->lasterror());
513
        }
514
515
        return $list;
516
    }
517
518
}
519