Completed
Branch develop (6f107e)
by
unknown
45:29
created

Documents   F

Complexity

Total Complexity 92

Size/Duplication

Total Lines 534
Duplicated Lines 0 %

Coupling/Cohesion

Components 2
Dependencies 13

Importance

Changes 0
Metric Value
dl 0
loc 534
rs 3.4814
c 0
b 0
f 0
wmc 92
lcom 2
cbo 13

5 Methods

Rating   Name   Duplication   Size   Complexity  
C index() 0 38 7
F builddoc() 0 85 22
D getDocumentsListByElement() 0 122 32
F post() 0 154 27
A _validate_file() 0 9 3

How to fix   Complexity   

Complex Class

Complex classes like Documents often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Documents, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* Copyright (C) 2016   Xebax Christy           <[email protected]>
3
 * Copyright (C) 2016	Laurent Destailleur		<[email protected]>
4
 * Copyright (C) 2016   Jean-François Ferry     <[email protected]>
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
27
/**
28
 * API class for receive files
29
 *
30
 * @access protected
31
 * @class Documents {@requires user,external}
32
 */
33
class Documents extends DolibarrApi
34
{
35
36
	/**
37
	 * @var array   $DOCUMENT_FIELDS     Mandatory fields, checked when create and update object
38
	 */
39
	static $DOCUMENT_FIELDS = array(
40
		'modulepart'
41
	);
42
43
	/**
44
	 * Constructor
45
	 */
46
	function __construct()
47
	{
48
		global $db;
49
		$this->db = $db;
50
	}
51
52
53
	/**
54
	 * Download a document.
55
	 *
56
	 * Note that, this API is similar to using the wrapper link "documents.php" to download a file (used for
57
	 * internal HTML links of documents into application), but with no need to have a session cookie (the token is used instead).
58
	 *
59
	 * @param   string  $module_part    Name of module or area concerned by file download ('facture', ...)
60
	 * @param   string  $original_file  Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf)
61
	 * @return  array                   List of documents
62
	 *
63
	 * @throws 400
64
	 * @throws 401
65
	 * @throws 404
66
	 * @throws 200
67
	 *
68
	 * @url GET /download
69
	 */
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
110
	/**
111
	 * Build a document.
112
	 *
113
	 * Test sample 1: { "module_part": "invoice", "original_file": "FA1701-001/FA1701-001.pdf", "doctemplate": "crabe", "langcode": "fr_FR" }.
114
	 *
115
	 * @param   string  $module_part    Name of module or area concerned by file download ('invoice', 'order', ...).
116
	 * @param   string  $original_file  Relative path with filename, relative to modulepart (for example: IN201701-999/IN201701-999.pdf).
117
	 * @param	string	$doctemplate	Set here the doc template to use for document generation (If not set, use the default template).
118
	 * @param	string	$langcode		Language code like 'en_US', 'fr_FR', 'es_ES', ... (If not set, use the default language).
119
	 * @return  array                   List of documents
120
	 *
121
	 * @throws 500
122
	 * @throws 501
123
	 * @throws 400
124
	 * @throws 401
125
	 * @throws 404
126
	 * @throws 200
127
	 *
128
	 * @url PUT /builddoc
129
	 */
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
		else
200
		{
201
			throw new RestException(403, 'Generation not available for this modulepart');
202
		}
203
204
		$filename = basename($original_file);
205
		$original_file_osencoded=dol_osencode($original_file);	// New file name encoded in OS encoding charset
206
207
		if (! file_exists($original_file_osencoded))
208
		{
209
			throw new RestException(404, 'File not found');
210
		}
211
212
		$file_content=file_get_contents($original_file_osencoded);
213
		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)' );
214
	}
