dolibarr 25.0.0-alpha
api_websites.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2026 Laurent Destailleur <eldy@users.sourceforge.net>
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 3 of the License, or
7 * (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16 */
17
18use Luracast\Restler\RestException;
19
20require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
21require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
22require_once DOL_DOCUMENT_ROOT.'/core/lib/website.lib.php';
23require_once DOL_DOCUMENT_ROOT.'/core/lib/website2.lib.php';
24
37class Websites extends DolibarrApi
38{
42 public $website;
43
47 public $websitepage;
48
52 public function __construct()
53 {
54 global $db;
55
56 $this->db = $db;
57 $this->website = new Website($this->db);
58 $this->websitepage = new WebsitePage($this->db);
59 }
60
76 public function get($id)
77 {
78 return $this->_fetchWebsite($id);
79 }
80
96 public function getByRef($ref)
97 {
98 return $this->_fetchWebsite(0, $ref);
99 }
100
120 public function index($sortfield = "t.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
121 {
122 if (!DolibarrApiAccess::$user->hasRight('website', 'read')) {
123 throw new RestException(403);
124 }
125
126 $obj_ret = array();
127
128 $sql = "SELECT t.rowid, t.ref";
129 $sql .= " FROM ".$this->db->prefix()."website as t";
130 $sql .= " WHERE t.entity IN (".getEntity('website').")";
131
132 // Add sql filters
133 if ($sqlfilters) {
134 $errormessage = '';
135 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
136 if ($errormessage) {
137 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
138 }
139 }
140
141 $sqlTotals = str_replace('SELECT t.rowid, t.ref', 'SELECT count(t.rowid) as total', $sql);
142
143 $sql .= $this->db->order($sortfield, $sortorder);
144 if ($limit) {
145 if ($page < 0) {
146 $page = 0;
147 }
148 $offset = $limit * $page;
149 $sql .= $this->db->plimit($limit + 1, $offset);
150 }
151
152 $result = $this->db->query($sql);
153 if ($result) {
154 $num = $this->db->num_rows($result);
155 $min = min($num, ($limit <= 0 ? $num : $limit));
156 $i = 0;
157 while ($i < $min) {
158 $obj = $this->db->fetch_object($result);
159 $website_static = new Website($this->db);
160 if ($website_static->fetch($obj->rowid)) {
161 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($website_static), $properties);
162 }
163 $i++;
164 }
165 } else {
166 throw new RestException(503, 'Error when retrieve website list : '.$this->db->lasterror());
167 }
168
169 // If pagination data is requested (page > 0), the response will contain element data with all values and element pagination with pagination data
170 if ($page > 0) {
171 $totalsResult = $this->db->query($sqlTotals);
172 $total = $this->db->fetch_object($totalsResult)->total;
173
174 $tmp = $obj_ret;
175 $obj_ret = array();
176
177 $obj_ret['data'] = $tmp;
178 $obj_ret['pagination'] = array(
179 'total' => (int) $total,
180 'page' => $page,
181 'page_count' => (int) ceil((int) $total / $limit),
182 'limit' => $limit
183 );
184 }
185
186 return $obj_ret;
187 }
188
212 public function indexPages($id, $sortfield = "t.pageurl", $sortorder = 'ASC', $limit = 100, $page = 0, $sqlfilters = '', $properties = '')
213 {
214 if (!DolibarrApiAccess::$user->hasRight('website', 'read')) {
215 throw new RestException(403);
216 }
217
218 $result = $this->website->fetch($id);
219 if (!$result) {
220 throw new RestException(404, 'Website not found');
221 }
222
223 if (!DolibarrApi::_checkAccessToResource('website', $this->website->id)) {
224 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
225 }
226
227 $obj_ret = array();
228
229 $sql = "SELECT t.rowid, t.pageurl";
230 $sql .= " FROM ".$this->db->prefix()."website_page as t";
231 $sql .= " WHERE t.fk_website = ".((int) $id);
232
233 // Add sql filters
234 if ($sqlfilters) {
235 $errormessage = '';
236 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
237 if ($errormessage) {
238 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
239 }
240 }
241
242 $sqlTotals = str_replace('SELECT t.rowid, t.pageurl', 'SELECT count(t.rowid) as total', $sql);
243
244 $sql .= $this->db->order($sortfield, $sortorder);
245 if ($limit) {
246 if ($page < 0) {
247 $page = 0;
248 }
249 $offset = $limit * $page;
250 $sql .= $this->db->plimit($limit + 1, $offset);
251 }
252
253 $result = $this->db->query($sql);
254 if ($result) {
255 $num = $this->db->num_rows($result);
256 $min = min($num, ($limit <= 0 ? $num : $limit));
257 $i = 0;
258 while ($i < $min) {
259 $obj = $this->db->fetch_object($result);
260 $page_static = new WebsitePage($this->db);
261 if ($page_static->fetch($obj->rowid)) {
262 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($page_static), $properties);
263 }
264 $i++;
265 }
266 } else {
267 throw new RestException(503, 'Error when retrieve page list : '.$this->db->lasterror());
268 }
269
270 if ($page > 0) {
271 $totalsResult = $this->db->query($sqlTotals);
272 $total = $this->db->fetch_object($totalsResult)->total;
273
274 $tmp = $obj_ret;
275 $obj_ret = array();
276
277 $obj_ret['data'] = $tmp;
278 $obj_ret['pagination'] = array(
279 'total' => (int) $total,
280 'page' => $page,
281 'page_count' => (int) ceil((int) $total / $limit),
282 'limit' => $limit
283 );
284 }
285
286 return $obj_ret;
287 }
288
305 public function getPage($id, $pageid)
306 {
307 if (!DolibarrApiAccess::$user->hasRight('website', 'read')) {
308 throw new RestException(403);
309 }
310
311 $result = $this->website->fetch($id);
312 if (!$result) {
313 throw new RestException(404, 'Website not found');
314 }
315
316 if (!DolibarrApi::_checkAccessToResource('website', $this->website->id)) {
317 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
318 }
319
320 $result = $this->websitepage->fetch($pageid);
321 if (!$result) {
322 throw new RestException(404, 'Page not found');
323 }
324
325 // Check that the page belongs to the website
326 if ($this->websitepage->fk_website != $this->website->id) {
327 throw new RestException(404, 'Page not found for this website');
328 }
329
330 return $this->_cleanObjectDatas($this->websitepage);
331 }
332
353 public function postPage($id, $request_data = null)
354 {
355 if (!DolibarrApiAccess::$user->hasRight('website', 'write')) {
356 throw new RestException(403);
357 }
358
359 $result = $this->website->fetch($id);
360 if ($result <= 0) {
361 throw new RestException(404, 'Website not found');
362 }
363
364 if (!DolibarrApi::_checkAccessToResource('website', $this->website->id)) {
365 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
366 }
367
368 $this->websitepage = new WebsitePage($this->db);
369
370 // Apply request data to the page object
371 foreach ((array) $request_data as $field => $value) {
372 if ($field == 'id' || $field == 'rowid' || $field == 'fk_website') {
373 continue;
374 }
375 if ($field == 'image') {
376 continue; // The image used by the CMS is the one found into the content
377 }
378 if ($field === 'caller') {
379 $this->websitepage->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
380 continue;
381 }
382 if ($field == 'array_options' && is_array($value)) {
383 foreach ($value as $index => $val) {
384 $this->websitepage->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->websitepage);
385 }
386 continue;
387 }
388 $this->websitepage->$field = $this->_checkValForAPI($field, $value, $this->websitepage);
389 }
390
391 $this->websitepage->fk_website = $this->website->id;
392 if (empty($this->websitepage->type_container)) {
393 $this->websitepage->type_container = 'page';
394 }
395 if (!isset($request_data['status'])) {
396 $this->websitepage->status = WebsitePage::STATUS_DRAFT;
397 }
398 if (is_null($this->websitepage->aliasalt)) {
399 $this->websitepage->aliasalt = ''; // Field is notnull (same default as web interface)
400 }
401 $this->websitepage->pageurl = preg_replace('/\.php$/i', '', trim((string) $this->websitepage->pageurl));
402 $this->websitepage->ref = $this->websitepage->pageurl;
403
404 // Check mandatory fields (same rules than web interface)
405 if (empty($this->websitepage->pageurl)) {
406 throw new RestException(400, 'Field pageurl is mandatory');
407 }
408 if (!preg_match('/^[a-z0-9\-\_]+$/i', $this->websitepage->pageurl) || preg_match('/^page\d+/i', $this->websitepage->pageurl)) {
409 throw new RestException(400, 'Field pageurl must contain only a-z, 0-9, - and _ characters and must not be pageX');
410 }
411 if (empty($this->websitepage->title)) {
412 throw new RestException(400, 'Field title is mandatory');
413 }
414
415 // Check there is no other page with the same name or alias
416 $websitepagetemp = new WebsitePage($this->db);
417 $result = $websitepagetemp->fetch(0, (string) $this->website->id, $this->websitepage->pageurl);
418 if ($result < 0) {
419 throw new RestException(500, $websitepagetemp->errorsToString());
420 }
421 if ($result > 0) {
422 throw new RestException(409, 'A page with this pageurl already exists in this website');
423 }
424
425 // Security: check PHP content is allowed, with same rules than web editor
426 $phpfullcodestringold = '';
427 $phpfullcodestring = dolKeepOnlyPhpCode((string) $this->websitepage->content);
428 if (checkPHPCode($phpfullcodestringold, $phpfullcodestring)) { // Contains the setEventMessages
429 throw new RestException(403, 'NotAllowedToAddDynamicContent');
430 }
431
432 // Clean data: remove head section from content (same as web interface)
433 $this->websitepage->content = preg_replace('/<head>.*<\/head>/ims', '', (string) $this->websitepage->content);
434
435 // A blog post gets the header and footer containers of its language, and its structured data
436 $phpwrappers = array();
437 if ($this->websitepage->type_container == 'blogpost') {
438 $phpwrappers = $this->_addBlogpostWrappers($this->website, $this->websitepage);
439 }
440
441 // Create the page in database
442 $pageid = $this->websitepage->create(DolibarrApiAccess::$user, 0, $phpwrappers);
443 if ($pageid <= 0) {
444 throw new RestException(500, $this->websitepage->errorsToString());
445 }
446
447 // Regenerate static files on disk (same as web interface in index.php)
448 $this->_regeneratePageFiles($this->website, $this->websitepage);
449
450 // If there is no home page yet, this new page is set as the home page (same as web interface)
451 if (empty($this->website->fk_default_home)) {
452 $this->website->fk_default_home = $pageid;
453 $result = $this->website->update(DolibarrApiAccess::$user);
454 if ($result > 0) {
455 global $conf, $dolibarr_main_data_root;
456
457 $pathofwebsite = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$this->website->ref;
458 dolSaveIndexPage($pathofwebsite, $pathofwebsite.'/index.php', $pathofwebsite.'/page'.$pageid.'.tpl.php', $pathofwebsite.'/wrapper.php', $this->website);
459 } else {
460 dol_syslog("Failed to set the default home page of website ".$this->website->ref, LOG_WARNING);
461 }
462 }
463
464 return $pageid;
465 }
466
488 public function putPage($id, $pageid, $request_data = null)
489 {
490 if (!DolibarrApiAccess::$user->hasRight('website', 'write')) {
491 throw new RestException(403);
492 }
493
494 $result = $this->website->fetch($id);
495 if (!$result) {
496 throw new RestException(404, 'Website not found');
497 }
498
499 if (!DolibarrApi::_checkAccessToResource('website', $this->website->id)) {
500 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
501 }
502
503 $result = $this->websitepage->fetch($pageid);
504 if (!$result) {
505 throw new RestException(404, 'Page not found');
506 }
507
508 // Check that the page belongs to the website
509 if ($this->websitepage->fk_website != $this->website->id) {
510 throw new RestException(404, 'Page not found for this website');
511 }
512
513 // Keep the old PHP content to detect if PHP content changed
514 $phpfullcodestringold = dolKeepOnlyPhpCode($this->websitepage->content);
515
516 // Apply request data to the page object
517 foreach ($request_data as $field => $value) {
518 if ($field == 'id' || $field == 'rowid') {
519 continue;
520 }
521 if ($field == 'image') {
522 continue; // The image used by the CMS is the one found into the content
523 }
524 if ($field == 'fk_website') {
525 // Do not allow changing the website ownership of a page via this endpoint
526 continue;
527 }
528 if ($field === 'caller') {
529 $this->websitepage->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
530 continue;
531 }
532 if ($field == 'array_options' && is_array($value)) {
533 foreach ($value as $index => $val) {
534 $this->websitepage->array_options[$index] = $this->_checkValExtrafieldsForAPI($index, $val, $this->websitepage);
535 }
536 continue;
537 }
538 $this->websitepage->$field = $this->_checkValForAPI($field, $value, $this->websitepage);
539 }
540
541 // Security: check PHP content is allowed, with same rules than web editor
542 // (checkPHPCode checks the permission website->writephp if PHP content has changed and
543 // checks the global option dolibarr_website_allow_custom_php and the forbidden PHP functions list)
544 $phpfullcodestring = dolKeepOnlyPhpCode($this->websitepage->content);
545 if (checkPHPCode($phpfullcodestringold, $phpfullcodestring)) { // Contains the setEventMessages
546 throw new RestException(403, 'NotAllowedToAddDynamicContent');
547 }
548
549 // Clean data: remove head section from content (same as web interface)
550 $this->websitepage->content = preg_replace('/<head>.*<\/head>/ims', '', $this->websitepage->content);
551
552 // Update the page in database
553 $result = $this->websitepage->update(DolibarrApiAccess::$user);
554 if ($result < 0) {
555 throw new RestException(500, $this->websitepage->errorsToString());
556 }
557
558 // Regenerate static files on disk (same as web interface in index.php)
559 $this->_regeneratePageFiles($this->website, $this->websitepage);
560
561 return $this->_cleanObjectDatas($this->websitepage);
562 }
563
564 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
575 protected function _cleanObjectDatas($object)
576 {
577 // phpcs:enable
578 $object = parent::_cleanObjectDatas($object);
579
580 // Remove properties not relevant for the website API response and not already cleaned by the parent
581 unset($object->canvas);
582 unset($object->name);
583 unset($object->lastname);
584 unset($object->firstname);
585 unset($object->civility_id);
586 unset($object->statut);
587 unset($object->region_id);
588 unset($object->state_id);
589 unset($object->country_id);
590 unset($object->country_code);
591 unset($object->barcode_type);
592 unset($object->barcode_type_coder);
593 unset($object->total_ht);
594 unset($object->total_tva);
595 unset($object->total_localtax1);
596 unset($object->total_localtax2);
597 unset($object->total_ttc);
598 unset($object->user);
599 unset($object->fk_account);
600 unset($object->shipping_method_id);
601 unset($object->fk_incoterms);
602 unset($object->label_incoterms);
603 unset($object->location_incoterms);
604 unset($object->multicurrency_code);
605 unset($object->multicurrency_tx);
606 unset($object->multicurrency_total_ht);
607 unset($object->multicurrency_total_ttc);
608 unset($object->multicurrency_total_tva);
609 unset($object->multicurrency_total_localtax1);
610 unset($object->multicurrency_total_localtax2);
611
612 unset($object->mode_reglement_id);
613 unset($object->cond_reglement_id);
614 unset($object->demand_reason_id);
615 unset($object->transport_mode_id);
616 unset($object->shipping_method);
617 unset($object->model_pdf);
618 unset($object->last_main_doc);
619 unset($object->lines);
620 unset($object->actiontypecode);
621 unset($object->civility_code);
622 unset($object->date_cloture);
623 unset($object->user_closing_id);
624 unset($object->totalpaid);
625 unset($object->totalpaid_multicurrency);
626 unset($object->cond_reglement_supplier_id);
627 unset($object->deposit_percent);
628 unset($object->warehouse_id);
629 unset($object->array_languages);
630 unset($object->contacts_ids);
631 unset($object->contacts_ids_internal);
632 unset($object->other_linked_objects);
633 unset($object->linkedObjectsIds);
634 unset($object->origin_type);
635 unset($object->origin_id);
636 unset($object->product);
637 unset($object->fk_project);
638 unset($object->contact_id);
639 unset($object->validation);
640 unset($object->user_validation_id);
641 unset($object->tms);
642
643 return $object;
644 }
645
659 private function _fetchWebsite($id, $ref = '')
660 {
661 if (empty($id) && empty($ref)) {
662 throw new RestException(400, 'bad value for parameter id or ref');
663 }
664
665 if (!DolibarrApiAccess::$user->hasRight('website', 'read')) {
666 throw new RestException(403);
667 }
668
669 $result = $this->website->fetch($id, $ref);
670 if (!$result) {
671 throw new RestException(404, 'Website not found');
672 }
673
674 if (!DolibarrApi::_checkAccessToResource('website', $this->website->id)) {
675 throw new RestException(403, 'Access not allowed for login '.DolibarrApiAccess::$user->login);
676 }
677
678 return $this->_cleanObjectDatas($this->website);
679 }
680
689 private function _addBlogpostWrappers($website, $websitepage)
690 {
691 dol_syslog("_addBlogpostWrappers");
692
693 $pagelang = (string) (empty($websitepage->lang) ? $website->lang : $websitepage->lang);
694
695 $websitepagetemp = new WebsitePage($this->db);
696 $containers = $websitepagetemp->fetchAll($website->id, '', '', 0, 0, "((t.type_container:=:'header') OR (t.type_container:=:'footer'))");
697 if (!is_array($containers)) {
698 throw new RestException(500, $websitepagetemp->errorsToString());
699 }
700
701 // Keep the containers of the language of the post (an empty language is the main language of the website)
702 $found = array('header' => array(), 'footer' => array());
703 foreach ($containers as $container) {
704 $containerlang = (string) (empty($container->lang) ? $website->lang : $container->lang);
705 if ($containerlang == $pagelang) {
706 $found[$container->type_container][] = $container->pageurl;
707 }
708 }
709
710 $phpwrappers = array();
711
712 $content = (string) $websitepage->content;
713 if (count($found['header']) == 1 && strpos($content, "includeContainer('".$found['header'][0]."')") === false) {
714 $wrapper = "<?php includeContainer('".$found['header'][0]."'); ?>\n";
715 $content = $wrapper.$content;
716 $phpwrappers[] = $wrapper;
717 }
718 if (count($found['footer']) == 1 && strpos($content, "includeContainer('".$found['footer'][0]."')") === false) {
719 $wrapper = "\n<?php includeContainer('".$found['footer'][0]."'); ?>\n";
720 $content .= $wrapper;
721 $phpwrappers[] = $wrapper;
722 }
723
724 $websitepage->content = $content;
725
726 return $phpwrappers;
727 }
728
738 private function _regeneratePageFiles($website, $websitepage)
739 {
740 global $conf;
741 global $dolibarr_main_data_root;
742
743 $pathofwebsite = $dolibarr_main_data_root.($conf->entity > 1 ? '/'.$conf->entity : '').'/website/'.$website->ref;
744
745 $filemaster = $pathofwebsite.'/master.inc.php';
746 $filealias = $pathofwebsite.'/'.$websitepage->pageurl.'.php';
747 $filetpl = $pathofwebsite.'/page'.$websitepage->id.'.tpl.php';
748
749 dol_mkdir($pathofwebsite);
750
751 // Regenerate the master.inc.php
752 $result = dolSaveMasterFile($filemaster);
753 if (!$result) {
754 dol_syslog("Failed to write the master file ".$filemaster, LOG_WARNING);
755 }
756
757 // Save page alias
758 $result = dolSavePageAlias($filealias, $website, $websitepage);
759 if (!$result) {
760 dol_syslog("Failed to write the alias file ".basename($filealias), LOG_WARNING);
761 }
762
763 // Save page content (the .tpl.php file)
764 $result = dolSavePageContent($filetpl, $website, $websitepage, 1);
765 if (!$result) {
766 dol_syslog("Failed to write the tpl file ".$filetpl, LOG_WARNING);
767 }
768 }
769}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class for API REST v1.
Definition api.class.php:35
__construct($db, $cachedir='', $refreshCache=false)
Constructor.
Definition api.class.php:53
_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.
_cleanObjectDatas($object)
Clean sensitive object data @phpstan-template T.
static _checkAccessToResource($resource, $resource_id=0, $dbtablename='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $parenttableforentity='')
Check access by user to a given resource.
Class Website.
dolKeepOnlyPhpCode($str)
Keep only PHP code part from a HTML string page.
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.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dolSaveMasterFile($filemaster)
Save content of a page on disk.
checkPHPCode(&$phpfullcodestringold, &$phpfullcodestring)
Check that the new string $phpfullcodestring contains only php code (including <php tag)
dolSaveIndexPage($pathofwebsite, $fileindex, $filetpl, $filewrapper, $object=null)
Save content of the index.php and/or the wrapper.php page.
dolSavePageAlias($filealias, $object, $objectpage)
Save an alias page on disk (A page that include the reference page).
dolSavePageContent($filetpl, Website $object, WebsitePage $objectpage, $backupold=0)
Save content of a page on disk (page name is generally ID_of_page.php).