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