dolibarr 22.0.5
api_knowledgemanagement.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015 Jean-François Ferry <jfefe@aternatik.fr>
3 * Copyright (C) 2021 SuperAdmin <test@dolibarr.com>
4 * Copyright (C) 2025 Charlene Benke <charlent@patas-monkey.com>
5 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21use Luracast\Restler\RestException;
22
23dol_include_once('/knowledgemanagement/class/knowledgerecord.class.php');
24dol_include_once('/categories/class/categorie.class.php');
25
26
27
41{
45 public $knowledgerecord;
46
52 public function __construct()
53 {
54 global $db, $conf;
55 $this->db = $db;
56 $this->knowledgerecord = new KnowledgeRecord($this->db);
57 }
58
72 public function get($id)
73 {
74 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read')) {
75 throw new RestException(403);
76 }
77
78 $result = $this->knowledgerecord->fetch($id);
79 if (!$result) {
80 throw new RestException(404, 'KnowledgeRecord not found');
81 }
82
83 if (!DolibarrApi::_checkAccessToResource('knowledgerecord', $this->knowledgerecord->id, 'knowledgemanagement_knowledgerecord')) {
84 throw new RestException(403, 'Access to instance id='.$this->knowledgerecord->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
85 }
86
87 return $this->_cleanObjectDatas($this->knowledgerecord);
88 }
89
103 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
104 {
105 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
106 throw new RestException(403);
107 }
108
109 $categories = new Categorie($this->db);
110
111 $result = $categories->getListForItem($id, 'knowledgemanagement', $sortfield, $sortorder, $limit, $page);
112
113 if ($result < 0) {
114 throw new RestException(503, 'Error when retrieve category list : '.implode(',', array_merge(array($categories->error), $categories->errors)));
115 }
116
117 return $result;
118 }
119
141 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
142 {
143 $obj_ret = array();
144 $tmpobject = new KnowledgeRecord($this->db);
145
146 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read')) {
147 throw new RestException(403);
148 }
149
150 $socid = DolibarrApiAccess::$user->socid ?: 0;
151
152 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
153
154 // If the internal user must only see his customers, force searching by him
155 $search_sale = 0;
156 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
157 $search_sale = DolibarrApiAccess::$user->id;
158 }
159
160 $sql = "SELECT t.rowid";
161 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t";
162 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$tmpobject->table_element."_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
163 if ($category > 0) {
164 $sql .= ", ".$this->db->prefix()."categorie_knowledgemanagement as c";
165 }
166 $sql .= " WHERE 1 = 1";
167 if ($tmpobject->ismultientitymanaged) {
168 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
169 }
170 if ($restrictonsocid && $socid) {
171 $sql .= " AND t.fk_soc = ".((int) $socid);
172 }
173 // Search on sale representative
174 if ($search_sale && $search_sale != '-1') {
175 if ($search_sale == -2) {
176 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
177 } elseif ($search_sale > 0) {
178 $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")";
179 }
180 }
181 // Select products of given category
182 if ($category > 0) {
183 $sql .= " AND c.fk_categorie = ".((int) $category);
184 $sql .= " AND c.fk_knowledgemanagement = t.rowid";
185 }
186 if ($sqlfilters) {
187 $errormessage = '';
188 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
189 if ($errormessage) {
190 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
191 }
192 }
193
194 //this query will return total orders with the filters given
195 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
196
197 $sql .= $this->db->order($sortfield, $sortorder);
198 if ($limit) {
199 if ($page < 0) {
200 $page = 0;
201 }
202 $offset = $limit * $page;
203
204 $sql .= $this->db->plimit($limit + 1, $offset);
205 }
206
207 $result = $this->db->query($sql);
208 $i = 0;
209 if ($result) {
210 $num = $this->db->num_rows($result);
211 while ($i < $num) {
212 $obj = $this->db->fetch_object($result);
213 $tmp_object = new KnowledgeRecord($this->db);
214 if ($tmp_object->fetch($obj->rowid)) {
215 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
216 }
217 $i++;
218 }
219 } else {
220 throw new RestException(503, 'Error when retrieving knowledgerecord list: '.$this->db->lasterror());
221 }
222
223 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
224 if ($pagination_data) {
225 $totalsResult = $this->db->query($sqlTotals);
226 $total = $this->db->fetch_object($totalsResult)->total;
227
228 $tmp = $obj_ret;
229 $obj_ret = [];
230
231 $obj_ret['data'] = $tmp;
232 $obj_ret['pagination'] = [
233 'total' => (int) $total,
234 'page' => $page, //count starts from 0
235 'page_count' => ceil((int) $total / $limit),
236 'limit' => $limit
237 ];
238 }
239
240 return $obj_ret;
241 }
242
255 public function post($request_data = null)
256 {
257 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
258 throw new RestException(403);
259 }
260
261 // Check mandatory fields
262 $result = $this->_validate($request_data);
263
264 foreach ($request_data as $field => $value) {
265 if ($field === 'caller') {
266 // 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
267 $this->knowledgerecord->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
268 continue;
269 }
270
271 $this->knowledgerecord->$field = $this->_checkValForAPI($field, $value, $this->knowledgerecord);
272 }
273
274 // Clean data
275 // $this->knowledgerecord->abc = sanitizeVal($this->knowledgerecord->abc, 'alphanohtml');
276
277 if ($this->knowledgerecord->create(DolibarrApiAccess::$user) < 0) {
278 throw new RestException(500, "Error creating KnowledgeRecord", array_merge(array($this->knowledgerecord->error), $this->knowledgerecord->errors));
279 }
280 return $this->knowledgerecord->id;
281 }
282
296 public function put($id, $request_data = null)
297 {
298 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
299 throw new RestException(403);
300 }
301
302 $result = $this->knowledgerecord->fetch($id);
303 if (!$result) {
304 throw new RestException(404, 'KnowledgeRecord not found');
305 }
306
307 if (!DolibarrApi::_checkAccessToResource('knowledgerecord', $this->knowledgerecord->id, 'knowledgemanagement_knowledgerecord')) {
308 throw new RestException(403, 'Access to instance id='.$this->knowledgerecord->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
309 }
310
311 foreach ($request_data as $field => $value) {
312 if ($field == 'id') {
313 continue;
314 }
315 if ($field === 'caller') {
316 // 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
317 $this->knowledgerecord->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
318 continue;
319 }
320
321 if ($field == 'array_options' && is_array($value)) {
322 foreach ($value as $index => $val) {
323 $this->knowledgerecord->array_options[$index] = $this->_checkValForAPI($field, $val, $this->knowledgerecord);
324 }
325 continue;
326 }
327
328 $this->knowledgerecord->$field = $this->_checkValForAPI($field, $value, $this->knowledgerecord);
329 }
330
331 // Clean data
332 // $this->knowledgerecord->abc = sanitizeVal($this->knowledgerecord->abc, 'alphanohtml');
333
334 if ($this->knowledgerecord->update(DolibarrApiAccess::$user, 0) > 0) {
335 return $this->get($id);
336 } else {
337 throw new RestException(500, $this->knowledgerecord->error);
338 }
339 }
340
353 public function delete($id)
354 {
355 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'delete')) {
356 throw new RestException(403);
357 }
358 $result = $this->knowledgerecord->fetch($id);
359 if (!$result) {
360 throw new RestException(404, 'KnowledgeRecord not found');
361 }
362
363 if (!DolibarrApi::_checkAccessToResource('knowledgerecord', $this->knowledgerecord->id, 'knowledgemanagement_knowledgerecord')) {
364 throw new RestException(403, 'Access to instance id='.$this->knowledgerecord->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
365 }
366
367 if (!$this->knowledgerecord->delete(DolibarrApiAccess::$user)) {
368 throw new RestException(500, 'Error when deleting KnowledgeRecord : '.$this->knowledgerecord->error);
369 }
370
371 return array(
372 'success' => array(
373 'code' => 200,
374 'message' => 'KnowledgeRecord deleted'
375 )
376 );
377 }
378
379
380 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
387 protected function _cleanObjectDatas($object)
388 {
389 // phpcs:enable
390 $object = parent::_cleanObjectDatas($object);
391
392 unset($object->rowid);
393 unset($object->canvas);
394
395 /*unset($object->name);
396 unset($object->lastname);
397 unset($object->firstname);
398 unset($object->civility_id);
399 unset($object->statut);
400 unset($object->state);
401 unset($object->state_id);
402 unset($object->state_code);
403 unset($object->region);
404 unset($object->region_code);
405 unset($object->country);
406 unset($object->country_id);
407 unset($object->country_code);
408 unset($object->barcode_type);
409 unset($object->barcode_type_code);
410 unset($object->barcode_type_label);
411 unset($object->barcode_type_coder);
412 unset($object->total_ht);
413 unset($object->total_tva);
414 unset($object->total_localtax1);
415 unset($object->total_localtax2);
416 unset($object->total_ttc);
417 unset($object->fk_account);
418 unset($object->comments);
419 unset($object->note);
420 unset($object->mode_reglement_id);
421 unset($object->cond_reglement_id);
422 unset($object->cond_reglement);
423 unset($object->shipping_method_id);
424 unset($object->fk_incoterms);
425 unset($object->label_incoterms);
426 unset($object->location_incoterms);
427 */
428
429 // If object has lines, remove $db property
430 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
431 $nboflines = count($object->lines);
432 for ($i = 0; $i < $nboflines; $i++) {
433 $this->_cleanObjectDatas($object->lines[$i]);
434
435 unset($object->lines[$i]->lines);
436 unset($object->lines[$i]->note);
437 }
438 }
439
440 return $object;
441 }
457 public function validate($id, $notrigger = 0)
458 {
459 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
460 throw new RestException(403, "Insuffisant rights");
461 }
462 $result = $this->knowledgerecord->fetch($id);
463 if (!$result) {
464 throw new RestException(404, 'knowledgerecord not found');
465 }
466
467
468 $result = $this->knowledgerecord->validate(DolibarrApiAccess::$user, $notrigger);
469 if ($result == 0) {
470 throw new RestException(304, 'Error nothing done. May be object is already validated');
471 }
472 if ($result < 0) {
473 throw new RestException(500, 'Error when validating knowledgerecord: '.$this->knowledgerecord->error);
474 }
475
476 return $this->_cleanObjectDatas($this->knowledgerecord);
477 }
478
494 public function cancel($id, $notrigger = 0)
495 {
496 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
497 throw new RestException(403, "Insuffisant rights");
498 }
499 $result = $this->knowledgerecord->fetch($id);
500 if (!$result) {
501 throw new RestException(404, 'knowledgerecord not found');
502 }
503
504
505 $result = $this->knowledgerecord->cancel(DolibarrApiAccess::$user, $notrigger);
506 if ($result == 0) {
507 throw new RestException(304, 'Error nothing done. May be object is already validated');
508 }
509 if ($result < 0) {
510 throw new RestException(500, 'Error when validating knowledgerecord: '.$this->knowledgerecord->error);
511 }
512
513 return $this->_cleanObjectDatas($this->knowledgerecord);
514 }
515
524 private function _validate($data)
525 {
526 if ($data === null) {
527 $data = array();
528 }
529 $knowledgerecord = array();
530 foreach ($this->knowledgerecord->fields as $field => $propfield) {
531 if (in_array($field, array('rowid', 'entity', 'ref', 'date_creation', 'tms', 'fk_user_creat')) || empty($propfield['notnull']) || $propfield['notnull'] != 1) {
532 continue; // Not a mandatory field
533 }
534 if (!isset($data[$field])) {
535 throw new RestException(400, "$field field missing");
536 }
537 $knowledgerecord[$field] = $data[$field];
538 }
539 return $knowledgerecord;
540 }
541}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
Class to manage categories.
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
cancel($id, $notrigger=0)
Cancel a knowledge.
post($request_data=null)
Create knowledgerecord object.
index($sortfield="t.rowid", $sortorder='ASC', $limit=100, $page=0, $category=0, $sqlfilters='', $properties='', $pagination_data=false)
List knowledgerecords.
validate($id, $notrigger=0)
Validate a knowledge.
_validate($data)
Validate fields before create or update object.
getCategories($id, $sortfield="s.rowid", $sortorder='ASC', $limit=0, $page=0)
Get categories for a knowledgerecord object.
put($id, $request_data=null)
Update knowledgerecord.
_cleanObjectDatas($object)
Clean sensible object datas.
Class for KnowledgeRecord.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
forgeSQLFromUniversalSearchCriteria
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79