Completed
Branch develop (4833c2)
by
unknown
24:33
created

Contacts::deleteCategory()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
nc 6
nop 2
dl 0
loc 27
rs 8.8657
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2015       Jean-François Ferry         <[email protected]>
3
 * Copyright (C) 2019       Frédéric France             <[email protected]>
4
 *
5
 * This program is free software; you can redistribute it and/or modify
6
 * it under the terms of the GNU General Public License as published by
7
 * the Free Software Foundation; either version 3 of the License, or
8
 * (at your option) any later version.
9
 *
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13
 * GNU General Public License for more details.
14
 *
15
 * You should have received a copy of the GNU General Public License
16
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17
 */
18
19
use Luracast\Restler\RestException;
20
21
//require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
22
//require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
23
24
25
/**
26
 * API class for contacts
27
 *
28
 * @access protected
29
 * @class  DolibarrApiAccess {@requires user,external}
30
 */
31
class Contacts extends DolibarrApi
32
{
33
	/**
34
	 *
35
	 * @var array   $FIELDS     Mandatory fields, checked when create and update object
36
	 */
37
	static $FIELDS = array(
38
		'lastname',
39
	);
40
41
	/**
42
	 * @var Contact $contact {@type Contact}
43
	 */
44
	public $contact;
45
46
	/**
47
	 * Constructor
48
	 */
49
    public function __construct()
50
	{
51
		global $db, $conf;
52
		$this->db = $db;
53
54
		require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
55
		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
56
57
		$this->contact = new Contact($this->db);
58
	}
59
60
	/**
61
	 * Get properties of a contact object
62
	 *
63
	 * Return an array with contact informations
64
	 *
65
	 * @param 	int    $id                  ID of contact
66
	 * @param   int    $includecount        Count and return also number of elements the contact is used as a link for
67
	 * @return 	array|mixed data without useless information
68
	 *
69
	 * @throws 	RestException
70
	 */
71
    public function get($id, $includecount = 0)
72
	{
73
		if (!DolibarrApiAccess::$user->rights->societe->contact->lire)
74
		{
75
			throw new RestException(401, 'No permission to read contacts');
76
		}
77
78
		$result = $this->contact->fetch($id);
79
80
		if (!$result)
81
		{
82
			throw new RestException(404, 'Contact not found');
83
		}
84
85
		if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
86
		{
87
			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
88
		}
89
90
		if ($includecount)
91
		{
92
		    $this->contact->load_ref_elements();
93
		}
94
95
		return $this->_cleanObjectDatas($this->contact);
96
	}
97
98
	/**
99
	 * List contacts
100
	 *
101
	 * Get a list of contacts
102
	 *
103
	 * @param string	$sortfield	        Sort field
104
	 * @param string	$sortorder	        Sort order
105
	 * @param int		$limit		        Limit for list
106
	 * @param int		$page		        Page number
107
	 * @param string   	$thirdparty_ids	    Thirdparty ids to filter contacts of. {@example '1' or '1,2,3'} {@pattern /^[0-9,]*$/i}
108
	 * @param string    $sqlfilters         Other criteria to filter answers separated by a comma. Syntax example "(t.ref:like:'SO-%') and (t.date_creation:<:'20160101')"
109
	 * @param int       $includecount       Count and return also number of elements the contact is used as a link for
110
	 * @return array                        Array of contact objects
111
     *
112
	 * @throws RestException
113
     */
114
    public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $thirdparty_ids = '', $sqlfilters = '', $includecount = 0)
115
    {
116
		global $db, $conf;
117
118
		$obj_ret = array();
119
120
		if (!DolibarrApiAccess::$user->rights->societe->contact->lire)
121
		{
122
		    throw new RestException(401, 'No permission to read contacts');
123
		}
124
125
        // case of external user, $thirdparty_ids param is ignored and replaced by user's socid
126
		$socids = DolibarrApiAccess::$user->socid ? DolibarrApiAccess::$user->socid : $thirdparty_ids;
127
128
		// If the internal user must only see his customers, force searching by him
129
		$search_sale = 0;
130
		if (!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids)
131
			$search_sale = DolibarrApiAccess::$user->id;
132
133
		$sql = "SELECT t.rowid";
134
		$sql.= " FROM " . MAIN_DB_PREFIX . "socpeople as t";
135
		$sql.= " LEFT JOIN ".MAIN_DB_PREFIX . "socpeople_extrafields as te ON te.fk_object = t.rowid";
136
		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0) {
137
			// We need this table joined to the select in order to filter by sale
138
			$sql.= ", " . MAIN_DB_PREFIX . "societe_commerciaux as sc";
139
		}
