dolibarr  13.0.2
api_documents.class.php
1 <?php
2 /* Copyright (C) 2016 Xebax Christy <xebax@wanadoo.fr>
3  * Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
4  * Copyright (C) 2016 Jean-François Ferry <jfefe@aternatik.fr>
5  *
6  * This program is free software you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  */
19 
20 use Luracast\Restler\RestException;
21 use Luracast\Restler\Format\UploadFormat;
22 
23 
24 require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
25 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
26 
33 class Documents extends DolibarrApi
34 {
35 
39  static $DOCUMENT_FIELDS = array(
40  'modulepart'
41  );
42 
46  public function __construct()
47  {
48  global $db;
49  $this->db = $db;
50  }
51 
52 
69  public function index($modulepart, $original_file = '')
70  {
71  global $conf, $langs;
72 
73  if (empty($modulepart)) {
74  throw new RestException(400, 'bad value for parameter modulepart');
75  }
76  if (empty($original_file)) {
77  throw new RestException(400, 'bad value for parameter original_file');
78  }
79 
80  //--- Finds and returns the document
81  $entity = $conf->entity;
82 
83  // Special cases that need to use get_exdir to get real dir of object
84  // If future, all object should use this to define path of documents.
85  /*
86  $tmpreldir = '';
87  if ($modulepart == 'supplier_invoice') {
88  $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
89  }
90 
91  $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
92  $relativefile = $original_file;
93 
94  $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
95  $accessallowed = $check_access['accessallowed'];
96  $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
97  $original_file = $check_access['original_file'];
98 
99  if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
100  throw new RestException(401);
101  }
102  if (!$accessallowed) {
103  throw new RestException(401);
104  }
105 
106  $filename = basename($original_file);
107  $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
108 
109  if (!file_exists($original_file_osencoded))
110  {
111  dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
112  throw new RestException(404, 'File not found');
113  }
114 
115  $file_content = file_get_contents($original_file_osencoded);
116  return array('filename'=>$filename, 'content-type' => dol_mimetype($filename), 'filesize'=>filesize($original_file), 'content'=>base64_encode($file_content), 'encoding'=>'base64');
117  }
118 
119 
139  public function builddoc($modulepart, $original_file = '', $doctemplate = '', $langcode = '')
140  {
141  global $conf, $langs;
142 
143  if (empty($modulepart)) {
144  throw new RestException(400, 'bad value for parameter modulepart');
145  }
146  if (empty($original_file)) {
147  throw new RestException(400, 'bad value for parameter original_file');
148  }
149 
150  $outputlangs = $langs;
151  if ($langcode && $langs->defaultlang != $langcode)
152  {
153  $outputlangs = new Translate('', $conf);
154  $outputlangs->setDefaultLang($langcode);
155  }
156 
157  //--- Finds and returns the document
158  $entity = $conf->entity;
159 
160  // Special cases that need to use get_exdir to get real dir of object
161  // If future, all object should use this to define path of documents.
162  /*
163  $tmpreldir = '';
164  if ($modulepart == 'supplier_invoice') {
165  $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
166  }
167 
168  $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
169  $relativefile = $original_file;
170 
171  $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
172  $accessallowed = $check_access['accessallowed'];
173  $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
174  $original_file = $check_access['original_file'];
175 
176  if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
177  throw new RestException(401);
178  }
179  if (!$accessallowed) {
180  throw new RestException(401);
181  }
182 
183  // --- Generates the document
184  $hidedetails = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 0 : 1;
185  $hidedesc = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 0 : 1;
186  $hideref = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 0 : 1;
187 
188  $templateused = '';
189 
190  if ($modulepart == 'facture' || $modulepart == 'invoice')
191  {
192  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
193  $this->invoice = new Facture($this->db);
194  $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
195  if (!$result) {
196  throw new RestException(404, 'Invoice not found');
197  }
198 
199  $templateused = $doctemplate ? $doctemplate : $this->invoice->model_pdf;
200  $result = $this->invoice->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
201  if ($result <= 0) {
202  throw new RestException(500, 'Error generating document');
203  }
204  }
205  elseif ($modulepart == 'commande' || $modulepart == 'order')
206  {
207  require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
208  $this->order = new Commande($this->db);
209  $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
210  if (!$result) {
211  throw new RestException(404, 'Order not found');
212  }
213  $templateused = $doctemplate ? $doctemplate : $this->order->model_pdf;
214  $result = $this->order->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
215  if ($result <= 0) {
216  throw new RestException(500, 'Error generating document');
217  }
218  }
219  elseif ($modulepart == 'propal' || $modulepart == 'proposal')
220  {
221  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
222  $this->propal = new Propal($this->db);
223  $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
224  if (!$result) {
225  throw new RestException(404, 'Proposal not found');
226  }
227  $templateused = $doctemplate ? $doctemplate : $this->propal->model_pdf;
228  $result = $this->propal->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
229  if ($result <= 0) {
230  throw new RestException(500, 'Error generating document');
231  }
232  } else {
233  throw new RestException(403, 'Generation not available for this modulepart');
234  }
235 
236  $filename = basename($original_file);
237  $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
238 
239  if (!file_exists($original_file_osencoded))
240  {
241  throw new RestException(404, 'File not found');
242  }
243 
244  $file_content = file_get_contents($original_file_osencoded);
245  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');
246  }
247 
265  public function getDocumentsListByElement($modulepart, $id = 0, $ref = '', $sortfield = '', $sortorder = '')
266  {
267  global $conf;
268 
269  if (empty($modulepart)) {
270  throw new RestException(400, 'bad value for parameter modulepart');
271  }
272 
273  if (empty($id) && empty($ref)) {
274  throw new RestException(400, 'bad value for parameter id or ref');
275  }
276 
277  $id = (empty($id) ? 0 : $id);
278  $recursive = 0;
279  $type = 'files';
280 
281  if ($modulepart == 'societe' || $modulepart == 'thirdparty')
282  {
283  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
284 
285  if (!DolibarrApiAccess::$user->rights->societe->lire) {
286  throw new RestException(401);
287  }
288 
289  $object = new Societe($this->db);
290  $result = $object->fetch($id, $ref);
291  if (!$result) {
292  throw new RestException(404, 'Thirdparty not found');
293  }
294 
295  $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
296  }
297  elseif ($modulepart == 'user')
298  {
299  require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
300 
301  // Can get doc if has permission to read all user or if it is user itself
302  if (!DolibarrApiAccess::$user->rights->user->user->lire && DolibarrApiAccess::$user->id != $id) {
303  throw new RestException(401);
304  }
305 
306  $object = new User($this->db);
307  $result = $object->fetch($id, $ref);
308  if (!$result) {
309  throw new RestException(404, 'User not found');
310  }
311 
312  $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id;
313  }
314  elseif ($modulepart == 'adherent' || $modulepart == 'member')
315  {
316  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
317 
318  if (!DolibarrApiAccess::$user->rights->adherent->lire) {
319  throw new RestException(401);
320  }
321 
322  $object = new Adherent($this->db);
323  $result = $object->fetch($id, $ref);
324  if (!$result) {
325  throw new RestException(404, 'Member not found');
326  }
327 
328  $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member');
329  }
330  elseif ($modulepart == 'propal' || $modulepart == 'proposal')
331  {
332  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
333 
334  if (!DolibarrApiAccess::$user->rights->propal->lire) {
335  throw new RestException(401);
336  }
337 
338  $object = new Propal($this->db);
339  $result = $object->fetch($id, $ref);
340  if (!$result) {
341  throw new RestException(404, 'Proposal not found');
342  }
343 
344  $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
345  }
346  elseif ($modulepart == 'commande' || $modulepart == 'order')
347  {
348  require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
349 
350  if (!DolibarrApiAccess::$user->rights->commande->lire) {
351  throw new RestException(401);
352  }
353 
354  $object = new Commande($this->db);
355  $result = $object->fetch($id, $ref);
356  if (!$result) {
357  throw new RestException(404, 'Order not found');
358  }
359 
360  $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
361  }
362  elseif ($modulepart == 'shipment' || $modulepart == 'expedition')
363  {
364  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
365 
366  if (!DolibarrApiAccess::$user->rights->expedition->lire) {
367  throw new RestException(401);
368  }
369 
370  $object = new Expedition($this->db);
371  $result = $object->fetch($id, $ref);
372  if (!$result) {
373  throw new RestException(404, 'Shipment not found');
374  }
375 
376  $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
377  }
378  elseif ($modulepart == 'facture' || $modulepart == 'invoice')
379  {
380  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
381 
382  if (!DolibarrApiAccess::$user->rights->facture->lire) {
383  throw new RestException(401);
384  }
385 
386  $object = new Facture($this->db);
387  $result = $object->fetch($id, $ref);
388  if (!$result) {
389  throw new RestException(404, 'Invoice not found');
390  }
391 
392  $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
393  }
394  elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
395  {
396  $modulepart = 'supplier_invoice';
397 
398  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
399 
400  if (!DolibarrApiAccess::$user->rights->fournisseur->facture->lire) {
401  throw new RestException(401);
402  }
403 
404  $object = new FactureFournisseur($this->db);
405  $result = $object->fetch($id, $ref);
406  if (!$result) {
407  throw new RestException(404, 'Invoice not found');
408  }
409 
410  $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
411  }
412  elseif ($modulepart == 'produit' || $modulepart == 'product')
413  {
414  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
415 
416  if (!DolibarrApiAccess::$user->rights->produit->lire) {
417  throw new RestException(401);
418  }
419 
420  $object = new Product($this->db);
421  $result = $object->fetch($id, $ref);
422  if ($result == 0) {
423  throw new RestException(404, 'Product not found');
424  } elseif ($result < 0) {
425  throw new RestException(500, 'Error while fetching object: '.$object->error);
426  }
427 
428  $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
429  }
430  elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event')
431  {
432  require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
433 
434  if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) {
435  throw new RestException(401);
436  }
437 
438  $object = new ActionComm($this->db);
439  $result = $object->fetch($id, $ref);
440  if (!$result) {
441  throw new RestException(404, 'Event not found');
442  }
443 
444  $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
445  }
446  elseif ($modulepart == 'expensereport')
447  {
448  require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
449 
450  if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) {
451  throw new RestException(401);
452  }
453 
454  $object = new ExpenseReport($this->db);
455  $result = $object->fetch($id, $ref);
456  if (!$result) {
457  throw new RestException(404, 'Expense report not found');
458  }
459 
460  $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
461  }
462  elseif ($modulepart == 'categorie' || $modulepart == 'category')
463  {
464  require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
465 
466  if (!DolibarrApiAccess::$user->rights->categorie->lire) {
467  throw new RestException(401);
468  }
469 
470  $object = new Categorie($this->db);
471  $result = $object->fetch($id, $ref);
472  if (!$result) {
473  throw new RestException(404, 'Category not found');
474  }
475 
476  $upload_dir = $conf->categorie->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'category').$object->id."/photos/".dol_sanitizeFileName($object->ref);
477  } elseif ($modulepart == 'ecm') {
478  throw new RestException(500, 'Modulepart Ecm not implemented yet.');
479  // // require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
480 
481  // if (!DolibarrApiAccess::$user->rights->ecm->read) {
482  // throw new RestException(401);
483  // }
484 
485  // // $object = new EcmDirectory($this->db);
486  // // $result = $object->fetch($ref);
487  // // if (!$result) {
488  // // throw new RestException(404, 'EcmDirectory not found');
489  // // }
490  // $upload_dir = $conf->ecm->dir_output;
491  // $type = 'all';
492  // $recursive = 0;
493  } else {
494  throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
495  }
496 
497  $filearray = dol_dir_list($upload_dir, $type, $recursive, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
498  if (empty($filearray)) {
499  throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$object->id.(!empty($object->ref) ? ' or Ref '.$object->ref : '').' does not return any document.');
500  } else {
501  if (($object->id) > 0 && !empty($modulepart)) {
502  require_once DOL_DOCUMENT_ROOT . '/ecm/class/ecmfiles.class.php';
503  $ecmfile = new EcmFiles($this->db);
504  $result = $ecmfile->fetchAll('', '', 0, 0, array('t.src_object_type' => $modulepart, 't.src_object_id' => $object->id));
505  if ($result < 0) {
506  throw new RestException(503, 'Error when retrieve ecm list : ' . $this->db->lasterror());
507  } elseif (is_array($ecmfile->lines) && count($ecmfile->lines) > 0) {
508  $filearray['ecmfiles_infos'] = $ecmfile->lines;
509  }
510  }
511  }
512 
513  return $filearray;
514  }
515 
516 
525  /*
526  public function get($id) {
527  return array('note'=>'xxx');
528  }*/
529 
530 
555  public function post($filename, $modulepart, $ref = '', $subdir = '', $filecontent = '', $fileencoding = '', $overwriteifexists = 0, $createdirifnotexists = 1)
556  {
557  global $db, $conf;
558 
559  /*var_dump($modulepart);
560  var_dump($filename);
561  var_dump($filecontent);
562  exit;*/
563 
564  if (empty($modulepart))
565  {
566  throw new RestException(400, 'Modulepart not provided.');
567  }
568 
569  if (!DolibarrApiAccess::$user->rights->ecm->upload) {
570  throw new RestException(401);
571  }
572 
573  $newfilecontent = '';
574  if (empty($fileencoding)) $newfilecontent = $filecontent;
575  if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent);
576 
577  $original_file = dol_sanitizeFileName($filename);
578 
579  // Define $uploadir
580  $object = null;
581  $entity = DolibarrApiAccess::$user->entity;
582  if (empty($entity)) $entity = 1;
583 
584  if ($ref)
585  {
586  $tmpreldir = '';
587 
588  if ($modulepart == 'facture' || $modulepart == 'invoice')
589  {
590  $modulepart = 'facture';
591 
592  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
593  $object = new Facture($this->db);
594  }
595  elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice')
596  {
597  $modulepart = 'supplier_invoice';
598 
599  require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
600  $object = new FactureFournisseur($this->db);
601  }
602  elseif ($modulepart == 'project')
603  {
604  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
605  $object = new Project($this->db);
606  }
607  elseif ($modulepart == 'task' || $modulepart == 'project_task')
608  {
609  $modulepart = 'project_task';
610 
611  require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
612  $object = new Task($this->db);
613 
614  $task_result = $object->fetch('', $ref);
615 
616  // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
617  if ($task_result > 0)
618  {
619  $project_result = $object->fetch_projet();
620 
621  if ($project_result >= 0)
622  {
623  $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
624  }
625  } else {
626  throw new RestException(500, 'Error while fetching Task '.$ref);
627  }
628  }
629  elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service')
630  {
631  require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
632  $object = new Product($this->db);
633  }
634  elseif ($modulepart == 'expensereport')
635  {
636  require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
637  $object = new ExpenseReport($this->db);
638  }
639  elseif ($modulepart == 'adherent' || $modulepart == 'member')
640  {
641  $modulepart = 'adherent';
642  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
643  $object = new Adherent($this->db);
644  }
645  elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale')
646  {
647  $modulepart = 'propale';
648  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
649  $object = new Propal($this->db);
650  } else {
651  // TODO Implement additional moduleparts
652  throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
653  }
654 
655  if (is_object($object))
656  {
657  $result = $object->fetch('', $ref);
658 
659  if ($result == 0)
660  {
661  throw new RestException(404, "Object with ref '".$ref."' was not found.");
662  }
663  elseif ($result < 0)
664  {
665  throw new RestException(500, 'Error while fetching object: '.$object->error);
666  }
667  }
668 
669  if (!($object->id > 0)) {
670  throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
671  }
672 
673  // Special cases that need to use get_exdir to get real dir of object
674  // If future, all object should use this to define path of documents.
675  if ($modulepart == 'supplier_invoice') {
676  $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
677  }
678 
679  $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref);
680 
681  $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
682  $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
683 
684  if (empty($upload_dir) || $upload_dir == '/')
685  {
686  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.');
687  }
688  } else {
689  if ($modulepart == 'invoice') $modulepart = 'facture';
690  if ($modulepart == 'member') $modulepart = 'adherent';
691 
692  $relativefile = $subdir;
693  $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
694  $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
695 
696  if (empty($upload_dir) || $upload_dir == '/') {
697  if (!empty($tmp['error'])) {
698  throw new RestException(401, 'Error returned by dol_check_secure_access_document: '.$tmp['error']);
699  } else {
700  throw new RestException(500, 'This value of modulepart ('.$modulepart.') is not allowed with this value of subdir ('.$relativefile.')');
701  }
702  }
703  }
704  // $original_file here is still value of filename without any dir.
705 
706  $upload_dir = dol_sanitizePathName($upload_dir);
707 
708  if (!empty($createdirifnotexists)) {
709  if (dol_mkdir($upload_dir) < 0) { // needed by products
710  throw new RestException(500, 'Error while trying to create directory '.$upload_dir);
711  }
712  }
713 
714  $destfile = $upload_dir.'/'.$original_file;
715  $destfiletmp = DOL_DATA_ROOT.'/admin/temp/'.$original_file;
716  dol_delete_file($destfiletmp);
717  //var_dump($original_file);exit;
718 
719  if (!dol_is_dir(dirname($destfile))) {
720  throw new RestException(401, 'Directory not exists : '.dirname($destfile));
721  }
722 
723  if (!$overwriteifexists && dol_is_file($destfile)) {
724  throw new RestException(500, "File with name '".$original_file."' already exists.");
725  }
726 
727  $fhandle = @fopen($destfiletmp, 'w');
728  if ($fhandle) {
729  $nbofbyteswrote = fwrite($fhandle, $newfilecontent);
730  fclose($fhandle);
731  @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK));
732  } else {
733  throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
734  }
735 
736  $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1);
737  if (!$result) {
738  throw new RestException(500, "Failed to move file into '".$destfile."'");
739  }
740 
741  return dol_basename($destfile);
742  }
743 
757  public function delete($modulepart, $original_file)
758  {
759  global $conf, $langs;
760 
761  if (empty($modulepart)) {
762  throw new RestException(400, 'bad value for parameter modulepart');
763  }
764  if (empty($original_file)) {
765  throw new RestException(400, 'bad value for parameter original_file');
766  }
767 
768  //--- Finds and returns the document
769  $entity = $conf->entity;
770 
771  // Special cases that need to use get_exdir to get real dir of object
772  // If future, all object should use this to define path of documents.
773  /*
774  $tmpreldir = '';
775  if ($modulepart == 'supplier_invoice') {
776  $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
777  }
778 
779  $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
780  $relativefile = $original_file;
781 
782  $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
783  $accessallowed = $check_access['accessallowed'];
784  $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
785  $original_file = $check_access['original_file'];
786 
787  if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
788  throw new RestException(401);
789  }
790  if (!$accessallowed) {
791  throw new RestException(401);
792  }
793 
794  $filename = basename($original_file);
795  $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
796 
797  if (!file_exists($original_file_osencoded))
798  {
799  dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
800  throw new RestException(404, 'File not found');
801  }
802 
803  if (@unlink($original_file_osencoded)) {
804  return array(
805  'success' => array(
806  'code' => 200,
807  'message' => 'Document deleted'
808  )
809  );
810  }
811 
812  throw new RestException(401);
813  }
814 
815  // phpcs:disable PEAR.NamingConventions.ValidFunctionName
823  private function _validate_file($data)
824  {
825  // phpcs:enable
826  $result = array();
827  foreach (Documents::$DOCUMENT_FIELDS as $field) {
828  if (!isset($data[$field]))
829  throw new RestException(400, "$field field missing");
830  $result[$field] = $data[$field];
831  }
832  return $result;
833  }
834 }
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
index($modulepart, $original_file= '')
Download a document.
dol_sanitizePathName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a path name.
_validate_file($data)
Validate fields before create or update object.
Class to manage agenda events (actions)
API class for receive files.
Class to manage products or services.
Class to manage Dolibarr users.
Definition: user.class.php:44
post($filename, $modulepart, $ref= '', $subdir= '', $filecontent= '', $fileencoding= '', $overwriteifexists=0, $createdirifnotexists=1)
Return a document.
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:432
Class to manage suppliers invoices.
builddoc($modulepart, $original_file= '', $doctemplate= '', $langcode= '')
Build a document.
$conf db
API class for accounts.
Definition: inc.php:54
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:817
Class for API REST v1.
Definition: api.class.php:30
getDocumentsListByElement($modulepart, $id=0, $ref= '', $sortfield= '', $sortorder= '')
Return the list of documents of a dedicated element (from its ID or Ref)
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage categories.
dol_check_secure_access_document($modulepart, $original_file, $entity, $fuser= '', $refname= '', $mode= 'read')
Security check when accessing to a document (used by document.php, viewimage.php and webservices) ...
Definition: files.lib.php:2230
Class to manage projects.
dol_mimetype($file, $default= 'application/octet-stream', $mode=0)
Return mime type of a file.
Class to manage shipments.
Class to manage customers orders.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart= '')
Return a path to have a the directory according to object where files are stored. ...
Class to manage members of a foundation.
dol_basename($pathfile)
Make a basename working with all page code (default PHP basenamed fails with cyrillic).
Definition: files.lib.php:36
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1)
Remove a file or several files with a mask.
Definition: files.lib.php:1144
Class to manage translations.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
Class to manage Trips and Expenses.
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:457
Class to manage tasks.
Definition: task.class.php:35
__construct()
Constructor.
Class to manage invoices.
Class to manage ECM files.
Class to manage proposals.
dol_mkdir($dir, $dataroot= '', $newmask=null)
Creation of a directory (this can create recursive subdir)