api_documents.class.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  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. use Luracast\Restler\RestException;
  20. use Luracast\Restler\Format\UploadFormat;
  21. require_once DOL_DOCUMENT_ROOT.'/main.inc.php';
  22. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  23. /**
  24. * API class for receive files
  25. *
  26. * @access protected
  27. * @class Documents {@requires user,external}
  28. */
  29. class Documents extends DolibarrApi
  30. {
  31. /**
  32. * @var array $DOCUMENT_FIELDS Mandatory fields, checked when create and update object
  33. */
  34. public static $DOCUMENT_FIELDS = array(
  35. 'modulepart'
  36. );
  37. /**
  38. * Constructor
  39. */
  40. public function __construct()
  41. {
  42. global $db;
  43. $this->db = $db;
  44. }
  45. /**
  46. * Download a document.
  47. *
  48. * Note that, this API is similar to using the wrapper link "documents.php" to download a file (used for
  49. * internal HTML links of documents into application), but with no need to have a session cookie (the token is used instead).
  50. *
  51. * @param string $modulepart Name of module or area concerned by file download ('facture', ...)
  52. * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf)
  53. * @return array List of documents
  54. *
  55. * @throws RestException 400
  56. * @throws RestException 401
  57. * @throws RestException 404
  58. *
  59. * @url GET /download
  60. */
  61. public function index($modulepart, $original_file = '')
  62. {
  63. global $conf, $langs;
  64. if (empty($modulepart)) {
  65. throw new RestException(400, 'bad value for parameter modulepart');
  66. }
  67. if (empty($original_file)) {
  68. throw new RestException(400, 'bad value for parameter original_file');
  69. }
  70. //--- Finds and returns the document
  71. $entity = $conf->entity;
  72. // Special cases that need to use get_exdir to get real dir of object
  73. // If future, all object should use this to define path of documents.
  74. /*
  75. $tmpreldir = '';
  76. if ($modulepart == 'supplier_invoice') {
  77. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  78. }
  79. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
  80. $relativefile = $original_file;
  81. $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
  82. $accessallowed = $check_access['accessallowed'];
  83. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  84. $original_file = $check_access['original_file'];
  85. if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
  86. throw new RestException(401);
  87. }
  88. if (!$accessallowed) {
  89. throw new RestException(401);
  90. }
  91. $filename = basename($original_file);
  92. $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
  93. if (!file_exists($original_file_osencoded)) {
  94. dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
  95. throw new RestException(404, 'File not found');
  96. }
  97. $file_content = file_get_contents($original_file_osencoded);
  98. return array('filename'=>$filename, 'content-type' => dol_mimetype($filename), 'filesize'=>filesize($original_file), 'content'=>base64_encode($file_content), 'encoding'=>'base64');
  99. }
  100. /**
  101. * Build a document.
  102. *
  103. * Test sample 1: { "modulepart": "invoice", "original_file": "FA1701-001/FA1701-001.pdf", "doctemplate": "crabe", "langcode": "fr_FR" }.
  104. *
  105. * @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', ...)
  106. * @param string $original_file Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf).
  107. * @param string $doctemplate Set here the doc template to use for document generation (If not set, use the default template).
  108. * @param string $langcode Language code like 'en_US', 'fr_FR', 'es_ES', ... (If not set, use the default language).
  109. * @return array List of documents
  110. *
  111. * @throws RestException 500 System error
  112. * @throws RestException 501
  113. * @throws RestException 400
  114. * @throws RestException 401
  115. * @throws RestException 404
  116. *
  117. * @url PUT /builddoc
  118. */
  119. public function builddoc($modulepart, $original_file = '', $doctemplate = '', $langcode = '')
  120. {
  121. global $conf, $langs;
  122. if (empty($modulepart)) {
  123. throw new RestException(400, 'bad value for parameter modulepart');
  124. }
  125. if (empty($original_file)) {
  126. throw new RestException(400, 'bad value for parameter original_file');
  127. }
  128. $outputlangs = $langs;
  129. if ($langcode && $langs->defaultlang != $langcode) {
  130. $outputlangs = new Translate('', $conf);
  131. $outputlangs->setDefaultLang($langcode);
  132. }
  133. //--- Finds and returns the document
  134. $entity = $conf->entity;
  135. // Special cases that need to use get_exdir to get real dir of object
  136. // If future, all object should use this to define path of documents.
  137. /*
  138. $tmpreldir = '';
  139. if ($modulepart == 'supplier_invoice') {
  140. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  141. }
  142. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
  143. $relativefile = $original_file;
  144. $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
  145. $accessallowed = $check_access['accessallowed'];
  146. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  147. $original_file = $check_access['original_file'];
  148. if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
  149. throw new RestException(401);
  150. }
  151. if (!$accessallowed) {
  152. throw new RestException(401);
  153. }
  154. // --- Generates the document
  155. $hidedetails = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 0 : 1;
  156. $hidedesc = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 0 : 1;
  157. $hideref = empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 0 : 1;
  158. $templateused = '';
  159. if ($modulepart == 'facture' || $modulepart == 'invoice') {
  160. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  161. $this->invoice = new Facture($this->db);
  162. $result = $this->invoice->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  163. if (!$result) {
  164. throw new RestException(404, 'Invoice not found');
  165. }
  166. $templateused = $doctemplate ? $doctemplate : $this->invoice->model_pdf;
  167. $result = $this->invoice->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  168. if ($result <= 0) {
  169. throw new RestException(500, 'Error generating document');
  170. }
  171. } elseif ($modulepart == 'commande' || $modulepart == 'order') {
  172. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  173. $this->order = new Commande($this->db);
  174. $result = $this->order->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  175. if (!$result) {
  176. throw new RestException(404, 'Order not found');
  177. }
  178. $templateused = $doctemplate ? $doctemplate : $this->order->model_pdf;
  179. $result = $this->order->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  180. if ($result <= 0) {
  181. throw new RestException(500, 'Error generating document');
  182. }
  183. } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
  184. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  185. $this->propal = new Propal($this->db);
  186. $result = $this->propal->fetch(0, preg_replace('/\.[^\.]+$/', '', basename($original_file)));
  187. if (!$result) {
  188. throw new RestException(404, 'Proposal not found');
  189. }
  190. $templateused = $doctemplate ? $doctemplate : $this->propal->model_pdf;
  191. $result = $this->propal->generateDocument($templateused, $outputlangs, $hidedetails, $hidedesc, $hideref);
  192. if ($result <= 0) {
  193. throw new RestException(500, 'Error generating document');
  194. }
  195. } else {
  196. throw new RestException(403, 'Generation not available for this modulepart');
  197. }
  198. $filename = basename($original_file);
  199. $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
  200. if (!file_exists($original_file_osencoded)) {
  201. throw new RestException(404, 'File not found');
  202. }
  203. $file_content = file_get_contents($original_file_osencoded);
  204. 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');
  205. }
  206. /**
  207. * Return the list of documents of a dedicated element (from its ID or Ref)
  208. *
  209. * @param string $modulepart Name of module or area concerned ('thirdparty', 'member', 'proposal', 'order', 'invoice', 'supplier_invoice', 'shipment', 'project', ...)
  210. * @param int $id ID of element
  211. * @param string $ref Ref of element
  212. * @param string $sortfield Sort criteria ('','fullname','relativename','name','date','size')
  213. * @param string $sortorder Sort order ('asc' or 'desc')
  214. * @return array Array of documents with path
  215. *
  216. * @throws RestException 400
  217. * @throws RestException 401
  218. * @throws RestException 404
  219. * @throws RestException 500 System error
  220. *
  221. * @url GET /
  222. */
  223. public function getDocumentsListByElement($modulepart, $id = 0, $ref = '', $sortfield = '', $sortorder = '')
  224. {
  225. global $conf;
  226. if (empty($modulepart)) {
  227. throw new RestException(400, 'bad value for parameter modulepart');
  228. }
  229. if (empty($id) && empty($ref)) {
  230. throw new RestException(400, 'bad value for parameter id or ref');
  231. }
  232. $id = (empty($id) ? 0 : $id);
  233. $recursive = 0;
  234. $type = 'files';
  235. if ($modulepart == 'societe' || $modulepart == 'thirdparty') {
  236. require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
  237. if (!DolibarrApiAccess::$user->rights->societe->lire) {
  238. throw new RestException(401);
  239. }
  240. $object = new Societe($this->db);
  241. $result = $object->fetch($id, $ref);
  242. if (!$result) {
  243. throw new RestException(404, 'Thirdparty not found');
  244. }
  245. $upload_dir = $conf->societe->multidir_output[$object->entity]."/".$object->id;
  246. } elseif ($modulepart == 'user') {
  247. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  248. // Can get doc if has permission to read all user or if it is user itself
  249. if (!DolibarrApiAccess::$user->rights->user->user->lire && DolibarrApiAccess::$user->id != $id) {
  250. throw new RestException(401);
  251. }
  252. $object = new User($this->db);
  253. $result = $object->fetch($id, $ref);
  254. if (!$result) {
  255. throw new RestException(404, 'User not found');
  256. }
  257. $upload_dir = $conf->user->dir_output.'/'.get_exdir(0, 0, 0, 0, $object, 'user').'/'.$object->id;
  258. } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
  259. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  260. if (!DolibarrApiAccess::$user->rights->adherent->lire) {
  261. throw new RestException(401);
  262. }
  263. $object = new Adherent($this->db);
  264. $result = $object->fetch($id, $ref);
  265. if (!$result) {
  266. throw new RestException(404, 'Member not found');
  267. }
  268. $upload_dir = $conf->adherent->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'member');
  269. } elseif ($modulepart == 'propal' || $modulepart == 'proposal') {
  270. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  271. if (!DolibarrApiAccess::$user->rights->propal->lire) {
  272. throw new RestException(401);
  273. }
  274. $object = new Propal($this->db);
  275. $result = $object->fetch($id, $ref);
  276. if (!$result) {
  277. throw new RestException(404, 'Proposal not found');
  278. }
  279. $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
  280. } elseif ($modulepart == 'supplier_proposal') {
  281. require_once DOL_DOCUMENT_ROOT.'/supplier_proposal/class/supplier_proposal.class.php';
  282. if (!DolibarrApiAccess::$user->rights->supplier_proposal->read) {
  283. throw new RestException(401);
  284. }
  285. $object = new Propal($this->db);
  286. $result = $object->fetch($id, $ref);
  287. if (!$result) {
  288. throw new RestException(404, 'Supplier proposal not found');
  289. }
  290. $upload_dir = $conf->propal->multidir_output[$object->entity]."/".get_exdir(0, 0, 0, 1, $object, 'propal');
  291. } elseif ($modulepart == 'commande' || $modulepart == 'order') {
  292. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  293. if (!DolibarrApiAccess::$user->rights->commande->lire) {
  294. throw new RestException(401);
  295. }
  296. $object = new Commande($this->db);
  297. $result = $object->fetch($id, $ref);
  298. if (!$result) {
  299. throw new RestException(404, 'Order not found');
  300. }
  301. $upload_dir = $conf->commande->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'commande');
  302. } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
  303. $modulepart = 'supplier_order';
  304. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  305. if (empty(DolibarrApiAccess::$user->rights->fournisseur->commande->lire) && empty(DolibarrApiAccess::$user->rights->supplier_order->lire)) {
  306. throw new RestException(401);
  307. }
  308. $object = new CommandeFournisseur($this->db);
  309. $result = $object->fetch($id, $ref);
  310. if (!$result) {
  311. throw new RestException(404, 'Purchase order not found');
  312. }
  313. $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
  314. } elseif ($modulepart == 'shipment' || $modulepart == 'expedition') {
  315. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  316. if (!DolibarrApiAccess::$user->rights->expedition->lire) {
  317. throw new RestException(401);
  318. }
  319. $object = new Expedition($this->db);
  320. $result = $object->fetch($id, $ref);
  321. if (!$result) {
  322. throw new RestException(404, 'Shipment not found');
  323. }
  324. $upload_dir = $conf->expedition->dir_output."/sending/".get_exdir(0, 0, 0, 1, $object, 'shipment');
  325. } elseif ($modulepart == 'facture' || $modulepart == 'invoice') {
  326. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  327. if (!DolibarrApiAccess::$user->rights->facture->lire) {
  328. throw new RestException(401);
  329. }
  330. $object = new Facture($this->db);
  331. $result = $object->fetch($id, $ref);
  332. if (!$result) {
  333. throw new RestException(404, 'Invoice not found');
  334. }
  335. $upload_dir = $conf->facture->dir_output."/".get_exdir(0, 0, 0, 1, $object, 'invoice');
  336. } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
  337. $modulepart = 'supplier_invoice';
  338. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  339. if (empty(DolibarrApiAccess::$user->rights->fournisseur->facture->lire) && empty(DolibarrApiAccess::$user->rights->supplier_invoice->lire)) {
  340. throw new RestException(401);
  341. }
  342. $object = new FactureFournisseur($this->db);
  343. $result = $object->fetch($id, $ref);
  344. if (!$result) {
  345. throw new RestException(404, 'Invoice not found');
  346. }
  347. $upload_dir = $conf->fournisseur->dir_output."/facture/".get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier').dol_sanitizeFileName($object->ref);
  348. } elseif ($modulepart == 'produit' || $modulepart == 'product') {
  349. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  350. if (!DolibarrApiAccess::$user->rights->produit->lire) {
  351. throw new RestException(401);
  352. }
  353. $object = new Product($this->db);
  354. $result = $object->fetch($id, $ref);
  355. if ($result == 0) {
  356. throw new RestException(404, 'Product not found');
  357. } elseif ($result < 0) {
  358. throw new RestException(500, 'Error while fetching object: '.$object->error);
  359. }
  360. $upload_dir = $conf->product->multidir_output[$object->entity].'/'.get_exdir(0, 0, 0, 1, $object, 'product');
  361. } elseif ($modulepart == 'agenda' || $modulepart == 'action' || $modulepart == 'event') {
  362. require_once DOL_DOCUMENT_ROOT.'/comm/action/class/actioncomm.class.php';
  363. if (!DolibarrApiAccess::$user->rights->agenda->myactions->read && !DolibarrApiAccess::$user->rights->agenda->allactions->read) {
  364. throw new RestException(401);
  365. }
  366. $object = new ActionComm($this->db);
  367. $result = $object->fetch($id, $ref);
  368. if (!$result) {
  369. throw new RestException(404, 'Event not found');
  370. }
  371. $upload_dir = $conf->agenda->dir_output.'/'.dol_sanitizeFileName($object->ref);
  372. } elseif ($modulepart == 'expensereport') {
  373. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  374. if (!DolibarrApiAccess::$user->rights->expensereport->read && !DolibarrApiAccess::$user->rights->expensereport->read) {
  375. throw new RestException(401);
  376. }
  377. $object = new ExpenseReport($this->db);
  378. $result = $object->fetch($id, $ref);
  379. if (!$result) {
  380. throw new RestException(404, 'Expense report not found');
  381. }
  382. $upload_dir = $conf->expensereport->dir_output.'/'.dol_sanitizeFileName($object->ref);
  383. } elseif ($modulepart == 'knowledgemanagement') {
  384. require_once DOL_DOCUMENT_ROOT.'/knowledgemanagement/class/knowledgerecord.class.php';
  385. if (!DolibarrApiAccess::$user->rights->knowledgemanagement->knowledgerecord->read && !DolibarrApiAccess::$user->rights->knowledgemanagement->knowledgerecord->read) {
  386. throw new RestException(401);
  387. }
  388. $object = new KnowledgeRecord($this->db);
  389. $result = $object->fetch($id, $ref);
  390. if (!$result) {
  391. throw new RestException(404, 'KM article not found');
  392. }
  393. $upload_dir = $conf->knowledgemanagement->dir_output.'/knowledgerecord/'.dol_sanitizeFileName($object->ref);
  394. } elseif ($modulepart == 'categorie' || $modulepart == 'category') {
  395. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  396. if (!DolibarrApiAccess::$user->rights->categorie->lire) {
  397. throw new RestException(401);
  398. }
  399. $object = new Categorie($this->db);
  400. $result = $object->fetch($id, $ref);
  401. if (!$result) {
  402. throw new RestException(404, 'Category not found');
  403. }
  404. $upload_dir = $conf->categorie->multidir_output[$object->entity].'/'.get_exdir($object->id, 2, 0, 0, $object, 'category').$object->id."/photos/".dol_sanitizeFileName($object->ref);
  405. } elseif ($modulepart == 'ecm') {
  406. throw new RestException(500, 'Modulepart Ecm not implemented yet.');
  407. // // require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmdirectory.class.php';
  408. // if (!DolibarrApiAccess::$user->rights->ecm->read) {
  409. // throw new RestException(401);
  410. // }
  411. // // $object = new EcmDirectory($this->db);
  412. // // $result = $object->fetch($ref);
  413. // // if (!$result) {
  414. // // throw new RestException(404, 'EcmDirectory not found');
  415. // // }
  416. // $upload_dir = $conf->ecm->dir_output;
  417. // $type = 'all';
  418. // $recursive = 0;
  419. } else {
  420. throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
  421. }
  422. $filearray = dol_dir_list($upload_dir, $type, $recursive, '', '(\.meta|_preview.*\.png)$', $sortfield, (strtolower($sortorder) == 'desc' ?SORT_DESC:SORT_ASC), 1);
  423. if (empty($filearray)) {
  424. throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$object->id.(!empty($object->ref) ? ' or Ref '.$object->ref : '').' does not return any document.');
  425. } else {
  426. if (($object->id) > 0 && !empty($modulepart)) {
  427. require_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
  428. $ecmfile = new EcmFiles($this->db);
  429. $result = $ecmfile->fetchAll('', '', 0, 0, array('t.src_object_type' => $modulepart, 't.src_object_id' => $object->id));
  430. if ($result < 0) {
  431. throw new RestException(503, 'Error when retrieve ecm list : '.$this->db->lasterror());
  432. } elseif (is_array($ecmfile->lines) && count($ecmfile->lines) > 0) {
  433. $filearray['ecmfiles_infos'] = $ecmfile->lines;
  434. }
  435. }
  436. }
  437. return $filearray;
  438. }
  439. /**
  440. * Return a document.
  441. *
  442. * @param int $id ID of document
  443. * @return array Array with data of file
  444. *
  445. * @throws RestException
  446. */
  447. /*
  448. public function get($id) {
  449. return array('note'=>'xxx');
  450. }*/
  451. /**
  452. * Upload a file.
  453. *
  454. * Test sample for invoice: { "filename": "mynewfile.txt", "modulepart": "invoice", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }.
  455. * Test sample for supplier invoice: { "filename": "mynewfile.txt", "modulepart": "supplier_invoice", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }.
  456. * Test sample for medias file: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "image/mywebsite", "filecontent": "Y29udGVudCB0ZXh0Cg==", "fileencoding": "base64", "overwriteifexists": "0" }.
  457. *
  458. * @param string $filename Name of file to create ('FA1705-0123.txt')
  459. * @param string $modulepart Name of module or area concerned by file upload ('product', 'service', 'invoice', 'proposal', 'project', 'project_task', 'supplier_invoice', 'expensereport', 'member', ...)
  460. * @param string $ref Reference of object (This will define subdir automatically and store submited file into it)
  461. * @param string $subdir Subdirectory (Only if ref not provided)
  462. * @param string $filecontent File content (string with file content. An empty file will be created if this parameter is not provided)
  463. * @param string $fileencoding File encoding (''=no encoding, 'base64'=Base 64)
  464. * @param int $overwriteifexists Overwrite file if exists (1 by default)
  465. * @param int $createdirifnotexists Create subdirectories if the doesn't exists (1 by default)
  466. * @return string
  467. *
  468. * @throws RestException 400
  469. * @throws RestException 401
  470. * @throws RestException 404
  471. * @throws RestException 500 System error
  472. *
  473. * @url POST /upload
  474. */
  475. public function post($filename, $modulepart, $ref = '', $subdir = '', $filecontent = '', $fileencoding = '', $overwriteifexists = 0, $createdirifnotexists = 1)
  476. {
  477. global $db, $conf;
  478. //var_dump($modulepart);
  479. //var_dump($filename);
  480. //var_dump($filecontent);exit;
  481. if (empty($modulepart)) {
  482. throw new RestException(400, 'Modulepart not provided.');
  483. }
  484. if (!DolibarrApiAccess::$user->rights->ecm->upload) {
  485. throw new RestException(401);
  486. }
  487. $newfilecontent = '';
  488. if (empty($fileencoding)) {
  489. $newfilecontent = $filecontent;
  490. }
  491. if ($fileencoding == 'base64') {
  492. $newfilecontent = base64_decode($filecontent);
  493. }
  494. $original_file = dol_sanitizeFileName($filename);
  495. // Define $uploadir
  496. $object = null;
  497. $entity = DolibarrApiAccess::$user->entity;
  498. if (empty($entity)) {
  499. $entity = 1;
  500. }
  501. if ($ref) {
  502. $tmpreldir = '';
  503. if ($modulepart == 'facture' || $modulepart == 'invoice') {
  504. $modulepart = 'facture';
  505. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  506. $object = new Facture($this->db);
  507. } elseif ($modulepart == 'facture_fournisseur' || $modulepart == 'supplier_invoice') {
  508. $modulepart = 'supplier_invoice';
  509. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  510. $object = new FactureFournisseur($this->db);
  511. } elseif ($modulepart == 'commande' || $modulepart == 'order') {
  512. $modulepart = 'commande';
  513. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  514. $object = new Commande($this->db);
  515. } elseif ($modulepart == 'commande_fournisseur' || $modulepart == 'supplier_order') {
  516. $modulepart = 'supplier_order';
  517. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  518. $object = new CommandeFournisseur($this->db);
  519. } elseif ($modulepart == 'project') {
  520. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  521. $object = new Project($this->db);
  522. } elseif ($modulepart == 'task' || $modulepart == 'project_task') {
  523. $modulepart = 'project_task';
  524. require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
  525. $object = new Task($this->db);
  526. $task_result = $object->fetch('', $ref);
  527. // Fetching the tasks project is required because its out_dir might be a sub-directory of the project
  528. if ($task_result > 0) {
  529. $project_result = $object->fetch_projet();
  530. if ($project_result >= 0) {
  531. $tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
  532. }
  533. } else {
  534. throw new RestException(500, 'Error while fetching Task '.$ref);
  535. }
  536. } elseif ($modulepart == 'product' || $modulepart == 'produit' || $modulepart == 'service' || $modulepart == 'produit|service') {
  537. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  538. $object = new Product($this->db);
  539. } elseif ($modulepart == 'expensereport') {
  540. require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
  541. $object = new ExpenseReport($this->db);
  542. } elseif ($modulepart == 'fichinter') {
  543. require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
  544. $object = new Fichinter($this->db);
  545. } elseif ($modulepart == 'adherent' || $modulepart == 'member') {
  546. $modulepart = 'adherent';
  547. require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
  548. $object = new Adherent($this->db);
  549. } elseif ($modulepart == 'proposal' || $modulepart == 'propal' || $modulepart == 'propale') {
  550. $modulepart = 'propale';
  551. require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
  552. $object = new Propal($this->db);
  553. } else {
  554. // TODO Implement additional moduleparts
  555. throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
  556. }
  557. if (is_object($object)) {
  558. $result = $object->fetch('', $ref);
  559. if ($result == 0) {
  560. throw new RestException(404, "Object with ref '".$ref."' was not found.");
  561. } elseif ($result < 0) {
  562. throw new RestException(500, 'Error while fetching object: '.$object->error);
  563. }
  564. }
  565. if (!($object->id > 0)) {
  566. throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
  567. }
  568. // Special cases that need to use get_exdir to get real dir of object
  569. // In future, all object should use this to define path of documents.
  570. if ($modulepart == 'supplier_invoice') {
  571. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  572. }
  573. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref);
  574. $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
  575. $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
  576. if (empty($upload_dir) || $upload_dir == '/') {
  577. 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.');
  578. }
  579. } else {
  580. if ($modulepart == 'invoice') {
  581. $modulepart = 'facture';
  582. }
  583. if ($modulepart == 'member') {
  584. $modulepart = 'adherent';
  585. }
  586. $relativefile = $subdir;
  587. $tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'write');
  588. $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
  589. if (empty($upload_dir) || $upload_dir == '/') {
  590. if (!empty($tmp['error'])) {
  591. throw new RestException(401, 'Error returned by dol_check_secure_access_document: '.$tmp['error']);
  592. } else {
  593. throw new RestException(500, 'This value of modulepart ('.$modulepart.') is not allowed with this value of subdir ('.$relativefile.')');
  594. }
  595. }
  596. }
  597. // $original_file here is still value of filename without any dir.
  598. $upload_dir = dol_sanitizePathName($upload_dir);
  599. if (!empty($createdirifnotexists)) {
  600. if (dol_mkdir($upload_dir) < 0) { // needed by products
  601. throw new RestException(500, 'Error while trying to create directory '.$upload_dir);
  602. }
  603. }
  604. $destfile = $upload_dir.'/'.$original_file;
  605. $destfiletmp = DOL_DATA_ROOT.'/admin/temp/'.$original_file;
  606. dol_delete_file($destfiletmp);
  607. //var_dump($original_file);exit;
  608. if (!dol_is_dir(dirname($destfile))) {
  609. throw new RestException(401, 'Directory not exists : '.dirname($destfile));
  610. }
  611. if (!$overwriteifexists && dol_is_file($destfile)) {
  612. throw new RestException(500, "File with name '".$original_file."' already exists.");
  613. }
  614. $fhandle = @fopen($destfiletmp, 'w');
  615. if ($fhandle) {
  616. $nbofbyteswrote = fwrite($fhandle, $newfilecontent);
  617. fclose($fhandle);
  618. @chmod($destfiletmp, octdec($conf->global->MAIN_UMASK));
  619. } else {
  620. throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
  621. }
  622. $result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1);
  623. if (!$result) {
  624. throw new RestException(500, "Failed to move file into '".$destfile."'");
  625. }
  626. return dol_basename($destfile);
  627. }
  628. /**
  629. * Delete a document.
  630. *
  631. * @param string $modulepart Name of module or area concerned by file download ('product', ...)
  632. * @param string $original_file Relative path with filename, relative to modulepart (for example: PRODUCT-REF-999/IMAGE-999.jpg)
  633. * @return array List of documents
  634. *
  635. * @throws RestException 400
  636. * @throws RestException 401
  637. * @throws RestException 404
  638. *
  639. * @url DELETE /
  640. */
  641. public function delete($modulepart, $original_file)
  642. {
  643. global $conf, $langs;
  644. if (empty($modulepart)) {
  645. throw new RestException(400, 'bad value for parameter modulepart');
  646. }
  647. if (empty($original_file)) {
  648. throw new RestException(400, 'bad value for parameter original_file');
  649. }
  650. //--- Finds and returns the document
  651. $entity = $conf->entity;
  652. // Special cases that need to use get_exdir to get real dir of object
  653. // If future, all object should use this to define path of documents.
  654. /*
  655. $tmpreldir = '';
  656. if ($modulepart == 'supplier_invoice') {
  657. $tmpreldir = get_exdir($object->id, 2, 0, 0, $object, 'invoice_supplier');
  658. }
  659. $relativefile = $tmpreldir.dol_sanitizeFileName($object->ref); */
  660. $relativefile = $original_file;
  661. $check_access = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', 'read');
  662. $accessallowed = $check_access['accessallowed'];
  663. $sqlprotectagainstexternals = $check_access['sqlprotectagainstexternals'];
  664. $original_file = $check_access['original_file'];
  665. if (preg_match('/\.\./', $original_file) || preg_match('/[<>|]/', $original_file)) {
  666. throw new RestException(401);
  667. }
  668. if (!$accessallowed) {
  669. throw new RestException(401);
  670. }
  671. $filename = basename($original_file);
  672. $original_file_osencoded = dol_osencode($original_file); // New file name encoded in OS encoding charset
  673. if (!file_exists($original_file_osencoded)) {
  674. dol_syslog("Try to download not found file ".$original_file_osencoded, LOG_WARNING);
  675. throw new RestException(404, 'File not found');
  676. }
  677. if (@unlink($original_file_osencoded)) {
  678. return array(
  679. 'success' => array(
  680. 'code' => 200,
  681. 'message' => 'Document deleted'
  682. )
  683. );
  684. }
  685. throw new RestException(401);
  686. }
  687. // phpcs:disable PEAR.NamingConventions.ValidFunctionName
  688. /**
  689. * Validate fields before create or update object
  690. *
  691. * @param array $data Array with data to verify
  692. * @return array
  693. * @throws RestException
  694. */
  695. private function _validate_file($data)
  696. {
  697. // phpcs:enable
  698. $result = array();
  699. foreach (Documents::$DOCUMENT_FIELDS as $field) {
  700. if (!isset($data[$field])) {
  701. throw new RestException(400, "$field field missing");
  702. }
  703. $result[$field] = $data[$field];
  704. }
  705. return $result;
  706. }
  707. }