dolibarr 23.0.4
api_subscriptions.class.php
1<?php
2/* Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
3 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
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 <https://www.gnu.org/licenses/>.
17 */
18
19use Luracast\Restler\RestException;
20
21require_once DOL_DOCUMENT_ROOT.'/adherents/class/subscription.class.php';
22
30{
34 public static $FIELDS = array(
35 'fk_adherent',
36 'dateh',
37 'datef',
38 'amount',
39 );
40
44 public $subscription;
45
49 public function __construct()
50 {
51 global $db, $conf;
52 $this->db = $db;
53 $this->subscription = new Subscription($this->db);
54 }
55
67 public function get($id)
68 {
69 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
70 throw new RestException(403);
71 }
72
73 $result = $this->subscription->fetch($id);
74 if (!$result) {
75 throw new RestException(404, 'Subscription not found');
76 }
77
78 // A subscription has no entity, the entity is the one of its member
79 if (!DolibarrApi::_checkAccessToResource('adherent', $this->subscription->fk_adherent)) {
80 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
81 }
82
83 $this->subscription->fetchObjectLinked();
84
85 return $this->_cleanObjectDatas($this->subscription);
86 }
87
108 public function index($sortfield = "dateadh", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
109 {
110 global $conf;
111
112 $obj_ret = array();
113
114 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'lire')) {
115 throw new RestException(403);
116 }
117
118 $sql = "SELECT rowid";
119 $sql .= " FROM ".MAIN_DB_PREFIX."subscription as t";
120 $sql .= ' WHERE 1 = 1';
121 // Add sql filters
122 if ($sqlfilters) {
123 $errormessage = '';
124 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
125 if ($errormessage) {
126 throw new RestException(503, 'Error when validating parameter sqlfilters -> '.$errormessage);
127 }
128 }
129
130 //this query will return total orders with the filters given
131 $sqlTotals = str_replace('SELECT rowid', 'SELECT count(rowid) as total', $sql);
132
133 $sql .= $this->db->order($sortfield, $sortorder);
134 if ($limit) {
135 if ($page < 0) {
136 $page = 0;
137 }
138 $offset = $limit * $page;
139
140 $sql .= $this->db->plimit($limit + 1, $offset);
141 }
142
143 $result = $this->db->query($sql);
144 if ($result) {
145 $i = 0;
146 $num = $this->db->num_rows($result);
147 $min = min($num, ($limit <= 0 ? $num : $limit));
148 while ($i < $min) {
149 $obj = $this->db->fetch_object($result);
150 $subscription = new Subscription($this->db);
151 if ($subscription->fetch($obj->rowid)) {
152 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($subscription), $properties);
153 }
154 $i++;
155 }
156 } else {
157 throw new RestException(503, 'Error when retrieve subscription list : '.$this->db->lasterror());
158 }
159
160 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
161 if ($pagination_data) {
162 $totalsResult = $this->db->query($sqlTotals);
163 $total = $this->db->fetch_object($totalsResult)->total;
164
165 $tmp = $obj_ret;
166 $obj_ret = [];
167
168 $obj_ret['data'] = $tmp;
169 $obj_ret['pagination'] = [
170 'total' => (int) $total,
171 'page' => $page, //count starts from 0
172 'page_count' => ceil((int) $total / $limit),
173 'limit' => $limit
174 ];
175 }
176
177 return $obj_ret;
178 }
179
191 public function post($request_data = null)
192 {
193 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
194 throw new RestException(403);
195 }
196 // Check mandatory fields
197 $result = $this->_validate($request_data);
198
199 // The member of the new subscription must be a member of an entity the user can access
200 if (!empty($request_data['fk_adherent']) && !DolibarrApi::_checkAccessToResource('adherent', (int) $request_data['fk_adherent'])) {
201 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
202 }
203
204 $subscription = new Subscription($this->db);
205 foreach ($request_data as $field => $value) {
206 if ($field === 'caller') {
207 // 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
208 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
209 continue;
210 }
211
212 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
213 }
214 if ($subscription->create(DolibarrApiAccess::$user) < 0) {
215 throw new RestException(500, 'Error when creating subscription', array_merge(array($subscription->error), $subscription->errors));
216 }
217 return $subscription->id;
218 }
219
233 public function put($id, $request_data = null)
234 {
235 if (!DolibarrApiAccess::$user->hasRight('adherent', 'creer')) {
236 throw new RestException(403);
237 }
238
239 $subscription = new Subscription($this->db);
240 $result = $subscription->fetch($id);
241 if (!$result) {
242 throw new RestException(404, 'Subscription not found');
243 }
244
245 // A subscription has no entity, the entity is the one of its member
246 if (!DolibarrApi::_checkAccessToResource('adherent', $subscription->fk_adherent)) {
247 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
248 }
249
250 foreach ($request_data as $field => $value) {
251 if ($field == 'id') {
252 continue;
253 }
254 if ($field === 'caller') {
255 // 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
256 $subscription->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
257 continue;
258 }
259
260 if ($field == 'array_options' && is_array($value)) {
261 foreach ($value as $index => $val) {
262 $subscription->array_options[$index] = $this->_checkValForAPI($field, $val, $subscription);
263 }
264 continue;
265 }
266 $subscription->$field = $this->_checkValForAPI($field, $value, $subscription);
267 }
268
269 if ($subscription->update(DolibarrApiAccess::$user) > 0) {
270 return $this->get($id);
271 } else {
272 throw new RestException(500, 'Error when updating contribution: '.$subscription->error);
273 }
274 }
275
289 public function delete($id)
290 {
291 // The right to delete a subscription comes with the right to create one.
292 if (!DolibarrApiAccess::$user->hasRight('adherent', 'cotisation', 'creer')) {
293 throw new RestException(403);
294 }
295 $subscription = new Subscription($this->db);
296 $result = $subscription->fetch($id);
297 if (!$result) {
298 throw new RestException(404, 'Subscription not found');
299 }
300
301 // A subscription has no entity, the entity is the one of its member
302 if (!DolibarrApi::_checkAccessToResource('adherent', $subscription->fk_adherent)) {
303 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
304 }
305
306 $res = $subscription->delete(DolibarrApiAccess::$user);
307 if ($res < 0) {
308 throw new RestException(500, "Can't delete, error occurs");
309 } elseif ($res == 0) {
310 throw new RestException(409, "No subscription whas deleted");
311 }
312
313 return array(
314 'success' => array(
315 'code' => 200,
316 'message' => 'Subscription deleted'
317 )
318 );
319 }
320
329 private function _validate($data)
330 {
331 $subscription = array();
332 foreach (Subscriptions::$FIELDS as $field) {
333 if (!isset($data[$field])) {
334 throw new RestException(400, "$field field missing");
335 }
336 $subscription[$field] = $data[$field];
337 }
338 return $subscription;
339 }
340}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
Class for API REST v1.
Definition api.class.php:33
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid')
Check access by user to a given resource.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
Definition api.class.php:98
_cleanObjectDatas($object)
Clean sensitive object data @phpstan-template T.
Class to manage subscriptions of foundation members.
_validate($data)
Validate fields before creating an object.
post($request_data=null)
Create subscription object.
index($sortfield="dateadh", $sortorder='ASC', $limit=100, $page=0, $sqlfilters='', $properties='', $pagination_data=false)
List subscriptions.
put($id, $request_data=null)
Update subscription.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.