140
		$sql.= " LEFT JOIN " . MAIN_DB_PREFIX . "societe as s ON t.fk_soc = s.rowid";
141
		$sql.= ' WHERE t.entity IN (' . getEntity('socpeople') . ')';
142
		if ($socids) $sql.= " AND t.fk_soc IN (" . $socids . ")";
143
144
		if ((!DolibarrApiAccess::$user->rights->societe->client->voir && !$socids) || $search_sale > 0)
145
			$sql.= " AND t.fk_soc = sc.fk_soc";
146
		if ($search_sale > 0)
147
			$sql.= " AND s.rowid = sc.fk_soc";  // Join for the needed table to filter by sale
148
		// Insert sale filter
149
		if ($search_sale > 0)
150
		{
151
			$sql .= " AND sc.fk_user = " . $search_sale;
152
		}
153
	    // Add sql filters
154
        if ($sqlfilters)
155
        {
156
            if (! DolibarrApi::_checkFilters($sqlfilters))
157
            {
158
                throw new RestException(503, 'Error when validating parameter sqlfilters '.$sqlfilters);
159
            }
160
	        $regexstring='\(([^:\'\(\)]+:[^:\'\(\)]+:[^:\(\)]+)\)';
161
            $sql.=" AND (".preg_replace_callback('/'.$regexstring.'/', 'DolibarrApi::_forge_criteria_callback', $sqlfilters).")";
162
        }
163
164
		$sql.= $db->order($sortfield, $sortorder);
165
166
		if ($limit)
167
		{
168
			if ($page < 0)
169
			{
170
				$page = 0;
171
			}
172
			$offset = $limit * $page;
173
174
			$sql.= $db->plimit($limit + 1, $offset);
175
		}
176
		$result = $db->query($sql);
177
		if ($result)
178
		{
179
			$num = $db->num_rows($result);
180
			$min = min($num, ($limit <= 0 ? $num : $limit));
181
            $i = 0;
182
			while ($i < $min)
183
			{
184
				$obj = $db->fetch_object($result);
185
				$contact_static = new Contact($db);
186
				if ($contact_static->fetch($obj->rowid))
187
				{
188
		            if ($includecount)
189
		            {
190
		                $contact_static->load_ref_elements();
191
		            }
192
					$obj_ret[] = $this->_cleanObjectDatas($contact_static);
193
				}
194
195
				$i++;
196
			}
197
		}
198
		else {
199
			throw new RestException(503, 'Error when retrieve contacts : ' . $sql);
200
		}
201
		if (!count($obj_ret))
202
		{
203
			throw new RestException(404, 'Contacts not found');
204
		}
205
		return $obj_ret;
206
	}
207
208
	/**
209
	 * Create contact object
210
	 *
211
	 * @param   array   $request_data   Request datas
212
	 * @return  int     ID of contact
213
	 */
214
    public function post($request_data = null)
215
    {
216
		if (!DolibarrApiAccess::$user->rights->societe->contact->creer)
217
		{
218
			throw new RestException(401, 'No permission to create/update contacts');
219
		}
220
		// Check mandatory fields
221
		$result = $this->_validate($request_data);
222
223
		foreach ($request_data as $field => $value)
224
		{
225
			$this->contact->$field = $value;
226
		}
227
		if ($this->contact->create(DolibarrApiAccess::$user) < 0) {
228
		    throw new RestException(500, "Error creating contact", array_merge(array($this->contact->error), $this->contact->errors));
229
		}
230
		return $this->contact->id;
231
	}
232
233
	/**
234
	 * Update contact
235
	 *
236
	 * @param int   $id             Id of contact to update
237
	 * @param array $request_data   Datas
238
	 * @return int
239
	 */
240
    public function put($id, $request_data = null)
