dolibarr 24.0.0-beta
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 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
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
24dol_include_once('/knowledgemanagement/class/knowledgerecord.class.php');
25dol_include_once('/categories/class/categorie.class.php');
26
27
28
42{
46 public $knowledgerecord;
47
53 public function __construct()
54 {
55 global $db, $conf;
56 $this->db = $db;
57 $this->knowledgerecord = new KnowledgeRecord($this->db);
58 }
59
73 public function get($id)
74 {
75 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read')) {
76 throw new RestException(403);
77 }
78
79 $result = $this->knowledgerecord->fetch($id);
80 if (!$result) {
81 throw new RestException(404, 'KnowledgeRecord not found');
82 }
83
84 if (!DolibarrApi::_checkAccessToResource('knowledgerecord', $this->knowledgerecord->id, 'knowledgemanagement_knowledgerecord')) {
85 throw new RestException(403, 'Access to instance id='.$this->knowledgerecord->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
86 }
87
88 return $this->_cleanObjectDatas($this->knowledgerecord);
89 }
90
104 public function getCategories($id, $sortfield = "s.rowid", $sortorder = 'ASC', $limit = 0, $page = 0)
105 {
106 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
107 throw new RestException(403);
108 }
109
110 $categories = new Categorie($this->db);
111
112 $result = $categories->getListForItem($id, 'knowledgemanagement', $sortfield, $sortorder, $limit, $page);
113
114 if ($result < 0) {
115 throw new RestException(503, 'Error when retrieve category list : '.implode(',', array_merge(array($categories->error), $categories->errors)));
116 }
117
118 return $result;
119 }
120
142 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $category = 0, $sqlfilters = '', $properties = '', $pagination_data = false)
143 {
144 $obj_ret = array();
145 $tmpobject = new KnowledgeRecord($this->db);
146
147 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read')) {
148 throw new RestException(403);
149 }
150
151 $socid = DolibarrApiAccess::$user->socid ?: 0;
152
153 $restrictonsocid = 0; // Set to 1 if there is a field socid in table of object
154
155 // If the internal user must only see his customers, force searching by him
156 $search_sale = 0;
157 if ($restrictonsocid && !DolibarrApiAccess::$user->hasRight('societe', 'client', 'voir') && !$socid) {
158 $search_sale = DolibarrApiAccess::$user->id;
159 }
160
161 $sql = "SELECT t.rowid";
162 $sql .= " FROM ".MAIN_DB_PREFIX.$tmpobject->table_element." AS t";
163 $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
164 if ($category > 0) {
165 $sql .= ", ".$this->db->prefix()."categorie_knowledgemanagement as c";
166 }
167 $sql .= " WHERE 1 = 1";
168 if ($tmpobject->ismultientitymanaged) {
169 $sql .= ' AND t.entity IN ('.getEntity($tmpobject->element).')';
170 }
171 if ($restrictonsocid && $socid) {
172 $sql .= " AND t.fk_soc = ".((int) $socid);
173 }
174 // Search on sale representative
175 if ($search_sale && $search_sale != '-1') {
176 if ($search_sale == -2) {
177 $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)";
178 } elseif ($search_sale > 0) {
179 $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).")";
180 }
181 }
182 // Select products of given category
183 if ($category > 0) {
184 $sql .= " AND c.fk_categorie = ".((int) $category);
185 $sql .= " AND c.fk_knowledgemanagement = t.rowid";
186 }
187 if ($sqlfilters) {
188 $errormessage = '';
189 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
190 if ($errormessage) {
191 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
192 }
193 }
194
195 //this query will return total orders with the filters given
196 $sqlTotals = str_replace('SELECT t.rowid', 'SELECT count(t.rowid) as total', $sql);
197
198 $sql .= $this->db->order($sortfield, $sortorder);
199 if ($limit) {
200 if ($page < 0) {
201 $page = 0;
202 }
203 $offset = $limit * $page;
204
205 $sql .= $this->db->plimit($limit + 1, $offset);
206 }
207
208 $result = $this->db->query($sql);
209 $i = 0;
210 if ($result) {
211 $num = $this->db->num_rows($result);
212 $min = min($num, ($limit <= 0 ? $num : $limit));
213 while ($i < $min) {
214 $obj = $this->db->fetch_object($result);
215 $tmp_object = new KnowledgeRecord($this->db);
216 if ($tmp_object->fetch($obj->rowid)) {
217 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($tmp_object), $properties);
218 }
219 $i++;
220 }
221 } else {
222 throw new RestException(503, 'Error when retrieving knowledgerecord list: '.$this->db->lasterror());
223 }
224
225 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
226 if ($pagination_data) {
227 $totalsResult = $this->db->query($sqlTotals);
228 $total = $this->db->fetch_object($totalsResult)->total;
229
230 $tmp = $obj_ret;
231 $obj_ret = [];
232
233 $obj_ret['data'] = $tmp;
234 $obj_ret['pagination'] = [
235 'total' => (int) $total,
236 'page' => $page, //count starts from 0
237 'page_count' => ceil((int) $total / $limit),
238 'limit' => $limit
239 ];
240 }
241
242 return $obj_ret;
243 }
244
257 public function post($request_data = null)
258 {
259 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
260 throw new RestException(403);
261 }
262
263 // Check mandatory fields
264 $result = $this->_validate($request_data);
265
266 foreach ($request_data as $field => $value) {
267 if ($field === 'caller') {
268 // 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
269 $this->knowledgerecord->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
270 continue;
271 }
272
273 $this->knowledgerecord->$field = $this->_checkValForAPI($field, $value, $this->knowledgerecord);
274 }
275
276 // Clean data
277 // $this->knowledgerecord->abc = sanitizeVal($this->knowledgerecord->abc, 'alphanohtml');
278
279 if ($this->knowledgerecord->create(DolibarrApiAccess::$user) < 0) {
280 throw new RestException(500, "Error creating KnowledgeRecord", array_merge(array($this->knowledgerecord->error), $this->knowledgerecord->errors));
281 }
282 return $this->knowledgerecord->id;
283 }
284
298 public function put($id, $request_data = null)
299 {
300 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
301 throw new RestException(403);
302 }
303
304 $result = $this->knowledgerecord->fetch($id);
305 if (!$result) {
306 throw new RestException(404, 'KnowledgeRecord not found');
307 }
308
309 if (!DolibarrApi::_checkAccessToResource('knowledgerecord', $this->knowledgerecord->id, 'knowledgemanagement_knowledgerecord')) {
310 throw new RestException(403, 'Access to instance id='.$this->knowledgerecord->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
311 }
312
313 foreach ($request_data as $field => $value) {
314 if ($field == 'id') {
315 continue;
316 }
317 if ($field === 'caller') {
318 // 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
319 $this->knowledgerecord->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
320 continue;
321 }
322
323 if ($field == 'array_options' && is_array($value)) {
324 foreach ($value as $index => $val) {
325 $this->knowledgerecord->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->knowledgerecord);
326 }
327 continue;
328 }
329
330 $this->knowledgerecord->$field = $this->_checkValForAPI($field, $value, $this->knowledgerecord);
331 }
332
333 // Clean data
334 // $this->knowledgerecord->abc = sanitizeVal($this->knowledgerecord->abc, 'alphanohtml');
335
336 if ($this->knowledgerecord->update(DolibarrApiAccess::$user, 0) > 0) {
337 return $this->get($id);
338 } else {
339 throw new RestException(500, $this->knowledgerecord->error);
340 }
341 }
342
355 public function delete($id)
356 {
357 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'delete')) {
358 throw new RestException(403);
359 }
360 $result = $this->knowledgerecord->fetch($id);
361 if (!$result) {
362 throw new RestException(404, 'KnowledgeRecord not found');
363 }
364
365 if (!DolibarrApi::_checkAccessToResource('knowledgerecord', $this->knowledgerecord->id, 'knowledgemanagement_knowledgerecord')) {
366 throw new RestException(403, 'Access to instance id='.$this->knowledgerecord->id.' of object not allowed for login '.DolibarrApiAccess::$user->login);
367 }
368
369 if (!$this->knowledgerecord->delete(DolibarrApiAccess::$user)) {
370 throw new RestException(500, 'Error when deleting KnowledgeRecord : '.$this->knowledgerecord->error);
371 }
372
373 return array(
374 'success' => array(
375 'code' => 200,
376 'message' => 'KnowledgeRecord deleted'
377 )
378 );
379 }
380
381
382 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
392 protected function _cleanObjectDatas($object)
393 {
394 // phpcs:enable
395 $object = parent::_cleanObjectDatas($object);
396
397 unset($object->rowid);
398 unset($object->canvas);
399
400 /*unset($object->name);
401 unset($object->lastname);
402 unset($object->firstname);
403 unset($object->civility_id);
404 unset($object->statut);
405 unset($object->state);
406 unset($object->state_id);
407 unset($object->state_code);
408 unset($object->region);
409 unset($object->region_code);
410 unset($object->country);
411 unset($object->country_id);
412 unset($object->country_code);
413 unset($object->barcode_type);
414 unset($object->barcode_type_code);
415 unset($object->barcode_type_label);
416 unset($object->barcode_type_coder);
417 unset($object->total_ht);
418 unset($object->total_tva);
419 unset($object->total_localtax1);
420 unset($object->total_localtax2);
421 unset($object->total_ttc);
422 unset($object->fk_account);
423 unset($object->comments);
424 unset($object->note);
425 unset($object->mode_reglement_id);
426 unset($object->cond_reglement_id);
427 unset($object->cond_reglement);
428 unset($object->shipping_method_id);
429 unset($object->fk_incoterms);
430 unset($object->label_incoterms);
431 unset($object->location_incoterms);
432 */
433
434 // If object has lines, remove $db property
435 if (isset($object->lines) && is_array($object->lines) && count($object->lines) > 0) {
436 $nboflines = count($object->lines);
437 for ($i = 0; $i < $nboflines; $i++) {
438 $this->_cleanObjectDatas($object->lines[$i]);
439
440 unset($object->lines[$i]->lines);
441 unset($object->lines[$i]->note);
442 }
443 }
444
445 return $object;
446 }
462 public function validate($id, $notrigger = 0)
463 {
464 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
465 throw new RestException(403, "Insufficiant rights");
466 }
467 $result = $this->knowledgerecord->fetch($id);
468 if (!$result) {
469 throw new RestException(404, 'knowledgerecord not found');
470 }
471
472
473 $result = $this->knowledgerecord->validate(DolibarrApiAccess::$user, $notrigger);
474 if ($result == 0) {
475 throw new RestException(304, 'Error nothing done. May be object is already validated');
476 }
477 if ($result < 0) {
478 throw new RestException(500, 'Error when validating knowledgerecord: '.$this->knowledgerecord->error);
479 }
480
481 return $this->_cleanObjectDatas($this->knowledgerecord);
482 }
483
499 public function cancel($id, $notrigger = 0)
500 {
501 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'write')) {
502 throw new RestException(403, "Insufficiant rights");
503 }
504 $result = $this->knowledgerecord->fetch($id);
505 if (!$result) {
506 throw new RestException(404, 'knowledgerecord not found');
507 }
508
509
510 $result = $this->knowledgerecord->cancel(DolibarrApiAccess::$user, $notrigger);
511 if ($result == 0) {
512 throw new RestException(304, 'Error nothing done. May be object is already validated');
513 }
514 if ($result < 0) {
515 throw new RestException(500, 'Error when validating knowledgerecord: '.$this->knowledgerecord->error);
516 }
517
518 return $this->_cleanObjectDatas($this->knowledgerecord);
519 }
520
529 private function _validate($data)
530 {
531 if ($data === null) {
532 $data = array();
533 }
534 $knowledgerecord = array();
535 foreach ($this->knowledgerecord->fields as $field => $propfield) {
536 if (in_array($field, array('rowid', 'entity', 'ref', 'date_creation', 'tms', 'fk_user_creat')) || empty($propfield['notnull']) || $propfield['notnull'] != 1) {
537 continue; // Not a mandatory field
538 }
539 if (!isset($data[$field])) {
540 throw new RestException(400, "$field field missing");
541 }
542 $knowledgerecord[$field] = $data[$field];
543 }
544 return $knowledgerecord;
545 }
546}
$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 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.
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.
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 @phpstan-template T.
Class for KnowledgeRecord.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.