dolibarr 25.0.0-alpha
api_members.class.php
1<?php
2/* Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
3 * Copyright (C) 2017 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2020 Thibault FOUCART <support@ptibogxiv.net>
5 * Copyright (C) 2020-2025 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22use Luracast\Restler\RestException;
23
24require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
25require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
26require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
27require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
28require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent_type.class.php';
29require_once DOL_DOCUMENT_ROOT . '/adherents/class/adherentstats.class.php';
30
31
38class Members extends DolibarrApi
39{
43 public static $FIELDS = array(
44 'morphy',
45 'typeid'
46 );
47
51 public $memberstats;
52
56 public function __construct()
57 {
58 global $db;
59 $this->db = $db;
60 $this->memberstats = new AdherentStats($this->db, DolibarrApiAccess::$user->socid, DolibarrApiAccess::$user->id);
61 }
62
74 public function get($id)
75 {
76 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
77 throw new RestException(403);
78 }
79
80 $member = new Adherent($this->db);
81 if ($id == 0) {
82 $result = $member->initAsSpecimen();
83 } else {
84 $result = $member->fetch($id);
85 }
86 if (!$result) {
87 throw new RestException(404, 'member not found');
88 }
89
90 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id) && $id > 0) {
91 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
92 }
93
94 return $this->_cleanObjectDatas($member);
95 }
96
111 public function getByThirdparty($thirdparty)
112 {
113 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
114 throw new RestException(403);
115 }
116
117 $member = new Adherent($this->db);
118 $result = $member->fetch(0, '', $thirdparty);
119 if (!$result) {
120 throw new RestException(404, 'member not found');
121 }
122
123 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
124 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
125 }
126
127 return $this->_cleanObjectDatas($member);
128 }
129
142 public function getByThirdpartyAccounts($site, $key_account)
143 {
144 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
145 throw new RestException(403);
146 }
147
148 $sql = "SELECT rowid, fk_soc as socid, key_account, site, date_creation, tms FROM ".MAIN_DB_PREFIX."societe_account";
149 $sql .= " WHERE site = '".$this->db->escape($site)."' AND key_account = '".$this->db->escape($key_account)."'";
150 $sql .= " AND entity IN (".getEntity('adherent').")";
151
152 $result = $this->db->query($sql);
153
154 if ($result && $this->db->num_rows($result) == 1) {
155 $obj = $this->db->fetch_object($result);
156 $thirdparty = new Societe($this->db);
157 $result = $thirdparty->fetch($obj->socid);
158
159 if ($result <= 0) {
160 throw new RestException(404, 'thirdparty not found');
161 }
162
163 $member = new Adherent($this->db);
164 $result = $member->fetch(0, '', $thirdparty->id);
165 if (!$result) {
166 throw new RestException(404, 'member not found');
167 }
168 } else {
169 throw new RestException(404, 'This account have many thirdparties attached or does not exist.');
170 }
171
172 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
173 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
174 }
175
176 return $this->_cleanObjectDatas($member);
177 }
178
193 public function getByThirdpartyEmail($email)
194 {
195 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
196 throw new RestException(403);
197 }
198
199 $thirdparty = new Societe($this->db);
200 $result = $thirdparty->fetch(0, '', '', '', '', '', '', '', '', '', $email);
201 if (!$result) {
202 throw new RestException(404, 'thirdparty not found');
203 }
204
205 $member = new Adherent($this->db);
206 $result = $member->fetch(0, '', $thirdparty->id);
207 if (!$result) {
208 throw new RestException(404, 'member not found');
209 }
210
211 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
212 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
213 }
214
215 return $this->_cleanObjectDatas($member);
216 }
217
232 public function getByThirdpartyBarcode($barcode)
233 {
234 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
235 throw new RestException(403);
236 }
237
238 $thirdparty = new Societe($this->db);
239 $result = $thirdparty->fetch(0, '', '', $barcode);
240 if (!$result) {
241 throw new RestException(404, 'thirdparty not found');
242 }
243
244 $member = new Adherent($this->db);
245 $result = $member->fetch(0, '', $thirdparty->id);
246 if (!$result) {
247 throw new RestException(404, 'member not found');
248 }
249
250 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
251 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
252 }
253
254 return $this->_cleanObjectDatas($member);
255 }
256
281 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $typeid = '', $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
282 {
283 $obj_ret = array();
284
285 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
286 throw new RestException(403);
287 }
288
289 $sql = "SELECT t.rowid";
290 $sql .= " FROM ".MAIN_DB_PREFIX."adherent AS t LEFT JOIN ".MAIN_DB_PREFIX."adherent_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call
291 if ($category > 0) {
292 $sql .= ", ".MAIN_DB_PREFIX."categorie_member as c";
293 }
294 $sql .= ' WHERE t.entity IN ('.getEntity('adherent').')';
295 if (!empty($typeid)) {
296 $sql .= ' AND t.fk_adherent_type='.((int) $typeid);
297 }
298 // Select members of given category
299 if ($category > 0) {
300 $sql .= " AND c.fk_categorie = ".((int) $category);
301 $sql .= " AND c.fk_member = t.rowid";
302 }
303 // Add sql filters
304 if ($sqlfilters) {
305 $errormessage = '';
306 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
307 if ($errormessage) {
308 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
309 }
310 }
311
312 //this query will return total orders with the filters given
313 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
314
315 $sql .= $this->db->order($sortfield, $sortorder);
316 if ($limit) {
317 if ($page < 0) {
318 $page = 0;
319 }
320 $offset = $limit * $page;
321
322 $sql .= $this->db->plimit($limit + 1, $offset);
323 }
324
325 $result = $this->db->query($sql);
326 if ($result) {
327 $i = 0;
328 $num = $this->db->num_rows($result);
329 $min = min($num, ($limit <= 0 ? $num : $limit));
330 while ($i < $min) {
331 $obj = $this->db->fetch_object($result);
332 $member = new Adherent($this->db);
333 if ($member->fetch($obj->rowid)) {
334 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($member), $properties);
335 }
336 $i++;
337 }
338 } else {
339 throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror());
340 }
341
342 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
343 if ($pagination_data) {
344 $totalsResult = $this->db->query($sqlTotals);
345 $total = $this->db->fetch_object($totalsResult)->total;
346
347 $tmp = $obj_ret;
348 $obj_ret = [];
349
350 $obj_ret['data'] = $tmp;
351 $obj_ret['pagination'] = [
352 'total' => (int) $total,
353 'page' => $page, //count starts from 0
354 'page_count' => ceil((int) $total / $limit),
355 'limit' => $limit
356 ];
357 }
358
359 return $obj_ret;
360 }
361
373 public function post($request_data = null)
374 {
375 if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
376 throw new RestException(403);
377 }
378 // Check mandatory fields
379 $result = $this->_validate($request_data);
380
381 $member = new Adherent($this->db);
382 foreach ($request_data as $field => $value) {
383 if (in_array($field, array('pass', 'pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
384 // This properties can't be set/modified with API
385 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
386 }
387 if (in_array($field, array('user_id')) && !DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
388 // This properties can't be set/modified with API without permission user->user->creer
389 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs without permission user->user->create");
390 }
391 if ($field === 'caller') {
392 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
393 $member->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
394 continue;
395 }
396
397 $member->$field = $this->_checkValForAPI($field, $value, $member);
398 }
399 if ($member->create(DolibarrApiAccess::$user) < 0) {
400 throw new RestException(500, 'Error creating member', array_merge(array($member->error), $member->errors));
401 }
402 return $member->id;
403 }
404
418 public function put($id, $request_data = null)
419 {
420 if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
421 throw new RestException(403);
422 }
423
424 $member = new Adherent($this->db);
425 $result = $member->fetch($id);
426 if (!$result) {
427 throw new RestException(404, 'member not found');
428 }
429
430 if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
431 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
432 }
433
434 $sav_user_id = $member->user_id;
435
436 foreach ($request_data as $field => $value) {
437 if (in_array($field, array('pass', 'pass_crypted', 'pass_indatabase', 'pass_indatabase_crypted', 'pass_temp', 'api_key'))) {
438 // This properties can't be set/modified with API
439 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs");
440 }
441 if (in_array($field, array('user_id')) && !DolibarrApiAccess::$user->hasRight('user', 'user', 'creer')) {
442 // This properties can't be set/modified with API without permission user->user->creer
443 throw new RestException(405, 'The property '.$field." can't be set/modified using the APIs without the permission user->user->create");
444 }
445 if ($field == 'id') {
446 continue;
447 }
448 if ($field === 'caller') {
449 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
450 $member->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
451 continue;
452 }
453 if ($field == 'array_options' && is_array($value)) {
454 foreach ($value as $index => $val) {
455 $member->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $member);
456 }
457 continue;
458 }
459 // Process the status separately because it must be updated using
460 // the validate(), resiliate() and exclude() methods of the class Adherent.
461 if ($field == 'statut') {
462 // Resiliating or excluding a member requires the permission to delete members, like on the member card
463 if (in_array((string) $value, array('0', '-2'), true) && (string) $member->status !== (string) $value && !DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
464 throw new RestException(403, 'Resiliating or excluding a member requires the permission to delete members');
465 }
466 if ($value == '0') {
467 $result = $member->resiliate(DolibarrApiAccess::$user);
468 if ($result < 0) {
469 throw new RestException(500, 'Error when resiliating member: '.$member->errorsToString());
470 }
471 } elseif ($value == '1') {
472 $result = $member->validate(DolibarrApiAccess::$user);
473 if ($result < 0) {
474 throw new RestException(500, 'Error when validating member: '.$member->errorsToString());
475 }
476 } elseif ($value == '-2') {
477 $result = $member->exclude(DolibarrApiAccess::$user);
478 if ($result < 0) {
479 throw new RestException(500, 'Error when excluding member: '.$member->errorsToString());
480 }
481 }
482 } else {
483 $member->$field = $this->_checkValForAPI($field, $value, $member);
484 }
485 }
486
487 // If there is no error, update() returns the number of affected rows
488 // so if the update is a no op, the return value is zero.
489 $nosyncuser = 0;
490 $nosyncpassword = 1; // Disable password sync. Management of password must be done using the user API only.
491 if ($member->update(DolibarrApiAccess::$user, 0, $nosyncuser, $nosyncpassword) >= 0) {
492 return $this->get($id);
493 } else {
494 throw new RestException(500, 'Error when updating member: '.$member->errorsToString());
495 }
496 }
497
510 public function delete($id)
511 {
512 if (!DolibarrApiAccess::$user->hasRight('adherent', 'supprimer')) {
513 throw new RestException(403);
514 }
515 $member = new Adherent($this->db);
516 $result = $member->fetch($id);
517 if (!$result) {
518 throw new RestException(404, 'member not found');
519 }
520
521 if (!DolibarrApi::_checkAccessToResource('member', $member->id)) {
522 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
523 }
524
525
526 $res = $member->delete(DolibarrApiAccess::$user);
527 if ($res < 0) {
528 throw new RestException(500, "Can't delete, error occurs");
529 }
530
531 return array(
532 'success' => array(
533 'code' => 200,
534 'message' => 'Member deleted'
535 )
536 );
537 }
538
548 private function _validate($data)
549 {
550 if ($data === null) {
551 $data = array();
552 }
553 $member = array();
554
555 $mandatoryfields = array(
556 'morphy',
557 'typeid'
558 );
559 foreach ($mandatoryfields as $field) {
560 if (!isset($data[$field])) {
561 throw new RestException(400, "$field field missing");
562 }
563 $member[$field] = $data[$field];
564 }
565 return $member;
566 }
567
568 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
578 public function _cleanObjectDatas($object)
579 {
580 // phpcs:enable
581 $object = parent::_cleanObjectDatas($object);
582
583 // Remove the subscriptions because they are handled as a subresource.
584 if ($object instanceof Adherent) {
585 unset($object->subscriptions);
586 unset($object->fk_incoterms);
587 unset($object->label_incoterms);
588 unset($object->location_incoterms);
589 unset($object->fk_delivery_address);
590 unset($object->shipping_method_id);
591
592 unset($object->pass);
593 unset($object->pass_crypted);
594
595 unset($object->total_ht);
596 unset($object->total_ttc);
597 unset($object->total_tva);
598 unset($object->total_localtax1);
599 unset($object->total_localtax2);
600 }
601
602 if ($object instanceof AdherentType) {
603 unset($object->linkedObjectsIds);
604 unset($object->context);
605 unset($object->canvas);
606 unset($object->fk_project);
607 unset($object->contact);
608 unset($object->contact_id);
609 unset($object->thirdparty);
610 unset($object->user);
611 unset($object->origin);
612 unset($object->origin_id);
613 unset($object->ref_ext);
614 unset($object->country);
615 unset($object->country_id);
616 unset($object->country_code);
617 unset($object->barcode_type);
618 unset($object->barcode_type_code);
619 unset($object->barcode_type_label);
620 unset($object->barcode_type_coder);
621 unset($object->mode_reglement_id);
622 unset($object->cond_reglement_id);
623 unset($object->cond_reglement);
624 unset($object->fk_delivery_address);
625 unset($object->shipping_method_id);
626 unset($object->model_pdf);
627 unset($object->fk_account);
628 unset($object->note_public);
629 unset($object->note_private);
630 unset($object->fk_incoterms);
631 unset($object->label_incoterms);
632 unset($object->location_incoterms);
633 unset($object->name);
634 unset($object->lastname);
635 unset($object->firstname);
636 unset($object->civility_id);
637 unset($object->total_ht);
638 unset($object->total_tva);
639 unset($object->total_localtax1);
640 unset($object->total_localtax2);
641 unset($object->total_ttc);
642 }
643
644 // Expose POST-friendly aliases on the Subscription GET response so the
645 // payload returned by GET /members/{id}/subscriptions matches the field
646 // names POST /members/{id}/subscriptions expects (see issue #38279).
647 // $dateh / $datef stay in the response for backward compatibility with
648 // existing consumers; date_start / date_end are the documented names
649 // used by the rest of the codebase (e.g. tasks, expenses, holidays).
650 if ($object instanceof Subscription) {
651 $object->date_start = $object->dateh;
652 $object->date_end = $object->datef;
653 }
654
655 return $object;
656 }
657
673 public function getSubscriptions($id)
674 {
675 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
676 throw new RestException(403);
677 }
678
679 $member = new Adherent($this->db);
680 $result = $member->fetch($id);
681 if (!$result) {
682 throw new RestException(404, 'member not found');
683 }
684
685 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
686 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
687 }
688
689 $obj_ret = array();
690 foreach ($member->subscriptions as $subscription) {
691 $obj_ret[] = $this->_cleanObjectDatas($subscription);
692 }
693 return $obj_ret;
694 }
695
713 public function createSubscription($id, $start_date, $end_date, $amount, $label = '')
714 {
715 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
716 throw new RestException(403);
717 }
718 if (!is_numeric($start_date) || !is_numeric($end_date) || !is_numeric($amount)) {
719 throw new RestException(422, 'Malformed data: subscription start or end date, or subscription amount, is not numeric');
720 }
721 if ($start_date > $end_date) {
722 throw new RestException(422, 'Malformed data: subscription start is not larger than end date');
723 }
724
725 $member = new Adherent($this->db);
726 $result = $member->fetch($id);
727 if (!$result) {
728 throw new RestException(404, 'member not found');
729 }
730
731 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
732 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
733 }
734
735 $result = $member->subscription((int) $start_date, (float) $amount, 0, '', $label, '', '', '', (int) $end_date);
736 if ($result < 1) {
737 throw new RestException(500, $member->errorsToString());
738 } else {
739 return $result;
740 }
741 }
742
760 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
761 {
762 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
763 throw new RestException(403);
764 }
765
766 $member = new Adherent($this->db);
767 $result = $member->fetch($id);
768 if (0 === $result) {
769 throw new RestException(404, 'Member not found');
770 }
771
772 if (!DolibarrApi::_checkAccessToResource('adherent', $member->id)) {
773 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
774 }
775
776 $categories = new Categorie($this->db);
777
778 $result = $categories->getListForItem($id, 'member', $sortfield, $sortorder, $limit, $page);
779
780 if ($result < 0) {
781 throw new RestException(503, 'Error when retrieve category list : '.$categories->errorsToString());
782 }
783
784 return $result;
785 }
786
787
788
789
803 public function getType($id)
804 {
805 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
806 throw new RestException(403);
807 }
808
809 $membertype = new AdherentType($this->db);
810 $result = $membertype->fetch($id);
811 if (!$result) {
812 throw new RestException(404, 'member type not found');
813 }
814
815 if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
816 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
817 }
818
819 return $this->_cleanObjectDatas($membertype);
820 }
821
844 public function indexType($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
845 {
846 $obj_ret = array();
847
848 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
849 throw new RestException(403);
850 }
851
852 $sql = "SELECT t.rowid";
853 $sql .= " FROM ".MAIN_DB_PREFIX."adherent_type AS t LEFT JOIN ".MAIN_DB_PREFIX."adherent_type_extrafields AS ef ON (ef.fk_object = t.rowid)"; // Modification VMR Global Solutions to include extrafields as search parameters in the API GET call, so we will be able to filter on extrafields
854 $sql .= ' WHERE t.entity IN ('.getEntity('member_type').')';
855
856 // Add sql filters
857 if ($sqlfilters) {
858 $errormessage = '';
859 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
860 if ($errormessage) {
861 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
862 }
863 }
864
865 //this query will return total orders with the filters given
866 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
867
868 $sql .= $this->db->order($sortfield, $sortorder);
869 if ($limit) {
870 if ($page < 0) {
871 $page = 0;
872 }
873 $offset = $limit * $page;
874
875 $sql .= $this->db->plimit($limit + 1, $offset);
876 }
877
878 $result = $this->db->query($sql);
879 if ($result) {
880 $i = 0;
881 $num = $this->db->num_rows($result);
882 $min = min($num, ($limit <= 0 ? $num : $limit));
883 while ($i < $min) {
884 $obj = $this->db->fetch_object($result);
885 $membertype = new AdherentType($this->db);
886 if ($membertype->fetch($obj->rowid)) {
887 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($membertype), $properties);
888 }
889 $i++;
890 }
891 } else {
892 throw new RestException(503, 'Error when retrieve member type list : '.$this->db->lasterror());
893 }
894
895 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
896 if ($pagination_data) {
897 $totalsResult = $this->db->query($sqlTotals);
898 $total = $this->db->fetch_object($totalsResult)->total;
899
900 $tmp = $obj_ret;
901 $obj_ret = [];
902
903 $obj_ret['data'] = $tmp;
904 $obj_ret['pagination'] = [
905 'total' => (int) $total,
906 'page' => $page, //count starts from 0
907 'page_count' => ceil((int) $total / $limit),
908 'limit' => $limit
909 ];
910 }
911
912 return $obj_ret;
913 }
914
928 public function postType($request_data = null)
929 {
930 if (!DolibarrApiAccess::$user->hasRight('adherent', 'configurer')) {
931 throw new RestException(403);
932 }
933 // Check mandatory fields
934 $result = $this->_validateType($request_data);
935
936 $membertype = new AdherentType($this->db);
937 foreach ($request_data as $field => $value) {
938 if ($field === 'caller') {
939 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
940 $membertype->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
941 continue;
942 }
943
944 $membertype->$field = $this->_checkValForAPI($field, $value, $membertype);
945 }
946 if ($membertype->create(DolibarrApiAccess::$user) < 0) {
947 throw new RestException(500, 'Error creating member type', array_merge(array($membertype->error), $membertype->errors));
948 }
949 return $membertype->id;
950 }
951
967 public function putType($id, $request_data = null)
968 {
969 if (!DolibarrApiAccess::$user->hasRight('adherent', 'configurer')) {
970 throw new RestException(403);
971 }
972
973 $membertype = new AdherentType($this->db);
974 $result = $membertype->fetch($id);
975 if (!$result) {
976 throw new RestException(404, 'member type not found');
977 }
978
979 if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
980 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
981 }
982
983 foreach ($request_data as $field => $value) {
984 if ($field == 'id') {
985 continue;
986 }
987 if ($field === 'caller') {
988 // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
989 $membertype->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
990 continue;
991 }
992 if ($field == 'array_options' && is_array($value)) {
993 foreach ($value as $index => $val) {
994 $membertype->array_options[$index] = $val;
995 }
996 continue;
997 }
998 // Process the status separately because it must be updated using
999 // the validate(), resiliate() and exclude() methods of the class AdherentType.
1000 $membertype->$field = $this->_checkValForAPI($field, $value, $membertype);
1001 }
1002
1003 // If there is no error, update() returns the number of affected rows
1004 // so if the update is a no op, the return value is zero.
1005 if ($membertype->update(DolibarrApiAccess::$user) >= 0) {
1006 return $this->get($id);
1007 } else {
1008 throw new RestException(500, 'Error when updating member type: '.$membertype->errorsToString());
1009 }
1010 }
1011
1026 public function deleteType($id)
1027 {
1028 if (!DolibarrApiAccess::$user->hasRight('adherent', 'configurer')) {
1029 throw new RestException(403);
1030 }
1031 $membertype = new AdherentType($this->db);
1032 $result = $membertype->fetch($id);
1033 if ($result < 1) {
1034 throw new RestException(404, 'member type not found');
1035 }
1036
1037 if (!DolibarrApi::_checkAccessToResource('member', $membertype->id, 'adherent_type')) {
1038 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
1039 }
1040
1041 $res = $membertype->delete(DolibarrApiAccess::$user);
1042 if ($res < 0) {
1043 throw new RestException(500, "Can't delete, error occurs");
1044 }
1045
1046 return array(
1047 'success' => array(
1048 'code' => 200,
1049 'message' => 'Member type deleted'
1050 )
1051 );
1052 }
1053
1068 public function getNbByMonth($year, $format = 0)
1069 {
1070 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
1071 throw new RestException(403);
1072 }
1073
1074 return $this->memberstats->getNbByMonth($year, $format);
1075 }
1076
1087 public function getNbByYear()
1088 {
1089 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
1090 throw new RestException(403);
1091 }
1092
1093 return $this->memberstats->getNbByYear();
1094 }
1095
1108 public function getAmountByMonth($year, $format = 0)
1109 {
1110 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
1111 throw new RestException(403);
1112 }
1113
1114 return $this->memberstats->getAmountByMonth($year, $format);
1115 }
1116
1130 public function getLastModifiedMembers($max)
1131 {
1132 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
1133 throw new RestException(403);
1134 }
1135
1136 return $this->memberstats->getLastModifiedMembers($max);
1137 }
1138
1147 private function _validateType($data)
1148 {
1149 $membertype = array();
1150
1151 $mandatoryfields = array('label');
1152
1153 foreach ($mandatoryfields as $field) {
1154 if (!isset($data[$field])) {
1155 throw new RestException(400, "$field field missing");
1156 }
1157 $membertype[$field] = $data[$field];
1158 }
1159 return $membertype;
1160 }
1161}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Class to manage members of a foundation.
Class to manage statistics of members.
Class to manage members type.
Class to manage categories.
Class for API REST v1.
Definition api.class.php:35
_checkValExtrafieldsForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
put($id, $request_data=null)
Update member.
getLastModifiedMembers($max)
Last Modified Members.
getType($id)
Get properties of a member type object.
createSubscription($id, $start_date, $end_date, $amount, $label='')
Add a subscription for a member.
indexType($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List members types.
_validate($data)
Validate fields before creating an object.
getByThirdparty($thirdparty)
Get properties of a member object by linked thirdparty.
getByThirdpartyBarcode($barcode)
Get properties of a member object by linked thirdparty barcode.
deleteType($id)
Delete member type.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $typeid='', $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List members.
__construct()
Constructor.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get categories for a member.
getByThirdpartyEmail($email)
Get properties of a member object by linked thirdparty email.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
getAmountByMonth($year, $format=0)
Return the number of subscriptions by month for a given year.
_validateType($data)
Validate fields before creating an object.
putType($id, $request_data=null)
Update member type.
getNbByYear()
Return an array with the number of subscriptions by year.
getSubscriptions($id)
List subscriptions of a member.
post($request_data=null)
Create member object.
getByThirdpartyAccounts($site, $key_account)
Get properties of a member object by linked thirdparty account.
getNbByMonth($year, $format=0)
Return an array with the number of members by month for a given year.
postType($request_data=null)
Create member type object.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage subscriptions of foundation members.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.