dolibarr  7.0.0-beta
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 <http://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  function __construct()
47  {
48  global $db;
49  $this->db = $db;
50  }
51 
52 
70  public function index($module_part, $original_file='')
71  {
72  global $conf, $langs;
73 
74  if (empty($module_part)) {
75  throw new RestException(400, 'bad value for parameter modulepart');
76  }
77  if (empty($original_file)) {
78  throw new RestException(400, 'bad value for parameter original_file');
79  }
80 
81  //--- Finds and returns the document
82  $entity=$conf->entity;
83 
84  $check_access = dol_check_secure_access_document($module_part, $original_file, $entity, DolibarrApiAccess::$user, '', 'read');
85  $accessallowed = $check_access['accessallowed'];
86  $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
87  $original_file = $check_access['original_file'];
88 
89  if (preg_match('/\.\./',$original_file) || preg_match('/[<>|]/',$original_file))
90  {
91  throw new RestException(401);
92  }
93  if (!$accessallowed) {
94  throw new RestException(401);
95  }
96 
97  $filename = basename($original_file);
98  $original_file_osencoded=dol_osencode($original_file); // New file name encoded in OS encoding charset
99 
100  if (! file_exists($original_file_osencoded))
101  {
102  throw new RestException(404, 'File not found');
103  }
104 
105  $file_content=file_get_contents($original_file_osencoded);
106  return array('filename'=>$filename, 'content'=>base64_encode($file_content), 'encoding'=>'MIME base64 (base64_encode php function, http://php.net/manual/en/function.base64-encode.php)' );
107  }
108 
109 
130  public function builddoc($module_part, $original_file='', $doctemplate='', $langcode='')
131  {
132  global $conf, $langs;
133 
134  if (empty($module_part)) {
135  throw new RestException(400, 'bad value for parameter modulepart');
136  }
137  if (empty($original_file)) {
138  throw new RestException(400, 'bad value for parameter original_file');
139  }
140 
141  $outputlangs = $langs;
142  if ($langcode && $langs->defaultlang != $langcode)
143  {
144  $outputlangs=new Translate('', $conf);
145  $outputlangs->setDefaultLang($langcode);
146  }
147 
148  //--- Finds and returns the document
149  $entity=$conf->entity;
150 
151  $check_access = dol_check_secure_access_document($module_part, $original_file, $entity, DolibarrApiAccess::$user, '', 'write');
152  $accessallowed = $check_access['accessallowed'];
153  $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
154  $original_file = $check_access['original_file'];
155 
156  if (preg_match('/\.\./',$original_file) || preg_match('/[<>|]/',$original_file)) {
157  throw new RestException(401);
158  }
159  if (!$accessallowed) {
160  throw new RestException(401);
161  }
162 
163  // --- Generates the document
164  $hidedetails = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 0 : 1;
165  $hidedesc = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 0 : 1;
166  $hideref = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 0 : 1;
167 
168  $templateused='';
169 
170  if ($module_part == 'facture' || $module_part == 'invoice')
171  {
172  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
173  $this->invoice = new Facture($this->db);
174  $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
175  if( ! $result ) {
176  throw new RestException(404, 'Invoice not found');
177  }
178 
179  $templateused = $doctemplate?$doctemplate:$this->invoice->modelpdf;
180  $result = $this->invoice->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
181  if( $result <= 0 ) {
182  throw new RestException(500, 'Error generating document');
183  }
184  }
185  elseif ($module_part == 'commande' || $module_part == 'order')
186  {
187  require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
188  $this->order = new Commande($this->db);
189  $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
190  if( ! $result ) {
191  throw new RestException(404, 'Order not found');
192  }
193  $templateused = $doctemplate?$doctemplate:$this->order->modelpdf;
194  $result = $this->order->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
195  if( $result <= 0 ) {
196  throw new RestException(500, 'Error generating document');
197  }
198  }
199  elseif ($module_part == 'propal' || $module_part == 'proposal')
200  {
201  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
202  $this->propal = new Propal($this->db);
203  $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
204  if( ! $result ) {
205  throw new RestException(404, 'Proposal not found');
206  }
207  $templateused = $doctemplate?$doctemplate:$this->propal->modelpdf;
208  $result = $this->propal->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
209  if( $result <= 0 ) {
210  throw new RestException(500, 'Error generating document');
211  }
212  }
213  else
214  {
215  throw new RestException(403, 'Generation not available for this modulepart');
216  }
217 
218  $filename = basename($original_file);
219  $original_file_osencoded=dol_osencode($original_file); // New file name encoded in OS encoding charset
220 
221  if (! file_exists($original_file_osencoded))
222  {
223  throw new RestException(404, 'File not found');
224  }
225 
226  $file_content=file_get_contents($original_file_osencoded);
227  return array('filename'=>$filename, 'content'=>base64_encode($file_content), 'langcode'=>$outputlangs->defaultlang, 'template'=>$templateused, 'encoding'=>'MIME base64 (base64_encode php function, http://php.net/manual/en/function.base64-encode.php)' );
228  }
229 
230 
249  function getDocumentsListByElement($modulepart, $id=0, $ref='', $sortfield='', $sortorder='')
250  {
251  global $conf;
252 
253  if (empty($modulepart)) {
254  throw new RestException(400, 'bad value for parameter modulepart');
255  }
256 
257  if (empty($id) && empty($ref)) {
258  throw new RestException(400, 'bad value for parameter id or ref');
259  }
260 
261  $id = (empty($id)?0:$id);
262 
263  if ($modulepart == 'societe' || $modulepart == 'thirdparty')
264  {
265  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
266 
267  if (!DolibarrApiAccess::$user->rights->societe->lire) {
268  throw new RestException(401);
269  }
270 
271  $object = new Societe($this->db);
272  $result=$object->fetch($id, $ref);
273  if ( ! $result ) {
274  throw new RestException(404, 'Thirdparty not found');
275  }
276 
277  $upload_dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id;
278  }
279  else if ($modulepart == 'adherent' || $modulepart == 'member')
280  {
281  require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
282 
283  if (!DolibarrApiAccess::$user->rights->adherent->lire) {
284  throw new RestException(401);
285  }
286 
287  $object = new Adherent($this->db);
288  $result=$object->fetch($id, $ref);
289  if ( ! $result ) {
290  throw new RestException(404, 'Member not found');
291  }
292 
293  $upload_dir = $conf->adherent->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'member');
294  }
295  else if ($modulepart == 'propal' || $modulepart == 'proposal')
296  {
297  require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
298 
299  if (!DolibarrApiAccess::$user->rights->propal->lire) {
300  throw new RestException(401);
301  }
302 
303  $object = new Propal($this->db);
304  $result=$object->fetch($id, $ref);
305  if ( ! $result ) {
306  throw new RestException(404, 'Proposal not found');
307  }
308 
309  $upload_dir = $conf->propal->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'propal');
310  }
311  else if ($modulepart == 'commande' || $modulepart == 'order')
312  {
313  require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
314 
315  if (!DolibarrApiAccess::$user->rights->commande->lire) {
316  throw new RestException(401);
317  }
318 
319  $object = new Commande($this->db);
320  $result=$object->fetch($id, $ref);
321  if ( ! $result ) {
322  throw new RestException(404, 'Order not found');
323  }
324 
325  $upload_dir = $conf->commande->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'commande');
326  }
327  else if ($modulepart == 'shipment' || $modulepart == 'expedition')
328  {
329  require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
330 
331  if (!DolibarrApiAccess::$user->rights->expedition->lire) {
332  throw new RestException(401);
333  }
334 
335  $object = new Expedition($this->db);
336  $result=$object->fetch($id, $ref);
337  if ( ! $result ) {
338  throw new RestException(404, 'Shipment not found');
339  }
340 
341  $upload_dir = $conf->expedition->dir_output . "/sending/" . get_exdir(0, 0, 0, 1, $object, 'shipment');
342  }
343  else if ($modulepart == 'facture' || $modulepart == 'invoice')
344  {
345  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
346 
347  if (!DolibarrApiAccess::$user->rights->facture->lire) {
348  throw new RestException(401);
349  }
350 
351  $object = new Facture($this->db);
352  $result=$object->fetch($id, $ref);
353  if ( ! $result ) {
354  throw new RestException(404, 'Invoice not found');
355  }
356 
357  $upload_dir = $conf->facture->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'invoice');
358  }
359  else
360  {
361  throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
362  }
363 
364  $filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
365  if (empty($filearray)) {
366  throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$object->id.(! empty($object->Ref)?' or Ref '.$object->ref:'').' does not return any document.');
367  }
368 
369  return $filearray;
370  }
371 
372 
381  /*
382  public function get($id) {
383  return array('note'=>'xxx');
384  }*/
385 
386 
409  public function post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0)
410  {
411  global $db, $conf;
412 
413  /*var_dump($modulepart);
414  var_dump($filename);
415  var_dump($filecontent);
416  exit;*/
417 
418  if(empty($modulepart))
419  {
420  throw new RestException(400, 'Modulepart not provided.');
421  }
422 
423  if (!DolibarrApiAccess::$user->rights->ecm->upload) {
424  throw new RestException(401);
425  }
426 
427  $newfilecontent = '';
428  if (empty($fileencoding)) $newfilecontent = $filecontent;
429  if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent);
430 
431  $original_file = dol_sanitizeFileName($filename);
432 
433  // Define $uploadir
434  $object = null;
435  $entity = DolibarrApiAccess::$user->entity;
436  if ($ref)
437  {
438  $tmpreldir='';
439 
440  if ($modulepart == 'facture' || $modulepart == 'invoice')
441  {
442  $modulepart='facture';
443 
444  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
445  $object = new Facture($this->db);
446  }
447  elseif ($modulepart == 'project')
448  {
449  require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
450  $object = new Project($this->db);
451  }
452  elseif ($modulepart == 'task' || $modulepart == 'project_task')
453  {
454  $modulepart = 'project_task';
455 
456  require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
457  $object = new Task($this->db);
458 
459  $task_result = $object->fetch('', $ref);
460 
461  // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
462  if($task_result > 0)
463  {
464  $project_result = $object->fetch_projet();
465 
466  if($project_result >= 0)
467  {
468  $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
469  }
470  }
471  else
472  {
473  throw new RestException(500, 'Error while fetching Task '.$ref);
474  }
475  }
476  // TODO Implement additional moduleparts
477  else
478  {
479  throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
480  }
481 
482  if(is_object($object))
483  {
484  $result = $object->fetch('', $ref);
485 
486  if($result == 0)
487  {
488  throw new RestException(404, "Object with ref '".$ref."' was not found.");
489  }
490  elseif ($result < 0)
491  {
492  throw new RestException(500, 'Error while fetching object.');
493  }
494  }
495 
496  if (! ($object->id > 0))
497  {
498  throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
499  }
500 
501  $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref);
502 
503  $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
504  $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
505 
506  if (empty($upload_dir) || $upload_dir == '/')
507  {
508  throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.');
509  }
510  }
511  else
512  {
513  if ($modulepart == 'invoice') $modulepart ='facture';
514 
515  $relativefile = $subdir;
516 
517  $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
518  $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
519 
520  if (empty($upload_dir) || $upload_dir == '/')
521  {
522  throw new RestException(500, 'This value of modulepart does not support yet usage of ref. Check modulepart parameter or try to use subdir parameter instead of ref.');
523  }
524  }
525  // $original_file here is still value of filename without any dir.
526 
527  $upload_dir = dol_sanitizePathName($upload_dir);
528 
529  $destfile = $upload_dir . '/' . $original_file;
530  $destfiletmp = DOL_DATA_ROOT.'/admin/temp/' . $original_file;
531  dol_delete_file($destfiletmp);
532  //var_dump($original_file);exit;
533 
534  if (!dol_is_dir(dirname($destfile))) {
535  throw new RestException(401, 'Directory not exists : '.dirname($destfile));
536  }
537 
538  if (! $overwriteifexists && dol_is_file($destfile))
539  {
540  throw new RestException(500, "File with name '".$original_file."' already exists.");
541  }
542 
543  $fhandle = @fopen($destfiletmp, 'w');
544  if ($fhandle)
545  {
546  $nbofbyteswrote = fwrite($fhandle, $newfilecontent);
547  fclose($fhandle);
548  @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK));
549  }
550  else
551  {
552  throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
553  }
554 
555  $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1);
556  if (! $result)
557  {
558  throw new RestException(500, "Failed to move file into '".$destfile."'");
559  }
560 
561  return dol_basename($destfile);
562  }
563 
571  function _validate_file($data) {
572  $result = array();
573  foreach (Documents::$DOCUMENT_FIELDS as $field) {
574  if (!isset($data[$field]))
575  throw new RestException(400, "$field field missing");
576  $result[$field] = $data[$field];
577  }
578  return $result;
579  }
580 }
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
index($module_part, $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.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
Return a path to have a the directory according to object where files are stored. ...
API class for receive files.
dol_is_dir($folder)
Test if filename is a directory.
Definition: files.lib.php:414
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:1970
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="")
Scan a directory and return a list of files/directories.
Definition: files.lib.php:58
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1)
Move a file into another name.
Definition: files.lib.php:780
Class for API REST v1.
Definition: api.class.php:29
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage projects.
Class to manage shipments.
Class to manage customers orders.
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:35
builddoc($module_part, $original_file='', $doctemplate='', $langcode='')
Build a document.
Class to manage translations.
dol_is_file($pathoffile)
Return if path is a file.
Definition: files.lib.php:427
Class to manage tasks.
Definition: task.class.php:32
__construct()
Constructor.
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null)
Remove a file or several files with a mask.
Definition: files.lib.php:1103
Class to manage invoices.
getDocumentsListByElement($modulepart, $id=0, $ref='', $sortfield='', $sortorder='')
Return the list of documents of a dedicated element (from its ID or Ref)
Class to manage proposals.