215
216
217
	/**
218
	 * Return the list of documents of a dedicated element (from its ID or Ref)
219
	 *
220
	 * @param   string 	$modulepart		Name of module or area concerned ('thirdparty', 'member', 'proposal', 'order', 'invoice', 'shipment', 'project',  ...)
221
	 * @param	int		$id				ID of element
222
	 * @param	string	$ref			Ref of element
223
	 * @param	string	$sortfield		Sort criteria ('','fullname','relativename','name','date','size')
224
	 * @param	string	$sortorder		Sort order ('asc' or 'desc')
225
	 * @return	array					Array of documents with path
226
	 *
227
	 * @throws 200
228
	 * @throws 400
229
	 * @throws 401
230
	 * @throws 404
231
	 * @throws 500
232
	 *
233
	 * @url GET /
234
	 */
235
	function getDocumentsListByElement($modulepart, $id=0, $ref='', $sortfield='', $sortorder='')
236
	{
237
		global $conf;
238
239
		if (empty($modulepart)) {
240
			throw new RestException(400, 'bad value for parameter modulepart');
241
		}
242
243
		if (empty($id) && empty($ref)) {
244
			throw new RestException(400, 'bad value for parameter id or ref');
245
		}
246
247
		$id = (empty($id)?0:$id);
248
249
		if ($modulepart == 'societe' || $modulepart == 'thirdparty')
250
		{
251
			require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
252
253
			if (!DolibarrApiAccess::$user->rights->societe->lire) {
254
				throw new RestException(401);
255
			}
256
257
			$object = new Societe($this->db);
258
			$result=$object->fetch($id, $ref);
259
			if ( ! $result ) {
260
				throw new RestException(404, 'Thirdparty not found');
261
			}
262
263
			$upload_dir = $conf->societe->multidir_output[$object->entity] . "/" . $object->id;
264
		}
265
		else if ($modulepart == 'adherent' || $modulepart == 'member')
266
		{
267
			require_once DOL_DOCUMENT_ROOT.'/adherents/class/adherent.class.php';
268
269
			if (!DolibarrApiAccess::$user->rights->adherent->lire) {
270
				throw new RestException(401);
271
			}
272
273
			$object = new Adherent($this->db);
274
			$result=$object->fetch($id, $ref);
275
			if ( ! $result ) {
276
				throw new RestException(404, 'Member not found');
277
			}
278
279
			$upload_dir = $conf->adherent->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'member');
280
		}
281
		else if ($modulepart == 'propal' || $modulepart == 'proposal')
282
		{
283
			require_once DOL_DOCUMENT_ROOT.'/comm/propal/class/propal.class.php';
284
285
			if (!DolibarrApiAccess::$user->rights->propal->lire) {
286
				throw new RestException(401);
287
			}
288
289
			$object = new Propal($this->db);
290
			$result=$object->fetch($id, $ref);
291
			if ( ! $result ) {
292
				throw new RestException(404, 'Proposal not found');
293
			}
294
295
			$upload_dir = $conf->propal->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'propal');
296
		}
297
		else if ($modulepart == 'commande' || $modulepart == 'order')
298
		{
299
			require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
300
301
			if (!DolibarrApiAccess::$user->rights->commande->lire) {
302
				throw new RestException(401);
303
			}
304
305
			$object = new Commande($this->db);
306
			$result=$object->fetch($id, $ref);
307
			if ( ! $result ) {
308
				throw new RestException(404, 'Order not found');
309
			}
310
311
			$upload_dir = $conf->commande->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'commande');
312
		}
313
		else if ($modulepart == 'shipment' || $modulepart == 'expedition')
314
		{
315
			require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
316
317
			if (!DolibarrApiAccess::$user->rights->expedition->lire) {
318
				throw new RestException(401);
319
			}
320
321
			$object = new Expedition($this->db);
322
			$result=$object->fetch($id, $ref);
323
			if ( ! $result ) {
324
				throw new RestException(404, 'Shipment not found');
325
			}
326
327
			$upload_dir = $conf->expedition->dir_output . "/sending/" . get_exdir(0, 0, 0, 1, $object, 'shipment');
328
		}
329
		else if ($modulepart == 'facture' || $modulepart == 'invoice')
