api_documents.class.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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. * Copyright (C) 2023 Romain Neil <contact@romain-neil.fr>
  6. *
  7. * This program is free software you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. use Luracast\Restler\RestException;
  21. use Luracast\Restler\Format\UploadFormat;
  22. require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
  23. require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
  24. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  25. /**
  26. * API class for receive files
  27. *
  28. * @access protected
  29. * @class Documents {@requires user,external}
  30. */
  31. class Documents extends DolibarrApi
  32. {
  33. /**
  34. * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object
  35. */
  36. public static $DOCUMENT_FIELDS = array(
  37. 'modulepart'
  38. );
  39. /**
  40. * Constructor
  41. */
  42. public function __construct()
  43. {
  44. global $db;
  45. $this->db = $db;
  46. }
  47. /**
  48. * Download a document.
  49. *
  50. * Note that, this API is similar to using the wrapper link "documents.php" to download a file (used for
  51. * internal HTML links of documents into application), but with no need to have a session cookie (the token is used instead).
  52. *
  53. * @param string $modulepart Name of module or area concerned by file download ('facture', ...)
  54. * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf)
  55. * @return array List of documents
  56. *
  57. * @throws RestException 400
  58. * @throws RestException 401
  59. * @throws RestException 404
  60. *
  61. * @url GET /download
  62. */
  63. public function index($modulepart, $original_file = '')
  64. {
  65. global $conf;
  66. if (empty($modulepart)) {
  67. throw new RestException(400, 'bad value for parameter modulepart');
  68. }
  69. if (empty($original_file)) {
  70. throw new RestException(400, 'bad value for parameter original_file');
  71. }
  72. //--- Finds and returns the document
  73. $entity = $conf->entity;
  74. // Special cases that need to use get_exdir to get real dir of object
  75. // If future, all object should use this to define path of documents.
  76. /*
  77. $tmpreldir = '';
  78. if ($modulepart == 'supplier_invoice') {
  79. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  80. }
  81. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
  82. $relativefile = $original_file;
  83. $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
  84. $accessallowed = $check_access['accessallowed'];
  85. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  86. $original_file = $check_access['original_file'];
  87. if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
  88. throw new RestException(401);
  89. }
  90. if (!$accessallowed) {
  91. throw new RestException(401);
  92. }
  93. $filename = basename($original_file);
  94. $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
  95. if (!file_exists($original_file_osencoded)) {
  96. dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
  97. throw new RestException(404, 'File not found');
  98. }
  99. $file_content = file_get_contents($original_file_osencoded);
  100. return array('filename'=>$filename, 'content-type' => dol_mimetype($filename), 'filesize'=>filesize($original_file), 'content'=>base64_encode($file_content), 'encoding'=>'base64');
  101. }
  102. /**
  103. * Build a document.
  104. *
  105. * Test sample 1: { "modulepart": "invoice", "original_file": "FA1701-001/FA1701-001.pdf", "doctemplate": "crabe", "langcode": "fr_FR" }.
  106. *
  107. * Supported modules: invoice, order, proposal, contract, shipment
  108. *
  109. * @param string $modulepart Name of module or area concerned by file download ('thirdparty', 'member', 'proposal', 'supplier_proposal', 'order', 'supplier_order', 'invoice', 'supplier_invoice', 'shipment', 'project', ...)
  110. * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf).
  111. * @param string $doctemplate Set here the doc template to use for document generation (If not set, use the default template).
  112. * @param string $langcode Language code like 'en_US', 'fr_FR', 'es_ES', ... (If not set, use the default language).
  113. * @return array List of documents
  114. *
  115. * @throws RestException 500 System error
  116. * @throws RestException 501
  117. * @throws RestException 400
  118. * @throws RestException 401
  119. * @throws RestException 404
  120. *
  121. * @url PUT /builddoc
  122. */
  123. public function builddoc($modulepart, $original_file = '', $doctemplate = '', $langcode = '')
  124. {
  125. global $conf, $langs;
  126. if (empty($modulepart)) {
  127. throw new RestException(400, 'bad value for parameter modulepart');
  128. }
  129. if (empty($original_file)) {
  130. throw new RestException(400, 'bad value for parameter original_file');
  131. }
  132. $outputlangs = $langs;
  133. if ($langcode && $langs->defaultlang != $langcode) {
  134. $outputlangs = new Translate('', $conf);
  135. $outputlangs->setDefaultLang($langcode);
  136. }
  137. //--- Finds and returns the document
  138. $entity = $conf->entity;
  139. // Special cases that need to use get_exdir to get real dir of object
  140. // If future, all object should use this to define path of documents.
  141. /*
  142. $tmpreldir = '';
  143. if ($modulepart == 'supplier_invoice') {
  144. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  145. }
  146. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
  147. $relativefile = $original_file;
  148. $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
  149. $accessallowed = $check_access['accessallowed'];
  150. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  151. $original_file = $check_access['original_file'];
  152. if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
  153. throw new RestException(401);
  154. }
  155. if (!$accessallowed) {
  156. throw new RestException(401);
  157. }
  158. // --- Generates the document
  159. $hidedetails = !getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 0 : 1;
  160. $hidedesc = !getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 0 : 1;
  161. $hideref = !getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 0 : 1;
  162. $templateused = '';
  163. if ($modulepart == 'facture' || $modulepart == 'invoice') {
  164. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  165. $tmpobject = new Facture($this->db);
  166. $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  167. if (!$result) {
  168. throw new RestException(404, 'Invoice not found');
  169. }
  170. $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
  171. $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  172. if ($result <= 0) {
  173. throw new RestException(500, 'Error generating document');
  174. }
  175. } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'invoice_supplier') {
  176. require_once DOL_DOCUMENT_ROOT . '/fourn/class/fournisseur.facture.class.php';
  177. $tmpobject = new FactureFournisseur($this->db);
  178. $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  179. if (!$result) {
  180. throw new RestException(404, 'Supplier invoice not found');
  181. }
  182. $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
  183. $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  184. if ($result < 0) {
  185. throw new RestException(500, 'Error generating document');
  186. }
  187. } elseif ($modulepart == 'commande' || $modulepart == 'order') {
  188. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  189. $tmpobject = new Commande($this->db);
  190. $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  191. if (!$result) {
  192. throw new RestException(404, 'Order not found');
  193. }
  194. $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
  195. $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  196. if ($result <= 0) {
  197. throw new RestException(500, 'Error generating document');
  198. }
  199. } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
  200. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  201. $tmpobject = new Propal($this->db);
  202. $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  203. if (!$result) {
  204. throw new RestException(404, 'Proposal not found');
  205. }
  206. $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
  207. $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  208. if ($result <= 0) {
  209. throw new RestException(500, 'Error generating document');
  210. }
  211. } elseif ($modulepart == 'contrat' || $modulepart == 'contract') {
  212. require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
  213. $tmpobject = new Contrat($this->db);
  214. $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  215. if (!$result) {
  216. throw new RestException(404, 'Contract not found');
  217. }
  218. $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
  219. $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  220. if ($result <= 0) {
  221. throw new RestException(500, 'Error generating document missing doctemplate parameter');
  222. }
  223. } elseif ($modulepart == 'expedition' || $modulepart == 'shipment') {
  224. require_once DOL_DOCUMENT_ROOT . '/expedition/class/expedition.class.php';
  225. $tmpobject = new Expedition($this->db);
  226. $result = $tmpobject->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  227. if (!$result) {
  228. throw new RestException(404, 'Shipment not found');
  229. }
  230. $templateused = $doctemplate ? $doctemplate : $tmpobject->model_pdf;
  231. $result = $tmpobject->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  232. if ($result <= 0) {
  233. throw new RestException(500, 'Error generating document missing doctemplate parameter');
  234. }
  235. } else {
  236. throw new RestException(403, 'Generation not available for this modulepart');
  237. }
  238. $filename = basename($original_file);
  239. $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
  240. if (!file_exists($original_file_osencoded)) {
  241. throw new RestException(404, 'File not found');
  242. }
  243. $file_content = file_get_contents($original_file_osencoded);
  244. 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');
  245. }
  246. /**
  247. * Return the list of documents of a dedicated element (from its ID or Ref)
  248. *
  249. * Supported modules: thirdparty, user, member, proposal, order, supplier_order, shipment, invoice, supplier_invoice, product, event, expensereport, knowledgemanagement, category, contract
  250. *
  251. * @param string $modulepart Name of module or area concerned ('thirdparty', 'member', 'proposal', 'order', 'invoice', 'supplier_invoice', 'shipment', 'project', ...)
  252. * @param int $id ID of element
  253. * @param string $ref Ref of element
  254. * @param string $sortfield Sort criteria ('','fullname','relativename','name','date','size')
  255. * @param string $sortorder Sort order ('asc' or 'desc')
  256. * @return array Array of documents with path
  257. *
  258. * @throws RestException 400
  259. * @throws RestException 401
  260. * @throws RestException 404
  261. * @throws RestException 500 System error
  262. *
  263. * @url GET /
  264. */
  265. public function getDocumentsListByElement($modulepart, $id = 0, $ref = '', $sortfield = '', $sortorder = '')
  266. {
  267. global $conf;
  268. if (empty($modulepart)) {
  269. throw new RestException(400, 'bad value for parameter modulepart');
  270. }
  271. if (empty($id) && empty($ref)) {
  272. throw new RestException(400, 'bad value for parameter id or ref');
  273. }
  274. $id = (empty($id) ? 0 : $id);
  275. $recursive = 0;
  276. $type = 'files';
  277. if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
  278. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  279. if (!DolibarrApiAccess::$user->hasRight('societe', 'lire')) {
  280. throw new RestException(401);
  281. }
  282. $object = new Societe($this->db);
  283. $result = $object->fetch($id, $ref);
  284. if (!$result) {
  285. throw new RestException(404, 'Thirdparty not found');
  286. }
  287. $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
  288. } elseif ($modulepart == 'user') {
  289. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  290. // Can get doc if has permission to read all user or if it is user itself
  291. if (!DolibarrApiAccess::$user->rights->user->user->lire && DolibarrApiAccess::$user->id != $id) {
  292. throw new RestException(401);
  293. }
  294. $object = new User($this->db);
  295. $result = $object->fetch($id, $ref);
  296. if (!$result) {
  297. throw new RestException(404, 'User not found');
  298. }
  299. $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id;
  300. } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
  301. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  302. if (!DolibarrApiAccess::$user->rights->adherent->lire) {
  303. throw new RestException(401);
  304. }
  305. $object = new Adherent($this->db);
  306. $result = $object->fetch($id, $ref);
  307. if (!$result) {
  308. throw new RestException(404, 'Member not found');
  309. }
  310. $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member');
  311. } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
  312. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  313. if (!DolibarrApiAccess::$user->hasRight('propal', 'lire')) {
  314. throw new RestException(401);
  315. }
  316. $object = new Propal($this->db);
  317. $result = $object->fetch($id, $ref);
  318. if (!$result) {
  319. throw new RestException(404, 'Proposal not found');
  320. }
  321. $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
  322. } elseif ($modulepart == 'supplier_proposal') {
  323. require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
  324. if (!DolibarrApiAccess::$user->rights->supplier_proposal->read) {
  325. throw new RestException(401);
  326. }
  327. $object = new Propal($this->db);
  328. $result = $object->fetch($id, $ref);
  329. if (!$result) {
  330. throw new RestException(404, 'Supplier proposal not found');
  331. }
  332. $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
  333. } elseif ($modulepart == 'commande' || $modulepart == 'order') {
  334. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  335. if (!DolibarrApiAccess::$user->hasRight('commande', 'lire')) {
  336. throw new RestException(401);
  337. }
  338. $object = new Commande($this->db);
  339. $result = $object->fetch($id, $ref);
  340. if (!$result) {
  341. throw new RestException(404, 'Order not found');
  342. }
  343. $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
  344. } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
  345. $modulepart = 'supplier_order';
  346. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  347. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->lire) && empty(DolibarrApiAccess::$user->rights->supplier_order->lire)) {
  348. throw new RestException(401);
  349. }
  350. $object = new CommandeFournisseur($this->db);
  351. $result = $object->fetch($id, $ref);
  352. if (!$result) {
  353. throw new RestException(404, 'Purchase order not found');
  354. }
  355. $upload_dir = $conf->fournisseur->dir_output."/commande/".dol_sanitizeFileName($object->ref);
  356. } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
  357. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  358. if (!DolibarrApiAccess::$user->rights->expedition->lire) {
  359. throw new RestException(401);
  360. }
  361. $object = new Expedition($this->db);
  362. $result = $object->fetch($id, $ref);
  363. if (!$result) {
  364. throw new RestException(404, 'Shipment not found');
  365. }
  366. $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
  367. } elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
  368. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  369. if (!DolibarrApiAccess::$user->hasRight('facture', 'lire')) {
  370. throw new RestException(401);
  371. }
  372. $object = new Facture($this->db);
  373. $result = $object->fetch($id, $ref);
  374. if (!$result) {
  375. throw new RestException(404, 'Invoice not found');
  376. }
  377. $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
  378. } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
  379. $modulepart = 'supplier_invoice';
  380. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  381. if (empty(DolibarrApiAccess::$user->rights->fournisseur->facture->lire) && empty(DolibarrApiAccess::$user->rights->supplier_invoice->lire)) {
  382. throw new RestException(401);
  383. }
  384. $object = new FactureFournisseur($this->db);
  385. $result = $object->fetch($id, $ref);
  386. if (!$result) {
  387. throw new RestException(404, 'Invoice not found');
  388. }
  389. $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
  390. } elseif ($modulepart == 'produit' || $modulepart == 'product') {
  391. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  392. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  393. throw new RestException(401);
  394. }
  395. $object = new Product($this->db);
  396. $result = $object->fetch($id, $ref);
  397. if ($result == 0) {
  398. throw new RestException(404, 'Product not found');
  399. } elseif ($result < 0) {
  400. throw new RestException(500, 'Error while fetching object: '.$object->error);
  401. }
  402. $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
  403. } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
  404. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  405. if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) {
  406. throw new RestException(401);
  407. }
  408. $object = new ActionComm($this->db);
  409. $result = $object->fetch($id, $ref);
  410. if (!$result) {
  411. throw new RestException(404, 'Event not found');
  412. }
  413. $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
  414. } elseif ($modulepart == 'expensereport') {
  415. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  416. if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) {
  417. throw new RestException(401);
  418. }
  419. $object = new ExpenseReport($this->db);
  420. $result = $object->fetch($id, $ref);
  421. if (!$result) {
  422. throw new RestException(404, 'Expense report not found');
  423. }
  424. $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
  425. } elseif ($modulepart == 'knowledgemanagement') {
  426. require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php';
  427. if (!DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read') && !DolibarrApiAccess::$user->hasRight('knowledgemanagement', 'knowledgerecord', 'read')) {
  428. throw new RestException(401);
  429. }
  430. $object = new KnowledgeRecord($this->db);
  431. $result = $object->fetch($id, $ref);
  432. if (!$result) {
  433. throw new RestException(404, 'KM article not found');
  434. }
  435. $upload_dir = $conf->knowledgemanagement->dir_output.'/knowledgerecord/'.dol_sanitizeFileName($object->ref);
  436. } elseif ($modulepart == 'categorie' || $modulepart == 'category') {
  437. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  438. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  439. throw new RestException(401);
  440. }
  441. $object = new Categorie($this->db);
  442. $result = $object->fetch($id, $ref);
  443. if (!$result) {
  444. throw new RestException(404, 'Category not found');
  445. }
  446. $upload_dir = $conf->categorie->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'category').$object->id."/photos/".dol_sanitizeFileName($object->ref);
  447. } elseif ($modulepart == 'ecm') {
  448. throw new RestException(500, 'Modulepart Ecm not implemented yet.');
  449. // require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
  450. // if (!DolibarrApiAccess::$user->rights->ecm->read) {
  451. // throw new RestException(401);
  452. // }
  453. // // $object = new EcmDirectory($this->db);
  454. // // $result = $object->fetch($ref);
  455. // // if (!$result) {
  456. // // throw new RestException(404, 'EcmDirectory not found');
  457. // // }
  458. // $upload_dir = $conf->ecm->dir_output;
  459. // $type = 'all';
  460. // $recursive = 0;
  461. } elseif ($modulepart == 'contrat' || $modulepart == 'contract') {
  462. $modulepart = 'contrat';
  463. require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
  464. $object = new Contrat($this->db);
  465. $result = $object->fetch($id, $ref);
  466. if (!$result) {
  467. throw new RestException(404, 'Contract not found');
  468. }
  469. $upload_dir = $conf->contrat->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'contract');
  470. } elseif ($modulepart == 'projet' || $modulepart == 'project') {
  471. $modulepart = 'project';
  472. require_once DOL_DOCUMENT_ROOT . '/projet/class/project.class.php';
  473. $object = new Project($this->db);
  474. $result = $object->fetch($id, $ref);
  475. if (!$result) {
  476. throw new RestException(404, 'Project not found');
  477. }
  478. $upload_dir = $conf->projet->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'project');
  479. } else {
  480. throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
  481. }
  482. $objectType = $modulepart;
  483. if (! empty($object->id) && ! empty($object->table_element)) {
  484. $objectType = $object->table_element;
  485. }
  486. $filearray = dol_dir_list($upload_dir, $type, $recursive, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ? SORT_DESC : SORT_ASC), 1);
  487. if (empty($filearray)) {
  488. throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$object->id.(!empty($object->ref) ? ' or Ref '.$object->ref : '').' does not return any document.');
  489. } else {
  490. if (($object->id) > 0 && !empty($modulepart)) {
  491. require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  492. $ecmfile = new EcmFiles($this->db);
  493. $result = $ecmfile->fetchAll('', '', 0, 0, array('t.src_object_type' => $objectType, 't.src_object_id' => $object->id));
  494. if ($result < 0) {
  495. throw new RestException(503, 'Error when retrieve ecm list : '.$this->db->lasterror());
  496. } elseif (is_array($ecmfile->lines) && count($ecmfile->lines) > 0) {
  497. $count = count($filearray);
  498. for ($i = 0 ; $i < $count ; $i++) {
  499. if ($filearray[$i]['name'] == $ecmfile->lines[$i]->filename) {
  500. $filearray[$i] = array_merge($filearray[$i], (array) $ecmfile->lines[0]);
  501. }
  502. }
  503. }
  504. }
  505. }
  506. return $filearray;
  507. }
  508. /**
  509. * Return a document.
  510. *
  511. * @param int $id ID of document
  512. * @return array Array with data of file
  513. *
  514. * @throws RestException
  515. */
  516. /*
  517. public function get($id) {
  518. return array('note'=>'xxx');
  519. }*/
  520. /**
  521. * Upload a document.
  522. *
  523. * Test sample for invoice: { "filename": "mynewfile.txt", "modulepart": "invoice", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }.
  524. * Test sample for supplier invoice: { "filename": "mynewfile.txt", "modulepart": "supplier_invoice", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }.
  525. * Test sample for medias file: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "image/mywebsite", "filecontent": "Y29udGVudCB0ZXh0Cg==", "fileencoding": "base64", "overwriteifexists": "0" }.
  526. *
  527. * Supported modules: invoice, order, supplier_order, task/project_task, product/service, expensereport, fichinter, member, propale, agenda, contact
  528. *
  529. * @param string $filename Name of file to create ('FA1705-0123.txt')
  530. * @param string $modulepart Name of module or area concerned by file upload ('product', 'service', 'invoice', 'proposal', 'project', 'project_task', 'supplier_invoice', 'expensereport', 'member', ...)
  531. * @param string $ref Reference of object (This will define subdir automatically and store submited file into it)
  532. * @param string $subdir Subdirectory (Only if ref not provided)
  533. * @param string $filecontent File content (string with file content. An empty file will be created if this parameter is not provided)
  534. * @param string $fileencoding File encoding (''=no encoding, 'base64'=Base 64)
  535. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  536. * @param int $createdirifnotexists Create subdirectories if the doesn't exists (1 by default)
  537. * @return string
  538. *
  539. * @throws RestException 400
  540. * @throws RestException 401
  541. * @throws RestException 404
  542. * @throws RestException 500 System error
  543. *
  544. * @url POST /upload
  545. */
  546. public function post($filename, $modulepart, $ref = '', $subdir = '', $filecontent = '', $fileencoding = '', $overwriteifexists = 0, $createdirifnotexists = 1)
  547. {
  548. global $conf;
  549. //var_dump($modulepart);
  550. //var_dump($filename);
  551. //var_dump($filecontent);exit;
  552. $modulepartorig = $modulepart;
  553. if (empty($modulepart)) {
  554. throw new RestException(400, 'Modulepart not provided.');
  555. }
  556. $newfilecontent = '';
  557. if (empty($fileencoding)) {
  558. $newfilecontent = $filecontent;
  559. }
  560. if ($fileencoding == 'base64') {
  561. $newfilecontent = base64_decode($filecontent);
  562. }
  563. $original_file = dol_sanitizeFileName($filename);
  564. // Define $uploadir
  565. $object = null;
  566. $entity = DolibarrApiAccess::$user->entity;
  567. if (empty($entity)) {
  568. $entity = 1;
  569. }
  570. if ($ref) {
  571. $tmpreldir = '';
  572. $fetchbyid = false;
  573. if ($modulepart == 'facture' || $modulepart == 'invoice') {
  574. $modulepart = 'facture';
  575. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  576. $object = new Facture($this->db);
  577. } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
  578. $modulepart = 'supplier_invoice';
  579. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  580. $object = new FactureFournisseur($this->db);
  581. } elseif ($modulepart == 'commande' || $modulepart == 'order') {
  582. $modulepart = 'commande';
  583. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  584. $object = new Commande($this->db);
  585. } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
  586. $modulepart = 'supplier_order';
  587. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  588. $object = new CommandeFournisseur($this->db);
  589. } elseif ($modulepart == 'projet' || $modulepart == 'project') {
  590. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  591. $object = new Project($this->db);
  592. } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
  593. $modulepart = 'project_task';
  594. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  595. $object = new Task($this->db);
  596. $task_result = $object->fetch('', $ref);
  597. // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
  598. if ($task_result > 0) {
  599. $project_result = $object->fetch_projet();
  600. if ($project_result >= 0) {
  601. $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
  602. }
  603. } else {
  604. throw new RestException(500, 'Error while fetching Task '.$ref);
  605. }
  606. } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
  607. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  608. $object = new Product($this->db);
  609. } elseif ($modulepart == 'expensereport') {
  610. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  611. $object = new ExpenseReport($this->db);
  612. } elseif ($modulepart == 'fichinter') {
  613. require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
  614. $object = new Fichinter($this->db);
  615. } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
  616. $modulepart = 'adherent';
  617. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  618. $object = new Adherent($this->db);
  619. } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
  620. $modulepart = 'propale';
  621. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  622. $object = new Propal($this->db);
  623. } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
  624. $modulepart = 'agenda';
  625. require_once DOL_DOCUMENT_ROOT . '/comm/action/class/actioncomm.class.php';
  626. $object = new ActionComm($this->db);
  627. } elseif ($modulepart == 'contact' || $modulepart == 'socpeople') {
  628. $modulepart = 'contact';
  629. require_once DOL_DOCUMENT_ROOT.'/contact/class/contact.class.php';
  630. $object = new Contact($this->db);
  631. $fetchbyid = true;
  632. } elseif ($modulepart == 'contrat' || $modulepart == 'contract') {
  633. $modulepart = 'contrat';
  634. require_once DOL_DOCUMENT_ROOT . '/contrat/class/contrat.class.php';
  635. $object = new Contrat($this->db);
  636. } else {
  637. // TODO Implement additional moduleparts
  638. throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
  639. }
  640. if (is_object($object)) {
  641. if ($fetchbyid) {
  642. $result = $object->fetch($ref);
  643. } else {
  644. $result = $object->fetch('', $ref);
  645. }
  646. if ($result == 0) {
  647. throw new RestException(404, "Object with ref '".$ref."' was not found.");
  648. } elseif ($result < 0) {
  649. throw new RestException(500, 'Error while fetching object: '.$object->error);
  650. }
  651. }
  652. if (!($object->id > 0)) {
  653. throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
  654. }
  655. // Special cases that need to use get_exdir to get real dir of object
  656. // In future, all object should use this to define path of documents.
  657. if ($modulepart == 'supplier_invoice') {
  658. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  659. }
  660. // Test on permissions
  661. if ($modulepart != 'ecm') {
  662. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref);
  663. $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
  664. $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
  665. } else {
  666. if (!DolibarrApiAccess::$user->hasRight('ecm', 'upload')) {
  667. throw new RestException(401, 'Missing permission to upload files in ECM module');
  668. }
  669. $upload_dir = $conf->medias->multidir_output[$conf->entity];
  670. }
  671. if (empty($upload_dir) || $upload_dir == '/') {
  672. 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.');
  673. }
  674. } else {
  675. if ($modulepart == 'invoice') {
  676. $modulepart = 'facture';
  677. }
  678. if ($modulepart == 'member') {
  679. $modulepart = 'adherent';
  680. }
  681. // Test on permissions
  682. if ($modulepart != 'ecm') {
  683. $relativefile = $subdir;
  684. $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
  685. $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
  686. } else {
  687. if (!DolibarrApiAccess::$user->hasRight('ecm', 'upload')) {
  688. throw new RestException(401, 'Missing permission to upload files in ECM module');
  689. }
  690. $upload_dir = $conf->medias->multidir_output[$conf->entity];
  691. }
  692. if (empty($upload_dir) || $upload_dir == '/') {
  693. if (!empty($tmp['error'])) {
  694. throw new RestException(401, 'Error returned by dol_check_secure_access_document: '.$tmp['error']);
  695. } else {
  696. throw new RestException(500, 'This value of modulepart ('.$modulepart.') is not allowed with this value of subdir ('.$relativefile.')');
  697. }
  698. }
  699. }
  700. // $original_file here is still value of filename without any dir.
  701. $upload_dir = dol_sanitizePathName($upload_dir);
  702. if (!empty($createdirifnotexists)) {
  703. if (dol_mkdir($upload_dir) < 0) { // needed by products
  704. throw new RestException(500, 'Error while trying to create directory '.$upload_dir);
  705. }
  706. }
  707. $destfile = $upload_dir.'/'.$original_file;
  708. $destfiletmp = DOL_DATA_ROOT.'/admin/temp/'.$original_file;
  709. dol_delete_file($destfiletmp);
  710. //var_dump($original_file);exit;
  711. if (!dol_is_dir(dirname($destfile))) {
  712. throw new RestException(401, 'Directory not exists : '.dirname($destfile));
  713. }
  714. if (!$overwriteifexists && dol_is_file($destfile)) {
  715. throw new RestException(500, "File with name '".$original_file."' already exists.");
  716. }
  717. // in case temporary directory admin/temp doesn't exist
  718. if (!dol_is_dir(dirname($destfiletmp))) {
  719. dol_mkdir(dirname($destfiletmp));
  720. }
  721. $fhandle = @fopen($destfiletmp, 'w');
  722. if ($fhandle) {
  723. $nbofbyteswrote = fwrite($fhandle, $newfilecontent);
  724. fclose($fhandle);
  725. dolChmod($destfiletmp);
  726. } else {
  727. throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
  728. }
  729. $disablevirusscan = 0;
  730. $src_file = $destfiletmp;
  731. $dest_file = $destfile;
  732. // Security:
  733. // If we need to make a virus scan
  734. if (empty($disablevirusscan) && file_exists($src_file)) {
  735. $checkvirusarray = dolCheckVirus($src_file);
  736. if (count($checkvirusarray)) {
  737. dol_syslog('Files.lib::dol_move_uploaded_file File "'.$src_file.'" (target name "'.$dest_file.'") KO with antivirus: errors='.join(',', $checkvirusarray), LOG_WARNING);
  738. throw new RestException(500, 'ErrorFileIsInfectedWithAVirus: '.join(',', $checkvirusarray));
  739. }
  740. }
  741. // Security:
  742. // Disallow file with some extensions. We rename them.
  743. // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
  744. if (isAFileWithExecutableContent($dest_file) && !getDolGlobalString('MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED')) {
  745. // $upload_dir ends with a slash, so be must be sure the medias dir to compare to ends with slash too.
  746. $publicmediasdirwithslash = $conf->medias->multidir_output[$conf->entity];
  747. if (!preg_match('/\/$/', $publicmediasdirwithslash)) {
  748. $publicmediasdirwithslash .= '/';
  749. }
  750. if (strpos($upload_dir, $publicmediasdirwithslash) !== 0 || !getDolGlobalInt("MAIN_DOCUMENT_DISABLE_NOEXE_IN_MEDIAS_DIR")) { // We never add .noexe on files into media directory
  751. $dest_file .= '.noexe';
  752. }
  753. }
  754. // Security:
  755. // We refuse cache files/dirs, upload using .. and pipes into filenames.
  756. if (preg_match('/^\./', basename($src_file)) || preg_match('/\.\./', $src_file) || preg_match('/[<>|]/', $src_file)) {
  757. dol_syslog("Refused to deliver file ".$src_file, LOG_WARNING);
  758. throw new RestException(500, "Refused to deliver file ".$src_file);
  759. }
  760. // Security:
  761. // We refuse cache files/dirs, upload using .. and pipes into filenames.
  762. if (preg_match('/^\./', basename($dest_file)) || preg_match('/\.\./', $dest_file) || preg_match('/[<>|]/', $dest_file)) {
  763. dol_syslog("Refused to deliver file ".$dest_file, LOG_WARNING);
  764. throw new RestException(500, "Refused to deliver file ".$dest_file);
  765. }
  766. $moreinfo = array('note_private' => 'File uploaded using API /documents from IP '.getUserRemoteIP());
  767. if (!empty($object) && is_object($object) && $object->id > 0) {
  768. $moreinfo['src_object_type'] = $object->table_element;
  769. $moreinfo['src_object_id'] = $object->id;
  770. }
  771. // Move the temporary file at its final emplacement
  772. $result = dol_move($destfiletmp, $dest_file, 0, $overwriteifexists, 1, 1, $moreinfo);
  773. if (!$result) {
  774. throw new RestException(500, "Failed to move file into '".$destfile."'");
  775. }
  776. return dol_basename($destfile);
  777. }
  778. /**
  779. * Delete a document.
  780. *
  781. * @param string $modulepart Name of module or area concerned by file download ('product', ...)
  782. * @param string $original_file Relative path with filename, relative to modulepart (for example: PRODUCT-REF-999/IMAGE-999.jpg)
  783. * @return array List of documents
  784. *
  785. * @throws RestException 400
  786. * @throws RestException 401
  787. * @throws RestException 404
  788. *
  789. * @url DELETE /
  790. */
  791. public function delete($modulepart, $original_file)
  792. {
  793. global $conf, $langs;
  794. if (empty($modulepart)) {
  795. throw new RestException(400, 'bad value for parameter modulepart');
  796. }
  797. if (empty($original_file)) {
  798. throw new RestException(400, 'bad value for parameter original_file');
  799. }
  800. //--- Finds and returns the document
  801. $entity = $conf->entity;
  802. // Special cases that need to use get_exdir to get real dir of object
  803. // If future, all object should use this to define path of documents.
  804. /*
  805. $tmpreldir = '';
  806. if ($modulepart == 'supplier_invoice') {
  807. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  808. }
  809. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
  810. $relativefile = $original_file;
  811. $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
  812. $accessallowed = $check_access['accessallowed'];
  813. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  814. $original_file = $check_access['original_file'];
  815. if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
  816. throw new RestException(401);
  817. }
  818. if (!$accessallowed) {
  819. throw new RestException(401);
  820. }
  821. $filename = basename($original_file);
  822. $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
  823. if (!file_exists($original_file_osencoded)) {
  824. dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
  825. throw new RestException(404, 'File not found');
  826. }
  827. if (@unlink($original_file_osencoded)) {
  828. return array(
  829. 'success' => array(
  830. 'code' => 200,
  831. 'message' => 'Document deleted'
  832. )
  833. );
  834. }
  835. throw new RestException(401);
  836. }
  837. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  838. /**
  839. * Validate fields before create or update object
  840. *
  841. * @param array $data Array with data to verify
  842. * @return array
  843. * @throws RestException
  844. */
  845. private function _validate_file($data)
  846. {
  847. // phpcs:enable
  848. $result = array();
  849. foreach (Documents::$DOCUMENT_FIELDS as $field) {
  850. if (!isset($data[$field])) {
  851. throw new RestException(400, "$field field missing");
  852. }
  853. $result[$field] = $data[$field];
  854. }
  855. return $result;
  856. }
  857. }