241
    {
242
		if (!DolibarrApiAccess::$user->rights->societe->contact->creer)
243
		{
244
			throw new RestException(401, 'No permission to create/update contacts');
245
		}
246
247
		$result = $this->contact->fetch($id);
248
		if (!$result)
249
		{
250
			throw new RestException(404, 'Contact not found');
251
		}
252
253
		if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
254
		{
255
			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
256
		}
257
258
		foreach ($request_data as $field => $value)
259
		{
260
            if ($field == 'id') continue;
261
		    $this->contact->$field = $value;
262
		}
263
264
		if ($this->contact->update($id, DolibarrApiAccess::$user, 1, '', '', 'update'))
265
			return $this->get($id);
266
267
		return false;
268
	}
269
270
	/**
271
	 * Delete contact
272
	 *
273
	 * @param   int     $id Contact ID
274
	 * @return  integer
275
	 */
276
    public function delete($id)
277
    {
278
		if (!DolibarrApiAccess::$user->rights->societe->contact->supprimer)
279
		{
280
			throw new RestException(401, 'No permission to delete contacts');
281
		}
282
		$result = $this->contact->fetch($id);
283
		if (!$result)
284
		{
285
			throw new RestException(404, 'Contact not found');
286
		}
287
288
		if (!DolibarrApi::_checkAccessToResource('contact', $this->contact->id, 'socpeople&societe'))
289
		{
290
			throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
291
		}
292
293
		return $this->contact->delete($id);
294
	}
295
296
	/**
297
	 * Create an user account object from contact (external user)
298
	 *
299
	 * @param   int   	$id   Id of contact
300
	 * @param   array   $request_data   Request datas
301
	 * @return  int     ID of user
302
	 *
303
	 * @url	POST {id}/createUser
304
	 */
305
    public function createUser($id, $request_data = null)
306
    {
307
	    //if (!DolibarrApiAccess::$user->rights->user->user->creer) {
308
	    //throw new RestException(401);
309
	    //}
310
311
	    if (!isset($request_data["login"]))
312
    		throw new RestException(400, "login field missing");
313
	    if (!isset($request_data["password"]))
314
	    	throw new RestException(400, "password field missing");
315
316
	    if (!DolibarrApiAccess::$user->rights->societe->contact->lire) {
317
	        throw new RestException(401, 'No permission to read contacts');
318
	    }
319
	    if (!DolibarrApiAccess::$user->rights->user->user->creer) {
320
	        throw new RestException(401, 'No permission to create user');
321
	    }
322
323
	    $contact = new Contact($this->db);
324
	    $contact->fetch($id);
325
	    if ($contact->id <= 0) {
326
	        throw new RestException(404, 'Contact not found');
327
	    }
328
329
	    if (!DolibarrApi::_checkAccessToResource('contact', $contact->id, 'socpeople&societe')) {
330
	        throw new RestException(401, 'Access not allowed for login ' . DolibarrApiAccess::$user->login);
331
	    }
332
333
	    // Check mandatory fields
334
	    $login = $request_data["login"];
335
	    $password = $request_data["password"];
336
	    $useraccount = new User($this->db);
337
	    $result = $useraccount->create_from_contact($contact, $login, $password);
338
	    if ($result <= 0) {
339
	        throw new RestException(500, "User not created");
340
	    }
341
	    // password parameter not used in create_from_contact
342
	    $useraccount->setPassword($useraccount, $password);
343
344
	    return $result;
345
	}
346
347
    /**
348
     * Get categories for a contact
349
     *
350
     * @param int		$id         ID of contact
351
     * @param string	$sortfield	Sort field
352
     * @param string	$sortorder	Sort order
353
     * @param int		$limit		Limit for list
354
     * @param int		$page		Page number
355
     *
356
     * @return mixed
357
     *
358
     * @url GET {id}/categories
359
     */
360
    public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
361
	{
362
		if (! DolibarrApiAccess::$user->rights->categorie->lire) {
363
			throw new RestException(401);
364
		}
365
366
		$categories = new Categorie($this->db);
367
368
		$result = $categories->getListForItem($id, 'contact', $sortfield, $sortorder, $limit, $page);
369
370
		if (empty($result)) {
371
			throw new RestException(404, 'No category found');
372
		}
373
374
		if ($result < 0) {
375
			throw new RestException(503, 'Error when retrieve category list : '.$categories->error);
376
		}
377
378
		return $result;
379
    }