330
		{
331
			require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
332
333
			if (!DolibarrApiAccess::$user->rights->facture->lire) {
334
				throw new RestException(401);
335
			}
336
337
			$object = new Facture($this->db);
338
			$result=$object->fetch($id, $ref);
339
			if ( ! $result ) {
340
				throw new RestException(404, 'Invoice not found');
341
			}
342
343
			$upload_dir = $conf->facture->dir_output . "/" . get_exdir(0, 0, 0, 1, $object, 'invoice');
344
		}
345
		else
346
		{
347
			throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
348
		}
349
350
		$filearray=dol_dir_list($upload_dir,"files",0,'','(\.meta|_preview.*\.png)$',$sortfield,(strtolower($sortorder)=='desc'?SORT_DESC:SORT_ASC),1);
351
		if (empty($filearray)) {
352
			throw new RestException(404, 'Search for modulepart '.$modulepart.' with Id '.$object->id.(! empty($object->Ref)?' or Ref '.$object->ref:'').' does not return any document.');
353
		}
354
355
		return $filearray;
356
	}
357
358
359
	/**
360
	 * Return a document.
361
	 *
362
	 * @param   int         $id          ID of document
363
	 * @return  array                    Array with data of file
364
	 *
365
	 * @throws RestException
366
	 */
367
	/*
368
    public function get($id) {
369
        return array('note'=>'xxx');
370
    }*/
371
372
373
	/**
374
	 * Upload a file.
375
	 *
376
	 * Test sample 1: { "filename": "mynewfile.txt", "modulepart": "facture", "ref": "FA1701-001", "subdir": "", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }.
377
	 * Test sample 2: { "filename": "mynewfile.txt", "modulepart": "medias", "ref": "", "subdir": "image/mywebsite", "filecontent": "content text", "fileencoding": "", "overwriteifexists": "0" }.
378
	 *
379
	 * @param   string  $filename           Name of file to create ('FA1705-0123.txt')
380
	 * @param   string  $modulepart         Name of module or area concerned by file upload ('facture', 'project', 'project_task', ...)
381
	 * @param   string  $ref                Reference of object (This will define subdir automatically and store submited file into it)
382
	 * @param   string  $subdir       		Subdirectory (Only if ref not provided)
383
	 * @param   string  $filecontent        File content (string with file content. An empty file will be created if this parameter is not provided)
384
	 * @param   string  $fileencoding       File encoding (''=no encoding, 'base64'=Base 64)
385
	 * @param   int 	$overwriteifexists  Overwrite file if exists (1 by default)
386
	 *
387
	 * @throws 200
388
	 * @throws 400
389
	 * @throws 401
390
	 * @throws 404
391
	 * @throws 500
392
	 *
393
	 * @url POST /upload
394
	 */
395
	public function post($filename, $modulepart, $ref='', $subdir='', $filecontent='', $fileencoding='', $overwriteifexists=0)
