dolibarr 25.0.0-alpha
api_documents.class.php
1<?php
2
3/* Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
4 * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2016 Jean-François Ferry <jfefe@aternatik.fr>
6 * Copyright (C) 2023 Romain Neil <contact@romain-neil.fr>
7 * Copyright (C) 2024-2025 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2025-2026 MDW <mdeweerd@users.noreply.github.com>
9 * Copyright (C) 2025 William Mead <william@m34d.com>
10 * Copyright (C) 2025-2026 Charlene Benke <charlene@patas-monkey.com>
11 * Copyright (C) 2026 Nick Fragoulis
12 *
13 * This program is free software you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
27use Luracast\Restler\RestException;
28
29require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
30require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
31require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
32
42{
46 public function __construct()
47 {
48 global $db;
49 $this->db = $db;
50 }
51
52
73 public function index($modulepart, $original_file = '')
74 {
75 global $conf;
76
77 if (empty($modulepart)) {
78 throw new RestException(400, 'bad value for parameter modulepart');
79 }
80 if (empty($original_file)) {
81 throw new RestException(400, 'bad value for parameter original_file');
82 }
83
84 // Normalize modulepart for project_task
85 if ($modulepart == 'task' || $modulepart == 'project_task') {
86 $modulepart = 'project_task';
87 }
88
89 //--- Finds and returns the document
90 $entity = $conf->entity;
91
92 // Special cases that need to use get_exdir to get real dir of object
93 // If future, all object should use this to define path of documents.
94 /*
95 $tmpreldir = '';
96 if ($modulepart == 'supplier_invoice') {
97 $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
98 }
99
100 $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
101 $relativefile = $original_file;
102
103 $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
104 $accessallowed = $check_access['accessallowed'];
105 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
106 $original_file = $check_access['original_file'];
107
108 if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
109 throw new RestException(403);
110 }
111 if (!$accessallowed) {
112 throw new RestException(403);
113 }
114 // Check permission on the object the document is attached to (thirdparties of a restricted sales representative, ...)
115 if (!checkUserAccessToDocumentObject(DolibarrApiAccess::$user, $modulepart, $relativefile, 'read')) {
116 throw new RestException(403, 'Access not allowed to the object of this document');
117 }
118
119 if (DolibarrApiAccess::$user->socid > 0) {
120 if ($sqlprotectagainstexternals) {
121 $resql = $this->db->query($sqlprotectagainstexternals);
122 if ($resql) {
123 $num = $this->db->num_rows($resql);
124 $i = 0;
125 while ($i < $num) {
126 $obj = $this->db->fetch_object($resql);
127 if (DolibarrApiAccess::$user->socid != $obj->fk_soc) {
128 throw new RestException(403, 'Not allowed to download documents with such a ref');
129 }
130 $i++;
131 }
132 }
133 }
134 }
135
136 $filename = basename($original_file);
137 $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
138
139 if (!file_exists($original_file_osencoded)) {
140 dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
141 throw new RestException(404, 'File not found');
142 }
143
144 $file_content = file_get_contents($original_file_osencoded);
145 return array('filename' => $filename, 'content-type' => dol_mimetype($filename), 'filesize' => filesize($original_file), 'content' => base64_encode($file_content), 'encoding' => 'base64');
146 }
147
148
179 public function builddoc($modulepart, $original_file = '', $doctemplate = '', $langcode = '')
180 {
181 global $conf, $langs;
182
183 if (empty($modulepart)) {
184 throw new RestException(400, 'bad value for parameter modulepart');
185 }
186 if (empty($original_file)) {
187 throw new RestException(400, 'bad value for parameter original_file');
188 }
189
190 $outputlangs = $langs;
191 if ($langcode && $langs->defaultlang != $langcode) {
192 $outputlangs = new Translate('', $conf);
193 $outputlangs->setDefaultLang($langcode);
194 }
195
196 //--- Finds and returns the document
197 $entity = $conf->entity;
198
199 // Special cases that need to use get_exdir to get real dir of object
200 // If future, all object should use this to define path of documents.
201 /*
202 $tmpreldir = '';
203 if ($modulepart == 'supplier_invoice') {
204 $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
205 }
206
207 $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
208 $relativefile = $original_file;
209
210 $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
211 $accessallowed = $check_access['accessallowed'];
212 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
213 $original_file = $check_access['original_file'];
214
215 if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
216 throw new RestException(403);
217 }
218 if (!$accessallowed) {
219 throw new RestException(403);
220 }
221 // Check permission on the object the document is attached to (thirdparties of a restricted sales representative, ...)
222 if (!checkUserAccessToDocumentObject(DolibarrApiAccess::$user, $modulepart, $relativefile, 'write')) {
223 throw new RestException(403, 'Access not allowed to the object of this document');
224 }
225
226 if (DolibarrApiAccess::$user->socid > 0) {
227 if ($sqlprotectagainstexternals) {
228 $resql = $this->db->query($sqlprotectagainstexternals);
229 if ($resql) {
230 $num = $this->db->num_rows($resql);
231 $i = 0;
232 while ($i < $num) {
233 $obj = $this->db->fetch_object($resql);
234 if (DolibarrApiAccess::$user->socid != $obj->fk_soc) {
235 throw new RestException(403, 'Not allowed to download documents with such a ref');
236 }
237 $i++;
238 }
239 }
240 }
241 }
242
243 // --- Generates the document
244 $hidedetails = !getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 0 : 1;
245 $hidedesc = !getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 0 : 1;
246 $hideref = !getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 0 : 1;
247
248 $templateused = '';
249
250 if ($modulepart == 'facture' || $modulepart == 'invoice') {
251 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
252 $tmpobject = new Facture($this->db);
253 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
254 if (!$result) {
255 throw new RestException(404, 'Invoice not found');
256 }
257
258 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
259 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
260 if ($result <= 0) {
261 throw new RestException(500, 'Error generating document');
262 }
263 } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') {
264 require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
265 $tmpobject = new FactureFournisseur($this->db);
266 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
267 if (!$result) {
268 throw new RestException(404, 'Supplier invoice not found');
269 }
270
271 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
272 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
273 if ($result < 0) {
274 throw new RestException(500, 'Error generating document');
275 }
276 } elseif ($modulepart == 'commande' || $modulepart == 'order') {
277 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
278 $tmpobject = new Commande($this->db);
279 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
280 if (!$result) {
281 throw new RestException(404, 'Order not found');
282 }
283 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
284 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
285 if ($result <= 0) {
286 throw new RestException(500, 'Error generating document');
287 }
288 } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
289 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
290 $tmpobject = new Propal($this->db);
291 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
292 if (!$result) {
293 throw new RestException(404, 'Proposal not found');
294 }
295 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
296 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
297 if ($result <= 0) {
298 throw new RestException(500, 'Error generating document');
299 }
300 } elseif ($modulepart == 'contrat' || $modulepart == 'contract') {
301 require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
302
303 $tmpobject = new Contrat($this->db);
304 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
305
306 if (!$result) {
307 throw new RestException(404, 'Contract not found');
308 }
309
310 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
311 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
312
313 if ($result <= 0) {
314 throw new RestException(500, 'Error generating document');
315 }
316 } elseif ($modulepart == 'expedition' || $modulepart == 'shipment') {
317 require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
318
319 $tmpobject = new Expedition($this->db);
320 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
321
322 if (!$result) {
323 throw new RestException(404, 'Shipment not found');
324 }
325
326 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
327 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
328
329 if ($result <= 0) {
330 throw new RestException(500, 'Error generating document');
331 }
332 } elseif ($modulepart == 'mrp') {
333 require_once DOL_DOCUMENT_ROOT . '/mrp/class/mo.class.php';
334
335 $tmpobject = new Mo($this->db);
336 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
337
338 if (!$result) {
339 throw new RestException(404, 'MO not found');
340 }
341
342 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
343 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
344
345 if ($result <= 0) {
346 throw new RestException(500, 'Error generating document');
347 }
348 } elseif ($modulepart == 'expensereport') {
349 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
350
351 $tmpobject = new ExpenseReport($this->db);
352 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
353
354 if (!$result) {
355 throw new RestException(404, 'Expense report not found');
356 }
357
358 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
359 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
360
361 if ($result <= 0) {
362 throw new RestException(500, 'Error generating document');
363 }
364 } elseif ($modulepart == 'holiday') {
365 require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
366
367 $tmpobject = new Holiday($this->db);
368 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
369
370 if (!$result) {
371 throw new RestException(404, 'Holiday not found');
372 }
373
374 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
375 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
376
377 if ($result <= 0) {
378 throw new RestException(500, 'Error generating document');
379 }
380 } elseif ($modulepart == 'product') {
381 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
382
383 $tmpobject = new Product($this->db);
384 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
385
386 if (!$result) {
387 throw new RestException(404, 'Product not found');
388 }
389
390 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
391 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
392
393 if ($result <= 0) {
394 throw new RestException(500, 'Error generating document');
395 }
396 } elseif ($modulepart == 'stock' || $modulepart == 'entrepot') {
397 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
398
399 $tmpobject = new Entrepot($this->db);
400 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
401
402 if (!$result) {
403 throw new RestException(404, 'Warehouse not found');
404 }
405
406 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
407 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
408
409 if ($result <= 0) {
410 throw new RestException(500, 'Error generating document');
411 }
412 } elseif ($modulepart == 'fichinter' || $modulepart == 'intervention') {
413 require_once DOL_DOCUMENT_ROOT . '/fichinter/class/fichinter.class.php';
414
415 $tmpobject = new Fichinter($this->db);
416 $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
417
418 if (!$result) {
419 throw new RestException(404, 'Intervention not found');
420 }
421
422 $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
423 $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
424
425 if ($result <= 0) {
426 throw new RestException(500, 'Error generating document');
427 }
428 } else {
429 throw new RestException(403, 'Generation not available for this modulepart');
430 }
431
432 $filename = basename($original_file);
433 $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
434
435 if (!file_exists($original_file_osencoded)) {
436 throw new RestException(404, 'File not found');
437 }
438
439 $file_content = file_get_contents($original_file_osencoded);
440 return array('filename' => $filename, 'content-type' => dol_mimetype($filename), 'filesize' => filesize($original_file), 'content' => base64_encode($file_content), 'langcode' => $outputlangs->defaultlang, 'template' => $templateused, 'encoding' => 'base64');
441 }
442
472 public function getDocumentsListByElement($modulepart, $id = 0, $ref = '', $sortfield = '', $sortorder = '', $limit = 100, $page = 0, $content_type = '', $pagination_data = false)
473 {
474 if (empty($modulepart)) {
475 throw new RestException(400, 'bad value for parameter modulepart');
476 }
477
478 if (empty($id) && empty($ref)) {
479 throw new RestException(400, 'bad value for parameter id or ref');
480 }
481
482 $id = (empty($id) ? 0 : $id);
483
484 if ($modulepart == 'facture_fournisseur') {
485 $modulepart = 'supplier_invoice'; // Alias unknown by fetchObjectByElement()
486 }
487
488 // Define $object
489 $object = fetchObjectByElement($id, $modulepart, $ref); // Note that we don't mind id and ref, we want to get a valid instantiated $object but not necessarily initialized
490 if (!is_object($object)) {
491 throw new RestException(404, 'Module for modulepart = '.$modulepart." is not enabled (or not yet supported by API");
492 }
493
494 // Define $upload_dir to scan
495 if ($object->element == 'invoice_supplier' && $object->id > 0) {
496 // Supplier invoices are stored under a hashed subdir, as in the other methods of this file
497 $upload_dir = getMultidirOutput($object).'/'.get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
498 } else {
499 $upload_dir = (string) getMultidirOutput($object, '', 1);
500 }
501
502 // Check object-level permissions
503 $ok = checkUserAccessToObject(DolibarrApiAccess::$user, array($object->element), $object, $object->table_element, '');
504 if (empty($ok)) {
505 throw new RestException(403, 'Access not allowed to this object (refused by checkUserAccessToObject)');
506 }
507
508 // Check permission on module
509 if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
510 if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
511 throw new RestException(403);
512 }
513 } elseif ($modulepart == 'user') {
514 // Can get doc if has permission to read all user or if it is user itself
515 if (!DolibarrApiAccess::$user->hasRight('user', 'user', 'lire') && DolibarrApiAccess::$user->id != $id) {
516 throw new RestException(403);
517 }
518 } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
519 if (!DolibarrApiAccess::$user->hasRight('adherent', 'lire')) {
520 throw new RestException(403);
521 }
522 } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
523 if (!DolibarrApiAccess::$user->hasRight('propal', 'lire')) {
524 throw new RestException(403);
525 }
526 } elseif ($modulepart == 'supplier_proposal') {
527 if (!DolibarrApiAccess::$user->hasRight('supplier_proposal', 'read')) {
528 throw new RestException(403);
529 }
530 } elseif ($modulepart == 'commande' || $modulepart == 'order') {
531 if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
532 throw new RestException(403);
533 }
534 } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
535 $modulepart = 'supplier_order';
536 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'commande', 'lire') && !DolibarrApiAccess::$user->hasRight('supplier_order', 'lire')) {
537 throw new RestException(403);
538 }
539 } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
540 if (!DolibarrApiAccess::$user->hasRight('expedition', 'lire')) {
541 throw new RestException(403);
542 }
543 } elseif ($modulepart == 'reception') {
544 if (!DolibarrApiAccess::$user->hasRight('reception', 'lire')) {
545 throw new RestException(403);
546 }
547 } elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
548 if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
549 throw new RestException(403);
550 }
551 } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
552 $modulepart = 'supplier_invoice';
553 if (!DolibarrApiAccess::$user->hasRight('fournisseur', 'facture', 'lire') && !DolibarrApiAccess::$user->hasRight('supplier_invoice', 'lire')) {
554 throw new RestException(403);
555 }
556 } elseif ($modulepart == 'produit' || $modulepart == 'product' || $modulepart == 'service') {
557 if (!DolibarrApiAccess::$user->hasRight('produit', 'lire')) {
558 throw new RestException(403);
559 }
560 } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event' || $modulepart == 'actioncomm') {
561 if (!DolibarrApiAccess::$user->hasRight('agenda', 'myactions', 'read') && !DolibarrApiAccess::$user->hasRight('agenda', 'allactions', 'read')) {
562 throw new RestException(403);
563 }
564 } elseif ($modulepart == 'expensereport') {
565 if (!DolibarrApiAccess::$user->hasRight('expensereport', 'read')) {
566 throw new RestException(403);
567 }
568 } elseif ($modulepart == 'holiday') {
569 if (!DolibarrApiAccess::$user->hasRight('holiday', 'read')) {
570 throw new RestException(403);
571 }
572 } elseif ($modulepart == 'ticket') {
573 if (!DolibarrApiAccess::$user->hasRight('ticket', 'read')) {
574 throw new RestException(403);
575 }
576 } elseif ($modulepart == 'knowledgemanagement') {
577 if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read')) {
578 throw new RestException(403);
579 }
580 } elseif ($modulepart == 'categorie' || $modulepart == 'category') {
581 if (!DolibarrApiAccess::$user->hasRight('categorie', 'lire')) {
582 throw new RestException(403);
583 }
584 } elseif ($modulepart == 'ecm') {
585 throw new RestException(500, 'Modulepart Ecm not implemented yet.');
586 // if (!DolibarrApiAccess::$user->hasRight('ecm', 'read')) {
587 // throw new RestException(403);
588 // }
589 } elseif ($modulepart == 'contrat' || $modulepart == 'contract') {
590 $modulepart = 'contrat';
591 if (!DolibarrApiAccess::$user->hasRight('contrat', 'lire')) {
592 throw new RestException(403);
593 }
594 } elseif ($modulepart == 'intervention' || $modulepart == 'ficheinter') {
595 $modulepart = 'ficheinter';
596 if (!DolibarrApiAccess::$user->hasRight('ficheinter', 'lire')) {
597 throw new RestException(403);
598 }
599 } elseif ($modulepart == 'projet' || $modulepart == 'project') {
600 $modulepart = 'project';
601 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
602 throw new RestException(403);
603 }
604 } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
605 $modulepart = 'project_task';
606 if (!DolibarrApiAccess::$user->hasRight('projet', 'lire')) {
607 throw new RestException(403);
608 }
609 } elseif ($modulepart == 'mrp') {
610 $modulepart = 'mrp';
611 if (!DolibarrApiAccess::$user->hasRight('mrp', 'read')) {
612 throw new RestException(403);
613 }
614 } elseif ($modulepart == 'contact' || $modulepart == 'socpeople') {
615 $modulepart = 'contact';
616 if (!DolibarrApiAccess::$user->hasRight('societe', 'contact', 'lire')) {
617 throw new RestException(403);
618 }
619 } elseif ($modulepart == 'stock') {
620 if (!DolibarrApiAccess::$user->hasRight('stock', 'lire')) {
621 throw new RestException(403);
622 }
623 } else {
624 throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
625 }
626
627 // Scan files into directory
628 $recursive = 0;
629 $type = 'files';
630
631 $objectType = $modulepart;
632 if (! empty($object->id) && ! empty($object->table_element)) {
633 $objectType = $object->table_element;
634 }
635
636 $filearray = dol_dir_list($upload_dir, $type, $recursive, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
637
638 $countarray = is_array($filearray) ? count($filearray) : 0;
639
640 if (empty($filearray)) {
641 throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$id.(!empty($ref) ? ' or Ref '.$ref : '').' does not return any document.');
642 } else {
643 $filearray = array_slice($filearray, $limit * $page, $limit);
644 if (($object->id) > 0 && !empty($modulepart)) {
645 require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
646 $ecmfile = new EcmFiles($this->db);
647 $result = $ecmfile->fetchAll('', '', 0, 0, array('t.src_object_type' => $objectType, 't.src_object_id' => $object->id));
648 if ($result < 0) {
649 throw new RestException(503, 'Error when retrieve ecm list : '.$this->db->lasterror());
650 } elseif (is_array($ecmfile->lines) && count($ecmfile->lines) > 0) {
651 foreach ($filearray as &$fileitem) {
652 foreach ($ecmfile->lines as $line) {
653 if ($fileitem['name'] == $line->filename) {
654 // Next line converts EcmFilesLine properties to array
655 //$fileitem = array_merge($fileitem, (array) $line);
656 $fileitem['ref'] = $line->ref;
657 $fileitem['label'] = $line->label;
658 $fileitem['filepath'] = $line->filepath;
659 $fileitem['filename'] = $line->filename;
660 $fileitem['fullpath_orig'] = $line->fullpath_orig;
661 $fileitem['position'] = $line->position;
662 $fileitem['gen_or_uploaded'] = $line->gen_or_uploaded;
663 $fileitem['description'] = $line->desc;
664 $fileitem['keywords'] = $line->keywords;
665 $fileitem['cover'] = $line->cover;
666 $fileitem['share'] = $line->share;
667 $fileitem['date_c'] = $line->date_c;
668 $fileitem['agenda_id'] = $line->agenda_id;
669 $fileitem['fk_user_c'] = $line->fk_user_c;
670 $fileitem['fk_user_m'] = $line->fk_user_m;
671 $fileitem['note_private'] = $line->note_private;
672 $fileitem['note_public'] = $line->note_public;
673 }
674 }
675 if (isset($fileitem['relativename'])) {
676 $fileitem['content-type'] = dol_mimetype((string) $fileitem['relativename']);
677 }
678 }
679
680 // Select only files that match the requested $content_type, if provided
681 $arraycontenttype = explode(",", $content_type);
682 if (!empty($content_type)) {
683 $filearray = array_filter(
684 $filearray,
689 static function ($fileitem) use (&$arraycontenttype) {
690 return in_array(($fileitem['content-type'] ?: 'UNKNOWN'), $arraycontenttype);
691 }
692 );
693 }
694 }
695 }
696 }
697
698 // Clean result from fullname
699 foreach ($filearray as $tmpkey => $tmpval) {
700 unset($filearray[$tmpkey]['path']);
701 unset($filearray[$tmpkey]['fullname']);
702 }
703
704 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
705 if ($pagination_data) {
706 $filearray = [
707 'data' => $filearray,
708 'pagination' => [
709 'total' => (int) $countarray,
710 'page' => $page, // count starts from 0
711 'page_count' => (int) ceil((int) $countarray / $limit),
712 'limit' => $limit
713 ]
714 ];
715 }
716
717 return $filearray;
718 }
719
720
747 public function getDocumentsListByDirectory($modulepart, $subdir = '', $recursive = 0, $search = '', $sortfield = 'name', $sortorder = 'asc', $limit = 100, $page = 0, $pagination_data = false)
748 {
749 global $conf;
750
751 if (!in_array($modulepart, array('ecm', 'medias'))) {
752 throw new RestException(400, 'bad value for parameter modulepart, only ecm and medias are supported');
753 }
754 if ($modulepart == 'ecm' && !isModEnabled('ecm')) {
755 throw new RestException(400, 'Module ECM is not enabled');
756 }
757 $subdir = trim((string) $subdir, '/');
758 if (preg_match('/\.\./', $subdir) || preg_match('/[<>|]/', $subdir)) {
759 throw new RestException(400, 'bad value for parameter subdir');
760 }
761 if (!in_array($sortfield, array('name', 'date', 'size'))) {
762 $sortfield = 'name';
763 }
764
765 $check_access = dol_check_secure_access_document($modulepart, $subdir, $conf->entity, DolibarrApiAccess::$user, '', 'read');
766 if (empty($check_access['accessallowed'])) {
767 throw new RestException(403);
768 }
769 $dir = rtrim($check_access['original_file'], '/');
770 if (!dol_is_dir($dir)) {
771 throw new RestException(404, 'Directory '.$subdir.' not found in area '.$modulepart);
772 }
773
774 $filter = ($search !== '' ? preg_quote($search, '/') : '');
775 $excludefilter = array('^\.', '(\.meta|_preview.*\.png)$', '^temp$', '^CVS$', '^thumbs$');
776 $filearray = dol_dir_list($dir, 'all', $recursive ? 1 : 0, $filter, $excludefilter, $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
777
778 $countarray = count($filearray);
779 $filearray = array_slice($filearray, $limit * $page, $limit);
780
781 // Return paths relative to the root of the area, so they can be used as original_file of /download
782 $result = array();
783 foreach ($filearray as $fileitem) {
784 $result[] = array(
785 'name' => $fileitem['name'],
786 'relativename' => ($subdir !== '' ? $subdir.'/' : '').$fileitem['relativename'],
787 'type' => ($fileitem['type'] == 'dir' ? 'dir' : 'file'),
788 'date' => (int) $fileitem['date'],
789 'size' => (int) $fileitem['size']
790 );
791 }
792
793 if ($pagination_data) {
794 $result = array(
795 'data' => $result,
796 'pagination' => array(
797 'total' => (int) $countarray,
798 'page' => (int) $page,
799 'page_count' => (int) ceil((int) $countarray / max(1, (int) $limit)),
800 'limit' => (int) $limit
801 )
802 );
803 }
804
805 return $result;
806 }
807
808
817 /*
818 public function get($id) {
819 return array('note'=>'xxx');
820 }*/
821
822
859 public function post($filename, $modulepart, $ref = '', $subdir = '', $filecontent = '', $fileencoding = '', $overwriteifexists = 0, $createdirifnotexists = 1, $position = 0, $cover = '', $array_options = [], $generateThumbs = 0, $share = 0)
860 {
861 dol_syslog(__METHOD__.'::begin', LOG_DEBUG);
862 global $conf, $langs;
863
864
865 $modulepartorig = $modulepart;
866
867 if (empty($modulepart)) {
868 throw new RestException(400, 'Modulepart not provided.');
869 }
870
871 $newfilecontent = '';
872 if (empty($fileencoding)) {
873 $newfilecontent = $filecontent;
874 }
875 if ($fileencoding == 'base64') {
876 $newfilecontent = base64_decode($filecontent);
877 }
878
879 $original_file = dol_sanitizeFileName($filename);
880 $relativefile = 'UNSET';
881
882 // Define $uploadir
883 $object = null;
884 $entity = DolibarrApiAccess::$user->entity;
885 if (empty($entity)) {
886 $entity = 1;
887 }
888
889 if ($ref) {
890 $tmpreldir = '';
891 $fetchbyid = false;
892
893 if ($modulepart == 'facture' || $modulepart == 'invoice') {
894 $modulepart = 'facture';
895
896 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
897 $object = new Facture($this->db);
898 } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
899 $modulepart = 'supplier_invoice';
900
901 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
902 $object = new FactureFournisseur($this->db);
903 } elseif ($modulepart == 'commande' || $modulepart == 'order') {
904 $modulepart = 'commande';
905
906 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
907 $object = new Commande($this->db);
908 } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
909 $modulepart = 'supplier_order';
910
911 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
912 $object = new CommandeFournisseur($this->db);
913 } elseif ($modulepart == 'projet' || $modulepart == 'project') {
914 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
915 $object = new Project($this->db);
916 } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
917 $modulepart = 'project_task';
918
919 require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
920 $object = new Task($this->db);
921
922 $task_result = $object->fetch(0, $ref);
923
924 // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
925 if ($task_result > 0) {
926 $project_result = $object->fetchProject();
927
928 if ($project_result >= 0) {
929 $tmpreldir = dol_sanitizeFileName((string) $object->project->ref).'/';
930 }
931 } else {
932 throw new RestException(500, 'Error while fetching Task '.$ref);
933 }
934 } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
935 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
936 $object = new Product($this->db);
937 } elseif ($modulepart == 'expensereport') {
938 require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
939 $object = new ExpenseReport($this->db);
940 } elseif ($modulepart == 'holiday') {
941 require_once DOL_DOCUMENT_ROOT.'/holiday/class/holiday.class.php';
942 $object = new Holiday($this->db);
943 } elseif ($modulepart == 'ficheinter' || $modulepart == 'intervention') {
944 require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
945 $object = new Fichinter($this->db);
946 } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
947 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
948 $object = new Expedition($this->db);
949 } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
950 $modulepart = 'adherent';
951 require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
952 $object = new Adherent($this->db);
953 } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
954 $modulepart = 'propale';
955 require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
956 $object = new Propal($this->db);
957 } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
958 $modulepart = 'agenda';
959 require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
960 $object = new ActionComm($this->db);
961 } elseif ($modulepart == 'contact' || $modulepart == 'socpeople') {
962 $modulepart = 'contact';
963 require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
964 $object = new Contact($this->db);
965 $fetchbyid = true;
966 } elseif ($modulepart == 'societe' || $modulepart == 'company') {
967 $modulepart = 'societe';
968 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
969 $object = new Societe($this->db);
970 $fetchbyid = true;
971 } elseif ($modulepart == 'knowledgemanagement') {
972 $modulepart = 'knowledgemanagement';
973 require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php';
974 $object = new KnowledgeRecord($this->db);
975 $fetchbyid = true;
976 } elseif ($modulepart == 'ticket') {
977 $modulepart = 'ticket';
978 require_once DOL_DOCUMENT_ROOT.'/ticket/class/ticket.class.php';
979 $object = new Ticket($this->db);
980 $fetchbyid = true;
981 } elseif ($modulepart == 'contrat' || $modulepart == 'contract') {
982 $modulepart = 'contrat';
983 require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
984 $object = new Contrat($this->db);
985 } elseif ($modulepart == 'mrp') {
986 $modulepart = 'mrp';
987 require_once DOL_DOCUMENT_ROOT . '/mrp/class/mo.class.php';
988 $object = new Mo($this->db);
989 } elseif ($modulepart == 'stock') {
990 $modulepart = 'stock';
991 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
992 $object = new Entrepot($this->db);
993 } elseif ($modulepart == 'ecm') {
994 throw new RestException(500, 'Using a non empty "ref" is not compatible with using modulepart = '.$modulepart);
995 } else {
996 // TODO Implement additional moduleparts
997 throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
998 }
999
1000 // at this step $object is always an object
1001 if ($fetchbyid) {
1002 // @phan-suppress-next-line PhanPluginSuspiciousParamPosition
1003 $result = $object->fetch((int) $ref);
1004 } else {
1005 $result = $object->fetch(0, $ref);
1006 }
1007
1008 if ($result == 0) {
1009 throw new RestException(404, "Object with ref '".$ref."' was not found.");
1010 } elseif ($result < 0) {
1011 throw new RestException(500, 'Error while fetching object: '.$object->errorsToString());
1012 }
1013
1014 if (!($object->id > 0)) {
1015 throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
1016 }
1017
1018 // Special cases that need to use get_exdir to get real dir of object
1019 // In future, all object should use this to define path of documents.
1020 if ($modulepart == 'supplier_invoice') {
1021 $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
1022 }
1023
1024 // Test on permissions
1025 //if ($modulepart != 'ecm') { // Here $modulepart is always != 'ecm'
1026 if ($modulepart == 'societe') {
1027 $relativefile = $tmpreldir.dol_sanitizeFileName((string) $object->id);
1028 } else {
1029 $relativefile = $tmpreldir.dol_sanitizeFileName((string) $object->ref);
1030 }
1031 $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
1032 if (empty($tmp['accessallowed'])) {
1033 throw new RestException(403, 'Access not allowed to upload file into this directory');
1034 }
1035 // Check permission on the object the document is attached to (thirdparties of a restricted sales representative, ...)
1036 if (!checkUserAccessToDocumentObject(DolibarrApiAccess::$user, $modulepart, $relativefile.'/'.$original_file, 'write')) {
1037 throw new RestException(403, 'Access not allowed to the object of this document');
1038 }
1039 $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir
1040 /*} else {
1041 if (!DolibarrApiAccess::$user->hasRight('ecm', 'upload')) {
1042 throw new RestException(403, 'Missing permission to upload files in ECM module');
1043 }
1044 $upload_dir = $conf->medias->multidir_output[$conf->entity];
1045 }*/
1046
1047 if (empty($upload_dir) || $upload_dir == '/') {
1048 throw new RestException(500, 'This value of modulepart ('.$modulepart.') does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.');
1049 }
1050 } else {
1051 if ($modulepart == 'invoice') {
1052 $modulepart = 'facture';
1053 }
1054 if ($modulepart == 'member') {
1055 $modulepart = 'adherent';
1056 }
1057
1058 // Test on permissions
1059 if ($modulepart != 'ecm') {
1060 $relativefile = $subdir;
1061 $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
1062 if (empty($tmp['accessallowed'])) {
1063 throw new RestException(403, 'Access not allowed to upload file into this directory');
1064 }
1065 // Check permission on the object the document is attached to (thirdparties of a restricted sales representative, ...)
1066 if (!checkUserAccessToDocumentObject(DolibarrApiAccess::$user, $modulepart, $relativefile.'/'.$original_file, 'write')) {
1067 throw new RestException(403, 'Access not allowed to the object of this document');
1068 }
1069 $upload_dir = $tmp['original_file']; // No dirname here, tmp['original_file'] is already the dir because dol_check_secure_access_document was called with param original_file that is only the dir
1070 } else {
1071 if (!DolibarrApiAccess::$user->hasRight('ecm', 'upload')) {
1072 throw new RestException(403, 'Missing permission to upload files in ECM module');
1073 }
1074 if (!isModEnabled('ecm') || empty($conf->ecm->dir_output)) {
1075 throw new RestException(400, 'Module ECM is not enabled');
1076 }
1077 $relativefile = $subdir;
1078 if (preg_match('/\.\./', $subdir) || preg_match('/[<>|]/', $subdir)) {
1079 throw new RestException(400, 'Bad value for parameter subdir');
1080 }
1081 // Manual area of the ECM module: the free tree of directories
1082 $upload_dir = $conf->ecm->dir_output.($subdir !== '' ? '/'.$subdir : '');
1083 }
1084
1085 if (empty($upload_dir) || $upload_dir == '/') {
1086 if (!empty($tmp['error'])) {
1087 throw new RestException(403, 'Error returned by dol_check_secure_access_document: '.$tmp['error']);
1088 } else {
1089 throw new RestException(400, 'This value of modulepart ('.$modulepart.') is not allowed with this value of subdir ('.$relativefile.')');
1090 }
1091 }
1092 }
1093 // $original_file here is still value of filename without any dir.
1094
1095 $upload_dir = dol_sanitizePathName($upload_dir);
1096
1097 if (!empty($createdirifnotexists)) {
1098 if (dol_mkdir($upload_dir) < 0) { // needed by products
1099 throw new RestException(500, 'Error while trying to create directory '.$upload_dir);
1100 }
1101 }
1102
1103 $destfile = $upload_dir.'/'.$original_file;
1104 $destfiletmp = DOL_DATA_ROOT.'/admin/temp/'.$original_file;
1105 dol_delete_file($destfiletmp);
1106 //var_dump($original_file);exit;
1107
1108 if (!dol_is_dir(dirname($destfile))) {
1109 throw new RestException(400, 'Directory does not exists : '.dirname($destfile));
1110 }
1111
1112 if (!$overwriteifexists && dol_is_file($destfile)) {
1113 throw new RestException(400, "File with name '".$original_file."' already exists.");
1114 }
1115
1116 // in case temporary directory admin/temp doesn't exist
1117 if (!dol_is_dir(dirname($destfiletmp))) {
1118 dol_mkdir(dirname($destfiletmp));
1119 }
1120
1121 $fhandle = @fopen($destfiletmp, 'w');
1122 if ($fhandle) {
1123 $nbofbyteswrote = fwrite($fhandle, $newfilecontent);
1124 fclose($fhandle);
1125 dolChmod($destfiletmp);
1126 } else {
1127 throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
1128 }
1129
1130 $disablevirusscan = 0;
1131 $src_file = $destfiletmp;
1132 $dest_file = $destfile;
1133
1134 // Security:
1135 // If we need to make a virus scan
1136 if (empty($disablevirusscan) && file_exists($src_file)) {
1137 $checkvirusarray = dolCheckVirus($src_file, $dest_file);
1138 if (count($checkvirusarray)) {
1139 dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: errors='.implode(',', $checkvirusarray), LOG_WARNING);
1140 // Differentiate based on the error key in the array
1141 $errorkey = array_keys($checkvirusarray)[0];
1142 $langs->load('errors');
1143 if (in_array($errorkey, array('ErrorFileIsInfectedKnownVirus', 'ErrorAntivirusNotAvailable', 'ErrorFileIsInfectedWithAVirus'))) {
1144 $restmsg = $langs->trans($errorkey);
1145 } else {
1146 $restmsg = $langs->trans('ErrorFileIsInfectedWithAVirus'); // fallback
1147 }
1148 throw new RestException(500, $restmsg . ': ' . implode(',', $checkvirusarray));
1149 }
1150 }
1151
1152 // Security:
1153 // Disallow file with some extensions. We rename them.
1154 // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
1155 if (isAFileWithExecutableContent($dest_file) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
1156 // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
1157 $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
1158 if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
1159 $publicmediasdirwithslash .= '/';
1160 }
1161
1162 if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !getDolGlobalInt("MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) { // We never add .noexe on files into media directory
1163 $dest_file .= '.noexe';
1164 }
1165 }
1166
1167 // Security:
1168 // We refuse cache files/dirs, upload using .. and pipes into filenames.
1169 if (preg_match('/^\./', basename($src_file)) || preg_match('/\.\./', $src_file) || preg_match('/[<>|]/', $src_file)) {
1170 dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
1171 throw new RestException(500, "Refused to deliver file ".$src_file);
1172 }
1173
1174 // Security:
1175 // We refuse cache files/dirs, upload using .. and pipes into filenames.
1176 if (preg_match('/^\./', basename($dest_file)) || preg_match('/\.\./', $dest_file) || preg_match('/[<>|]/', $dest_file)) {
1177 dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
1178 throw new RestException(500, "Refused to deliver file ".$dest_file);
1179 }
1180
1181 $moreinfo = array('note_private' => 'File uploaded using API /documents from IP '.getUserRemoteIP());
1182 // $object may be null
1183 if (is_object($object) && $object->id > 0) {
1184 $moreinfo['src_object_type'] = $object->table_element;
1185 $moreinfo['src_object_id'] = $object->id;
1186 }
1187 if (!empty($array_options)) {
1188 $moreinfo = array_merge($moreinfo, ["array_options" => $array_options]);
1189 }
1190 if (!empty($position)) {
1191 $moreinfo = array_merge($moreinfo, ["position" => $position]);
1192 }
1193 if (!empty($cover)) {
1194 $moreinfo = array_merge($moreinfo, ["cover" => $cover]);
1195 }
1196 if (!empty($share)) {
1197 require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
1198 $moreinfo = array_merge($moreinfo, ["share" => getRandomPassword(true)]);
1199 }
1200 $moreinfo['gen_or_uploaded'] = 'api';
1201
1202 // Move the temporary file at its final emplacement
1203 $result = dol_move($destfiletmp, $dest_file, '0', $overwriteifexists, 1, 1, $moreinfo);
1204 if (!$result) {
1205 throw new RestException(500, "Failed to move file into '".$dest_file."'");
1206 }
1207
1208 if (is_object($object) && $generateThumbs) {
1209 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1210 require_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php'; // image_format_supported() is defined here
1211 if (image_format_supported($dest_file)) {
1212 $object->addThumbs($dest_file);
1213 }
1214 }
1215
1216 return dol_basename($destfile);
1217 }
1218
1238 public function delete($modulepart, $original_file)
1239 {
1240 global $conf;
1241
1242 if (empty($modulepart)) {
1243 throw new RestException(400, 'bad value for parameter modulepart');
1244 }
1245 if (empty($original_file)) {
1246 throw new RestException(400, 'bad value for parameter original_file');
1247 }
1248
1249 // Normalize modulepart for project_task
1250 if ($modulepart == 'task') {
1251 $modulepart = 'project_task';
1252 }
1253
1254 //--- Finds and returns the document
1255 $entity = $conf->entity;
1256
1257 // Special cases that need to use get_exdir to get real dir of object
1258 // If future, all object should use this to define path of documents.
1259 /*
1260 $tmpreldir = '';
1261 if ($modulepart == 'supplier_invoice') {
1262 $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
1263 }
1264
1265 $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
1266 $relativefile = $original_file;
1267
1268 $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
1269 $accessallowed = $check_access['accessallowed'];
1270 $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
1271 $original_file = $check_access['original_file'];
1272
1273 if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
1274 throw new RestException(403);
1275 }
1276 if (!$accessallowed) {
1277 throw new RestException(403);
1278 }
1279 // Check permission on the object the document is attached to (thirdparties of a restricted sales representative, ...)
1280 if (!checkUserAccessToDocumentObject(DolibarrApiAccess::$user, $modulepart, $relativefile, 'write')) {
1281 throw new RestException(403, 'Access not allowed to the object of this document');
1282 }
1283
1284 if (DolibarrApiAccess::$user->socid > 0) {
1285 if ($sqlprotectagainstexternals) {
1286 $resql = $this->db->query($sqlprotectagainstexternals);
1287 if ($resql) {
1288 $num = $this->db->num_rows($resql);
1289 $i = 0;
1290 while ($i < $num) {
1291 $obj = $this->db->fetch_object($resql);
1292 if (DolibarrApiAccess::$user->socid != $obj->fk_soc) {
1293 throw new RestException(403, 'Not allowed to download documents with such a ref');
1294 }
1295 $i++;
1296 }
1297 }
1298 }
1299 }
1300
1301 $filename = basename($original_file);
1302 $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
1303
1304 if (!file_exists($original_file_osencoded)) {
1305 dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
1306 throw new RestException(404, 'File not found');
1307 }
1308
1309 if (@unlink($original_file_osencoded)) {
1310 return array(
1311 'success' => array(
1312 'code' => 200,
1313 'message' => 'Document deleted'
1314 )
1315 );
1316 }
1317
1318 throw new RestException(403);
1319 }
1320}
$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 to manage agenda events (actions)
Class to manage members of a foundation.
Class to manage predefined suppliers products.
Class to manage customers orders.
Class to manage contact/addresses.
API class to receive files.
post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0, $createdirifnotexists=1, $position=0, $cover='', $array_options=[], $generateThumbs=0, $share=0)
Return a document.
__construct()
Constructor.
getDocumentsListByElement($modulepart, $id=0, $ref='', $sortfield='', $sortorder='', $limit=100, $page=0, $content_type='', $pagination_data=false)
List all documents of an element.
index($modulepart, $original_file='')
Download a given document.
getDocumentsListByDirectory($modulepart, $subdir='', $recursive=0, $search='', $sortfield='name', $sortorder='asc', $limit=100, $page=0, $pagination_data=false)
Return the list of files and subdirectories of a directory of a documents area not linked to an objec...
builddoc($modulepart, $original_file='', $doctemplate='', $langcode='')
Build a document.
Class for API REST v1.
Definition api.class.php:35
Class to manage ECM files.
Class to manage warehouses.
Class to manage Trips and Expenses.
Class to manage suppliers invoices.
Class to manage invoices.
Class of the module paid holiday.
Class for KnowledgeRecord.
Class for Mo.
Definition mo.class.php:35
Class to manage products or services.
Class to manage projects.
Class to manage proposals.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage tasks.
Class to manage translations.
dol_move($srcfile, $destfile, $newmask='0', $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array(), $entity=null)
Move a file into another name.
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
Definition files.lib.php:41
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser=null, $refname='', $mode='read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices to g...
dol_is_file($pathoffile)
Return if path is a file.
dolCheckVirus($src_file, $dest_file='')
Check virus into a file.
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_is_dir($folder)
Test if filename is a directory.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_sanitizePathName($str, $newstr='_', $unaccent=0, $allowdash=0)
Clean a string to use it as a path name.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dolChmod($filepath, $newmask='')
Change mod of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
getUserRemoteIP($trusted=0)
Return the real IP of remote user.
isAFileWithExecutableContent($filename)
Return if a file can contains executable content.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart='')
Return a path to have a the directory according to object where files are stored.
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)
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.
Class to generate the form for creating a new ticket.
getRandomPassword($generic=false, $replaceambiguouschars=null, $length=32)
Return a generated password using default module.
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.
checkUserAccessToDocumentObject(User $user, $modulepart, $original_file, $mode='read')
Check that a user can access the object a document is attached to.