380
381
    /**
382
     * Add a category to a contact
383
     *
384
     * @url POST {id}/categories/{category_id}
385
     *
386
     * @param   int		$id             Id of contact
387
     * @param   int     $category_id    Id of category
388
     *
389
     * @return  mixed
390
     *
391
     * @throws  401     RestException   Insufficient rights
392
     * @throws  401     RestException   Access not allowed for login
393
     * @throws  404     RestException   Category not found
394
     * @throws  404     RestException   Contact not found
395
     */
396
    public function addCategory($id, $category_id)
397
    {
398
        if(! DolibarrApiAccess::$user->rights->societe->contact->creer) {
399
            throw new RestException(401, 'Insufficient rights');
400
        }
401
402
        $result = $this->contact->fetch($id);
403
        if (! $result) {
404
            throw new RestException(404, 'Contact not found');
405
        }
406
        $category = new Categorie($this->db);
407
        $result = $category->fetch($category_id);
408
        if (! $result) {
409
            throw new RestException(404, 'category not found');
410
        }
411
412
        if (! DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
413
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
414
        }
415
        if (! DolibarrApi::_checkAccessToResource('category', $category->id)) {
416
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
417
        }
418
419
        $category->add_type($this->contact, 'contact');
420
421
        return $this->_cleanObjectDatas($this->contact);
422
    }
423
424
    /**
425
     * Remove the link between a category and a contact
426
     *
427
     * @url DELETE {id}/categories/{category_id}
428
     *
429
     * @param   int		$id				Id of contact
430
     * @param   int		$category_id	Id of category
431
     * @return  mixed
432
     *
433
     * @throws  401     RestException   Insufficient rights
434
     * @throws  401     RestException   Access not allowed for login
435
     * @throws  404     RestException   Category not found
436
     * @throws  404     RestException   Contact not found
437
     */
438
    public function deleteCategory($id, $category_id)
439
    {
440
        if(! DolibarrApiAccess::$user->rights->societe->contact->creer) {
441
            throw new RestException(401, 'Insufficient rights');
442
        }
443
444
        $result = $this->contact->fetch($id);
445
        if( ! $result ) {
446
            throw new RestException(404, 'Contact not found');
447
        }
448
        $category = new Categorie($this->db);
449
        $result = $category->fetch($category_id);
450
        if( ! $result ) {
451
            throw new RestException(404, 'category not found');
452
        }
453
454
        if( ! DolibarrApi::_checkAccessToResource('contact', $this->contact->id)) {
455
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
456
        }
457
        if( ! DolibarrApi::_checkAccessToResource('category', $category->id)) {
458
            throw new RestException(401, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
459
        }
460
461
        $category->del_type($this->contact, 'contact');
462
463
        return $this->_cleanObjectDatas($this->contact);
464
    }
465
466
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
467
    /**
468
     * Clean sensible object datas
469
     *
470
     * @param   Object  $object     Object to clean
471
     * @return  array               Array of cleaned object properties
472
     */
473
    protected function _cleanObjectDatas($object)
474
    {
475
        // phpcs:enable
476
        $object = parent::_cleanObjectDatas($object);
477
478
        unset($object->total_ht);
479
        unset($object->total_tva);
480
        unset($object->total_localtax1);
481
        unset($object->total_localtax2);
482
        unset($object->total_ttc);
483
484
        unset($object->note);
485
        unset($object->lines);
486
        unset($object->thirdparty);
487
488
        return $object;
489
    }
490
491
    /**
492
     * Validate fields before create or update object
493
     *
494
     * @param   array|null     $data   Data to validate
495
     * @return  array
496
     * @throws  RestException
497
     */
498
    private function _validate($data)
499
    {
500
        $contact = array();
501
        foreach (Contacts::$FIELDS as $field) {
502
            if (!isset($data[$field])) {
503
                throw new RestException(400, "$field field missing");
504
            }
505
            $contact[$field] = $data[$field];
506
        }
507
508
        return $contact;
509
    }
510
}
511