396
	{
397
		global $db, $conf;
398
399
		/*var_dump($modulepart);
400
        var_dump($filename);
401
        var_dump($filecontent);
402
        exit;*/
403
404
		if(empty($modulepart))
405
		{
406
			throw new RestException(400, 'Modulepart not provided.');
407
		}
408
409
		if (!DolibarrApiAccess::$user->rights->ecm->upload) {
410
			throw new RestException(401);
411
		}
412
413
		$newfilecontent = '';
414
		if (empty($fileencoding)) $newfilecontent = $filecontent;
415
		if ($fileencoding == 'base64') $newfilecontent = base64_decode($filecontent);
416
417
		$original_file = dol_sanitizeFileName($filename);
418
419
		// Define $uploadir
420
		$object = null;
421
		$entity = DolibarrApiAccess::$user->entity;
422
		if ($ref)
423
		{
424
			$tmpreldir='';
425
426
			if ($modulepart == 'facture' || $modulepart == 'invoice')
427
			{
428
				$modulepart='facture';
429
430
				require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
431
				$object = new Facture($this->db);
432
			}
433
			elseif ($modulepart == 'project')
434
			{
435
				require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
436
				$object = new Project($this->db);
437
			}
438
			elseif ($modulepart == 'task' || $modulepart == 'project_task')
439
			{
440
				$modulepart = 'project_task';
441
442
				require_once DOL_DOCUMENT_ROOT.'/projet/class/task.class.php';
443
				$object = new Task($this->db);
444
445
				$task_result = $object->fetch('', $ref);
446
447
				// Fetching the tasks project is required because its out_dir might be a sub-directory of the project
448
				if($task_result > 0)
449
				{
450
					$project_result = $object->fetch_projet();
451
452
					if($project_result >= 0)
453
					{
454
						$tmpreldir = dol_sanitizeFileName($object->project->ref).'/';
455
					}
456
				}
457
				else
458
				{
459
					throw new RestException(500, 'Error while fetching Task '.$ref);
460
				}
461
			}
462
			// TODO Implement additional moduleparts
463
			else
464
			{
465
				throw new RestException(500, 'Modulepart '.$modulepart.' not implemented yet.');
466
			}
467
468
			if(is_object($object))
469
			{
470
				$result = $object->fetch('', $ref);
471
472
				if($result == 0)
473
				{
474
					throw new RestException(404, "Object with ref '".$ref."' was not found.");
475
			}
476
				elseif ($result < 0)
477
				{
478
					throw new RestException(500, 'Error while fetching object.');
479
				}
480
			}
481
482
			if (! ($object->id > 0))
483
			{
484
   				throw new RestException(404, 'The object '.$modulepart." with ref '".$ref."' was not found.");
485
			}
486
487
			$relativefile = $tmpreldir.dol_sanitizeFileName($object->ref);
488
489
			$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, $ref, 'write');
490
			$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
491
492
			if (empty($upload_dir) || $upload_dir == '/')
493
			{
494
				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.');
495
			}
496
		}
497
		else
498
		{
499
			if ($modulepart == 'invoice') $modulepart ='facture';
500
501
			$relativefile = $subdir;
502
503
			$tmp = dol_check_secure_access_document($modulepart, $relativefile, $entity, DolibarrApiAccess::$user, '', '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
		// $original_file here is still value of filename without any dir.
512
513
		$upload_dir = dol_sanitizePathName($upload_dir);
514
515
		$destfile = $upload_dir . '/' . $original_file;
516
		$destfiletmp = DOL_DATA_ROOT.'/admin/temp/' . $original_file;
517
		dol_delete_file($destfiletmp);
518
		//var_dump($original_file);exit;
519
520
		if (!dol_is_dir(dirname($destfile))) {
521
			throw new RestException(401, 'Directory not exists : '.dirname($destfile));
522
		}
523
524
		if (! $overwriteifexists && dol_is_file($destfile))
525
		{
526
			throw new RestException(500, "File with name '".$original_file."' already exists.");
527
		}
528
529
		$fhandle = @fopen($destfiletmp, 'w');
530
		if ($fhandle)
531
		{
532
			$nbofbyteswrote = fwrite($fhandle, $newfilecontent);
533
			fclose($fhandle);
534
			@chmod($destfiletmp, octdec($conf->global->MAIN_UMASK));
535
		}
536
		else
537
		{
538
			throw new RestException(500, "Failed to open file '".$destfiletmp."' for write");
539
		}
540
541
		$result = dol_move($destfiletmp, $destfile, 0, $overwriteifexists, 1);
542
		if (! $result)
543
		{
544
			throw new RestException(500, "Failed to move file into '".$destfile."'");
545
		}
546
547
		return dol_basename($destfile);
548
	}
549
550
	/**
551
	 * Validate fields before create or update object
552
	 *
553
	 * @param   array           $data   Array with data to verify
554
	 * @return  array
555
	 * @throws  RestException
556
	 */
557
	function _validate_file($data) {
558
		$result = array();
559
		foreach (Documents::$DOCUMENT_FIELDS as $field) {
560
			if (!isset($data[$field]))
561
				throw new RestException(400, "$field field missing");
562
			$result[$field] = $data[$field];
563
		}
564
		return $result;
565
	}
566
}
567