Passed
Push — master ( db7d4f...be8d41 )
by Alxarafe
21:50
created
dolibarr/htdocs/core/antispamimage.php 2 patches
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -21,14 +21,14 @@  discard block
 block discarded – undo
21 21
  *		\brief      Return antispam image
22 22
  */
23 23
 
24
-define('NOLOGIN',1);
24
+define('NOLOGIN', 1);
25 25
 
26
-if (! defined('NOREQUIREUSER'))   define('NOREQUIREUSER',1);
27
-if (! defined('NOREQUIREDB'))     define('NOREQUIREDB',1);
28
-if (! defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN',1);
29
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
30
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC',1);
31
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
26
+if (!defined('NOREQUIREUSER'))   define('NOREQUIREUSER', 1);
27
+if (!defined('NOREQUIREDB'))     define('NOREQUIREDB', 1);
28
+if (!defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN', 1);
29
+if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
30
+if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', 1);
31
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
32 32
 
33 33
 require_once '../main.inc.php';
34 34
 
@@ -37,24 +37,24 @@  discard block
 block discarded – undo
37 37
  * View
38 38
  */
39 39
 
40
-$length=5;
40
+$length = 5;
41 41
 $letters = 'aAbBCDeEFgGhHJKLmMnNpPqQRsStTuVwWXYZz2345679';
42 42
 $number = strlen($letters);
43 43
 $string = '';
44
-for($i = 0; $i < $length; $i++)
44
+for ($i = 0; $i < $length; $i++)
45 45
 {
46 46
     $string .= $letters{mt_rand(0, $number - 1)};
47 47
 }
48 48
 //print $string;
49 49
 
50 50
 
51
-$sessionkey='dol_antispam_value';
52
-$_SESSION[$sessionkey]=$string;
51
+$sessionkey = 'dol_antispam_value';
52
+$_SESSION[$sessionkey] = $string;
53 53
 
54
-$img = imagecreate(80,32);
54
+$img = imagecreate(80, 32);
55 55
 if (empty($img))
56 56
 {
57
-    dol_print_error('',"Problem with GD creation");
57
+    dol_print_error('', "Problem with GD creation");
58 58
     exit;
59 59
 }
60 60
 
Please login to merge, or discard this patch.
Braces   +18 added lines, -6 removed lines patch added patch discarded remove patch
@@ -23,12 +23,24 @@
 block discarded – undo
23 23
 
24 24
 define('NOLOGIN',1);
25 25
 
26
-if (! defined('NOREQUIREUSER'))   define('NOREQUIREUSER',1);
27
-if (! defined('NOREQUIREDB'))     define('NOREQUIREDB',1);
28
-if (! defined('NOREQUIRETRAN'))   define('NOREQUIRETRAN',1);
29
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
30
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC',1);
31
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
26
+if (! defined('NOREQUIREUSER')) {
27
+    define('NOREQUIREUSER',1);
28
+}
29
+if (! defined('NOREQUIREDB')) {
30
+    define('NOREQUIREDB',1);
31
+}
32
+if (! defined('NOREQUIRETRAN')) {
33
+    define('NOREQUIRETRAN',1);
34
+}
35
+if (! defined('NOREQUIREMENU')) {
36
+    define('NOREQUIREMENU',1);
37
+}
38
+if (! defined('NOREQUIRESOC')) {
39
+    define('NOREQUIRESOC',1);
40
+}
41
+if (! defined('NOTOKENRENEWAL')) {
42
+    define('NOTOKENRENEWAL',1);
43
+}
32 44
 
33 45
 require_once '../main.inc.php';
34 46
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/extrafieldsinexport.inc.php 3 patches
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -13,55 +13,55 @@
 block discarded – undo
13 13
 $resql=$this->db->query($sql);
14 14
 if ($resql)    // This can fail when class is used on old database (during migration for example)
15 15
 {
16
-	while ($obj=$this->db->fetch_object($resql))
17
-	{
18
-		$fieldname=$keyforaliasextra.'.'.$obj->name;
19
-		$fieldlabel=ucfirst($obj->label);
20
-		$typeFilter="Text";
21
-		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
22
-		switch ($typefield) {
23
-			case 'int':
24
-			case 'integer':
25
-			case 'double':
26
-			case 'price':
27
-				$typeFilter="Numeric";
28
-				break;
29
-			case 'date':
30
-			case 'datetime':
31
-			case 'timestamp':
32
-				$typeFilter="Date";
33
-				break;
34
-			case 'boolean':
35
-				$typeFilter="Boolean";
36
-				break;
37
-			case 'sellist':
38
-				$tmp='';
39
-				$tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
40
-				if ($tmpparam['options'] && is_array($tmpparam['options'])) {
41
-					$tmpkeys=array_keys($tmpparam['options']);
42
-					$tmp=array_shift($tmpkeys);
43
-				}
44
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
45
-				break;
46
-		}
47
-		if ($obj->type!='separate')
48
-		{
49
-		    // If not a computed field
50
-		    if (empty($obj->fieldcomputed))
51
-		    {
52
-    			$this->export_fields_array[$r][$fieldname]=$fieldlabel;
53
-    			$this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
54
-    			$this->export_entities_array[$r][$fieldname]=$keyforelement;
55
-		    }
56
-			// If this is a computed field
57
-			else
58
-			{
59
-			    $this->export_fields_array[$r][$fieldname]=$fieldlabel;
60
-			    $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
61
-			    $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
62
-			    $this->export_entities_array[$r][$fieldname]=$keyforelement;
63
-			}
64
-		}
65
-	}
16
+    while ($obj=$this->db->fetch_object($resql))
17
+    {
18
+        $fieldname=$keyforaliasextra.'.'.$obj->name;
19
+        $fieldlabel=ucfirst($obj->label);
20
+        $typeFilter="Text";
21
+        $typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
22
+        switch ($typefield) {
23
+            case 'int':
24
+            case 'integer':
25
+            case 'double':
26
+            case 'price':
27
+                $typeFilter="Numeric";
28
+                break;
29
+            case 'date':
30
+            case 'datetime':
31
+            case 'timestamp':
32
+                $typeFilter="Date";
33
+                break;
34
+            case 'boolean':
35
+                $typeFilter="Boolean";
36
+                break;
37
+            case 'sellist':
38
+                $tmp='';
39
+                $tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
40
+                if ($tmpparam['options'] && is_array($tmpparam['options'])) {
41
+                    $tmpkeys=array_keys($tmpparam['options']);
42
+                    $tmp=array_shift($tmpkeys);
43
+                }
44
+                if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
45
+                break;
46
+        }
47
+        if ($obj->type!='separate')
48
+        {
49
+            // If not a computed field
50
+            if (empty($obj->fieldcomputed))
51
+            {
52
+                $this->export_fields_array[$r][$fieldname]=$fieldlabel;
53
+                $this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
54
+                $this->export_entities_array[$r][$fieldname]=$keyforelement;
55
+            }
56
+            // If this is a computed field
57
+            else
58
+            {
59
+                $this->export_fields_array[$r][$fieldname]=$fieldlabel;
60
+                $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
61
+                $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
62
+                $this->export_entities_array[$r][$fieldname]=$keyforelement;
63
+            }
64
+        }
65
+    }
66 66
 }
67 67
 // End add axtra fields
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -8,58 +8,58 @@
 block discarded – undo
8 8
 }
9 9
 
10 10
 // Add extra fields
11
-$sql="SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.')';
11
+$sql = "SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.')';
12 12
 //print $sql;
13
-$resql=$this->db->query($sql);
13
+$resql = $this->db->query($sql);
14 14
 if ($resql)    // This can fail when class is used on old database (during migration for example)
15 15
 {
16
-	while ($obj=$this->db->fetch_object($resql))
16
+	while ($obj = $this->db->fetch_object($resql))
17 17
 	{
18
-		$fieldname=$keyforaliasextra.'.'.$obj->name;
19
-		$fieldlabel=ucfirst($obj->label);
20
-		$typeFilter="Text";
21
-		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
18
+		$fieldname = $keyforaliasextra.'.'.$obj->name;
19
+		$fieldlabel = ucfirst($obj->label);
20
+		$typeFilter = "Text";
21
+		$typefield = preg_replace('/\(.*$/', '', $obj->type); // double(24,8) -> double
22 22
 		switch ($typefield) {
23 23
 			case 'int':
24 24
 			case 'integer':
25 25
 			case 'double':
26 26
 			case 'price':
27
-				$typeFilter="Numeric";
27
+				$typeFilter = "Numeric";
28 28
 				break;
29 29
 			case 'date':
30 30
 			case 'datetime':
31 31
 			case 'timestamp':
32
-				$typeFilter="Date";
32
+				$typeFilter = "Date";
33 33
 				break;
34 34
 			case 'boolean':
35
-				$typeFilter="Boolean";
35
+				$typeFilter = "Boolean";
36 36
 				break;
37 37
 			case 'sellist':
38
-				$tmp='';
39
-				$tmpparam=unserialize($obj->param);	// $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
38
+				$tmp = '';
39
+				$tmpparam = unserialize($obj->param); // $tmp ay be array 'options' => array 'c_currencies:code_iso:code_iso' => null
40 40
 				if ($tmpparam['options'] && is_array($tmpparam['options'])) {
41
-					$tmpkeys=array_keys($tmpparam['options']);
42
-					$tmp=array_shift($tmpkeys);
41
+					$tmpkeys = array_keys($tmpparam['options']);
42
+					$tmp = array_shift($tmpkeys);
43 43
 				}
44
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
44
+				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter = "List:".$tmp;
45 45
 				break;
46 46
 		}
47
-		if ($obj->type!='separate')
47
+		if ($obj->type != 'separate')
48 48
 		{
49 49
 		    // If not a computed field
50 50
 		    if (empty($obj->fieldcomputed))
51 51
 		    {
52
-    			$this->export_fields_array[$r][$fieldname]=$fieldlabel;
53
-    			$this->export_TypeFields_array[$r][$fieldname]=$typeFilter;
54
-    			$this->export_entities_array[$r][$fieldname]=$keyforelement;
52
+    			$this->export_fields_array[$r][$fieldname] = $fieldlabel;
53
+    			$this->export_TypeFields_array[$r][$fieldname] = $typeFilter;
54
+    			$this->export_entities_array[$r][$fieldname] = $keyforelement;
55 55
 		    }
56 56
 			// If this is a computed field
57 57
 			else
58 58
 			{
59
-			    $this->export_fields_array[$r][$fieldname]=$fieldlabel;
60
-			    $this->export_TypeFields_array[$r][$fieldname]=$typeFilter.'Compute';
61
-			    $this->export_special_array[$r][$fieldname]=$obj->fieldcomputed;
62
-			    $this->export_entities_array[$r][$fieldname]=$keyforelement;
59
+			    $this->export_fields_array[$r][$fieldname] = $fieldlabel;
60
+			    $this->export_TypeFields_array[$r][$fieldname] = $typeFilter.'Compute';
61
+			    $this->export_special_array[$r][$fieldname] = $obj->fieldcomputed;
62
+			    $this->export_entities_array[$r][$fieldname] = $keyforelement;
63 63
 			}
64 64
 		}
65 65
 	}
Please login to merge, or discard this patch.
Braces   +6 added lines, -2 removed lines patch added patch discarded remove patch
@@ -11,11 +11,13 @@  discard block
 block discarded – undo
11 11
 $sql="SELECT name, label, type, param, fieldcomputed, fielddefault FROM ".MAIN_DB_PREFIX."extrafields WHERE elementtype = '".$keyforselect."' AND type != 'separate' AND entity IN (0, ".$conf->entity.')';
12 12
 //print $sql;
13 13
 $resql=$this->db->query($sql);
14
-if ($resql)    // This can fail when class is used on old database (during migration for example)
14
+if ($resql) {
15
+    // This can fail when class is used on old database (during migration for example)
15 16
 {
16 17
 	while ($obj=$this->db->fetch_object($resql))
17 18
 	{
18 19
 		$fieldname=$keyforaliasextra.'.'.$obj->name;
20
+}
19 21
 		$fieldlabel=ucfirst($obj->label);
20 22
 		$typeFilter="Text";
21 23
 		$typefield=preg_replace('/\(.*$/', '', $obj->type);	// double(24,8) -> double
@@ -41,7 +43,9 @@  discard block
 block discarded – undo
41 43
 					$tmpkeys=array_keys($tmpparam['options']);
42 44
 					$tmp=array_shift($tmpkeys);
43 45
 				}
44
-				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) $typeFilter="List:".$tmp;
46
+				if (preg_match('/[a-z0-9_]+:[a-z0-9_]+:[a-z0-9_]+/', $tmp)) {
47
+				    $typeFilter="List:".$tmp;
48
+				}
45 49
 				break;
46 50
 		}
47 51
 		if ($obj->type!='separate')
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_massactions.inc.php 3 patches
Indentation   +1097 added lines, -1097 removed lines patch added patch discarded remove patch
@@ -36,8 +36,8 @@  discard block
 block discarded – undo
36 36
 // Protection
37 37
 if (empty($objectclass) || empty($uploaddir))
38 38
 {
39
-	dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined');
40
-	exit;
39
+    dol_print_error(null, 'include of actions_massactions.inc.php is done but var $massaction or $objectclass or $uploaddir was not defined');
40
+    exit;
41 41
 }
42 42
 
43 43
 
@@ -45,1029 +45,1029 @@  discard block
 block discarded – undo
45 45
 $maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
46 46
 if (! empty($massaction) && count($toselect) < 1)
47 47
 {
48
-	$error++;
49
-	setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
48
+    $error++;
49
+    setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
50 50
 }
51 51
 if (! $error && is_array($toselect) && count($toselect) > $maxformassaction)
52 52
 {
53
-	setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
54
-	$error++;
53
+    setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
54
+    $error++;
55 55
 }
56 56
 
57 57
 if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
58 58
 {
59
-	$massaction='presend';
59
+    $massaction='presend';
60 60
 }
61 61
 if (! $error && $massaction == 'confirm_presend')
62 62
 {
63
-	$resaction = '';
64
-	$nbsent = 0;
65
-	$nbignored = 0;
66
-	$langs->load("mails");
67
-	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68
-
69
-	$listofobjectid=array();
70
-	$listofobjectthirdparties=array();
71
-	$listofobjectref=array();
72
-
73
-	if (! $error)
74
-	{
75
-		$thirdparty=new Societe($db);
76
-		if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
-		if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
78
-
79
-		$objecttmp=new $objectclass($db);
80
-		foreach($toselect as $toselectid)
81
-		{
82
-			$objecttmp=new $objectclass($db);	// we must create new instance because instance is saved into $listofobjectref array for future use
83
-			$result=$objecttmp->fetch($toselectid);
84
-			if ($result > 0)
85
-			{
86
-				$listofobjectid[$toselectid]=$toselectid;
87
-				$thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
-				if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
-				if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
-				if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
91
-				$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92
-				$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
93
-			}
94
-		}
95
-	}
96
-
97
-	// Check mandatory parameters
98
-	if (GETPOST('fromtype','alpha') === 'user' && empty($user->email))
99
-	{
100
-		$error++;
101
-		setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
102
-		$massaction='presend';
103
-	}
104
-
105
-	$receiver=$_POST['receiver'];
106
-	if (! is_array($receiver))
107
-	{
108
-		if (empty($receiver) || $receiver == '-1') $receiver=array();
109
-		else $receiver=array($receiver);
110
-	}
111
-	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
112
-	{
113
-	 	$error++;
114
-	   	setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115
-	   	$massaction='presend';
116
-	}
117
-
118
-	if (! GETPOST('subject','none'))
119
-	{
120
-		$error++;
121
-		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
122
-		$massaction='presend';
123
-	}
124
-
125
-	// Loop on each recipient/thirdparty
126
-	if (! $error)
127
-	{
128
-		foreach ($listofobjectthirdparties as $thirdpartyid)
129
-		{
130
-			$result = $thirdparty->fetch($thirdpartyid);
131
-			if ($result < 0)
132
-			{
133
-				dol_print_error($db);
134
-				exit;
135
-			}
136
-
137
-			$sendto='';
138
-			$sendtocc='';
139
-			$sendtobcc='';
140
-			$sendtoid = array();
141
-
142
-			// Define $sendto
143
-			$tmparray=array();
144
-			if (trim($_POST['sendto']))
145
-			{
146
-				// Recipients are provided into free text
147
-				$tmparray[] = trim($_POST['sendto']);
148
-			}
149
-			if (count($receiver)>0)
150
-			{
151
-				foreach($receiver as $key=>$val)
152
-				{
153
-					// Recipient was provided from combo list
154
-					if ($val == 'thirdparty') // Id of third party or user
155
-					{
156
-						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
157
-					}
158
-					elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
159
-					{
160
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
161
-						$sendtoid[] = $val;
162
-					}
163
-				}
164
-			}
165
-			$sendto=implode(',',$tmparray);
166
-
167
-			// Define $sendtocc
168
-			$receivercc=$_POST['receivercc'];
169
-			if (! is_array($receivercc))
170
-			{
171
-				if ($receivercc == '-1') $receivercc=array();
172
-				else $receivercc=array($receivercc);
173
-			}
174
-			$tmparray=array();
175
-			if (trim($_POST['sendtocc']))
176
-			{
177
-				$tmparray[] = trim($_POST['sendtocc']);
178
-			}
179
-			if (count($receivercc) > 0)
180
-			{
181
-				foreach($receivercc as $key=>$val)
182
-				{
183
-					// Recipient was provided from combo list
184
-					if ($val == 'thirdparty') // Id of third party
185
-					{
186
-						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
187
-					}
188
-					elseif ($val)	// Id du contact
189
-					{
190
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
191
-						//$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192
-					}
193
-				}
194
-			}
195
-			$sendtocc=implode(',',$tmparray);
196
-
197
-			//var_dump($listofobjectref);exit;
198
-			$attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
-			$listofqualifiedobj=array();
200
-			$listofqualifiedref=array();
201
-			$thirdpartywithoutemail=array();
202
-
203
-			foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
204
-			{
205
-				//var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
206
-				if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
207
-				{
208
-					$langs->load("errors");
209
-					$nbignored++;
210
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
211
-					continue; // Payment done or started or canceled
212
-				}
213
-				if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
214
-				{
215
-					$langs->load("errors");
216
-					$nbignored++;
217
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
218
-					continue;
219
-				}
220
-				if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
221
-				{
222
-					$langs->load("errors");
223
-					$nbignored++;
224
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
225
-					continue; // Payment done or started or canceled
226
-				}
227
-
228
-				// Test recipient
229
-				if (empty($sendto)) 	// For the case, no recipient were set (multi thirdparties send)
230
-				{
231
-					if ($objectobj->element == 'expensereport')
232
-					{
233
-						$fuser = new User($db);
234
-						$fuser->fetch($objectobj->fk_user_author);
235
-						$sendto = $fuser->email;
236
-					}
237
-					else
238
-					{
239
-						$objectobj->fetch_thirdparty();
240
-						$sendto = $objectobj->thirdparty->email;
241
-					}
242
-				}
243
-
244
-				if (empty($sendto))
245
-				{
246
-				   	//print "No recipient for thirdparty ".$objectobj->thirdparty->name;
247
-				   	$nbignored++;
248
-				   	if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
249
-					{
250
-						$resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
251
-					}
252
-					dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
253
-					$thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
254
-				   	continue;
255
-				}
256
-
257
-				if ($_POST['addmaindocfile'])
258
-				{
259
-					// TODO Use future field $objectobj->fullpathdoc to know where is stored default file
260
-					// TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
261
-					$filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
262
-					$filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
263
-					$file = $filedir . '/' . $filename;
264
-					$mime = dol_mimetype($file);
265
-
266
-	   				if (dol_is_file($file))
267
-					{
268
-							// Create form object
269
-							$attachedfiles=array(
270
-							'paths'=>array_merge($attachedfiles['paths'],array($file)),
271
-							'names'=>array_merge($attachedfiles['names'],array($filename)),
272
-							'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
273
-							);
274
-					}
275
-					else
276
-					{
277
-							$nbignored++;
278
-							$langs->load("errors");
279
-							$resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
280
-							dol_syslog('Failed to read file: '.$file, LOG_WARNING);
281
-							continue;
282
-					}
283
-				}
284
-
285
-				// Object of thirdparty qualified
286
-				$listofqualifiedobj[$objectid]=$objectobj;
287
-				$listofqualifiedref[$objectid]=$objectobj->ref;
288
-
289
-
290
-				//var_dump($listofqualifiedref);
291
-			}
292
-
293
-			// Send email if there is at least one qualified record
294
-			if (count($listofqualifiedobj) > 0)
295
-			{
296
-				$langs->load("commercial");
297
-
298
-				$fromtype = GETPOST('fromtype');
299
-				if ($fromtype === 'user') {
300
-					$from = $user->getFullName($langs) .' <'.$user->email.'>';
301
-				}
302
-				elseif ($fromtype === 'company') {
303
-					$from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304
-				}
305
-				elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306
-					$tmp=explode(',', $user->email_aliases);
307
-					$from = trim($tmp[($reg[1] - 1)]);
308
-				}
309
-				elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310
-					$tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311
-					$from = trim($tmp[($reg[1] - 1)]);
312
-				}
313
-				elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314
-					$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315
-					$resql = $db->query($sql);
316
-					$obj = $db->fetch_object($resql);
317
-					if ($obj)
318
-					{
319
-						$from = $obj->label.' <'.$obj->email.'>';
320
-					}
321
-				}
322
-				else {
323
-					$from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
324
-				}
325
-
326
-				$replyto = $from;
327
-				$subject = GETPOST('subject','none');
328
-				$message = GETPOST('message','none');
329
-
330
-				$sendtobcc = GETPOST('sendtoccc');
331
-				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
-				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
-				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
-				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
-				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
-				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
337
-
338
-				// $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339
-				$oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
340
-				$looparray=array();
341
-				if (! $oneemailperrecipient)
342
-				{
343
-					$looparray = $listofqualifiedobj;
344
-					foreach ($looparray as $key => $objecttmp)
345
-					{
346
-						$looparray[$key]->thirdparty = $thirdparty;
347
-					}
348
-				}
349
-				else
350
-				{
351
-					$objectforloop=new $objectclass($db);
352
-					$objectforloop->thirdparty = $thirdparty;
353
-					$looparray[0]=$objectforloop;
354
-				}
355
-				//var_dump($looparray);exit;
356
-
357
-				foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358
-				{
359
-					// Make substitution in email content
360
-					$substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
-					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362
-					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
363
-					$substitutionarray['__EMAIL__'] = $thirdparty->email;
364
-					$substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
365
-
366
-					$parameters=array('mode'=>'formemail');
367
-
368
-					if ( ! empty( $listofobjectthirdparties ) ) {
369
-						$parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
370
-					}
371
-					if ( ! empty( $listofobjectref ) ) {
372
-						$parameters['listofobjectref'] = $listofobjectref;
373
-					}
374
-
375
-					complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
376
-
377
-					$subject=make_substitutions($subject, $substitutionarray);
378
-					$message=make_substitutions($message, $substitutionarray);
379
-
380
-					$filepath = $attachedfiles['paths'];
381
-					$filename = $attachedfiles['names'];
382
-					$mimetype = $attachedfiles['mimes'];
383
-
384
-					// Define the trackid when emails sent from the mass action
385
-					if ($oneemailperrecipient)
386
-					{
387
-						$trackid='thi'.$thirdparty->id;
388
-						if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
-						if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
390
-					}
391
-					else
392
-					{
393
-						$trackid=strtolower(get_class($objecttmp));
394
-						if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
-						if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
-						if (get_class($objecttmp)=='Commande') $trackid='ord';
397
-						if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
-						if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
-						if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
-						if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
401
-
402
-						$trackid.=$objecttmp->id;
403
-					}
404
-					//var_dump($filepath);
405
-					//var_dump($trackid);exit;
406
-
407
-					// Send mail (substitutionarray must be done just before this)
408
-					require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
409
-					$mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
410
-					if ($mailfile->error)
411
-					{
412
-						$resaction.='<div class="error">'.$mailfile->error.'</div>';
413
-					}
414
-					else
415
-					{
416
-						$result=$mailfile->sendfile();
417
-						if ($result)
418
-						{
419
-							$resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>';		// Must not contain "
420
-
421
-							$error=0;
422
-
423
-							// Insert logs into agenda
424
-							foreach($listofqualifiedobj as $objid => $objectobj)
425
-							{
426
-								/*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
63
+    $resaction = '';
64
+    $nbsent = 0;
65
+    $nbignored = 0;
66
+    $langs->load("mails");
67
+    include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68
+
69
+    $listofobjectid=array();
70
+    $listofobjectthirdparties=array();
71
+    $listofobjectref=array();
72
+
73
+    if (! $error)
74
+    {
75
+        $thirdparty=new Societe($db);
76
+        if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
+        if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
78
+
79
+        $objecttmp=new $objectclass($db);
80
+        foreach($toselect as $toselectid)
81
+        {
82
+            $objecttmp=new $objectclass($db);	// we must create new instance because instance is saved into $listofobjectref array for future use
83
+            $result=$objecttmp->fetch($toselectid);
84
+            if ($result > 0)
85
+            {
86
+                $listofobjectid[$toselectid]=$toselectid;
87
+                $thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
+                if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
+                if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
+                if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
91
+                $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92
+                $listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
93
+            }
94
+        }
95
+    }
96
+
97
+    // Check mandatory parameters
98
+    if (GETPOST('fromtype','alpha') === 'user' && empty($user->email))
99
+    {
100
+        $error++;
101
+        setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
102
+        $massaction='presend';
103
+    }
104
+
105
+    $receiver=$_POST['receiver'];
106
+    if (! is_array($receiver))
107
+    {
108
+        if (empty($receiver) || $receiver == '-1') $receiver=array();
109
+        else $receiver=array($receiver);
110
+    }
111
+    if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
112
+    {
113
+            $error++;
114
+            setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115
+            $massaction='presend';
116
+    }
117
+
118
+    if (! GETPOST('subject','none'))
119
+    {
120
+        $error++;
121
+        setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
122
+        $massaction='presend';
123
+    }
124
+
125
+    // Loop on each recipient/thirdparty
126
+    if (! $error)
127
+    {
128
+        foreach ($listofobjectthirdparties as $thirdpartyid)
129
+        {
130
+            $result = $thirdparty->fetch($thirdpartyid);
131
+            if ($result < 0)
132
+            {
133
+                dol_print_error($db);
134
+                exit;
135
+            }
136
+
137
+            $sendto='';
138
+            $sendtocc='';
139
+            $sendtobcc='';
140
+            $sendtoid = array();
141
+
142
+            // Define $sendto
143
+            $tmparray=array();
144
+            if (trim($_POST['sendto']))
145
+            {
146
+                // Recipients are provided into free text
147
+                $tmparray[] = trim($_POST['sendto']);
148
+            }
149
+            if (count($receiver)>0)
150
+            {
151
+                foreach($receiver as $key=>$val)
152
+                {
153
+                    // Recipient was provided from combo list
154
+                    if ($val == 'thirdparty') // Id of third party or user
155
+                    {
156
+                        $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
157
+                    }
158
+                    elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
159
+                    {
160
+                        $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
161
+                        $sendtoid[] = $val;
162
+                    }
163
+                }
164
+            }
165
+            $sendto=implode(',',$tmparray);
166
+
167
+            // Define $sendtocc
168
+            $receivercc=$_POST['receivercc'];
169
+            if (! is_array($receivercc))
170
+            {
171
+                if ($receivercc == '-1') $receivercc=array();
172
+                else $receivercc=array($receivercc);
173
+            }
174
+            $tmparray=array();
175
+            if (trim($_POST['sendtocc']))
176
+            {
177
+                $tmparray[] = trim($_POST['sendtocc']);
178
+            }
179
+            if (count($receivercc) > 0)
180
+            {
181
+                foreach($receivercc as $key=>$val)
182
+                {
183
+                    // Recipient was provided from combo list
184
+                    if ($val == 'thirdparty') // Id of third party
185
+                    {
186
+                        $tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
187
+                    }
188
+                    elseif ($val)	// Id du contact
189
+                    {
190
+                        $tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
191
+                        //$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192
+                    }
193
+                }
194
+            }
195
+            $sendtocc=implode(',',$tmparray);
196
+
197
+            //var_dump($listofobjectref);exit;
198
+            $attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
+            $listofqualifiedobj=array();
200
+            $listofqualifiedref=array();
201
+            $thirdpartywithoutemail=array();
202
+
203
+            foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
204
+            {
205
+                //var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
206
+                if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
207
+                {
208
+                    $langs->load("errors");
209
+                    $nbignored++;
210
+                    $resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
211
+                    continue; // Payment done or started or canceled
212
+                }
213
+                if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
214
+                {
215
+                    $langs->load("errors");
216
+                    $nbignored++;
217
+                    $resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
218
+                    continue;
219
+                }
220
+                if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
221
+                {
222
+                    $langs->load("errors");
223
+                    $nbignored++;
224
+                    $resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
225
+                    continue; // Payment done or started or canceled
226
+                }
227
+
228
+                // Test recipient
229
+                if (empty($sendto)) 	// For the case, no recipient were set (multi thirdparties send)
230
+                {
231
+                    if ($objectobj->element == 'expensereport')
232
+                    {
233
+                        $fuser = new User($db);
234
+                        $fuser->fetch($objectobj->fk_user_author);
235
+                        $sendto = $fuser->email;
236
+                    }
237
+                    else
238
+                    {
239
+                        $objectobj->fetch_thirdparty();
240
+                        $sendto = $objectobj->thirdparty->email;
241
+                    }
242
+                }
243
+
244
+                if (empty($sendto))
245
+                {
246
+                        //print "No recipient for thirdparty ".$objectobj->thirdparty->name;
247
+                        $nbignored++;
248
+                        if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
249
+                    {
250
+                        $resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
251
+                    }
252
+                    dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
253
+                    $thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
254
+                        continue;
255
+                }
256
+
257
+                if ($_POST['addmaindocfile'])
258
+                {
259
+                    // TODO Use future field $objectobj->fullpathdoc to know where is stored default file
260
+                    // TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
261
+                    $filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
262
+                    $filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
263
+                    $file = $filedir . '/' . $filename;
264
+                    $mime = dol_mimetype($file);
265
+
266
+                        if (dol_is_file($file))
267
+                    {
268
+                            // Create form object
269
+                            $attachedfiles=array(
270
+                            'paths'=>array_merge($attachedfiles['paths'],array($file)),
271
+                            'names'=>array_merge($attachedfiles['names'],array($filename)),
272
+                            'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
273
+                            );
274
+                    }
275
+                    else
276
+                    {
277
+                            $nbignored++;
278
+                            $langs->load("errors");
279
+                            $resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
280
+                            dol_syslog('Failed to read file: '.$file, LOG_WARNING);
281
+                            continue;
282
+                    }
283
+                }
284
+
285
+                // Object of thirdparty qualified
286
+                $listofqualifiedobj[$objectid]=$objectobj;
287
+                $listofqualifiedref[$objectid]=$objectobj->ref;
288
+
289
+
290
+                //var_dump($listofqualifiedref);
291
+            }
292
+
293
+            // Send email if there is at least one qualified record
294
+            if (count($listofqualifiedobj) > 0)
295
+            {
296
+                $langs->load("commercial");
297
+
298
+                $fromtype = GETPOST('fromtype');
299
+                if ($fromtype === 'user') {
300
+                    $from = $user->getFullName($langs) .' <'.$user->email.'>';
301
+                }
302
+                elseif ($fromtype === 'company') {
303
+                    $from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304
+                }
305
+                elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306
+                    $tmp=explode(',', $user->email_aliases);
307
+                    $from = trim($tmp[($reg[1] - 1)]);
308
+                }
309
+                elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310
+                    $tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311
+                    $from = trim($tmp[($reg[1] - 1)]);
312
+                }
313
+                elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314
+                    $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315
+                    $resql = $db->query($sql);
316
+                    $obj = $db->fetch_object($resql);
317
+                    if ($obj)
318
+                    {
319
+                        $from = $obj->label.' <'.$obj->email.'>';
320
+                    }
321
+                }
322
+                else {
323
+                    $from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
324
+                }
325
+
326
+                $replyto = $from;
327
+                $subject = GETPOST('subject','none');
328
+                $message = GETPOST('message','none');
329
+
330
+                $sendtobcc = GETPOST('sendtoccc');
331
+                if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
+                if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
+                if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
+                if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
+                if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
+                if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
337
+
338
+                // $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339
+                $oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
340
+                $looparray=array();
341
+                if (! $oneemailperrecipient)
342
+                {
343
+                    $looparray = $listofqualifiedobj;
344
+                    foreach ($looparray as $key => $objecttmp)
345
+                    {
346
+                        $looparray[$key]->thirdparty = $thirdparty;
347
+                    }
348
+                }
349
+                else
350
+                {
351
+                    $objectforloop=new $objectclass($db);
352
+                    $objectforloop->thirdparty = $thirdparty;
353
+                    $looparray[0]=$objectforloop;
354
+                }
355
+                //var_dump($looparray);exit;
356
+
357
+                foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358
+                {
359
+                    // Make substitution in email content
360
+                    $substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
+                    $substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362
+                    $substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
363
+                    $substitutionarray['__EMAIL__'] = $thirdparty->email;
364
+                    $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
365
+
366
+                    $parameters=array('mode'=>'formemail');
367
+
368
+                    if ( ! empty( $listofobjectthirdparties ) ) {
369
+                        $parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
370
+                    }
371
+                    if ( ! empty( $listofobjectref ) ) {
372
+                        $parameters['listofobjectref'] = $listofobjectref;
373
+                    }
374
+
375
+                    complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
376
+
377
+                    $subject=make_substitutions($subject, $substitutionarray);
378
+                    $message=make_substitutions($message, $substitutionarray);
379
+
380
+                    $filepath = $attachedfiles['paths'];
381
+                    $filename = $attachedfiles['names'];
382
+                    $mimetype = $attachedfiles['mimes'];
383
+
384
+                    // Define the trackid when emails sent from the mass action
385
+                    if ($oneemailperrecipient)
386
+                    {
387
+                        $trackid='thi'.$thirdparty->id;
388
+                        if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
+                        if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
390
+                    }
391
+                    else
392
+                    {
393
+                        $trackid=strtolower(get_class($objecttmp));
394
+                        if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
+                        if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
+                        if (get_class($objecttmp)=='Commande') $trackid='ord';
397
+                        if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
+                        if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
+                        if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
+                        if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
401
+
402
+                        $trackid.=$objecttmp->id;
403
+                    }
404
+                    //var_dump($filepath);
405
+                    //var_dump($trackid);exit;
406
+
407
+                    // Send mail (substitutionarray must be done just before this)
408
+                    require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
409
+                    $mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
410
+                    if ($mailfile->error)
411
+                    {
412
+                        $resaction.='<div class="error">'.$mailfile->error.'</div>';
413
+                    }
414
+                    else
415
+                    {
416
+                        $result=$mailfile->sendfile();
417
+                        if ($result)
418
+                        {
419
+                            $resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>';		// Must not contain "
420
+
421
+                            $error=0;
422
+
423
+                            // Insert logs into agenda
424
+                            foreach($listofqualifiedobj as $objid => $objectobj)
425
+                            {
426
+                                /*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
427 427
 	                            if ($objectclass == 'Commande') $actiontypecode='AC_COM';
428 428
 	                            if ($objectclass == 'Facture') $actiontypecode='AC_FAC';
429 429
 	                            if ($objectclass == 'Supplier_Proposal') $actiontypecode='AC_SUP_PRO';
430 430
 	                            if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
431 431
 	                            if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
432 432
 
433
-								$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434
-								if ($message)
435
-								{
436
-									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
437
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
439
-									$actionmsg = dol_concatdesc($actionmsg, $message);
440
-								}
441
-								$actionmsg2='';
442
-
443
-								// Initialisation donnees
444
-								$objectobj->sendtoid		= 0;
445
-								$objectobj->actionmsg		= $actionmsg;  // Long text
446
-								$objectobj->actionmsg2		= $actionmsg2; // Short text
447
-								$objectobj->fk_element		= $objid;
448
-								$objectobj->elementtype	= $objectobj->element;
449
-
450
-								$triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
451
-								if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452
-								if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453
-								if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
454
-								if ($triggername == 'FACTURE_SENTBYMAIL')    $triggername = 'BILL_SENTBYMAIL';
455
-								if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
456
-								if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
457
-								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458
-								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
459
-
460
-								if (! empty($triggername))
461
-								{
462
-									// Appel des triggers
463
-									include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
464
-									$interface=new Interfaces($db);
465
-									$result=$interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
-									if ($result < 0) { $error++; $errors=$interface->errors; }
467
-									// Fin appel triggers
468
-
469
-									if ($error)
470
-									{
471
-										setEventMessages($db->lasterror(), $errors, 'errors');
472
-										dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
473
-									}
474
-								}
475
-
476
-								$nbsent++;
477
-							}
478
-						}
479
-						else
480
-						{
481
-							$langs->load("other");
482
-							if ($mailfile->error)
483
-							{
484
-								$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485
-								$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
486
-							}
487
-							else
488
-							{
489
-								$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490
-							}
491
-						}
492
-					}
493
-				}
494
-			}
495
-		}
496
-
497
-		$resaction.=($resaction?'<br>':$resaction);
498
-		$resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
-		$resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
-		$resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
501
-		$resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
502
-
503
-		if ($nbsent)
504
-		{
505
-			$action='';	// Do not show form post if there was at least one successfull sent
506
-			//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507
-			setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508
-			setEventMessages($resaction, null, 'mesgs');
509
-		}
510
-		else
511
-		{
512
-			//setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings');  // May be object has no generated PDF file
513
-			setEventMessages($resaction, null, 'warnings');
514
-		}
515
-
516
-		$action='list';
517
-		$massaction='';
518
-	}
433
+                                $actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434
+                                if ($message)
435
+                                {
436
+                                    if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
437
+                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438
+                                    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
439
+                                    $actionmsg = dol_concatdesc($actionmsg, $message);
440
+                                }
441
+                                $actionmsg2='';
442
+
443
+                                // Initialisation donnees
444
+                                $objectobj->sendtoid		= 0;
445
+                                $objectobj->actionmsg		= $actionmsg;  // Long text
446
+                                $objectobj->actionmsg2		= $actionmsg2; // Short text
447
+                                $objectobj->fk_element		= $objid;
448
+                                $objectobj->elementtype	= $objectobj->element;
449
+
450
+                                $triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
451
+                                if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452
+                                if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453
+                                if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
454
+                                if ($triggername == 'FACTURE_SENTBYMAIL')    $triggername = 'BILL_SENTBYMAIL';
455
+                                if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
456
+                                if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
457
+                                if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458
+                                if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
459
+
460
+                                if (! empty($triggername))
461
+                                {
462
+                                    // Appel des triggers
463
+                                    include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
464
+                                    $interface=new Interfaces($db);
465
+                                    $result=$interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
+                                    if ($result < 0) { $error++; $errors=$interface->errors; }
467
+                                    // Fin appel triggers
468
+
469
+                                    if ($error)
470
+                                    {
471
+                                        setEventMessages($db->lasterror(), $errors, 'errors');
472
+                                        dol_syslog("Error in trigger ".$triggername.' '.$db->lasterror(), LOG_ERR);
473
+                                    }
474
+                                }
475
+
476
+                                $nbsent++;
477
+                            }
478
+                        }
479
+                        else
480
+                        {
481
+                            $langs->load("other");
482
+                            if ($mailfile->error)
483
+                            {
484
+                                $resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485
+                                $resaction.='<br><div class="error">'.$mailfile->error.'</div>';
486
+                            }
487
+                            else
488
+                            {
489
+                                $resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490
+                            }
491
+                        }
492
+                    }
493
+                }
494
+            }
495
+        }
496
+
497
+        $resaction.=($resaction?'<br>':$resaction);
498
+        $resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
+        $resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
+        $resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
501
+        $resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
502
+
503
+        if ($nbsent)
504
+        {
505
+            $action='';	// Do not show form post if there was at least one successfull sent
506
+            //setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507
+            setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508
+            setEventMessages($resaction, null, 'mesgs');
509
+        }
510
+        else
511
+        {
512
+            //setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings');  // May be object has no generated PDF file
513
+            setEventMessages($resaction, null, 'warnings');
514
+        }
515
+
516
+        $action='list';
517
+        $massaction='';
518
+    }
519 519
 }
520 520
 
521 521
 if ($massaction == 'confirm_createbills')
522 522
 {
523
-	$orders = GETPOST('toselect','array');
524
-	$createbills_onebythird = GETPOST('createbills_onebythird', 'int');
525
-	$validate_invoices = GETPOST('valdate_invoices', 'int');
526
-
527
-	$TFact = array();
528
-	$TFactThird = array();
529
-
530
-	$nb_bills_created = 0;
531
-
532
-	$db->begin();
533
-
534
-	foreach($orders as $id_order)
535
-	{
536
-		$cmd = new Commande($db);
537
-		if ($cmd->fetch($id_order) <= 0) continue;
538
-
539
-		$objecttmp = new Facture($db);
540
-		if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
541
-		else {
542
-
543
-			$objecttmp->socid = $cmd->socid;
544
-			$objecttmp->type = Facture::TYPE_STANDARD;
545
-			$objecttmp->cond_reglement_id	= $cmd->cond_reglement_id;
546
-			$objecttmp->mode_reglement_id	= $cmd->mode_reglement_id;
547
-			$objecttmp->fk_project			= $cmd->fk_project;
548
-
549
-			$datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
550
-			if (empty($datefacture))
551
-			{
552
-				$datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y"));
553
-			}
554
-
555
-			$objecttmp->date = $datefacture;
556
-			$objecttmp->origin    = 'commande';
557
-			$objecttmp->origin_id = $id_order;
558
-
559
-			$res = $objecttmp->create($user);
560
-
561
-			if($res > 0) $nb_bills_created++;
562
-		}
563
-
564
-		if ($objecttmp->id > 0)
565
-		{
566
-			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
567
-			$sql.= "fk_source";
568
-			$sql.= ", sourcetype";
569
-			$sql.= ", fk_target";
570
-			$sql.= ", targettype";
571
-			$sql.= ") VALUES (";
572
-			$sql.= $id_order;
573
-			$sql.= ", '".$objecttmp->origin."'";
574
-			$sql.= ", ".$objecttmp->id;
575
-			$sql.= ", '".$objecttmp->element."'";
576
-			$sql.= ")";
577
-
578
-			if (! $db->query($sql))
579
-			{
580
-				$error++;
581
-			}
582
-
583
-			if (! $error)
584
-			{
585
-				$lines = $cmd->lines;
586
-				if (empty($lines) && method_exists($cmd, 'fetch_lines'))
587
-				{
588
-					$cmd->fetch_lines();
589
-					$lines = $cmd->lines;
590
-				}
591
-
592
-				$fk_parent_line=0;
593
-				$num=count($lines);
594
-
595
-				for ($i=0;$i<$num;$i++)
596
-				{
597
-					$desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
598
-					if ($lines[$i]->subprice < 0)
599
-					{
600
-						// Negative line, we create a discount line
601
-						$discount = new DiscountAbsolute($db);
602
-						$discount->fk_soc=$objecttmp->socid;
603
-						$discount->amount_ht=abs($lines[$i]->total_ht);
604
-						$discount->amount_tva=abs($lines[$i]->total_tva);
605
-						$discount->amount_ttc=abs($lines[$i]->total_ttc);
606
-						$discount->tva_tx=$lines[$i]->tva_tx;
607
-						$discount->fk_user=$user->id;
608
-						$discount->description=$desc;
609
-						$discountid=$discount->create($user);
610
-						if ($discountid > 0)
611
-						{
612
-							$result=$objecttmp->insert_discount($discountid);
613
-							//$result=$discount->link_to_invoice($lineid,$id);
614
-						}
615
-						else
616
-						{
617
-							setEventMessages($discount->error, $discount->errors, 'errors');
618
-							$error++;
619
-							break;
620
-						}
621
-					}
622
-					else
623
-					{
624
-						// Positive line
625
-						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
626
-						// Date start
627
-						$date_start=false;
628
-						if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
-						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
-						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
631
-						//Date end
632
-						$date_end=false;
633
-						if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
-						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
-						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
636
-						// Reset fk_parent_line for no child products and special product
637
-						if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638
-						{
639
-							$fk_parent_line = 0;
640
-						}
641
-
642
-						// Extrafields
643
-						if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
644
-							$lines[$i]->fetch_optionals($lines[$i]->rowid);
645
-							$array_options = $lines[$i]->array_options;
646
-						}
647
-
648
-						$result = $objecttmp->addline(
649
-							$desc,
650
-							$lines[$i]->subprice,
651
-							$lines[$i]->qty,
652
-							$lines[$i]->tva_tx,
653
-							$lines[$i]->localtax1_tx,
654
-							$lines[$i]->localtax2_tx,
655
-							$lines[$i]->fk_product,
656
-							$lines[$i]->remise_percent,
657
-							$date_start,
658
-							$date_end,
659
-							0,
660
-							$lines[$i]->info_bits,
661
-							$lines[$i]->fk_remise_except,
662
-							'HT',
663
-							0,
664
-							$product_type,
665
-							$ii,
666
-							$lines[$i]->special_code,
667
-							$objecttmp->origin,
668
-							$lines[$i]->rowid,
669
-							$fk_parent_line,
670
-							$lines[$i]->fk_fournprice,
671
-							$lines[$i]->pa_ht,
672
-							$lines[$i]->label,
673
-							$array_options
674
-							);
675
-						if ($result > 0)
676
-						{
677
-							$lineid=$result;
678
-						}
679
-						else
680
-						{
681
-							$lineid=0;
682
-							$error++;
683
-							break;
684
-						}
685
-						// Defined the new fk_parent_line
686
-						if ($result > 0 && $lines[$i]->product_type == 9)
687
-						{
688
-							$fk_parent_line = $result;
689
-						}
690
-					}
691
-				}
692
-			}
693
-		}
694
-
695
-		//$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696
-
697
-		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698
-		else $TFact[$objecttmp->id] = $objecttmp;
699
-	}
700
-
701
-	// Build doc with all invoices
702
-	$TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
703
-	$toselect = array();
704
-
705
-	if (! $error && $validate_invoices)
706
-	{
707
-		$massaction = $action = 'builddoc';
708
-		foreach($TAllFact as &$objecttmp)
709
-		{
710
-			$result = $objecttmp->validate($user);
711
-			if ($result <= 0)
712
-			{
713
-				$error++;
714
-				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
715
-				break;
716
-			}
717
-
718
-			$id = $objecttmp->id; // For builddoc action
719
-
720
-			// Builddoc
721
-			$donotredirect = 1;
722
-			$upload_dir = $conf->facture->dir_output;
723
-			$permissioncreate=$user->rights->facture->creer;
724
-			include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
725
-		}
726
-
727
-		$massaction = $action = 'confirm_createbills';
728
-	}
729
-
730
-	if (! $error)
731
-	{
732
-		$db->commit();
733
-		setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
734
-
735
-		// Make a redirect to avoid to bill twice if we make a refresh or back
736
-		$param='';
737
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
-		if ($sall)					$param.='&sall='.urlencode($sall);
740
-		if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
-		if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
-		if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
-		if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
-		if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
-		if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
-		if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
-		if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
-		if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
-		if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
-		if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
-		if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
-		if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
-		if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
-		if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
-		if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
-		if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
-		if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
-		if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
-		if ($billed != '')			$param.='&billed='.urlencode($billed);
760
-
761
-		header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762
-		exit;
763
-	}
764
-	else
765
-	{
766
-		$db->rollback();
767
-		$action='create';
768
-		$_GET["origin"]=$_POST["origin"];
769
-		$_GET["originid"]=$_POST["originid"];
770
-		setEventMessages("Error", null, 'errors');
771
-		$error++;
772
-	}
523
+    $orders = GETPOST('toselect','array');
524
+    $createbills_onebythird = GETPOST('createbills_onebythird', 'int');
525
+    $validate_invoices = GETPOST('valdate_invoices', 'int');
526
+
527
+    $TFact = array();
528
+    $TFactThird = array();
529
+
530
+    $nb_bills_created = 0;
531
+
532
+    $db->begin();
533
+
534
+    foreach($orders as $id_order)
535
+    {
536
+        $cmd = new Commande($db);
537
+        if ($cmd->fetch($id_order) <= 0) continue;
538
+
539
+        $objecttmp = new Facture($db);
540
+        if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
541
+        else {
542
+
543
+            $objecttmp->socid = $cmd->socid;
544
+            $objecttmp->type = Facture::TYPE_STANDARD;
545
+            $objecttmp->cond_reglement_id	= $cmd->cond_reglement_id;
546
+            $objecttmp->mode_reglement_id	= $cmd->mode_reglement_id;
547
+            $objecttmp->fk_project			= $cmd->fk_project;
548
+
549
+            $datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
550
+            if (empty($datefacture))
551
+            {
552
+                $datefacture = dol_mktime(date("h"), date("M"), 0, date("m"), date("d"), date("Y"));
553
+            }
554
+
555
+            $objecttmp->date = $datefacture;
556
+            $objecttmp->origin    = 'commande';
557
+            $objecttmp->origin_id = $id_order;
558
+
559
+            $res = $objecttmp->create($user);
560
+
561
+            if($res > 0) $nb_bills_created++;
562
+        }
563
+
564
+        if ($objecttmp->id > 0)
565
+        {
566
+            $sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
567
+            $sql.= "fk_source";
568
+            $sql.= ", sourcetype";
569
+            $sql.= ", fk_target";
570
+            $sql.= ", targettype";
571
+            $sql.= ") VALUES (";
572
+            $sql.= $id_order;
573
+            $sql.= ", '".$objecttmp->origin."'";
574
+            $sql.= ", ".$objecttmp->id;
575
+            $sql.= ", '".$objecttmp->element."'";
576
+            $sql.= ")";
577
+
578
+            if (! $db->query($sql))
579
+            {
580
+                $error++;
581
+            }
582
+
583
+            if (! $error)
584
+            {
585
+                $lines = $cmd->lines;
586
+                if (empty($lines) && method_exists($cmd, 'fetch_lines'))
587
+                {
588
+                    $cmd->fetch_lines();
589
+                    $lines = $cmd->lines;
590
+                }
591
+
592
+                $fk_parent_line=0;
593
+                $num=count($lines);
594
+
595
+                for ($i=0;$i<$num;$i++)
596
+                {
597
+                    $desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
598
+                    if ($lines[$i]->subprice < 0)
599
+                    {
600
+                        // Negative line, we create a discount line
601
+                        $discount = new DiscountAbsolute($db);
602
+                        $discount->fk_soc=$objecttmp->socid;
603
+                        $discount->amount_ht=abs($lines[$i]->total_ht);
604
+                        $discount->amount_tva=abs($lines[$i]->total_tva);
605
+                        $discount->amount_ttc=abs($lines[$i]->total_ttc);
606
+                        $discount->tva_tx=$lines[$i]->tva_tx;
607
+                        $discount->fk_user=$user->id;
608
+                        $discount->description=$desc;
609
+                        $discountid=$discount->create($user);
610
+                        if ($discountid > 0)
611
+                        {
612
+                            $result=$objecttmp->insert_discount($discountid);
613
+                            //$result=$discount->link_to_invoice($lineid,$id);
614
+                        }
615
+                        else
616
+                        {
617
+                            setEventMessages($discount->error, $discount->errors, 'errors');
618
+                            $error++;
619
+                            break;
620
+                        }
621
+                    }
622
+                    else
623
+                    {
624
+                        // Positive line
625
+                        $product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
626
+                        // Date start
627
+                        $date_start=false;
628
+                        if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
+                        if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
+                        if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
631
+                        //Date end
632
+                        $date_end=false;
633
+                        if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
+                        if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
+                        if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
636
+                        // Reset fk_parent_line for no child products and special product
637
+                        if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638
+                        {
639
+                            $fk_parent_line = 0;
640
+                        }
641
+
642
+                        // Extrafields
643
+                        if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED) && method_exists($lines[$i], 'fetch_optionals')) {
644
+                            $lines[$i]->fetch_optionals($lines[$i]->rowid);
645
+                            $array_options = $lines[$i]->array_options;
646
+                        }
647
+
648
+                        $result = $objecttmp->addline(
649
+                            $desc,
650
+                            $lines[$i]->subprice,
651
+                            $lines[$i]->qty,
652
+                            $lines[$i]->tva_tx,
653
+                            $lines[$i]->localtax1_tx,
654
+                            $lines[$i]->localtax2_tx,
655
+                            $lines[$i]->fk_product,
656
+                            $lines[$i]->remise_percent,
657
+                            $date_start,
658
+                            $date_end,
659
+                            0,
660
+                            $lines[$i]->info_bits,
661
+                            $lines[$i]->fk_remise_except,
662
+                            'HT',
663
+                            0,
664
+                            $product_type,
665
+                            $ii,
666
+                            $lines[$i]->special_code,
667
+                            $objecttmp->origin,
668
+                            $lines[$i]->rowid,
669
+                            $fk_parent_line,
670
+                            $lines[$i]->fk_fournprice,
671
+                            $lines[$i]->pa_ht,
672
+                            $lines[$i]->label,
673
+                            $array_options
674
+                            );
675
+                        if ($result > 0)
676
+                        {
677
+                            $lineid=$result;
678
+                        }
679
+                        else
680
+                        {
681
+                            $lineid=0;
682
+                            $error++;
683
+                            break;
684
+                        }
685
+                        // Defined the new fk_parent_line
686
+                        if ($result > 0 && $lines[$i]->product_type == 9)
687
+                        {
688
+                            $fk_parent_line = $result;
689
+                        }
690
+                    }
691
+                }
692
+            }
693
+        }
694
+
695
+        //$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696
+
697
+        if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698
+        else $TFact[$objecttmp->id] = $objecttmp;
699
+    }
700
+
701
+    // Build doc with all invoices
702
+    $TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
703
+    $toselect = array();
704
+
705
+    if (! $error && $validate_invoices)
706
+    {
707
+        $massaction = $action = 'builddoc';
708
+        foreach($TAllFact as &$objecttmp)
709
+        {
710
+            $result = $objecttmp->validate($user);
711
+            if ($result <= 0)
712
+            {
713
+                $error++;
714
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
715
+                break;
716
+            }
717
+
718
+            $id = $objecttmp->id; // For builddoc action
719
+
720
+            // Builddoc
721
+            $donotredirect = 1;
722
+            $upload_dir = $conf->facture->dir_output;
723
+            $permissioncreate=$user->rights->facture->creer;
724
+            include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
725
+        }
726
+
727
+        $massaction = $action = 'confirm_createbills';
728
+    }
729
+
730
+    if (! $error)
731
+    {
732
+        $db->commit();
733
+        setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
734
+
735
+        // Make a redirect to avoid to bill twice if we make a refresh or back
736
+        $param='';
737
+        if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
+        if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
+        if ($sall)					$param.='&sall='.urlencode($sall);
740
+        if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
+        if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
+        if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
+        if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
+        if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
+        if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
+        if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
+        if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
+        if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
+        if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
+        if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
+        if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
+        if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
+        if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
+        if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
+        if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
+        if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
+        if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
+        if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
+        if ($billed != '')			$param.='&billed='.urlencode($billed);
760
+
761
+        header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762
+        exit;
763
+    }
764
+    else
765
+    {
766
+        $db->rollback();
767
+        $action='create';
768
+        $_GET["origin"]=$_POST["origin"];
769
+        $_GET["originid"]=$_POST["originid"];
770
+        setEventMessages("Error", null, 'errors');
771
+        $error++;
772
+    }
773 773
 }
774 774
 
775 775
 if (!$error && $massaction == 'cancelorders')
776 776
 {
777 777
 
778
-	$db->begin();
779
-
780
-	$nbok = 0;
781
-
782
-
783
-	$orders = GETPOST('toselect', 'array');
784
-	foreach ($orders as $id_order)
785
-	{
786
-
787
-		$cmd = new Commande($db);
788
-		if ($cmd->fetch($id_order) <= 0)
789
-			continue;
790
-
791
-		if ($cmd->statut != Commande::STATUS_VALIDATED)
792
-		{
793
-			$langs->load('errors');
794
-			setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
795
-			$error++;
796
-			break;
797
-		}
798
-		else
799
-			$result = $cmd->cancel();
800
-
801
-		if ($result < 0)
802
-		{
803
-			setEventMessages($cmd->error, $cmd->errors, 'errors');
804
-			$error++;
805
-			break;
806
-		}
807
-		else
808
-			$nbok++;
809
-	}
810
-	if (!$error)
811
-	{
812
-		if ($nbok > 1)
813
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814
-		else
815
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
816
-		$db->commit();
817
-	}
818
-	else
819
-	{
820
-		$db->rollback();
821
-	}
778
+    $db->begin();
779
+
780
+    $nbok = 0;
781
+
782
+
783
+    $orders = GETPOST('toselect', 'array');
784
+    foreach ($orders as $id_order)
785
+    {
786
+
787
+        $cmd = new Commande($db);
788
+        if ($cmd->fetch($id_order) <= 0)
789
+            continue;
790
+
791
+        if ($cmd->statut != Commande::STATUS_VALIDATED)
792
+        {
793
+            $langs->load('errors');
794
+            setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
795
+            $error++;
796
+            break;
797
+        }
798
+        else
799
+            $result = $cmd->cancel();
800
+
801
+        if ($result < 0)
802
+        {
803
+            setEventMessages($cmd->error, $cmd->errors, 'errors');
804
+            $error++;
805
+            break;
806
+        }
807
+        else
808
+            $nbok++;
809
+    }
810
+    if (!$error)
811
+    {
812
+        if ($nbok > 1)
813
+            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814
+        else
815
+            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
816
+        $db->commit();
817
+    }
818
+    else
819
+    {
820
+        $db->rollback();
821
+    }
822 822
 }
823 823
 
824 824
 
825 825
 if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search'))
826 826
 {
827
-	if (empty($diroutputmassaction))
828
-	{
829
-		dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
830
-		exit;
831
-	}
832
-
833
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
834
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
835
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
836
-
837
-	$objecttmp=new $objectclass($db);
838
-	$listofobjectid=array();
839
-	$listofobjectthirdparties=array();
840
-	$listofobjectref=array();
841
-	foreach($toselect as $toselectid)
842
-	{
843
-		$objecttmp=new $objectclass($db);	// must create new instance because instance is saved into $listofobjectref array for future use
844
-		$result=$objecttmp->fetch($toselectid);
845
-		if ($result > 0)
846
-		{
847
-			$listofobjectid[$toselectid]=$toselectid;
848
-			$thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
849
-			$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
850
-			$listofobjectref[$toselectid]=$objecttmp->ref;
851
-		}
852
-	}
853
-
854
-	$arrayofinclusion=array();
855
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
857
-	$listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
858
-
859
-	// build list of files with full path
860
-	$files = array();
861
-	foreach($listofobjectref as $basename)
862
-	{
863
-		$basename = dol_sanitizeFileName($basename);
864
-		foreach($listoffiles as $filefound)
865
-		{
866
-			if (strstr($filefound["name"],$basename))
867
-			{
868
-				$files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
869
-				break;
870
-			}
871
-		}
872
-	}
873
-
874
-	// Define output language (Here it is not used because we do only merging existing PDF)
875
-	$outputlangs = $langs;
876
-	$newlang='';
877
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
879
-	if (! empty($newlang))
880
-	{
881
-		$outputlangs = new Translate("",$conf);
882
-		$outputlangs->setDefaultLang($newlang);
883
-	}
884
-
885
-	if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT))
886
-	{
887
-		// Create output dir if not exists
888
-		dol_mkdir($diroutputmassaction);
889
-
890
-		// Defined name of merged file
891
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
-		$filename=preg_replace('/\s/','_',$filename);
893
-
894
-		// Save merged file
895
-		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896
-		{
897
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899
-		}
900
-		if ($year) $filename.='_'.$year;
901
-		if ($month) $filename.='_'.$month;
902
-
903
-		if (count($files)>0)
904
-		{
905
-			$now=dol_now();
906
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
907
-
908
-			$input_files = '';
909
-			foreach($files as $f) {
910
-				$input_files.=' '.escapeshellarg($f);
911
-			}
912
-
913
-			$cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914
-			exec($cmd);
915
-
916
-			if (! empty($conf->global->MAIN_UMASK))
917
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
918
-
919
-			$langs->load("exports");
920
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
921
-		}
922
-		else
923
-		{
924
-			setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
925
-		}
926
-	}
927
-	else {
928
-		// Create empty PDF
929
-		$formatarray=pdf_getFormat();
930
-		$page_largeur = $formatarray['width'];
931
-		$page_hauteur = $formatarray['height'];
932
-		$format = array($page_largeur,$page_hauteur);
933
-
934
-		$pdf=pdf_getInstance($format);
935
-
936
-		if (class_exists('TCPDF'))
937
-		{
938
-			$pdf->setPrintHeader(false);
939
-			$pdf->setPrintFooter(false);
940
-		}
941
-		$pdf->SetFont(pdf_getPDFFont($outputlangs));
942
-
943
-		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
944
-
945
-		// Add all others
946
-		foreach($files as $file)
947
-		{
948
-			// Charge un document PDF depuis un fichier.
949
-			$pagecount = $pdf->setSourceFile($file);
950
-			for ($i = 1; $i <= $pagecount; $i++)
951
-			{
952
-				$tplidx = $pdf->importPage($i);
953
-				$s = $pdf->getTemplatesize($tplidx);
954
-				$pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
955
-				$pdf->useTemplate($tplidx);
956
-			}
957
-		}
958
-
959
-		// Create output dir if not exists
960
-		dol_mkdir($diroutputmassaction);
961
-
962
-		// Defined name of merged file
963
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
-		$filename=preg_replace('/\s/','_',$filename);
965
-
966
-		// Save merged file
967
-		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968
-		{
969
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
971
-		}
972
-		if ($year) $filename.='_'.$year;
973
-		if ($month) $filename.='_'.$month;
974
-		if ($pagecount)
975
-		{
976
-			$now=dol_now();
977
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978
-			$pdf->Output($file,'F');
979
-			if (! empty($conf->global->MAIN_UMASK))
980
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
981
-
982
-			$langs->load("exports");
983
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
984
-		}
985
-		else
986
-		{
987
-		setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
988
-		}
989
-	}
827
+    if (empty($diroutputmassaction))
828
+    {
829
+        dol_print_error(null, 'include of actions_massactions.inc.php is done but var $diroutputmassaction was not defined');
830
+        exit;
831
+    }
832
+
833
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
834
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
835
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
836
+
837
+    $objecttmp=new $objectclass($db);
838
+    $listofobjectid=array();
839
+    $listofobjectthirdparties=array();
840
+    $listofobjectref=array();
841
+    foreach($toselect as $toselectid)
842
+    {
843
+        $objecttmp=new $objectclass($db);	// must create new instance because instance is saved into $listofobjectref array for future use
844
+        $result=$objecttmp->fetch($toselectid);
845
+        if ($result > 0)
846
+        {
847
+            $listofobjectid[$toselectid]=$toselectid;
848
+            $thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
849
+            $listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
850
+            $listofobjectref[$toselectid]=$objecttmp->ref;
851
+        }
852
+    }
853
+
854
+    $arrayofinclusion=array();
855
+    foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
+    foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
857
+    $listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
858
+
859
+    // build list of files with full path
860
+    $files = array();
861
+    foreach($listofobjectref as $basename)
862
+    {
863
+        $basename = dol_sanitizeFileName($basename);
864
+        foreach($listoffiles as $filefound)
865
+        {
866
+            if (strstr($filefound["name"],$basename))
867
+            {
868
+                $files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
869
+                break;
870
+            }
871
+        }
872
+    }
873
+
874
+    // Define output language (Here it is not used because we do only merging existing PDF)
875
+    $outputlangs = $langs;
876
+    $newlang='';
877
+    if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
+    if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
879
+    if (! empty($newlang))
880
+    {
881
+        $outputlangs = new Translate("",$conf);
882
+        $outputlangs->setDefaultLang($newlang);
883
+    }
884
+
885
+    if (!empty($conf->global->USE_PDFTK_FOR_PDF_CONCAT))
886
+    {
887
+        // Create output dir if not exists
888
+        dol_mkdir($diroutputmassaction);
889
+
890
+        // Defined name of merged file
891
+        $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
+        $filename=preg_replace('/\s/','_',$filename);
893
+
894
+        // Save merged file
895
+        if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896
+        {
897
+            if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
+            else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899
+        }
900
+        if ($year) $filename.='_'.$year;
901
+        if ($month) $filename.='_'.$month;
902
+
903
+        if (count($files)>0)
904
+        {
905
+            $now=dol_now();
906
+            $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
907
+
908
+            $input_files = '';
909
+            foreach($files as $f) {
910
+                $input_files.=' '.escapeshellarg($f);
911
+            }
912
+
913
+            $cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914
+            exec($cmd);
915
+
916
+            if (! empty($conf->global->MAIN_UMASK))
917
+                @chmod($file, octdec($conf->global->MAIN_UMASK));
918
+
919
+            $langs->load("exports");
920
+            setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
921
+        }
922
+        else
923
+        {
924
+            setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
925
+        }
926
+    }
927
+    else {
928
+        // Create empty PDF
929
+        $formatarray=pdf_getFormat();
930
+        $page_largeur = $formatarray['width'];
931
+        $page_hauteur = $formatarray['height'];
932
+        $format = array($page_largeur,$page_hauteur);
933
+
934
+        $pdf=pdf_getInstance($format);
935
+
936
+        if (class_exists('TCPDF'))
937
+        {
938
+            $pdf->setPrintHeader(false);
939
+            $pdf->setPrintFooter(false);
940
+        }
941
+        $pdf->SetFont(pdf_getPDFFont($outputlangs));
942
+
943
+        if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
944
+
945
+        // Add all others
946
+        foreach($files as $file)
947
+        {
948
+            // Charge un document PDF depuis un fichier.
949
+            $pagecount = $pdf->setSourceFile($file);
950
+            for ($i = 1; $i <= $pagecount; $i++)
951
+            {
952
+                $tplidx = $pdf->importPage($i);
953
+                $s = $pdf->getTemplatesize($tplidx);
954
+                $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L');
955
+                $pdf->useTemplate($tplidx);
956
+            }
957
+        }
958
+
959
+        // Create output dir if not exists
960
+        dol_mkdir($diroutputmassaction);
961
+
962
+        // Defined name of merged file
963
+        $filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
+        $filename=preg_replace('/\s/','_',$filename);
965
+
966
+        // Save merged file
967
+        if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968
+        {
969
+            if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
+            else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
971
+        }
972
+        if ($year) $filename.='_'.$year;
973
+        if ($month) $filename.='_'.$month;
974
+        if ($pagecount)
975
+        {
976
+            $now=dol_now();
977
+            $file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978
+            $pdf->Output($file,'F');
979
+            if (! empty($conf->global->MAIN_UMASK))
980
+                @chmod($file, octdec($conf->global->MAIN_UMASK));
981
+
982
+            $langs->load("exports");
983
+            setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
984
+        }
985
+        else
986
+        {
987
+        setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
988
+        }
989
+    }
990 990
 }
991 991
 
992 992
 // Remove a file from massaction area
993 993
 if ($action == 'remove_file')
994 994
 {
995
-	require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
996
-
997
-	$langs->load("other");
998
-	$upload_dir = $diroutputmassaction;
999
-	$file = $upload_dir . '/' . GETPOST('file');
1000
-	$ret=dol_delete_file($file);
1001
-	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002
-	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1003
-	$action='';
995
+    require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
996
+
997
+    $langs->load("other");
998
+    $upload_dir = $diroutputmassaction;
999
+    $file = $upload_dir . '/' . GETPOST('file');
1000
+    $ret=dol_delete_file($file);
1001
+    if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002
+    else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1003
+    $action='';
1004 1004
 }
1005 1005
 
1006 1006
 // Validate records
1007 1007
 if (! $error && $massaction == 'validate' && $permtocreate)
1008 1008
 {
1009
-	$objecttmp=new $objectclass($db);
1010
-
1011
-	if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
1012
-	{
1013
-		$langs->load("errors");
1014
-		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1015
-		$error++;
1016
-	}
1017
-	if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1018
-	{
1019
-		$langs->load("errors");
1020
-		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1021
-		$error++;
1022
-	}
1023
-	if (! $error)
1024
-	{
1025
-		$db->begin();
1026
-
1027
-		$nbok = 0;
1028
-		foreach($toselect as $toselectid)
1029
-		{
1030
-			$result=$objecttmp->fetch($toselectid);
1031
-			if ($result > 0)
1032
-			{
1033
-				//if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1034
-				//else
1035
-				$result = $objecttmp->validate($user);
1036
-				if ($result == 0)
1037
-				{
1038
-					$langs->load("errors");
1039
-					setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1040
-					$error++;
1041
-					break;
1042
-				}
1043
-				elseif ($result < 0)
1044
-				{
1045
-					setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1046
-					$error++;
1047
-					break;
1048
-				}
1049
-				else $nbok++;
1050
-			}
1051
-			else
1052
-			{
1053
-				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1054
-				$error++;
1055
-				break;
1056
-			}
1057
-		}
1058
-
1059
-		if (! $error)
1060
-		{
1061
-			if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062
-			else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1063
-			$db->commit();
1064
-		}
1065
-		else
1066
-		{
1067
-			$db->rollback();
1068
-		}
1069
-		//var_dump($listofobjectthirdparties);exit;
1070
-	}
1009
+    $objecttmp=new $objectclass($db);
1010
+
1011
+    if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
1012
+    {
1013
+        $langs->load("errors");
1014
+        setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1015
+        $error++;
1016
+    }
1017
+    if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1018
+    {
1019
+        $langs->load("errors");
1020
+        setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1021
+        $error++;
1022
+    }
1023
+    if (! $error)
1024
+    {
1025
+        $db->begin();
1026
+
1027
+        $nbok = 0;
1028
+        foreach($toselect as $toselectid)
1029
+        {
1030
+            $result=$objecttmp->fetch($toselectid);
1031
+            if ($result > 0)
1032
+            {
1033
+                //if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1034
+                //else
1035
+                $result = $objecttmp->validate($user);
1036
+                if ($result == 0)
1037
+                {
1038
+                    $langs->load("errors");
1039
+                    setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1040
+                    $error++;
1041
+                    break;
1042
+                }
1043
+                elseif ($result < 0)
1044
+                {
1045
+                    setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1046
+                    $error++;
1047
+                    break;
1048
+                }
1049
+                else $nbok++;
1050
+            }
1051
+            else
1052
+            {
1053
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1054
+                $error++;
1055
+                break;
1056
+            }
1057
+        }
1058
+
1059
+        if (! $error)
1060
+        {
1061
+            if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062
+            else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1063
+            $db->commit();
1064
+        }
1065
+        else
1066
+        {
1067
+            $db->rollback();
1068
+        }
1069
+        //var_dump($listofobjectthirdparties);exit;
1070
+    }
1071 1071
 }
1072 1072
 // Closed records
1073 1073
 if (!$error && $massaction == 'closed' && $objectclass == "Propal" && $permtoclose) {
@@ -1107,127 +1107,127 @@  discard block
 block discarded – undo
1107 1107
 // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1108 1108
 if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
1109 1109
 {
1110
-	$db->begin();
1111
-
1112
-	$objecttmp=new $objectclass($db);
1113
-	$nbok = 0;
1114
-	foreach($toselect as $toselectid)
1115
-	{
1116
-		$result=$objecttmp->fetch($toselectid);
1117
-		if ($result > 0)
1118
-		{
1119
-			// Refuse deletion for some objects/status
1120
-			if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT)
1121
-			{
1122
-				$langs->load("errors");
1123
-				$nbignored++;
1124
-				$resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
1125
-				continue;
1126
-			}
1127
-
1128
-			if ($objectclass == "Task" && $objecttmp->hasChildren() > 0)
1129
-			{
1130
-				$sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id;
1131
-				$res = $db->query($sql);
1132
-
1133
-				if (!$res)
1134
-				{
1135
-					setEventMessage('ErrorRecordParentingNotModified', 'errors');
1136
-					$error++;
1137
-				}
1138
-			}
1139
-
1140
-			if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1141
-			else $result = $objecttmp->delete($user);
1142
-
1143
-			if ($result <= 0)
1144
-			{
1145
-			    setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1146
-			    $error++;
1147
-			    break;
1148
-			}
1149
-			else $nbok++;
1150
-		}
1151
-		else
1152
-		{
1153
-			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1154
-			$error++;
1155
-			break;
1156
-		}
1157
-	}
1158
-
1159
-	if (! $error)
1160
-	{
1161
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162
-		else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1163
-		$db->commit();
1164
-	}
1165
-	else
1166
-	{
1167
-		$db->rollback();
1168
-	}
1169
-	//var_dump($listofobjectthirdparties);exit;
1110
+    $db->begin();
1111
+
1112
+    $objecttmp=new $objectclass($db);
1113
+    $nbok = 0;
1114
+    foreach($toselect as $toselectid)
1115
+    {
1116
+        $result=$objecttmp->fetch($toselectid);
1117
+        if ($result > 0)
1118
+        {
1119
+            // Refuse deletion for some objects/status
1120
+            if ($objectclass == 'Facture' && empty($conf->global->INVOICE_CAN_ALWAYS_BE_REMOVED) && $objecttmp->status != Facture::STATUS_DRAFT)
1121
+            {
1122
+                $langs->load("errors");
1123
+                $nbignored++;
1124
+                $resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
1125
+                continue;
1126
+            }
1127
+
1128
+            if ($objectclass == "Task" && $objecttmp->hasChildren() > 0)
1129
+            {
1130
+                $sql = "UPDATE ".MAIN_DB_PREFIX."projet_task SET fk_task_parent = 0 WHERE fk_task_parent = ".$objecttmp->id;
1131
+                $res = $db->query($sql);
1132
+
1133
+                if (!$res)
1134
+                {
1135
+                    setEventMessage('ErrorRecordParentingNotModified', 'errors');
1136
+                    $error++;
1137
+                }
1138
+            }
1139
+
1140
+            if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1141
+            else $result = $objecttmp->delete($user);
1142
+
1143
+            if ($result <= 0)
1144
+            {
1145
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1146
+                $error++;
1147
+                break;
1148
+            }
1149
+            else $nbok++;
1150
+        }
1151
+        else
1152
+        {
1153
+            setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1154
+            $error++;
1155
+            break;
1156
+        }
1157
+    }
1158
+
1159
+    if (! $error)
1160
+    {
1161
+        if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162
+        else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1163
+        $db->commit();
1164
+    }
1165
+    else
1166
+    {
1167
+        $db->rollback();
1168
+    }
1169
+    //var_dump($listofobjectthirdparties);exit;
1170 1170
 }
1171 1171
 
1172 1172
 // Generate document foreach object according to model linked to object
1173 1173
 // @TODO : propose model selection
1174 1174
 if (! $error && $massaction == 'generate_doc' && $permtoread)
1175 1175
 {
1176
-	$db->begin();
1177
-
1178
-	$objecttmp=new $objectclass($db);
1179
-	$nbok = 0;
1180
-	foreach($toselect as $toselectid)
1181
-	{
1182
-		$result=$objecttmp->fetch($toselectid);
1183
-		if ($result > 0)
1184
-		{
1185
-			$outputlangs = $langs;
1186
-			$newlang='';
1176
+    $db->begin();
1177
+
1178
+    $objecttmp=new $objectclass($db);
1179
+    $nbok = 0;
1180
+    foreach($toselect as $toselectid)
1181
+    {
1182
+        $result=$objecttmp->fetch($toselectid);
1183
+        if ($result > 0)
1184
+        {
1185
+            $outputlangs = $langs;
1186
+            $newlang='';
1187 1187
 	
1188
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1191
-			if (! empty($newlang))
1192
-			{
1193
-				$outputlangs = new Translate("",$conf);
1194
-				$outputlangs->setDefaultLang($newlang);
1195
-			}
1188
+            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
+            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
+            if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1191
+            if (! empty($newlang))
1192
+            {
1193
+                $outputlangs = new Translate("",$conf);
1194
+                $outputlangs->setDefaultLang($newlang);
1195
+            }
1196 1196
 	
1197
-			// To be sure vars is defined
1198
-			if (empty($hidedetails)) $hidedetails=0;
1199
-			if (empty($hidedesc)) $hidedesc=0;
1200
-			if (empty($hideref)) $hideref=0;
1201
-			if (empty($moreparams)) $moreparams=null;
1197
+            // To be sure vars is defined
1198
+            if (empty($hidedetails)) $hidedetails=0;
1199
+            if (empty($hidedesc)) $hidedesc=0;
1200
+            if (empty($hideref)) $hideref=0;
1201
+            if (empty($moreparams)) $moreparams=null;
1202 1202
 			
1203
-			$result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204
-
1205
-			if ($result <= 0)
1206
-			{
1207
-				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1208
-				$error++;
1209
-				break;
1210
-			}
1211
-			else $nbok++;
1212
-		}
1213
-		else
1214
-		{
1215
-			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1216
-			$error++;
1217
-			break;
1218
-		}
1219
-	}
1220
-
1221
-	if (! $error)
1222
-	{
1223
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224
-		else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1225
-		$db->commit();
1226
-	}
1227
-	else
1228
-	{
1229
-		$db->rollback();
1230
-	}
1203
+            $result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204
+
1205
+            if ($result <= 0)
1206
+            {
1207
+                setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1208
+                $error++;
1209
+                break;
1210
+            }
1211
+            else $nbok++;
1212
+        }
1213
+        else
1214
+        {
1215
+            setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1216
+            $error++;
1217
+            break;
1218
+        }
1219
+    }
1220
+
1221
+    if (! $error)
1222
+    {
1223
+        if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224
+        else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1225
+        $db->commit();
1226
+    }
1227
+    else
1228
+    {
1229
+        $db->rollback();
1230
+    }
1231 1231
 }
1232 1232
 
1233 1233
 $parameters['toselect']=$toselect;
Please login to merge, or discard this patch.
Spacing   +304 added lines, -304 removed lines patch added patch discarded remove patch
@@ -42,23 +42,23 @@  discard block
 block discarded – undo
42 42
 
43 43
 
44 44
 // Mass actions. Controls on number of lines checked.
45
-$maxformassaction=(empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS)?1000:$conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
46
-if (! empty($massaction) && count($toselect) < 1)
45
+$maxformassaction = (empty($conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS) ? 1000 : $conf->global->MAIN_LIMIT_FOR_MASS_ACTIONS);
46
+if (!empty($massaction) && count($toselect) < 1)
47 47
 {
48 48
 	$error++;
49 49
 	setEventMessages($langs->trans("NoRecordSelected"), null, "warnings");
50 50
 }
51
-if (! $error && is_array($toselect) && count($toselect) > $maxformassaction)
51
+if (!$error && is_array($toselect) && count($toselect) > $maxformassaction)
52 52
 {
53
-	setEventMessages($langs->trans('TooManyRecordForMassAction',$maxformassaction), null, 'errors');
53
+	setEventMessages($langs->trans('TooManyRecordForMassAction', $maxformassaction), null, 'errors');
54 54
 	$error++;
55 55
 }
56 56
 
57
-if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
57
+if (!$error && $massaction == 'confirm_presend' && !GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
58 58
 {
59
-	$massaction='presend';
59
+	$massaction = 'presend';
60 60
 }
61
-if (! $error && $massaction == 'confirm_presend')
61
+if (!$error && $massaction == 'confirm_presend')
62 62
 {
63 63
 	$resaction = '';
64 64
 	$nbsent = 0;
@@ -66,64 +66,64 @@  discard block
 block discarded – undo
66 66
 	$langs->load("mails");
67 67
 	include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
68 68
 
69
-	$listofobjectid=array();
70
-	$listofobjectthirdparties=array();
71
-	$listofobjectref=array();
69
+	$listofobjectid = array();
70
+	$listofobjectthirdparties = array();
71
+	$listofobjectref = array();
72 72
 
73
-	if (! $error)
73
+	if (!$error)
74 74
 	{
75
-		$thirdparty=new Societe($db);
76
-		if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
-		if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
75
+		$thirdparty = new Societe($db);
76
+		if ($objecttmp->element == 'expensereport') $thirdparty = new User($db);
77
+		if ($objecttmp->element == 'holiday')       $thirdparty = new User($db);
78 78
 
79
-		$objecttmp=new $objectclass($db);
80
-		foreach($toselect as $toselectid)
79
+		$objecttmp = new $objectclass($db);
80
+		foreach ($toselect as $toselectid)
81 81
 		{
82
-			$objecttmp=new $objectclass($db);	// we must create new instance because instance is saved into $listofobjectref array for future use
83
-			$result=$objecttmp->fetch($toselectid);
82
+			$objecttmp = new $objectclass($db); // we must create new instance because instance is saved into $listofobjectref array for future use
83
+			$result = $objecttmp->fetch($toselectid);
84 84
 			if ($result > 0)
85 85
 			{
86
-				$listofobjectid[$toselectid]=$toselectid;
87
-				$thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
-				if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
-				if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
-				if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
91
-				$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92
-				$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
86
+				$listofobjectid[$toselectid] = $toselectid;
87
+				$thirdpartyid = ($objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid);
88
+				if ($objecttmp->element == 'societe')       $thirdpartyid = $objecttmp->id;
89
+				if ($objecttmp->element == 'expensereport') $thirdpartyid = $objecttmp->fk_user_author;
90
+				if ($objecttmp->element == 'holiday')       $thirdpartyid = $objecttmp->fk_user;
91
+				$listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
92
+				$listofobjectref[$thirdpartyid][$toselectid] = $objecttmp;
93 93
 			}
94 94
 		}
95 95
 	}
96 96
 
97 97
 	// Check mandatory parameters
98
-	if (GETPOST('fromtype','alpha') === 'user' && empty($user->email))
98
+	if (GETPOST('fromtype', 'alpha') === 'user' && empty($user->email))
99 99
 	{
100 100
 		$error++;
101 101
 		setEventMessages($langs->trans("NoSenderEmailDefined"), null, 'warnings');
102
-		$massaction='presend';
102
+		$massaction = 'presend';
103 103
 	}
104 104
 
105
-	$receiver=$_POST['receiver'];
106
-	if (! is_array($receiver))
105
+	$receiver = $_POST['receiver'];
106
+	if (!is_array($receiver))
107 107
 	{
108
-		if (empty($receiver) || $receiver == '-1') $receiver=array();
109
-		else $receiver=array($receiver);
108
+		if (empty($receiver) || $receiver == '-1') $receiver = array();
109
+		else $receiver = array($receiver);
110 110
 	}
111
-	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
111
+	if (!trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
112 112
 	{
113 113
 	 	$error++;
114 114
 	   	setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115
-	   	$massaction='presend';
115
+	   	$massaction = 'presend';
116 116
 	}
117 117
 
118
-	if (! GETPOST('subject','none'))
118
+	if (!GETPOST('subject', 'none'))
119 119
 	{
120 120
 		$error++;
121 121
 		setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTopic")), null, 'warnings');
122
-		$massaction='presend';
122
+		$massaction = 'presend';
123 123
 	}
124 124
 
125 125
 	// Loop on each recipient/thirdparty
126
-	if (! $error)
126
+	if (!$error)
127 127
 	{
128 128
 		foreach ($listofobjectthirdparties as $thirdpartyid)
129 129
 		{
@@ -134,21 +134,21 @@  discard block
 block discarded – undo
134 134
 				exit;
135 135
 			}
136 136
 
137
-			$sendto='';
138
-			$sendtocc='';
139
-			$sendtobcc='';
137
+			$sendto = '';
138
+			$sendtocc = '';
139
+			$sendtobcc = '';
140 140
 			$sendtoid = array();
141 141
 
142 142
 			// Define $sendto
143
-			$tmparray=array();
143
+			$tmparray = array();
144 144
 			if (trim($_POST['sendto']))
145 145
 			{
146 146
 				// Recipients are provided into free text
147 147
 				$tmparray[] = trim($_POST['sendto']);
148 148
 			}
149
-			if (count($receiver)>0)
149
+			if (count($receiver) > 0)
150 150
 			{
151
-				foreach($receiver as $key=>$val)
151
+				foreach ($receiver as $key=>$val)
152 152
 				{
153 153
 					// Recipient was provided from combo list
154 154
 					if ($val == 'thirdparty') // Id of third party or user
@@ -157,28 +157,28 @@  discard block
 block discarded – undo
157 157
 					}
158 158
 					elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
159 159
 					{
160
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
160
+						$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
161 161
 						$sendtoid[] = $val;
162 162
 					}
163 163
 				}
164 164
 			}
165
-			$sendto=implode(',',$tmparray);
165
+			$sendto = implode(',', $tmparray);
166 166
 
167 167
 			// Define $sendtocc
168
-			$receivercc=$_POST['receivercc'];
169
-			if (! is_array($receivercc))
168
+			$receivercc = $_POST['receivercc'];
169
+			if (!is_array($receivercc))
170 170
 			{
171
-				if ($receivercc == '-1') $receivercc=array();
172
-				else $receivercc=array($receivercc);
171
+				if ($receivercc == '-1') $receivercc = array();
172
+				else $receivercc = array($receivercc);
173 173
 			}
174
-			$tmparray=array();
174
+			$tmparray = array();
175 175
 			if (trim($_POST['sendtocc']))
176 176
 			{
177 177
 				$tmparray[] = trim($_POST['sendtocc']);
178 178
 			}
179 179
 			if (count($receivercc) > 0)
180 180
 			{
181
-				foreach($receivercc as $key=>$val)
181
+				foreach ($receivercc as $key=>$val)
182 182
 				{
183 183
 					// Recipient was provided from combo list
184 184
 					if ($val == 'thirdparty') // Id of third party
@@ -187,41 +187,41 @@  discard block
 block discarded – undo
187 187
 					}
188 188
 					elseif ($val)	// Id du contact
189 189
 					{
190
-						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
190
+						$tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
191 191
 						//$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192 192
 					}
193 193
 				}
194 194
 			}
195
-			$sendtocc=implode(',',$tmparray);
195
+			$sendtocc = implode(',', $tmparray);
196 196
 
197 197
 			//var_dump($listofobjectref);exit;
198
-			$attachedfiles=array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
-			$listofqualifiedobj=array();
200
-			$listofqualifiedref=array();
201
-			$thirdpartywithoutemail=array();
198
+			$attachedfiles = array('paths'=>array(), 'names'=>array(), 'mimes'=>array());
199
+			$listofqualifiedobj = array();
200
+			$listofqualifiedref = array();
201
+			$thirdpartywithoutemail = array();
202 202
 
203
-			foreach($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
203
+			foreach ($listofobjectref[$thirdpartyid] as $objectid => $objectobj)
204 204
 			{
205 205
 				//var_dump($thirdpartyid.' - '.$objectid.' - '.$objectobj->statut);
206 206
 				if ($objectclass == 'Propal' && $objectobj->statut == Propal::STATUS_DRAFT)
207 207
 				{
208 208
 					$langs->load("errors");
209 209
 					$nbignored++;
210
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
210
+					$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyProposalNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
211 211
 					continue; // Payment done or started or canceled
212 212
 				}
213 213
 				if ($objectclass == 'Commande' && $objectoj->statut == Commande::STATUS_DRAFT)
214 214
 				{
215 215
 					$langs->load("errors");
216 216
 					$nbignored++;
217
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction',$objectobj->ref).'</div><br>';
217
+					$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyOrderNotDraftCanBeSentInMassAction', $objectobj->ref).'</div><br>';
218 218
 					continue;
219 219
 				}
220 220
 				if ($objectclass == 'Facture' && $objectobj->statut == Facture::STATUS_DRAFT)
221 221
 				{
222 222
 					$langs->load("errors");
223 223
 					$nbignored++;
224
-					$resaction.='<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction',$objectobj->ref).'</div><br>';
224
+					$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyInvoiceValidatedCanBeSentInMassAction', $objectobj->ref).'</div><br>';
225 225
 					continue; // Payment done or started or canceled
226 226
 				}
227 227
 
@@ -247,10 +247,10 @@  discard block
 block discarded – undo
247 247
 				   	$nbignored++;
248 248
 				   	if (empty($thirdpartywithoutemail[$objectobj->thirdparty->id]))
249 249
 					{
250
-						$resaction.='<div class="error">'.$langs->trans('NoRecipientEmail',$objectobj->thirdparty->name).'</div><br>';
250
+						$resaction .= '<div class="error">'.$langs->trans('NoRecipientEmail', $objectobj->thirdparty->name).'</div><br>';
251 251
 					}
252 252
 					dol_syslog('No recipient for thirdparty: '.$objectobj->thirdparty->name, LOG_WARNING);
253
-					$thirdpartywithoutemail[$objectobj->thirdparty->id]=1;
253
+					$thirdpartywithoutemail[$objectobj->thirdparty->id] = 1;
254 254
 				   	continue;
255 255
 				}
256 256
 
@@ -258,33 +258,33 @@  discard block
 block discarded – undo
258 258
 				{
259 259
 					// TODO Use future field $objectobj->fullpathdoc to know where is stored default file
260 260
 					// TODO If not defined, use $objectobj->modelpdf (or defaut invoice config) to know what is template to use to regenerate doc.
261
-					$filename=dol_sanitizeFileName($objectobj->ref).'.pdf';
262
-					$filedir=$uploaddir . '/' . dol_sanitizeFileName($objectobj->ref);
263
-					$file = $filedir . '/' . $filename;
261
+					$filename = dol_sanitizeFileName($objectobj->ref).'.pdf';
262
+					$filedir = $uploaddir.'/'.dol_sanitizeFileName($objectobj->ref);
263
+					$file = $filedir.'/'.$filename;
264 264
 					$mime = dol_mimetype($file);
265 265
 
266 266
 	   				if (dol_is_file($file))
267 267
 					{
268 268
 							// Create form object
269
-							$attachedfiles=array(
270
-							'paths'=>array_merge($attachedfiles['paths'],array($file)),
271
-							'names'=>array_merge($attachedfiles['names'],array($filename)),
272
-							'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
269
+							$attachedfiles = array(
270
+							'paths'=>array_merge($attachedfiles['paths'], array($file)),
271
+							'names'=>array_merge($attachedfiles['names'], array($filename)),
272
+							'mimes'=>array_merge($attachedfiles['mimes'], array($mime))
273 273
 							);
274 274
 					}
275 275
 					else
276 276
 					{
277 277
 							$nbignored++;
278 278
 							$langs->load("errors");
279
-							$resaction.='<div class="error">'.$langs->trans('ErrorCantReadFile',$file).'</div><br>';
279
+							$resaction .= '<div class="error">'.$langs->trans('ErrorCantReadFile', $file).'</div><br>';
280 280
 							dol_syslog('Failed to read file: '.$file, LOG_WARNING);
281 281
 							continue;
282 282
 					}
283 283
 				}
284 284
 
285 285
 				// Object of thirdparty qualified
286
-				$listofqualifiedobj[$objectid]=$objectobj;
287
-				$listofqualifiedref[$objectid]=$objectobj->ref;
286
+				$listofqualifiedobj[$objectid] = $objectobj;
287
+				$listofqualifiedref[$objectid] = $objectobj->ref;
288 288
 
289 289
 
290 290
 				//var_dump($listofqualifiedref);
@@ -297,21 +297,21 @@  discard block
 block discarded – undo
297 297
 
298 298
 				$fromtype = GETPOST('fromtype');
299 299
 				if ($fromtype === 'user') {
300
-					$from = $user->getFullName($langs) .' <'.$user->email.'>';
300
+					$from = $user->getFullName($langs).' <'.$user->email.'>';
301 301
 				}
302 302
 				elseif ($fromtype === 'company') {
303
-					$from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
303
+					$from = $conf->global->MAIN_INFO_SOCIETE_NOM.' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304 304
 				}
305 305
 				elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306
-					$tmp=explode(',', $user->email_aliases);
306
+					$tmp = explode(',', $user->email_aliases);
307 307
 					$from = trim($tmp[($reg[1] - 1)]);
308 308
 				}
309 309
 				elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310
-					$tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
310
+					$tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311 311
 					$from = trim($tmp[($reg[1] - 1)]);
312 312
 				}
313 313
 				elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314
-					$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
314
+					$sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315 315
 					$resql = $db->query($sql);
316 316
 					$obj = $db->fetch_object($resql);
317 317
 					if ($obj)
@@ -320,25 +320,25 @@  discard block
 block discarded – undo
320 320
 					}
321 321
 				}
322 322
 				else {
323
-					$from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
323
+					$from = $_POST['fromname'].' <'.$_POST['frommail'].'>';
324 324
 				}
325 325
 
326 326
 				$replyto = $from;
327
-				$subject = GETPOST('subject','none');
328
-				$message = GETPOST('message','none');
327
+				$subject = GETPOST('subject', 'none');
328
+				$message = GETPOST('message', 'none');
329 329
 
330 330
 				$sendtobcc = GETPOST('sendtoccc');
331
-				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
-				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
-				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
-				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
-				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
-				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
331
+				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
+				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
+				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
+				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
+				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
+				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc ? ", " : "").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
337 337
 
338 338
 				// $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339
-				$oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
340
-				$looparray=array();
341
-				if (! $oneemailperrecipient)
339
+				$oneemailperrecipient = (GETPOST('oneemailperrecipient') == 'on' ? 1 : 0);
340
+				$looparray = array();
341
+				if (!$oneemailperrecipient)
342 342
 				{
343 343
 					$looparray = $listofqualifiedobj;
344 344
 					foreach ($looparray as $key => $objecttmp)
@@ -348,34 +348,34 @@  discard block
 block discarded – undo
348 348
 				}
349 349
 				else
350 350
 				{
351
-					$objectforloop=new $objectclass($db);
351
+					$objectforloop = new $objectclass($db);
352 352
 					$objectforloop->thirdparty = $thirdparty;
353
-					$looparray[0]=$objectforloop;
353
+					$looparray[0] = $objectforloop;
354 354
 				}
355 355
 				//var_dump($looparray);exit;
356 356
 
357 357
 				foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358 358
 				{
359 359
 					// Make substitution in email content
360
-					$substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
-					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362
-					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
360
+					$substitutionarray = getCommonSubstitutionArray($langs, 0, null, $objecttmp);
361
+					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ', array_keys($listofqualifiedobj)) : $objecttmp->id);
362
+					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ', $listofqualifiedref) : $objecttmp->ref);
363 363
 					$substitutionarray['__EMAIL__'] = $thirdparty->email;
364 364
 					$substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$thirdparty->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
365 365
 
366
-					$parameters=array('mode'=>'formemail');
366
+					$parameters = array('mode'=>'formemail');
367 367
 
368
-					if ( ! empty( $listofobjectthirdparties ) ) {
368
+					if (!empty($listofobjectthirdparties)) {
369 369
 						$parameters['listofobjectthirdparties'] = $listofobjectthirdparties;
370 370
 					}
371
-					if ( ! empty( $listofobjectref ) ) {
371
+					if (!empty($listofobjectref)) {
372 372
 						$parameters['listofobjectref'] = $listofobjectref;
373 373
 					}
374 374
 
375 375
 					complete_substitutions_array($substitutionarray, $langs, $objecttmp, $parameters);
376 376
 
377
-					$subject=make_substitutions($subject, $substitutionarray);
378
-					$message=make_substitutions($message, $substitutionarray);
377
+					$subject = make_substitutions($subject, $substitutionarray);
378
+					$message = make_substitutions($message, $substitutionarray);
379 379
 
380 380
 					$filepath = $attachedfiles['paths'];
381 381
 					$filename = $attachedfiles['names'];
@@ -384,44 +384,44 @@  discard block
 block discarded – undo
384 384
 					// Define the trackid when emails sent from the mass action
385 385
 					if ($oneemailperrecipient)
386 386
 					{
387
-						$trackid='thi'.$thirdparty->id;
388
-						if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
-						if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
387
+						$trackid = 'thi'.$thirdparty->id;
388
+						if ($objecttmp->element == 'expensereport') $trackid = 'use'.$thirdparty->id;
389
+						if ($objecttmp->element == 'holiday') $trackid = 'use'.$thirdparty->id;
390 390
 					}
391 391
 					else
392 392
 					{
393
-						$trackid=strtolower(get_class($objecttmp));
394
-						if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
-						if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
-						if (get_class($objecttmp)=='Commande') $trackid='ord';
397
-						if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
-						if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
-						if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
-						if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
401
-
402
-						$trackid.=$objecttmp->id;
393
+						$trackid = strtolower(get_class($objecttmp));
394
+						if (get_class($objecttmp) == 'Contrat')  $trackid = 'con';
395
+						if (get_class($objecttmp) == 'Propal')   $trackid = 'pro';
396
+						if (get_class($objecttmp) == 'Commande') $trackid = 'ord';
397
+						if (get_class($objecttmp) == 'Facture')  $trackid = 'inv';
398
+						if (get_class($objecttmp) == 'Supplier_Proposal')   $trackid = 'spr';
399
+						if (get_class($objecttmp) == 'CommandeFournisseur') $trackid = 'sor';
400
+						if (get_class($objecttmp) == 'FactureFournisseur')  $trackid = 'sin';
401
+
402
+						$trackid .= $objecttmp->id;
403 403
 					}
404 404
 					//var_dump($filepath);
405 405
 					//var_dump($trackid);exit;
406 406
 
407 407
 					// Send mail (substitutionarray must be done just before this)
408 408
 					require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
409
-					$mailfile = new CMailFile($subject,$sendto,$from,$message,$filepath,$mimetype,$filename,$sendtocc,$sendtobcc,$deliveryreceipt,-1,'','',$trackid);
409
+					$mailfile = new CMailFile($subject, $sendto, $from, $message, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid);
410 410
 					if ($mailfile->error)
411 411
 					{
412
-						$resaction.='<div class="error">'.$mailfile->error.'</div>';
412
+						$resaction .= '<div class="error">'.$mailfile->error.'</div>';
413 413
 					}
414 414
 					else
415 415
 					{
416
-						$result=$mailfile->sendfile();
416
+						$result = $mailfile->sendfile();
417 417
 						if ($result)
418 418
 						{
419
-							$resaction.=$langs->trans('MailSuccessfulySent',$mailfile->getValidAddress($from,2),$mailfile->getValidAddress($sendto,2)).'<br>';		// Must not contain "
419
+							$resaction .= $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($from, 2), $mailfile->getValidAddress($sendto, 2)).'<br>'; // Must not contain "
420 420
 
421
-							$error=0;
421
+							$error = 0;
422 422
 
423 423
 							// Insert logs into agenda
424
-							foreach($listofqualifiedobj as $objid => $objectobj)
424
+							foreach ($listofqualifiedobj as $objid => $objectobj)
425 425
 							{
426 426
 								/*if ($objectclass == 'Propale') $actiontypecode='AC_PROP';
427 427
 	                            if ($objectclass == 'Commande') $actiontypecode='AC_COM';
@@ -430,24 +430,24 @@  discard block
 block discarded – undo
430 430
 	                            if ($objectclass == 'CommandeFournisseur') $actiontypecode='AC_SUP_ORD';
431 431
 	                            if ($objectclass == 'FactureFournisseur') $actiontypecode='AC_SUP_INV';*/
432 432
 
433
-								$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
433
+								$actionmsg = $langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434 434
 								if ($message)
435 435
 								{
436
-									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
437
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438
-									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
436
+									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".$sendtocc);
437
+									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
438
+									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
439 439
 									$actionmsg = dol_concatdesc($actionmsg, $message);
440 440
 								}
441
-								$actionmsg2='';
441
+								$actionmsg2 = '';
442 442
 
443 443
 								// Initialisation donnees
444
-								$objectobj->sendtoid		= 0;
445
-								$objectobj->actionmsg		= $actionmsg;  // Long text
444
+								$objectobj->sendtoid = 0;
445
+								$objectobj->actionmsg = $actionmsg; // Long text
446 446
 								$objectobj->actionmsg2		= $actionmsg2; // Short text
447 447
 								$objectobj->fk_element		= $objid;
448 448
 								$objectobj->elementtype	= $objectobj->element;
449 449
 
450
-								$triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
450
+								$triggername = strtoupper(get_class($objectobj)).'_SENTBYMAIL';
451 451
 								if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452 452
 								if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453 453
 								if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
@@ -457,13 +457,13 @@  discard block
 block discarded – undo
457 457
 								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458 458
 								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
459 459
 
460
-								if (! empty($triggername))
460
+								if (!empty($triggername))
461 461
 								{
462 462
 									// Appel des triggers
463
-									include_once DOL_DOCUMENT_ROOT . "/core/class/interfaces.class.php";
464
-									$interface=new Interfaces($db);
465
-									$result=$interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
-									if ($result < 0) { $error++; $errors=$interface->errors; }
463
+									include_once DOL_DOCUMENT_ROOT."/core/class/interfaces.class.php";
464
+									$interface = new Interfaces($db);
465
+									$result = $interface->run_triggers($triggername, $objectobj, $user, $langs, $conf);
466
+									if ($result < 0) { $error++; $errors = $interface->errors; }
467 467
 									// Fin appel triggers
468 468
 
469 469
 									if ($error)
@@ -481,12 +481,12 @@  discard block
 block discarded – undo
481 481
 							$langs->load("other");
482 482
 							if ($mailfile->error)
483 483
 							{
484
-								$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485
-								$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
484
+								$resaction .= $langs->trans('ErrorFailedToSendMail', $from, $sendto);
485
+								$resaction .= '<br><div class="error">'.$mailfile->error.'</div>';
486 486
 							}
487 487
 							else
488 488
 							{
489
-								$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
489
+								$resaction .= '<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490 490
 							}
491 491
 						}
492 492
 					}
@@ -494,15 +494,15 @@  discard block
 block discarded – undo
494 494
 			}
495 495
 		}
496 496
 
497
-		$resaction.=($resaction?'<br>':$resaction);
498
-		$resaction.='<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
-		$resaction.=$langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
-		$resaction.=$langs->trans("NbIgnored").': '.($nbignored?$nbignored:0)."\n<br>";
501
-		$resaction.=$langs->trans("NbSent").': '.($nbsent?$nbsent:0)."\n<br>";
497
+		$resaction .= ($resaction ? '<br>' : $resaction);
498
+		$resaction .= '<strong>'.$langs->trans("ResultOfMailSending").':</strong><br>'."\n";
499
+		$resaction .= $langs->trans("NbSelected").': '.count($toselect)."\n<br>";
500
+		$resaction .= $langs->trans("NbIgnored").': '.($nbignored ? $nbignored : 0)."\n<br>";
501
+		$resaction .= $langs->trans("NbSent").': '.($nbsent ? $nbsent : 0)."\n<br>";
502 502
 
503 503
 		if ($nbsent)
504 504
 		{
505
-			$action='';	// Do not show form post if there was at least one successfull sent
505
+			$action = ''; // Do not show form post if there was at least one successfull sent
506 506
 			//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507 507
 			setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508 508
 			setEventMessages($resaction, null, 'mesgs');
@@ -513,14 +513,14 @@  discard block
 block discarded – undo
513 513
 			setEventMessages($resaction, null, 'warnings');
514 514
 		}
515 515
 
516
-		$action='list';
517
-		$massaction='';
516
+		$action = 'list';
517
+		$massaction = '';
518 518
 	}
519 519
 }
520 520
 
521 521
 if ($massaction == 'confirm_createbills')
522 522
 {
523
-	$orders = GETPOST('toselect','array');
523
+	$orders = GETPOST('toselect', 'array');
524 524
 	$createbills_onebythird = GETPOST('createbills_onebythird', 'int');
525 525
 	$validate_invoices = GETPOST('valdate_invoices', 'int');
526 526
 
@@ -531,7 +531,7 @@  discard block
 block discarded – undo
531 531
 
532 532
 	$db->begin();
533 533
 
534
-	foreach($orders as $id_order)
534
+	foreach ($orders as $id_order)
535 535
 	{
536 536
 		$cmd = new Commande($db);
537 537
 		if ($cmd->fetch($id_order) <= 0) continue;
@@ -544,7 +544,7 @@  discard block
 block discarded – undo
544 544
 			$objecttmp->type = Facture::TYPE_STANDARD;
545 545
 			$objecttmp->cond_reglement_id	= $cmd->cond_reglement_id;
546 546
 			$objecttmp->mode_reglement_id	= $cmd->mode_reglement_id;
547
-			$objecttmp->fk_project			= $cmd->fk_project;
547
+			$objecttmp->fk_project = $cmd->fk_project;
548 548
 
549 549
 			$datefacture = dol_mktime(12, 0, 0, $_POST['remonth'], $_POST['reday'], $_POST['reyear']);
550 550
 			if (empty($datefacture))
@@ -558,29 +558,29 @@  discard block
 block discarded – undo
558 558
 
559 559
 			$res = $objecttmp->create($user);
560 560
 
561
-			if($res > 0) $nb_bills_created++;
561
+			if ($res > 0) $nb_bills_created++;
562 562
 		}
563 563
 
564 564
 		if ($objecttmp->id > 0)
565 565
 		{
566 566
 			$sql = "INSERT INTO ".MAIN_DB_PREFIX."element_element (";
567
-			$sql.= "fk_source";
568
-			$sql.= ", sourcetype";
569
-			$sql.= ", fk_target";
570
-			$sql.= ", targettype";
571
-			$sql.= ") VALUES (";
572
-			$sql.= $id_order;
573
-			$sql.= ", '".$objecttmp->origin."'";
574
-			$sql.= ", ".$objecttmp->id;
575
-			$sql.= ", '".$objecttmp->element."'";
576
-			$sql.= ")";
577
-
578
-			if (! $db->query($sql))
567
+			$sql .= "fk_source";
568
+			$sql .= ", sourcetype";
569
+			$sql .= ", fk_target";
570
+			$sql .= ", targettype";
571
+			$sql .= ") VALUES (";
572
+			$sql .= $id_order;
573
+			$sql .= ", '".$objecttmp->origin."'";
574
+			$sql .= ", ".$objecttmp->id;
575
+			$sql .= ", '".$objecttmp->element."'";
576
+			$sql .= ")";
577
+
578
+			if (!$db->query($sql))
579 579
 			{
580 580
 				$error++;
581 581
 			}
582 582
 
583
-			if (! $error)
583
+			if (!$error)
584 584
 			{
585 585
 				$lines = $cmd->lines;
586 586
 				if (empty($lines) && method_exists($cmd, 'fetch_lines'))
@@ -589,27 +589,27 @@  discard block
 block discarded – undo
589 589
 					$lines = $cmd->lines;
590 590
 				}
591 591
 
592
-				$fk_parent_line=0;
593
-				$num=count($lines);
592
+				$fk_parent_line = 0;
593
+				$num = count($lines);
594 594
 
595
-				for ($i=0;$i<$num;$i++)
595
+				for ($i = 0; $i < $num; $i++)
596 596
 				{
597
-					$desc=($lines[$i]->desc?$lines[$i]->desc:$lines[$i]->libelle);
597
+					$desc = ($lines[$i]->desc ? $lines[$i]->desc : $lines[$i]->libelle);
598 598
 					if ($lines[$i]->subprice < 0)
599 599
 					{
600 600
 						// Negative line, we create a discount line
601 601
 						$discount = new DiscountAbsolute($db);
602
-						$discount->fk_soc=$objecttmp->socid;
603
-						$discount->amount_ht=abs($lines[$i]->total_ht);
604
-						$discount->amount_tva=abs($lines[$i]->total_tva);
605
-						$discount->amount_ttc=abs($lines[$i]->total_ttc);
606
-						$discount->tva_tx=$lines[$i]->tva_tx;
607
-						$discount->fk_user=$user->id;
608
-						$discount->description=$desc;
609
-						$discountid=$discount->create($user);
602
+						$discount->fk_soc = $objecttmp->socid;
603
+						$discount->amount_ht = abs($lines[$i]->total_ht);
604
+						$discount->amount_tva = abs($lines[$i]->total_tva);
605
+						$discount->amount_ttc = abs($lines[$i]->total_ttc);
606
+						$discount->tva_tx = $lines[$i]->tva_tx;
607
+						$discount->fk_user = $user->id;
608
+						$discount->description = $desc;
609
+						$discountid = $discount->create($user);
610 610
 						if ($discountid > 0)
611 611
 						{
612
-							$result=$objecttmp->insert_discount($discountid);
612
+							$result = $objecttmp->insert_discount($discountid);
613 613
 							//$result=$discount->link_to_invoice($lineid,$id);
614 614
 						}
615 615
 						else
@@ -622,17 +622,17 @@  discard block
 block discarded – undo
622 622
 					else
623 623
 					{
624 624
 						// Positive line
625
-						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
625
+						$product_type = ($lines[$i]->product_type ? $lines[$i]->product_type : 0);
626 626
 						// Date start
627
-						$date_start=false;
628
-						if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
-						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
-						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
627
+						$date_start = false;
628
+						if ($lines[$i]->date_debut_prevue) $date_start = $lines[$i]->date_debut_prevue;
629
+						if ($lines[$i]->date_debut_reel) $date_start = $lines[$i]->date_debut_reel;
630
+						if ($lines[$i]->date_start) $date_start = $lines[$i]->date_start;
631 631
 						//Date end
632
-						$date_end=false;
633
-						if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
-						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
-						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
632
+						$date_end = false;
633
+						if ($lines[$i]->date_fin_prevue) $date_end = $lines[$i]->date_fin_prevue;
634
+						if ($lines[$i]->date_fin_reel) $date_end = $lines[$i]->date_fin_reel;
635
+						if ($lines[$i]->date_end) $date_end = $lines[$i]->date_end;
636 636
 						// Reset fk_parent_line for no child products and special product
637 637
 						if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638 638
 						{
@@ -674,11 +674,11 @@  discard block
 block discarded – undo
674 674
 							);
675 675
 						if ($result > 0)
676 676
 						{
677
-							$lineid=$result;
677
+							$lineid = $result;
678 678
 						}
679 679
 						else
680 680
 						{
681
-							$lineid=0;
681
+							$lineid = 0;
682 682
 							$error++;
683 683
 							break;
684 684
 						}
@@ -694,7 +694,7 @@  discard block
 block discarded – undo
694 694
 
695 695
 		//$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696 696
 
697
-		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
697
+		if (!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698 698
 		else $TFact[$objecttmp->id] = $objecttmp;
699 699
 	}
700 700
 
@@ -702,10 +702,10 @@  discard block
 block discarded – undo
702 702
 	$TAllFact = empty($createbills_onebythird) ? $TFact : $TFactThird;
703 703
 	$toselect = array();
704 704
 
705
-	if (! $error && $validate_invoices)
705
+	if (!$error && $validate_invoices)
706 706
 	{
707 707
 		$massaction = $action = 'builddoc';
708
-		foreach($TAllFact as &$objecttmp)
708
+		foreach ($TAllFact as &$objecttmp)
709 709
 		{
710 710
 			$result = $objecttmp->validate($user);
711 711
 			if ($result <= 0)
@@ -720,43 +720,43 @@  discard block
 block discarded – undo
720 720
 			// Builddoc
721 721
 			$donotredirect = 1;
722 722
 			$upload_dir = $conf->facture->dir_output;
723
-			$permissioncreate=$user->rights->facture->creer;
723
+			$permissioncreate = $user->rights->facture->creer;
724 724
 			include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
725 725
 		}
726 726
 
727 727
 		$massaction = $action = 'confirm_createbills';
728 728
 	}
729 729
 
730
-	if (! $error)
730
+	if (!$error)
731 731
 	{
732 732
 		$db->commit();
733 733
 		setEventMessages($langs->trans('BillCreated', $nb_bills_created), null, 'mesgs');
734 734
 
735 735
 		// Make a redirect to avoid to bill twice if we make a refresh or back
736
-		$param='';
737
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
-		if ($sall)					$param.='&sall='.urlencode($sall);
740
-		if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
-		if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
-		if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
-		if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
-		if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
-		if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
-		if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
-		if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
-		if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
-		if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
-		if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
-		if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
-		if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
-		if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
-		if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
-		if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
-		if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
-		if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
-		if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
-		if ($billed != '')			$param.='&billed='.urlencode($billed);
736
+		$param = '';
737
+		if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param .= '&contextpage='.urlencode($contextpage);
738
+		if ($limit > 0 && $limit != $conf->liste_limit) $param .= '&limit='.urlencode($limit);
739
+		if ($sall)					$param .= '&sall='.urlencode($sall);
740
+		if ($socid > 0)             $param .= '&socid='.urlencode($socid);
741
+		if ($viewstatut != '')      $param .= '&viewstatut='.urlencode($viewstatut);
742
+		if ($search_orderday)      		$param .= '&search_orderday='.urlencode($search_orderday);
743
+		if ($search_ordermonth)      		$param .= '&search_ordermonth='.urlencode($search_ordermonth);
744
+		if ($search_orderyear)       		$param .= '&search_orderyear='.urlencode($search_orderyear);
745
+		if ($search_deliveryday)   		$param .= '&search_deliveryday='.urlencode($search_deliveryday);
746
+		if ($search_deliverymonth)   		$param .= '&search_deliverymonth='.urlencode($search_deliverymonth);
747
+		if ($search_deliveryyear)    		$param .= '&search_deliveryyear='.urlencode($search_deliveryyear);
748
+		if ($search_ref)      		$param .= '&search_ref='.urlencode($search_ref);
749
+		if ($search_company)  		$param .= '&search_company='.urlencode($search_company);
750
+		if ($search_ref_customer)	$param .= '&search_ref_customer='.urlencode($search_ref_customer);
751
+		if ($search_user > 0) 		$param .= '&search_user='.urlencode($search_user);
752
+		if ($search_sale > 0) 		$param .= '&search_sale='.urlencode($search_sale);
753
+		if ($search_total_ht != '') $param .= '&search_total_ht='.urlencode($search_total_ht);
754
+		if ($search_total_vat != '') $param .= '&search_total_vat='.urlencode($search_total_vat);
755
+		if ($search_total_ttc != '') $param .= '&search_total_ttc='.urlencode($search_total_ttc);
756
+		if ($search_project_ref >= 0)  	$param .= "&search_project_ref=".urlencode($search_project_ref);
757
+		if ($show_files)            $param .= '&show_files='.urlencode($show_files);
758
+		if ($optioncss != '')       $param .= '&optioncss='.urlencode($optioncss);
759
+		if ($billed != '')			$param .= '&billed='.urlencode($billed);
760 760
 
761 761
 		header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762 762
 		exit;
@@ -764,9 +764,9 @@  discard block
 block discarded – undo
764 764
 	else
765 765
 	{
766 766
 		$db->rollback();
767
-		$action='create';
768
-		$_GET["origin"]=$_POST["origin"];
769
-		$_GET["originid"]=$_POST["originid"];
767
+		$action = 'create';
768
+		$_GET["origin"] = $_POST["origin"];
769
+		$_GET["originid"] = $_POST["originid"];
770 770
 		setEventMessages("Error", null, 'errors');
771 771
 		$error++;
772 772
 	}
@@ -822,7 +822,7 @@  discard block
 block discarded – undo
822 822
 }
823 823
 
824 824
 
825
-if (! $error && $massaction == "builddoc" && $permtoread && ! GETPOST('button_search'))
825
+if (!$error && $massaction == "builddoc" && $permtoread && !GETPOST('button_search'))
826 826
 {
827 827
 	if (empty($diroutputmassaction))
828 828
 	{
@@ -834,36 +834,36 @@  discard block
 block discarded – undo
834 834
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/pdf.lib.php';
835 835
 	require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
836 836
 
837
-	$objecttmp=new $objectclass($db);
838
-	$listofobjectid=array();
839
-	$listofobjectthirdparties=array();
840
-	$listofobjectref=array();
841
-	foreach($toselect as $toselectid)
837
+	$objecttmp = new $objectclass($db);
838
+	$listofobjectid = array();
839
+	$listofobjectthirdparties = array();
840
+	$listofobjectref = array();
841
+	foreach ($toselect as $toselectid)
842 842
 	{
843
-		$objecttmp=new $objectclass($db);	// must create new instance because instance is saved into $listofobjectref array for future use
844
-		$result=$objecttmp->fetch($toselectid);
843
+		$objecttmp = new $objectclass($db); // must create new instance because instance is saved into $listofobjectref array for future use
844
+		$result = $objecttmp->fetch($toselectid);
845 845
 		if ($result > 0)
846 846
 		{
847
-			$listofobjectid[$toselectid]=$toselectid;
848
-			$thirdpartyid=$objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid;
849
-			$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
850
-			$listofobjectref[$toselectid]=$objecttmp->ref;
847
+			$listofobjectid[$toselectid] = $toselectid;
848
+			$thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid;
849
+			$listofobjectthirdparties[$thirdpartyid] = $thirdpartyid;
850
+			$listofobjectref[$toselectid] = $objecttmp->ref;
851 851
 		}
852 852
 	}
853 853
 
854
-	$arrayofinclusion=array();
855
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
857
-	$listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
854
+	$arrayofinclusion = array();
855
+	foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'\.pdf$';
856
+	foreach ($listofobjectref as $tmppdf) $arrayofinclusion[] = '^'.preg_quote(dol_sanitizeFileName($tmppdf), '/').'_[a-zA-Z0-9-_]+\.pdf$'; // To include PDF generated from ODX files
857
+	$listoffiles = dol_dir_list($uploaddir, 'all', 1, implode('|', $arrayofinclusion), '\.meta$|\.png', 'date', SORT_DESC, 0, true);
858 858
 
859 859
 	// build list of files with full path
860 860
 	$files = array();
861
-	foreach($listofobjectref as $basename)
861
+	foreach ($listofobjectref as $basename)
862 862
 	{
863 863
 		$basename = dol_sanitizeFileName($basename);
864
-		foreach($listoffiles as $filefound)
864
+		foreach ($listoffiles as $filefound)
865 865
 		{
866
-			if (strstr($filefound["name"],$basename))
866
+			if (strstr($filefound["name"], $basename))
867 867
 			{
868 868
 				$files[] = $uploaddir.'/'.$basename.'/'.$filefound["name"];
869 869
 				break;
@@ -873,12 +873,12 @@  discard block
 block discarded – undo
873 873
 
874 874
 	// Define output language (Here it is not used because we do only merging existing PDF)
875 875
 	$outputlangs = $langs;
876
-	$newlang='';
877
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
879
-	if (! empty($newlang))
876
+	$newlang = '';
877
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
878
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $objecttmp->thirdparty->default_lang;
879
+	if (!empty($newlang))
880 880
 	{
881
-		$outputlangs = new Translate("",$conf);
881
+		$outputlangs = new Translate("", $conf);
882 882
 		$outputlangs->setDefaultLang($newlang);
883 883
 	}
884 884
 
@@ -888,36 +888,36 @@  discard block
 block discarded – undo
888 888
 		dol_mkdir($diroutputmassaction);
889 889
 
890 890
 		// Defined name of merged file
891
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
-		$filename=preg_replace('/\s/','_',$filename);
891
+		$filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
892
+		$filename = preg_replace('/\s/', '_', $filename);
893 893
 
894 894
 		// Save merged file
895 895
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896 896
 		{
897
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
897
+			if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
+			else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
899 899
 		}
900
-		if ($year) $filename.='_'.$year;
901
-		if ($month) $filename.='_'.$month;
900
+		if ($year) $filename .= '_'.$year;
901
+		if ($month) $filename .= '_'.$month;
902 902
 
903
-		if (count($files)>0)
903
+		if (count($files) > 0)
904 904
 		{
905
-			$now=dol_now();
906
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
905
+			$now = dol_now();
906
+			$file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
907 907
 
908 908
 			$input_files = '';
909
-			foreach($files as $f) {
910
-				$input_files.=' '.escapeshellarg($f);
909
+			foreach ($files as $f) {
910
+				$input_files .= ' '.escapeshellarg($f);
911 911
 			}
912 912
 
913 913
 			$cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914 914
 			exec($cmd);
915 915
 
916
-			if (! empty($conf->global->MAIN_UMASK))
916
+			if (!empty($conf->global->MAIN_UMASK))
917 917
 				@chmod($file, octdec($conf->global->MAIN_UMASK));
918 918
 
919 919
 			$langs->load("exports");
920
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
920
+			setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
921 921
 		}
922 922
 		else
923 923
 		{
@@ -926,12 +926,12 @@  discard block
 block discarded – undo
926 926
 	}
927 927
 	else {
928 928
 		// Create empty PDF
929
-		$formatarray=pdf_getFormat();
929
+		$formatarray = pdf_getFormat();
930 930
 		$page_largeur = $formatarray['width'];
931 931
 		$page_hauteur = $formatarray['height'];
932
-		$format = array($page_largeur,$page_hauteur);
932
+		$format = array($page_largeur, $page_hauteur);
933 933
 
934
-		$pdf=pdf_getInstance($format);
934
+		$pdf = pdf_getInstance($format);
935 935
 
936 936
 		if (class_exists('TCPDF'))
937 937
 		{
@@ -940,10 +940,10 @@  discard block
 block discarded – undo
940 940
 		}
941 941
 		$pdf->SetFont(pdf_getPDFFont($outputlangs));
942 942
 
943
-		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
943
+		if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
944 944
 
945 945
 		// Add all others
946
-		foreach($files as $file)
946
+		foreach ($files as $file)
947 947
 		{
948 948
 			// Charge un document PDF depuis un fichier.
949 949
 			$pagecount = $pdf->setSourceFile($file);
@@ -960,27 +960,27 @@  discard block
 block discarded – undo
960 960
 		dol_mkdir($diroutputmassaction);
961 961
 
962 962
 		// Defined name of merged file
963
-		$filename=strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
-		$filename=preg_replace('/\s/','_',$filename);
963
+		$filename = strtolower(dol_sanitizeFileName($langs->transnoentities($objectlabel)));
964
+		$filename = preg_replace('/\s/', '_', $filename);
965 965
 
966 966
 		// Save merged file
967 967
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968 968
 		{
969
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
969
+			if ($option == 'late') $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
+			else $filename .= '_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
971 971
 		}
972
-		if ($year) $filename.='_'.$year;
973
-		if ($month) $filename.='_'.$month;
972
+		if ($year) $filename .= '_'.$year;
973
+		if ($month) $filename .= '_'.$month;
974 974
 		if ($pagecount)
975 975
 		{
976
-			$now=dol_now();
977
-			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978
-			$pdf->Output($file,'F');
979
-			if (! empty($conf->global->MAIN_UMASK))
976
+			$now = dol_now();
977
+			$file = $diroutputmassaction.'/'.$filename.'_'.dol_print_date($now, 'dayhourlog').'.pdf';
978
+			$pdf->Output($file, 'F');
979
+			if (!empty($conf->global->MAIN_UMASK))
980 980
 				@chmod($file, octdec($conf->global->MAIN_UMASK));
981 981
 
982 982
 			$langs->load("exports");
983
-			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
983
+			setEventMessages($langs->trans('FileSuccessfullyBuilt', $filename.'_'.dol_print_date($now, 'dayhourlog')), null, 'mesgs');
984 984
 		}
985 985
 		else
986 986
 		{
@@ -996,38 +996,38 @@  discard block
 block discarded – undo
996 996
 
997 997
 	$langs->load("other");
998 998
 	$upload_dir = $diroutputmassaction;
999
-	$file = $upload_dir . '/' . GETPOST('file');
1000
-	$ret=dol_delete_file($file);
999
+	$file = $upload_dir.'/'.GETPOST('file');
1000
+	$ret = dol_delete_file($file);
1001 1001
 	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002 1002
 	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1003
-	$action='';
1003
+	$action = '';
1004 1004
 }
1005 1005
 
1006 1006
 // Validate records
1007
-if (! $error && $massaction == 'validate' && $permtocreate)
1007
+if (!$error && $massaction == 'validate' && $permtocreate)
1008 1008
 {
1009
-	$objecttmp=new $objectclass($db);
1009
+	$objecttmp = new $objectclass($db);
1010 1010
 
1011
-	if ($objecttmp->element == 'invoice' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
1011
+	if ($objecttmp->element == 'invoice' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_BILL))
1012 1012
 	{
1013 1013
 		$langs->load("errors");
1014 1014
 		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1015 1015
 		$error++;
1016 1016
 	}
1017
-	if ($objecttmp->element == 'invoice_supplier' && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1017
+	if ($objecttmp->element == 'invoice_supplier' && !empty($conf->stock->enabled) && !empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL))
1018 1018
 	{
1019 1019
 		$langs->load("errors");
1020 1020
 		setEventMessages($langs->trans('ErrorMassValidationNotAllowedWhenStockIncreaseOnAction'), null, 'errors');
1021 1021
 		$error++;
1022 1022
 	}
1023
-	if (! $error)
1023
+	if (!$error)
1024 1024
 	{
1025 1025
 		$db->begin();
1026 1026
 
1027 1027
 		$nbok = 0;
1028
-		foreach($toselect as $toselectid)
1028
+		foreach ($toselect as $toselectid)
1029 1029
 		{
1030
-			$result=$objecttmp->fetch($toselectid);
1030
+			$result = $objecttmp->fetch($toselectid);
1031 1031
 			if ($result > 0)
1032 1032
 			{
1033 1033
 				//if (in_array($objecttmp->element, array('societe','member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
 			}
1057 1057
 		}
1058 1058
 
1059
-		if (! $error)
1059
+		if (!$error)
1060 1060
 		{
1061 1061
 			if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062 1062
 			else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
@@ -1105,15 +1105,15 @@  discard block
 block discarded – undo
1105 1105
     }
1106 1106
 }
1107 1107
 // Delete record from mass action (massaction = 'delete' for direct delete, action/confirm='delete'/'yes' with a confirmation step before)
1108
-if (! $error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
1108
+if (!$error && ($massaction == 'delete' || ($action == 'delete' && $confirm == 'yes')) && $permtodelete)
1109 1109
 {
1110 1110
 	$db->begin();
1111 1111
 
1112
-	$objecttmp=new $objectclass($db);
1112
+	$objecttmp = new $objectclass($db);
1113 1113
 	$nbok = 0;
1114
-	foreach($toselect as $toselectid)
1114
+	foreach ($toselect as $toselectid)
1115 1115
 	{
1116
-		$result=$objecttmp->fetch($toselectid);
1116
+		$result = $objecttmp->fetch($toselectid);
1117 1117
 		if ($result > 0)
1118 1118
 		{
1119 1119
 			// Refuse deletion for some objects/status
@@ -1121,7 +1121,7 @@  discard block
 block discarded – undo
1121 1121
 			{
1122 1122
 				$langs->load("errors");
1123 1123
 				$nbignored++;
1124
-				$resaction.='<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction',$objecttmp->ref).'</div><br>';
1124
+				$resaction .= '<div class="error">'.$langs->trans('ErrorOnlyDraftStatusCanBeDeletedInMassAction', $objecttmp->ref).'</div><br>';
1125 1125
 				continue;
1126 1126
 			}
1127 1127
 
@@ -1156,7 +1156,7 @@  discard block
 block discarded – undo
1156 1156
 		}
1157 1157
 	}
1158 1158
 
1159
-	if (! $error)
1159
+	if (!$error)
1160 1160
 	{
1161 1161
 		if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162 1162
 		else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
@@ -1171,36 +1171,36 @@  discard block
 block discarded – undo
1171 1171
 
1172 1172
 // Generate document foreach object according to model linked to object
1173 1173
 // @TODO : propose model selection
1174
-if (! $error && $massaction == 'generate_doc' && $permtoread)
1174
+if (!$error && $massaction == 'generate_doc' && $permtoread)
1175 1175
 {
1176 1176
 	$db->begin();
1177 1177
 
1178
-	$objecttmp=new $objectclass($db);
1178
+	$objecttmp = new $objectclass($db);
1179 1179
 	$nbok = 0;
1180
-	foreach($toselect as $toselectid)
1180
+	foreach ($toselect as $toselectid)
1181 1181
 	{
1182
-		$result=$objecttmp->fetch($toselectid);
1182
+		$result = $objecttmp->fetch($toselectid);
1183 1183
 		if ($result > 0)
1184 1184
 		{
1185 1185
 			$outputlangs = $langs;
1186
-			$newlang='';
1186
+			$newlang = '';
1187 1187
 	
1188
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1191
-			if (! empty($newlang))
1188
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id', 'aZ09')) $newlang = GETPOST('lang_id', 'aZ09');
1189
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang = $objecttmp->thirdparty->default_lang; // for proposal, order, invoice, ...
1190
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang = $objecttmp->default_lang; // for thirdparty
1191
+			if (!empty($newlang))
1192 1192
 			{
1193
-				$outputlangs = new Translate("",$conf);
1193
+				$outputlangs = new Translate("", $conf);
1194 1194
 				$outputlangs->setDefaultLang($newlang);
1195 1195
 			}
1196 1196
 	
1197 1197
 			// To be sure vars is defined
1198
-			if (empty($hidedetails)) $hidedetails=0;
1199
-			if (empty($hidedesc)) $hidedesc=0;
1200
-			if (empty($hideref)) $hideref=0;
1201
-			if (empty($moreparams)) $moreparams=null;
1198
+			if (empty($hidedetails)) $hidedetails = 0;
1199
+			if (empty($hidedesc)) $hidedesc = 0;
1200
+			if (empty($hideref)) $hideref = 0;
1201
+			if (empty($moreparams)) $moreparams = null;
1202 1202
 			
1203
-			$result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1203
+			$result = $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204 1204
 
1205 1205
 			if ($result <= 0)
1206 1206
 			{
@@ -1218,7 +1218,7 @@  discard block
 block discarded – undo
1218 1218
 		}
1219 1219
 	}
1220 1220
 
1221
-	if (! $error)
1221
+	if (!$error)
1222 1222
 	{
1223 1223
 		if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224 1224
 		else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
@@ -1230,10 +1230,10 @@  discard block
 block discarded – undo
1230 1230
 	}
1231 1231
 }
1232 1232
 
1233
-$parameters['toselect']=$toselect;
1234
-$parameters['uploaddir']=$uploaddir;
1233
+$parameters['toselect'] = $toselect;
1234
+$parameters['uploaddir'] = $uploaddir;
1235 1235
 
1236
-$reshook=$hookmanager->executeHooks('doMassActions',$parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1236
+$reshook = $hookmanager->executeHooks('doMassActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
1237 1237
 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1238 1238
 
1239 1239
 
Please login to merge, or discard this patch.
Braces   +372 added lines, -189 removed lines patch added patch discarded remove patch
@@ -54,10 +54,12 @@  discard block
 block discarded – undo
54 54
 	$error++;
55 55
 }
56 56
 
57
-if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail'))  // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
57
+if (! $error && $massaction == 'confirm_presend' && ! GETPOST('sendmail')) {
58
+    // If we do not choose button send (for example when we change template or limit), we must not send email, but keep on send email form
58 59
 {
59 60
 	$massaction='presend';
60 61
 }
62
+}
61 63
 if (! $error && $massaction == 'confirm_presend')
62 64
 {
63 65
 	$resaction = '';
@@ -73,8 +75,12 @@  discard block
 block discarded – undo
73 75
 	if (! $error)
74 76
 	{
75 77
 		$thirdparty=new Societe($db);
76
-		if ($objecttmp->element == 'expensereport') $thirdparty=new User($db);
77
-		if ($objecttmp->element == 'holiday')       $thirdparty=new User($db);
78
+		if ($objecttmp->element == 'expensereport') {
79
+		    $thirdparty=new User($db);
80
+		}
81
+		if ($objecttmp->element == 'holiday') {
82
+		    $thirdparty=new User($db);
83
+		}
78 84
 
79 85
 		$objecttmp=new $objectclass($db);
80 86
 		foreach($toselect as $toselectid)
@@ -85,9 +91,15 @@  discard block
 block discarded – undo
85 91
 			{
86 92
 				$listofobjectid[$toselectid]=$toselectid;
87 93
 				$thirdpartyid=($objecttmp->fk_soc?$objecttmp->fk_soc:$objecttmp->socid);
88
-				if ($objecttmp->element == 'societe')       $thirdpartyid=$objecttmp->id;
89
-				if ($objecttmp->element == 'expensereport') $thirdpartyid=$objecttmp->fk_user_author;
90
-				if ($objecttmp->element == 'holiday')       $thirdpartyid=$objecttmp->fk_user;
94
+				if ($objecttmp->element == 'societe') {
95
+				    $thirdpartyid=$objecttmp->id;
96
+				}
97
+				if ($objecttmp->element == 'expensereport') {
98
+				    $thirdpartyid=$objecttmp->fk_user_author;
99
+				}
100
+				if ($objecttmp->element == 'holiday') {
101
+				    $thirdpartyid=$objecttmp->fk_user;
102
+				}
91 103
 				$listofobjectthirdparties[$thirdpartyid]=$thirdpartyid;
92 104
 				$listofobjectref[$thirdpartyid][$toselectid]=$objecttmp;
93 105
 			}
@@ -105,12 +117,17 @@  discard block
 block discarded – undo
105 117
 	$receiver=$_POST['receiver'];
106 118
 	if (! is_array($receiver))
107 119
 	{
108
-		if (empty($receiver) || $receiver == '-1') $receiver=array();
109
-		else $receiver=array($receiver);
120
+		if (empty($receiver) || $receiver == '-1') {
121
+		    $receiver=array();
122
+		} else {
123
+		    $receiver=array($receiver);
124
+		}
110 125
 	}
111
-	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1)	// if only one recipient, receiver is mandatory
126
+	if (! trim($_POST['sendto']) && count($receiver) == 0 && count($listofobjectthirdparties) == 1) {
127
+	    // if only one recipient, receiver is mandatory
112 128
 	{
113 129
 	 	$error++;
130
+	}
114 131
 	   	setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Recipient")), null, 'warnings');
115 132
 	   	$massaction='presend';
116 133
 	}
@@ -151,13 +168,16 @@  discard block
 block discarded – undo
151 168
 				foreach($receiver as $key=>$val)
152 169
 				{
153 170
 					// Recipient was provided from combo list
154
-					if ($val == 'thirdparty') // Id of third party or user
171
+					if ($val == 'thirdparty') {
172
+					    // Id of third party or user
155 173
 					{
156 174
 						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
157 175
 					}
158
-					elseif ($val && method_exists($thirdparty, 'contact_get_property'))		// Id of contact
176
+					} elseif ($val && method_exists($thirdparty, 'contact_get_property')) {
177
+					    // Id of contact
159 178
 					{
160 179
 						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
180
+					}
161 181
 						$sendtoid[] = $val;
162 182
 					}
163 183
 				}
@@ -168,8 +188,11 @@  discard block
 block discarded – undo
168 188
 			$receivercc=$_POST['receivercc'];
169 189
 			if (! is_array($receivercc))
170 190
 			{
171
-				if ($receivercc == '-1') $receivercc=array();
172
-				else $receivercc=array($receivercc);
191
+				if ($receivercc == '-1') {
192
+				    $receivercc=array();
193
+				} else {
194
+				    $receivercc=array($receivercc);
195
+				}
173 196
 			}
174 197
 			$tmparray=array();
175 198
 			if (trim($_POST['sendtocc']))
@@ -181,13 +204,16 @@  discard block
 block discarded – undo
181 204
 				foreach($receivercc as $key=>$val)
182 205
 				{
183 206
 					// Recipient was provided from combo list
184
-					if ($val == 'thirdparty') // Id of third party
207
+					if ($val == 'thirdparty') {
208
+					    // Id of third party
185 209
 					{
186 210
 						$tmparray[] = $thirdparty->name.' <'.$thirdparty->email.'>';
187 211
 					}
188
-					elseif ($val)	// Id du contact
212
+					} elseif ($val) {
213
+					    // Id du contact
189 214
 					{
190 215
 						$tmparray[] = $thirdparty->contact_get_property((int) $val,'email');
216
+					}
191 217
 						//$sendtoid[] = $val;  TODO Add also id of contact in CC ?
192 218
 					}
193 219
 				}
@@ -226,15 +252,16 @@  discard block
 block discarded – undo
226 252
 				}
227 253
 
228 254
 				// Test recipient
229
-				if (empty($sendto)) 	// For the case, no recipient were set (multi thirdparties send)
255
+				if (empty($sendto)) {
256
+				    // For the case, no recipient were set (multi thirdparties send)
230 257
 				{
231 258
 					if ($objectobj->element == 'expensereport')
232 259
 					{
233 260
 						$fuser = new User($db);
261
+				}
234 262
 						$fuser->fetch($objectobj->fk_user_author);
235 263
 						$sendto = $fuser->email;
236
-					}
237
-					else
264
+					} else
238 265
 					{
239 266
 						$objectobj->fetch_thirdparty();
240 267
 						$sendto = $objectobj->thirdparty->email;
@@ -271,8 +298,7 @@  discard block
 block discarded – undo
271 298
 							'names'=>array_merge($attachedfiles['names'],array($filename)),
272 299
 							'mimes'=>array_merge($attachedfiles['mimes'],array($mime))
273 300
 							);
274
-					}
275
-					else
301
+					} else
276 302
 					{
277 303
 							$nbignored++;
278 304
 							$langs->load("errors");
@@ -298,19 +324,15 @@  discard block
 block discarded – undo
298 324
 				$fromtype = GETPOST('fromtype');
299 325
 				if ($fromtype === 'user') {
300 326
 					$from = $user->getFullName($langs) .' <'.$user->email.'>';
301
-				}
302
-				elseif ($fromtype === 'company') {
327
+				} elseif ($fromtype === 'company') {
303 328
 					$from = $conf->global->MAIN_INFO_SOCIETE_NOM .' <'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'>';
304
-				}
305
-				elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
329
+				} elseif (preg_match('/user_aliases_(\d+)/', $fromtype, $reg)) {
306 330
 					$tmp=explode(',', $user->email_aliases);
307 331
 					$from = trim($tmp[($reg[1] - 1)]);
308
-				}
309
-				elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
332
+				} elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
310 333
 					$tmp=explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
311 334
 					$from = trim($tmp[($reg[1] - 1)]);
312
-				}
313
-				elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
335
+				} elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
314 336
 					$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE rowid = '.(int) $reg[1];
315 337
 					$resql = $db->query($sql);
316 338
 					$obj = $db->fetch_object($resql);
@@ -318,8 +340,7 @@  discard block
 block discarded – undo
318 340
 					{
319 341
 						$from = $obj->label.' <'.$obj->email.'>';
320 342
 					}
321
-				}
322
-				else {
343
+				} else {
323 344
 					$from = $_POST['fromname'] . ' <' . $_POST['frommail'] .'>';
324 345
 				}
325 346
 
@@ -328,12 +349,24 @@  discard block
 block discarded – undo
328 349
 				$message = GETPOST('message','none');
329 350
 
330 351
 				$sendtobcc = GETPOST('sendtoccc');
331
-				if ($objectclass == 'Propal') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
332
-				if ($objectclass == 'Commande') 			$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
333
-				if ($objectclass == 'Facture') 				$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
334
-				if ($objectclass == 'Supplier_Proposal') 	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
335
-				if ($objectclass == 'CommandeFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
336
-				if ($objectclass == 'FactureFournisseur')	$sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
352
+				if ($objectclass == 'Propal') {
353
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO));
354
+				}
355
+				if ($objectclass == 'Commande') {
356
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO));
357
+				}
358
+				if ($objectclass == 'Facture') {
359
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO));
360
+				}
361
+				if ($objectclass == 'Supplier_Proposal') {
362
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO));
363
+				}
364
+				if ($objectclass == 'CommandeFournisseur') {
365
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO));
366
+				}
367
+				if ($objectclass == 'FactureFournisseur') {
368
+				    $sendtobcc .= (empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) ? '' : (($sendtobcc?", ":"").$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO));
369
+				}
337 370
 
338 371
 				// $listofqualifiedobj is array with key = object id and value is instance of qualified objects, for the current thirdparty (but thirdparty property is not loaded yet)
339 372
 				$oneemailperrecipient=(GETPOST('oneemailperrecipient')=='on'?1:0);
@@ -345,8 +378,7 @@  discard block
 block discarded – undo
345 378
 					{
346 379
 						$looparray[$key]->thirdparty = $thirdparty;
347 380
 					}
348
-				}
349
-				else
381
+				} else
350 382
 				{
351 383
 					$objectforloop=new $objectclass($db);
352 384
 					$objectforloop->thirdparty = $thirdparty;
@@ -354,10 +386,12 @@  discard block
 block discarded – undo
354 386
 				}
355 387
 				//var_dump($looparray);exit;
356 388
 
357
-				foreach ($looparray as $objecttmp)		// $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
389
+				foreach ($looparray as $objecttmp) {
390
+				    // $objecttmp is a real object or an empty object if we choose to send one email per thirdparty instead of one per record
358 391
 				{
359 392
 					// Make substitution in email content
360 393
 					$substitutionarray=getCommonSubstitutionArray($langs, 0, null, $objecttmp);
394
+				}
361 395
 					$substitutionarray['__ID__']    = ($oneemailperrecipient ? join(', ',array_keys($listofqualifiedobj)) : $objecttmp->id);
362 396
 					$substitutionarray['__REF__']   = ($oneemailperrecipient ? join(', ',$listofqualifiedref) : $objecttmp->ref);
363 397
 					$substitutionarray['__EMAIL__'] = $thirdparty->email;
@@ -385,19 +419,36 @@  discard block
 block discarded – undo
385 419
 					if ($oneemailperrecipient)
386 420
 					{
387 421
 						$trackid='thi'.$thirdparty->id;
388
-						if ($objecttmp->element == 'expensereport') $trackid='use'.$thirdparty->id;
389
-						if ($objecttmp->element == 'holiday') $trackid='use'.$thirdparty->id;
390
-					}
391
-					else
422
+						if ($objecttmp->element == 'expensereport') {
423
+						    $trackid='use'.$thirdparty->id;
424
+						}
425
+						if ($objecttmp->element == 'holiday') {
426
+						    $trackid='use'.$thirdparty->id;
427
+						}
428
+					} else
392 429
 					{
393 430
 						$trackid=strtolower(get_class($objecttmp));
394
-						if (get_class($objecttmp)=='Contrat')  $trackid='con';
395
-						if (get_class($objecttmp)=='Propal')   $trackid='pro';
396
-						if (get_class($objecttmp)=='Commande') $trackid='ord';
397
-						if (get_class($objecttmp)=='Facture')  $trackid='inv';
398
-						if (get_class($objecttmp)=='Supplier_Proposal')   $trackid='spr';
399
-						if (get_class($objecttmp)=='CommandeFournisseur') $trackid='sor';
400
-						if (get_class($objecttmp)=='FactureFournisseur')  $trackid='sin';
431
+						if (get_class($objecttmp)=='Contrat') {
432
+						    $trackid='con';
433
+						}
434
+						if (get_class($objecttmp)=='Propal') {
435
+						    $trackid='pro';
436
+						}
437
+						if (get_class($objecttmp)=='Commande') {
438
+						    $trackid='ord';
439
+						}
440
+						if (get_class($objecttmp)=='Facture') {
441
+						    $trackid='inv';
442
+						}
443
+						if (get_class($objecttmp)=='Supplier_Proposal') {
444
+						    $trackid='spr';
445
+						}
446
+						if (get_class($objecttmp)=='CommandeFournisseur') {
447
+						    $trackid='sor';
448
+						}
449
+						if (get_class($objecttmp)=='FactureFournisseur') {
450
+						    $trackid='sin';
451
+						}
401 452
 
402 453
 						$trackid.=$objecttmp->id;
403 454
 					}
@@ -410,8 +461,7 @@  discard block
 block discarded – undo
410 461
 					if ($mailfile->error)
411 462
 					{
412 463
 						$resaction.='<div class="error">'.$mailfile->error.'</div>';
413
-					}
414
-					else
464
+					} else
415 465
 					{
416 466
 						$result=$mailfile->sendfile();
417 467
 						if ($result)
@@ -433,7 +483,9 @@  discard block
 block discarded – undo
433 483
 								$actionmsg=$langs->transnoentities('MailSentBy').' '.$from.' '.$langs->transnoentities('To').' '.$sendto;
434 484
 								if ($message)
435 485
 								{
436
-									if ($sendtocc) $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
486
+									if ($sendtocc) {
487
+									    $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc') . ": " . $sendtocc);
488
+									}
437 489
 									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic') . ": " . $subject);
438 490
 									$actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody') . ":");
439 491
 									$actionmsg = dol_concatdesc($actionmsg, $message);
@@ -448,14 +500,30 @@  discard block
 block discarded – undo
448 500
 								$objectobj->elementtype	= $objectobj->element;
449 501
 
450 502
 								$triggername = strtoupper(get_class($objectobj)) .'_SENTBYMAIL';
451
-								if ($triggername == 'SOCIETE_SENTBYMAIL')    $triggername = 'COMPANY_SENTBYEMAIL';
452
-								if ($triggername == 'CONTRAT_SENTBYMAIL')    $triggername = 'CONTRACT_SENTBYEMAIL';
453
-								if ($triggername == 'COMMANDE_SENTBYMAIL')   $triggername = 'ORDER_SENTBYEMAIL';
454
-								if ($triggername == 'FACTURE_SENTBYMAIL')    $triggername = 'BILL_SENTBYMAIL';
455
-								if ($triggername == 'EXPEDITION_SENTBYMAIL') $triggername = 'SHIPPING_SENTBYEMAIL';
456
-								if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
457
-								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
458
-								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
503
+								if ($triggername == 'SOCIETE_SENTBYMAIL') {
504
+								    $triggername = 'COMPANY_SENTBYEMAIL';
505
+								}
506
+								if ($triggername == 'CONTRAT_SENTBYMAIL') {
507
+								    $triggername = 'CONTRACT_SENTBYEMAIL';
508
+								}
509
+								if ($triggername == 'COMMANDE_SENTBYMAIL') {
510
+								    $triggername = 'ORDER_SENTBYEMAIL';
511
+								}
512
+								if ($triggername == 'FACTURE_SENTBYMAIL') {
513
+								    $triggername = 'BILL_SENTBYMAIL';
514
+								}
515
+								if ($triggername == 'EXPEDITION_SENTBYMAIL') {
516
+								    $triggername = 'SHIPPING_SENTBYEMAIL';
517
+								}
518
+								if ($triggername == 'COMMANDEFOURNISSEUR_SENTBYMAIL') {
519
+								    $triggername = 'ORDER_SUPPLIER_SENTBYMAIL';
520
+								}
521
+								if ($triggername == 'FACTUREFOURNISSEUR_SENTBYMAIL') {
522
+								    $triggername = 'BILL_SUPPLIER_SENTBYEMAIL';
523
+								}
524
+								if ($triggername == 'SUPPLIERPROPOSAL_SENTBYMAIL') {
525
+								    $triggername = 'PROPOSAL_SUPPLIER_SENTBYEMAIL';
526
+								}
459 527
 
460 528
 								if (! empty($triggername))
461 529
 								{
@@ -475,16 +543,14 @@  discard block
 block discarded – undo
475 543
 
476 544
 								$nbsent++;
477 545
 							}
478
-						}
479
-						else
546
+						} else
480 547
 						{
481 548
 							$langs->load("other");
482 549
 							if ($mailfile->error)
483 550
 							{
484 551
 								$resaction.=$langs->trans('ErrorFailedToSendMail',$from,$sendto);
485 552
 								$resaction.='<br><div class="error">'.$mailfile->error.'</div>';
486
-							}
487
-							else
553
+							} else
488 554
 							{
489 555
 								$resaction.='<div class="warning">No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS</div>';
490 556
 							}
@@ -506,8 +572,7 @@  discard block
 block discarded – undo
506 572
 			//setEventMessages($langs->trans("EMailSentToNRecipients", $nbsent.'/'.count($toselect)), null, 'mesgs');
507 573
 			setEventMessages($langs->trans("EMailSentForNElements", $nbsent.'/'.count($toselect)), null, 'mesgs');
508 574
 			setEventMessages($resaction, null, 'mesgs');
509
-		}
510
-		else
575
+		} else
511 576
 		{
512 577
 			//setEventMessages($langs->trans("EMailSentToNRecipients", 0), null, 'warnings');  // May be object has no generated PDF file
513 578
 			setEventMessages($resaction, null, 'warnings');
@@ -534,10 +599,15 @@  discard block
 block discarded – undo
534 599
 	foreach($orders as $id_order)
535 600
 	{
536 601
 		$cmd = new Commande($db);
537
-		if ($cmd->fetch($id_order) <= 0) continue;
602
+		if ($cmd->fetch($id_order) <= 0) {
603
+		    continue;
604
+		}
538 605
 
539 606
 		$objecttmp = new Facture($db);
540
-		if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) $objecttmp = $TFactThird[$cmd->socid]; // If option "one bill per third" is set, we use already created order.
607
+		if (!empty($createbills_onebythird) && !empty($TFactThird[$cmd->socid])) {
608
+		    $objecttmp = $TFactThird[$cmd->socid];
609
+		}
610
+		// If option "one bill per third" is set, we use already created order.
541 611
 		else {
542 612
 
543 613
 			$objecttmp->socid = $cmd->socid;
@@ -558,7 +628,9 @@  discard block
 block discarded – undo
558 628
 
559 629
 			$res = $objecttmp->create($user);
560 630
 
561
-			if($res > 0) $nb_bills_created++;
631
+			if($res > 0) {
632
+			    $nb_bills_created++;
633
+			}
562 634
 		}
563 635
 
564 636
 		if ($objecttmp->id > 0)
@@ -611,28 +683,38 @@  discard block
 block discarded – undo
611 683
 						{
612 684
 							$result=$objecttmp->insert_discount($discountid);
613 685
 							//$result=$discount->link_to_invoice($lineid,$id);
614
-						}
615
-						else
686
+						} else
616 687
 						{
617 688
 							setEventMessages($discount->error, $discount->errors, 'errors');
618 689
 							$error++;
619 690
 							break;
620 691
 						}
621
-					}
622
-					else
692
+					} else
623 693
 					{
624 694
 						// Positive line
625 695
 						$product_type=($lines[$i]->product_type?$lines[$i]->product_type:0);
626 696
 						// Date start
627 697
 						$date_start=false;
628
-						if ($lines[$i]->date_debut_prevue) $date_start=$lines[$i]->date_debut_prevue;
629
-						if ($lines[$i]->date_debut_reel) $date_start=$lines[$i]->date_debut_reel;
630
-						if ($lines[$i]->date_start) $date_start=$lines[$i]->date_start;
698
+						if ($lines[$i]->date_debut_prevue) {
699
+						    $date_start=$lines[$i]->date_debut_prevue;
700
+						}
701
+						if ($lines[$i]->date_debut_reel) {
702
+						    $date_start=$lines[$i]->date_debut_reel;
703
+						}
704
+						if ($lines[$i]->date_start) {
705
+						    $date_start=$lines[$i]->date_start;
706
+						}
631 707
 						//Date end
632 708
 						$date_end=false;
633
-						if ($lines[$i]->date_fin_prevue) $date_end=$lines[$i]->date_fin_prevue;
634
-						if ($lines[$i]->date_fin_reel) $date_end=$lines[$i]->date_fin_reel;
635
-						if ($lines[$i]->date_end) $date_end=$lines[$i]->date_end;
709
+						if ($lines[$i]->date_fin_prevue) {
710
+						    $date_end=$lines[$i]->date_fin_prevue;
711
+						}
712
+						if ($lines[$i]->date_fin_reel) {
713
+						    $date_end=$lines[$i]->date_fin_reel;
714
+						}
715
+						if ($lines[$i]->date_end) {
716
+						    $date_end=$lines[$i]->date_end;
717
+						}
636 718
 						// Reset fk_parent_line for no child products and special product
637 719
 						if (($lines[$i]->product_type != 9 && empty($lines[$i]->fk_parent_line)) || $lines[$i]->product_type == 9)
638 720
 						{
@@ -675,8 +757,7 @@  discard block
 block discarded – undo
675 757
 						if ($result > 0)
676 758
 						{
677 759
 							$lineid=$result;
678
-						}
679
-						else
760
+						} else
680 761
 						{
681 762
 							$lineid=0;
682 763
 							$error++;
@@ -694,8 +775,11 @@  discard block
 block discarded – undo
694 775
 
695 776
 		//$cmd->classifyBilled($user);        // Disabled. This behavior must be set or not using the workflow module.
696 777
 
697
-		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) $TFactThird[$cmd->socid] = $objecttmp;
698
-		else $TFact[$objecttmp->id] = $objecttmp;
778
+		if(!empty($createbills_onebythird) && empty($TFactThird[$cmd->socid])) {
779
+		    $TFactThird[$cmd->socid] = $objecttmp;
780
+		} else {
781
+		    $TFact[$objecttmp->id] = $objecttmp;
782
+		}
699 783
 	}
700 784
 
701 785
 	// Build doc with all invoices
@@ -734,34 +818,79 @@  discard block
 block discarded – undo
734 818
 
735 819
 		// Make a redirect to avoid to bill twice if we make a refresh or back
736 820
 		$param='';
737
-		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) $param.='&contextpage='.urlencode($contextpage);
738
-		if ($limit > 0 && $limit != $conf->liste_limit) $param.='&limit='.urlencode($limit);
739
-		if ($sall)					$param.='&sall='.urlencode($sall);
740
-		if ($socid > 0)             $param.='&socid='.urlencode($socid);
741
-		if ($viewstatut != '')      $param.='&viewstatut='.urlencode($viewstatut);
742
-		if ($search_orderday)      		$param.='&search_orderday='.urlencode($search_orderday);
743
-		if ($search_ordermonth)      		$param.='&search_ordermonth='.urlencode($search_ordermonth);
744
-		if ($search_orderyear)       		$param.='&search_orderyear='.urlencode($search_orderyear);
745
-		if ($search_deliveryday)   		$param.='&search_deliveryday='.urlencode($search_deliveryday);
746
-		if ($search_deliverymonth)   		$param.='&search_deliverymonth='.urlencode($search_deliverymonth);
747
-		if ($search_deliveryyear)    		$param.='&search_deliveryyear='.urlencode($search_deliveryyear);
748
-		if ($search_ref)      		$param.='&search_ref='.urlencode($search_ref);
749
-		if ($search_company)  		$param.='&search_company='.urlencode($search_company);
750
-		if ($search_ref_customer)	$param.='&search_ref_customer='.urlencode($search_ref_customer);
751
-		if ($search_user > 0) 		$param.='&search_user='.urlencode($search_user);
752
-		if ($search_sale > 0) 		$param.='&search_sale='.urlencode($search_sale);
753
-		if ($search_total_ht != '') $param.='&search_total_ht='.urlencode($search_total_ht);
754
-		if ($search_total_vat != '') $param.='&search_total_vat='.urlencode($search_total_vat);
755
-		if ($search_total_ttc != '') $param.='&search_total_ttc='.urlencode($search_total_ttc);
756
-		if ($search_project_ref >= 0)  	$param.="&search_project_ref=".urlencode($search_project_ref);
757
-		if ($show_files)            $param.='&show_files=' .urlencode($show_files);
758
-		if ($optioncss != '')       $param.='&optioncss='.urlencode($optioncss);
759
-		if ($billed != '')			$param.='&billed='.urlencode($billed);
821
+		if (! empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) {
822
+		    $param.='&contextpage='.urlencode($contextpage);
823
+		}
824
+		if ($limit > 0 && $limit != $conf->liste_limit) {
825
+		    $param.='&limit='.urlencode($limit);
826
+		}
827
+		if ($sall) {
828
+		    $param.='&sall='.urlencode($sall);
829
+		}
830
+		if ($socid > 0) {
831
+		    $param.='&socid='.urlencode($socid);
832
+		}
833
+		if ($viewstatut != '') {
834
+		    $param.='&viewstatut='.urlencode($viewstatut);
835
+		}
836
+		if ($search_orderday) {
837
+		    $param.='&search_orderday='.urlencode($search_orderday);
838
+		}
839
+		if ($search_ordermonth) {
840
+		    $param.='&search_ordermonth='.urlencode($search_ordermonth);
841
+		}
842
+		if ($search_orderyear) {
843
+		    $param.='&search_orderyear='.urlencode($search_orderyear);
844
+		}
845
+		if ($search_deliveryday) {
846
+		    $param.='&search_deliveryday='.urlencode($search_deliveryday);
847
+		}
848
+		if ($search_deliverymonth) {
849
+		    $param.='&search_deliverymonth='.urlencode($search_deliverymonth);
850
+		}
851
+		if ($search_deliveryyear) {
852
+		    $param.='&search_deliveryyear='.urlencode($search_deliveryyear);
853
+		}
854
+		if ($search_ref) {
855
+		    $param.='&search_ref='.urlencode($search_ref);
856
+		}
857
+		if ($search_company) {
858
+		    $param.='&search_company='.urlencode($search_company);
859
+		}
860
+		if ($search_ref_customer) {
861
+		    $param.='&search_ref_customer='.urlencode($search_ref_customer);
862
+		}
863
+		if ($search_user > 0) {
864
+		    $param.='&search_user='.urlencode($search_user);
865
+		}
866
+		if ($search_sale > 0) {
867
+		    $param.='&search_sale='.urlencode($search_sale);
868
+		}
869
+		if ($search_total_ht != '') {
870
+		    $param.='&search_total_ht='.urlencode($search_total_ht);
871
+		}
872
+		if ($search_total_vat != '') {
873
+		    $param.='&search_total_vat='.urlencode($search_total_vat);
874
+		}
875
+		if ($search_total_ttc != '') {
876
+		    $param.='&search_total_ttc='.urlencode($search_total_ttc);
877
+		}
878
+		if ($search_project_ref >= 0) {
879
+		    $param.="&search_project_ref=".urlencode($search_project_ref);
880
+		}
881
+		if ($show_files) {
882
+		    $param.='&show_files=' .urlencode($show_files);
883
+		}
884
+		if ($optioncss != '') {
885
+		    $param.='&optioncss='.urlencode($optioncss);
886
+		}
887
+		if ($billed != '') {
888
+		    $param.='&billed='.urlencode($billed);
889
+		}
760 890
 
761 891
 		header("Location: ".$_SERVER['PHP_SELF'].'?'.$param);
762 892
 		exit;
763
-	}
764
-	else
893
+	} else
765 894
 	{
766 895
 		$db->rollback();
767 896
 		$action='create';
@@ -785,8 +914,9 @@  discard block
 block discarded – undo
785 914
 	{
786 915
 
787 916
 		$cmd = new Commande($db);
788
-		if ($cmd->fetch($id_order) <= 0)
789
-			continue;
917
+		if ($cmd->fetch($id_order) <= 0) {
918
+					continue;
919
+		}
790 920
 
791 921
 		if ($cmd->statut != Commande::STATUS_VALIDATED)
792 922
 		{
@@ -794,28 +924,28 @@  discard block
 block discarded – undo
794 924
 			setEventMessages($langs->trans("ErrorObjectMustHaveStatusValidToBeCanceled", $cmd->ref), null, 'errors');
795 925
 			$error++;
796 926
 			break;
927
+		} else {
928
+					$result = $cmd->cancel();
797 929
 		}
798
-		else
799
-			$result = $cmd->cancel();
800 930
 
801 931
 		if ($result < 0)
802 932
 		{
803 933
 			setEventMessages($cmd->error, $cmd->errors, 'errors');
804 934
 			$error++;
805 935
 			break;
936
+		} else {
937
+					$nbok++;
806 938
 		}
807
-		else
808
-			$nbok++;
809 939
 	}
810 940
 	if (!$error)
811 941
 	{
812
-		if ($nbok > 1)
813
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
814
-		else
815
-			setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
942
+		if ($nbok > 1) {
943
+					setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
944
+		} else {
945
+					setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
946
+		}
816 947
 		$db->commit();
817
-	}
818
-	else
948
+	} else
819 949
 	{
820 950
 		$db->rollback();
821 951
 	}
@@ -852,8 +982,13 @@  discard block
 block discarded – undo
852 982
 	}
853 983
 
854 984
 	$arrayofinclusion=array();
855
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
856
-	foreach($listofobjectref as $tmppdf) $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';	// To include PDF generated from ODX files
985
+	foreach($listofobjectref as $tmppdf) {
986
+	    $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'\.pdf$';
987
+	}
988
+	foreach($listofobjectref as $tmppdf) {
989
+	    $arrayofinclusion[]='^'.preg_quote(dol_sanitizeFileName($tmppdf),'/').'_[a-zA-Z0-9-_]+\.pdf$';
990
+	}
991
+	// To include PDF generated from ODX files
857 992
 	$listoffiles = dol_dir_list($uploaddir,'all',1,implode('|',$arrayofinclusion),'\.meta$|\.png','date',SORT_DESC,0,true);
858 993
 
859 994
 	// build list of files with full path
@@ -874,8 +1009,12 @@  discard block
 block discarded – undo
874 1009
 	// Define output language (Here it is not used because we do only merging existing PDF)
875 1010
 	$outputlangs = $langs;
876 1011
 	$newlang='';
877
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
878
-	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang=$objecttmp->thirdparty->default_lang;
1012
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
1013
+	    $newlang=GETPOST('lang_id','aZ09');
1014
+	}
1015
+	if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
1016
+	    $newlang=$objecttmp->thirdparty->default_lang;
1017
+	}
879 1018
 	if (! empty($newlang))
880 1019
 	{
881 1020
 		$outputlangs = new Translate("",$conf);
@@ -894,11 +1033,18 @@  discard block
 block discarded – undo
894 1033
 		// Save merged file
895 1034
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
896 1035
 		{
897
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
898
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1036
+			if ($option=='late') {
1037
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
1038
+			} else {
1039
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1040
+			}
1041
+		}
1042
+		if ($year) {
1043
+		    $filename.='_'.$year;
1044
+		}
1045
+		if ($month) {
1046
+		    $filename.='_'.$month;
899 1047
 		}
900
-		if ($year) $filename.='_'.$year;
901
-		if ($month) $filename.='_'.$month;
902 1048
 
903 1049
 		if (count($files)>0)
904 1050
 		{
@@ -913,18 +1059,17 @@  discard block
 block discarded – undo
913 1059
 			$cmd = 'pdftk '.escapeshellarg($input_files).' cat output '.escapeshellarg($file);
914 1060
 			exec($cmd);
915 1061
 
916
-			if (! empty($conf->global->MAIN_UMASK))
917
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
1062
+			if (! empty($conf->global->MAIN_UMASK)) {
1063
+							@chmod($file, octdec($conf->global->MAIN_UMASK));
1064
+			}
918 1065
 
919 1066
 			$langs->load("exports");
920 1067
 			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
921
-		}
922
-		else
1068
+		} else
923 1069
 		{
924 1070
 			setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
925 1071
 		}
926
-	}
927
-	else {
1072
+	} else {
928 1073
 		// Create empty PDF
929 1074
 		$formatarray=pdf_getFormat();
930 1075
 		$page_largeur = $formatarray['width'];
@@ -940,7 +1085,9 @@  discard block
 block discarded – undo
940 1085
 		}
941 1086
 		$pdf->SetFont(pdf_getPDFFont($outputlangs));
942 1087
 
943
-		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
1088
+		if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
1089
+		    $pdf->SetCompression(false);
1090
+		}
944 1091
 
945 1092
 		// Add all others
946 1093
 		foreach($files as $file)
@@ -966,23 +1113,30 @@  discard block
 block discarded – undo
966 1113
 		// Save merged file
967 1114
 		if (in_array($objecttmp->element, array('facture', 'facture_fournisseur')) && $search_status == Facture::STATUS_VALIDATED)
968 1115
 		{
969
-			if ($option=='late') $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
970
-			else $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1116
+			if ($option=='late') {
1117
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid"))).'_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Late")));
1118
+			} else {
1119
+			    $filename.='_'.strtolower(dol_sanitizeFileName($langs->transnoentities("Unpaid")));
1120
+			}
1121
+		}
1122
+		if ($year) {
1123
+		    $filename.='_'.$year;
1124
+		}
1125
+		if ($month) {
1126
+		    $filename.='_'.$month;
971 1127
 		}
972
-		if ($year) $filename.='_'.$year;
973
-		if ($month) $filename.='_'.$month;
974 1128
 		if ($pagecount)
975 1129
 		{
976 1130
 			$now=dol_now();
977 1131
 			$file=$diroutputmassaction.'/'.$filename.'_'.dol_print_date($now,'dayhourlog').'.pdf';
978 1132
 			$pdf->Output($file,'F');
979
-			if (! empty($conf->global->MAIN_UMASK))
980
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
1133
+			if (! empty($conf->global->MAIN_UMASK)) {
1134
+							@chmod($file, octdec($conf->global->MAIN_UMASK));
1135
+			}
981 1136
 
982 1137
 			$langs->load("exports");
983 1138
 			setEventMessages($langs->trans('FileSuccessfullyBuilt',$filename.'_'.dol_print_date($now,'dayhourlog')), null, 'mesgs');
984
-		}
985
-		else
1139
+		} else
986 1140
 		{
987 1141
 		setEventMessages($langs->trans('NoPDFAvailableForDocGenAmongChecked'), null, 'errors');
988 1142
 		}
@@ -998,8 +1152,11 @@  discard block
 block discarded – undo
998 1152
 	$upload_dir = $diroutputmassaction;
999 1153
 	$file = $upload_dir . '/' . GETPOST('file');
1000 1154
 	$ret=dol_delete_file($file);
1001
-	if ($ret) setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1002
-	else setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1155
+	if ($ret) {
1156
+	    setEventMessages($langs->trans("FileWasRemoved", GETPOST('file')), null, 'mesgs');
1157
+	} else {
1158
+	    setEventMessages($langs->trans("ErrorFailToDeleteFile", GETPOST('file')), null, 'errors');
1159
+	}
1003 1160
 	$action='';
1004 1161
 }
1005 1162
 
@@ -1039,16 +1196,15 @@  discard block
 block discarded – undo
1039 1196
 					setEventMessages($langs->trans("ErrorObjectMustHaveStatusDraftToBeValidated", $objecttmp->ref), null, 'errors');
1040 1197
 					$error++;
1041 1198
 					break;
1042
-				}
1043
-				elseif ($result < 0)
1199
+				} elseif ($result < 0)
1044 1200
 				{
1045 1201
 					setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1046 1202
 					$error++;
1047 1203
 					break;
1204
+				} else {
1205
+				    $nbok++;
1048 1206
 				}
1049
-				else $nbok++;
1050
-			}
1051
-			else
1207
+			} else
1052 1208
 			{
1053 1209
 				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1054 1210
 				$error++;
@@ -1058,11 +1214,13 @@  discard block
 block discarded – undo
1058 1214
 
1059 1215
 		if (! $error)
1060 1216
 		{
1061
-			if ($nbok > 1) setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1062
-			else setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1217
+			if ($nbok > 1) {
1218
+			    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1219
+			} else {
1220
+			    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1221
+			}
1063 1222
 			$db->commit();
1064
-		}
1065
-		else
1223
+		} else
1066 1224
 		{
1067 1225
 			$db->rollback();
1068 1226
 		}
@@ -1083,10 +1241,10 @@  discard block
 block discarded – undo
1083 1241
                 setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1084 1242
                 $error++;
1085 1243
                 break;
1086
-            } else
1087
-                $nbok++;
1088
-        }
1089
-        else {
1244
+            } else {
1245
+                            $nbok++;
1246
+            }
1247
+        } else {
1090 1248
             setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1091 1249
             $error++;
1092 1250
             break;
@@ -1094,13 +1252,13 @@  discard block
 block discarded – undo
1094 1252
     }
1095 1253
 
1096 1254
     if (!$error) {
1097
-        if ($nbok > 1)
1098
-            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1099
-        else
1100
-            setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1255
+        if ($nbok > 1) {
1256
+                    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1257
+        } else {
1258
+                    setEventMessages($langs->trans("RecordsModified", $nbok), null, 'mesgs');
1259
+        }
1101 1260
         $db->commit();
1102
-    }
1103
-    else {
1261
+    } else {
1104 1262
         $db->rollback();
1105 1263
     }
1106 1264
 }
@@ -1137,18 +1295,21 @@  discard block
 block discarded – undo
1137 1295
 				}
1138 1296
 			}
1139 1297
 
1140
-			if (in_array($objecttmp->element, array('societe', 'member'))) $result = $objecttmp->delete($objecttmp->id, $user, 1);
1141
-			else $result = $objecttmp->delete($user);
1298
+			if (in_array($objecttmp->element, array('societe', 'member'))) {
1299
+			    $result = $objecttmp->delete($objecttmp->id, $user, 1);
1300
+			} else {
1301
+			    $result = $objecttmp->delete($user);
1302
+			}
1142 1303
 
1143 1304
 			if ($result <= 0)
1144 1305
 			{
1145 1306
 			    setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1146 1307
 			    $error++;
1147 1308
 			    break;
1309
+			} else {
1310
+			    $nbok++;
1148 1311
 			}
1149
-			else $nbok++;
1150
-		}
1151
-		else
1312
+		} else
1152 1313
 		{
1153 1314
 			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1154 1315
 			$error++;
@@ -1158,11 +1319,13 @@  discard block
 block discarded – undo
1158 1319
 
1159 1320
 	if (! $error)
1160 1321
 	{
1161
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1162
-		else setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1322
+		if ($nbok > 1) {
1323
+		    setEventMessages($langs->trans("RecordsDeleted", $nbok), null, 'mesgs');
1324
+		} else {
1325
+		    setEventMessages($langs->trans("RecordDeleted", $nbok), null, 'mesgs');
1326
+		}
1163 1327
 		$db->commit();
1164
-	}
1165
-	else
1328
+	} else
1166 1329
 	{
1167 1330
 		$db->rollback();
1168 1331
 	}
@@ -1185,9 +1348,17 @@  discard block
 block discarded – undo
1185 1348
 			$outputlangs = $langs;
1186 1349
 			$newlang='';
1187 1350
 	
1188
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) $newlang=GETPOST('lang_id','aZ09');
1189
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) $newlang=$objecttmp->thirdparty->default_lang;  // for proposal, order, invoice, ...
1190
-			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) $newlang=$objecttmp->default_lang;                  // for thirdparty
1351
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && GETPOST('lang_id','aZ09')) {
1352
+			    $newlang=GETPOST('lang_id','aZ09');
1353
+			}
1354
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->thirdparty->default_lang)) {
1355
+			    $newlang=$objecttmp->thirdparty->default_lang;
1356
+			}
1357
+			// for proposal, order, invoice, ...
1358
+			if ($conf->global->MAIN_MULTILANGS && empty($newlang) && isset($objecttmp->default_lang)) {
1359
+			    $newlang=$objecttmp->default_lang;
1360
+			}
1361
+			// for thirdparty
1191 1362
 			if (! empty($newlang))
1192 1363
 			{
1193 1364
 				$outputlangs = new Translate("",$conf);
@@ -1195,10 +1366,18 @@  discard block
 block discarded – undo
1195 1366
 			}
1196 1367
 	
1197 1368
 			// To be sure vars is defined
1198
-			if (empty($hidedetails)) $hidedetails=0;
1199
-			if (empty($hidedesc)) $hidedesc=0;
1200
-			if (empty($hideref)) $hideref=0;
1201
-			if (empty($moreparams)) $moreparams=null;
1369
+			if (empty($hidedetails)) {
1370
+			    $hidedetails=0;
1371
+			}
1372
+			if (empty($hidedesc)) {
1373
+			    $hidedesc=0;
1374
+			}
1375
+			if (empty($hideref)) {
1376
+			    $hideref=0;
1377
+			}
1378
+			if (empty($moreparams)) {
1379
+			    $moreparams=null;
1380
+			}
1202 1381
 			
1203 1382
 			$result= $objecttmp->generateDocument($objecttmp->modelpdf, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1204 1383
 
@@ -1207,10 +1386,10 @@  discard block
 block discarded – undo
1207 1386
 				setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1208 1387
 				$error++;
1209 1388
 				break;
1389
+			} else {
1390
+			    $nbok++;
1210 1391
 			}
1211
-			else $nbok++;
1212
-		}
1213
-		else
1392
+		} else
1214 1393
 		{
1215 1394
 			setEventMessages($objecttmp->error, $objecttmp->errors, 'errors');
1216 1395
 			$error++;
@@ -1220,11 +1399,13 @@  discard block
 block discarded – undo
1220 1399
 
1221 1400
 	if (! $error)
1222 1401
 	{
1223
-		if ($nbok > 1) setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1224
-		else setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1402
+		if ($nbok > 1) {
1403
+		    setEventMessages($langs->trans("RecordsGenerated", $nbok), null, 'mesgs');
1404
+		} else {
1405
+		    setEventMessages($langs->trans("RecordGenerated", $nbok), null, 'mesgs');
1406
+		}
1225 1407
 		$db->commit();
1226
-	}
1227
-	else
1408
+	} else
1228 1409
 	{
1229 1410
 		$db->rollback();
1230 1411
 	}
@@ -1234,7 +1415,9 @@  discard block
 block discarded – undo
1234 1415
 $parameters['uploaddir']=$uploaddir;
1235 1416
 
1236 1417
 $reshook=$hookmanager->executeHooks('doMassActions',$parameters, $object, $action);    // Note that $action and $object may have been modified by some hooks
1237
-if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1418
+if ($reshook < 0) {
1419
+    setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
1420
+}
1238 1421
 
1239 1422
 
1240 1423
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/js/lib_notification.js.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
 
29 29
 require_once '../../main.inc.php';
30 30
 
31
-if (! ($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/' || $_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root . '/index.php'
31
+if (!($_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root.'/' || $_SERVER['HTTP_REFERER'] === $dolibarr_main_url_root.'/index.php'
32 32
     || preg_match('/getmenu_div\.php/', $_SERVER['HTTP_REFERER'])))
33 33
 {
34 34
     global $langs, $conf;
@@ -44,17 +44,17 @@  discard block
 block discarded – undo
44 44
     header('Cache-Control: no-cache');
45 45
     session_set_cookie_params(0, '/', null, false, true);   // Add tag httponly on session cookie
46 46
     session_start();*/
47
-    if (! isset($_SESSION['auto_check_events_not_before']))
47
+    if (!isset($_SESSION['auto_check_events_not_before']))
48 48
     {
49 49
         print 'console.log("_SESSION[auto_check_events_not_before] is not set");'."\n";
50 50
         // Round to eliminate the seconds
51 51
         $_SESSION['auto_check_events_not_before'] = $nowtime;
52 52
     }
53
-    print 'var nowtime = ' . $nowtime . ';' . "\n";
54
-    print 'var login = \'' . $_SESSION['dol_login'] . '\';' . "\n";
55
-    print 'var auto_check_events_not_before = '.$_SESSION['auto_check_events_not_before']. ';'."\n";
53
+    print 'var nowtime = '.$nowtime.';'."\n";
54
+    print 'var login = \''.$_SESSION['dol_login'].'\';'."\n";
55
+    print 'var auto_check_events_not_before = '.$_SESSION['auto_check_events_not_before'].';'."\n";
56 56
     print 'var time_js_next_test = Math.max(nowtime, auto_check_events_not_before);'."\n";
57
-    print 'var time_auto_update = '.$conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY.';'."\n";   // Always defined
57
+    print 'var time_auto_update = '.$conf->global->MAIN_BROWSER_NOTIFICATION_FREQUENCY.';'."\n"; // Always defined
58 58
     ?>
59 59
 
60 60
 	/* Check if permission ok */
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
                     if (arr.length > 0) {
91 91
                     	var audio = null;
92 92
                         <?php
93
-                        if (! empty($conf->global->AGENDA_REMINDER_BROWSER_SOUND)) {
93
+                        if (!empty($conf->global->AGENDA_REMINDER_BROWSER_SOUND)) {
94 94
                             print 'audio = new Audio(\''.DOL_URL_ROOT.'/theme/common/sound/notification_agenda.wav'.'\');';
95 95
                         }
96 96
                         ?>
Please login to merge, or discard this patch.
Braces   +21 added lines, -7 removed lines patch added patch discarded remove patch
@@ -18,13 +18,27 @@
 block discarded – undo
18 18
  * Library javascript to enable Browser notifications
19 19
  */
20 20
 
21
-if (!defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1');
22
-if (!defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1');
23
-if (!defined('NOCSRFCHECK')) define('NOCSRFCHECK', 1);
24
-if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', 1);
25
-if (!defined('NOLOGIN')) define('NOLOGIN', 1);
26
-if (!defined('NOREQUIREMENU')) define('NOREQUIREMENU', 1);
27
-if (!defined('NOREQUIREHTML')) define('NOREQUIREHTML', 1);
21
+if (!defined('NOREQUIREUSER')) {
22
+    define('NOREQUIREUSER', '1');
23
+}
24
+if (!defined('NOREQUIRESOC')) {
25
+    define('NOREQUIRESOC', '1');
26
+}
27
+if (!defined('NOCSRFCHECK')) {
28
+    define('NOCSRFCHECK', 1);
29
+}
30
+if (!defined('NOTOKENRENEWAL')) {
31
+    define('NOTOKENRENEWAL', 1);
32
+}
33
+if (!defined('NOLOGIN')) {
34
+    define('NOLOGIN', 1);
35
+}
36
+if (!defined('NOREQUIREMENU')) {
37
+    define('NOREQUIREMENU', 1);
38
+}
39
+if (!defined('NOREQUIREHTML')) {
40
+    define('NOREQUIREHTML', 1);
41
+}
28 42
 
29 43
 require_once '../../main.inc.php';
30 44
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/js/lib_gravatar.js.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -24,14 +24,14 @@
 block discarded – undo
24 24
 
25 25
 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');	// Not disabled cause need to load personalized language
26 26
 //if (! defined('NOREQUIREDB'))   define('NOREQUIREDB','1');
27
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
27
+if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', '1');
28 28
 //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');	// Not disabled cause need to do translations
29
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
30
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
31
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
32
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
33
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
34
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
29
+if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', 1);
30
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
31
+if (!defined('NOLOGIN'))         define('NOLOGIN', 1);
32
+if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
33
+if (!defined('NOREQUIREHTML'))   define('NOREQUIREHTML', 1);
34
+if (!defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX', '1');
35 35
 
36 36
 session_cache_limiter('public');
37 37
 
Please login to merge, or discard this patch.
Braces   +26 added lines, -9 removed lines patch added patch discarded remove patch
@@ -24,14 +24,28 @@  discard block
 block discarded – undo
24 24
 
25 25
 //if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER','1');	// Not disabled cause need to load personalized language
26 26
 //if (! defined('NOREQUIREDB'))   define('NOREQUIREDB','1');
27
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
27
+if (! defined('NOREQUIRESOC')) {
28
+    define('NOREQUIRESOC','1');
29
+}
28 30
 //if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN','1');	// Not disabled cause need to do translations
29
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
30
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
31
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
32
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
33
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
34
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
31
+if (! defined('NOCSRFCHECK')) {
32
+    define('NOCSRFCHECK',1);
33
+}
34
+if (! defined('NOTOKENRENEWAL')) {
35
+    define('NOTOKENRENEWAL',1);
36
+}
37
+if (! defined('NOLOGIN')) {
38
+    define('NOLOGIN',1);
39
+}
40
+if (! defined('NOREQUIREMENU')) {
41
+    define('NOREQUIREMENU',1);
42
+}
43
+if (! defined('NOREQUIREHTML')) {
44
+    define('NOREQUIREHTML',1);
45
+}
46
+if (! defined('NOREQUIREAJAX')) {
47
+    define('NOREQUIREAJAX','1');
48
+}
35 49
 
36 50
 session_cache_limiter('public');
37 51
 
@@ -40,8 +54,11 @@  discard block
 block discarded – undo
40 54
 // Define javascript type
41 55
 top_httphead('text/javascript; charset=UTF-8');
42 56
 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
43
-if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate');
44
-else header('Cache-Control: no-cache');
57
+if (empty($dolibarr_nocache)) {
58
+    header('Cache-Control: max-age=10800, public, must-revalidate');
59
+} else {
60
+    header('Cache-Control: no-cache');
61
+}
45 62
 
46 63
 ?>
47 64
 
Please login to merge, or discard this patch.
dolibarr/htdocs/core/js/timepicker.js.php 2 patches
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -21,13 +21,13 @@  discard block
 block discarded – undo
21 21
  * \brief      File that include javascript functions for timepicker
22 22
  */
23 23
 
24
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
25
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
26
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
27
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
28
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
29
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
30
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
24
+if (!defined('NOREQUIRESOC'))    define('NOREQUIRESOC', '1');
25
+if (!defined('NOCSRFCHECK'))     define('NOCSRFCHECK', 1);
26
+if (!defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL', 1);
27
+if (!defined('NOLOGIN'))         define('NOLOGIN', 1);
28
+if (!defined('NOREQUIREMENU'))   define('NOREQUIREMENU', 1);
29
+if (!defined('NOREQUIREHTML'))   define('NOREQUIREHTML', 1);
30
+if (!defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX', '1');
31 31
 
32 32
 session_cache_limiter('public');
33 33
 
@@ -55,7 +55,7 @@  discard block
 block discarded – undo
55 55
 		timeFormat: 'HH:mm',
56 56
 		amNames: ['AM', 'A'],
57 57
 		pmNames: ['PM', 'P'],
58
-		isRTL: <?php echo ($langs->trans("DIRECTION")=='rtl'?'true':'false'); ?>
58
+		isRTL: <?php echo ($langs->trans("DIRECTION") == 'rtl' ? 'true' : 'false'); ?>
59 59
 	};
60 60
 	$.timepicker.setDefaults($.timepicker.regional['<?php echo $langs->defaultlang ?>']);
61 61
 });
Please login to merge, or discard this patch.
Braces   +29 added lines, -10 removed lines patch added patch discarded remove patch
@@ -21,13 +21,27 @@  discard block
 block discarded – undo
21 21
  * \brief      File that include javascript functions for timepicker
22 22
  */
23 23
 
24
-if (! defined('NOREQUIRESOC'))    define('NOREQUIRESOC','1');
25
-if (! defined('NOCSRFCHECK'))     define('NOCSRFCHECK',1);
26
-if (! defined('NOTOKENRENEWAL'))  define('NOTOKENRENEWAL',1);
27
-if (! defined('NOLOGIN'))         define('NOLOGIN',1);
28
-if (! defined('NOREQUIREMENU'))   define('NOREQUIREMENU',1);
29
-if (! defined('NOREQUIREHTML'))   define('NOREQUIREHTML',1);
30
-if (! defined('NOREQUIREAJAX'))   define('NOREQUIREAJAX','1');
24
+if (! defined('NOREQUIRESOC')) {
25
+    define('NOREQUIRESOC','1');
26
+}
27
+if (! defined('NOCSRFCHECK')) {
28
+    define('NOCSRFCHECK',1);
29
+}
30
+if (! defined('NOTOKENRENEWAL')) {
31
+    define('NOTOKENRENEWAL',1);
32
+}
33
+if (! defined('NOLOGIN')) {
34
+    define('NOLOGIN',1);
35
+}
36
+if (! defined('NOREQUIREMENU')) {
37
+    define('NOREQUIREMENU',1);
38
+}
39
+if (! defined('NOREQUIREHTML')) {
40
+    define('NOREQUIREHTML',1);
41
+}
42
+if (! defined('NOREQUIREAJAX')) {
43
+    define('NOREQUIREAJAX','1');
44
+}
31 45
 
32 46
 session_cache_limiter('public');
33 47
 
@@ -36,8 +50,11 @@  discard block
 block discarded – undo
36 50
 // Define javascript type
37 51
 top_httphead('text/javascript; charset=UTF-8');
38 52
 // Important: Following code is to avoid page request by browser and PHP CPU at each Dolibarr page access.
39
-if (empty($dolibarr_nocache)) header('Cache-Control: max-age=10800, public, must-revalidate');
40
-else header('Cache-Control: no-cache');
53
+if (empty($dolibarr_nocache)) {
54
+    header('Cache-Control: max-age=10800, public, must-revalidate');
55
+} else {
56
+    header('Cache-Control: no-cache');
57
+}
41 58
 ?>
42 59
 
43 60
 // For JQuery Timepicker
@@ -61,4 +78,6 @@  discard block
 block discarded – undo
61 78
 });
62 79
 
63 80
 <?php
64
-if (is_object($db)) $db->close();
81
+if (is_object($db)) {
82
+    $db->close();
83
+}
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_linkedfiles.inc.php 3 patches
Indentation   +145 added lines, -145 removed lines patch added patch discarded remove patch
@@ -29,41 +29,41 @@  discard block
 block discarded – undo
29 29
 // Submit file/link
30 30
 if (GETPOST('sendit','alpha') && ! empty($conf->global->MAIN_UPLOAD_DOC))
31 31
 {
32
-	if (! empty($_FILES))
33
-	{
34
-		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
-		else $userfiles=array($_FILES['userfile']['tmp_name']);
32
+    if (! empty($_FILES))
33
+    {
34
+        if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
+        else $userfiles=array($_FILES['userfile']['tmp_name']);
36 36
 
37
-		foreach($userfiles as $key => $userfile)
38
-		{
39
-			if (empty($_FILES['userfile']['tmp_name'][$key]))
40
-			{
41
-				$error++;
42
-				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
43
-					setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44
-				}
45
-				else {
46
-					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
47
-				}
48
-			}
49
-		}
37
+        foreach($userfiles as $key => $userfile)
38
+        {
39
+            if (empty($_FILES['userfile']['tmp_name'][$key]))
40
+            {
41
+                $error++;
42
+                if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
43
+                    setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44
+                }
45
+                else {
46
+                    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
47
+                }
48
+            }
49
+        }
50 50
 
51
-		if (! $error)
52
-		{
53
-			// Define if we have to generate thumbs or not
54
-			$generatethumbs = 1;
55
-			if (GETPOST('section_dir')) $generatethumbs=0;
51
+        if (! $error)
52
+        {
53
+            // Define if we have to generate thumbs or not
54
+            $generatethumbs = 1;
55
+            if (GETPOST('section_dir')) $generatethumbs=0;
56 56
 
57
-			if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58
-			{
59
-				$result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60
-			}
61
-			elseif (! empty($upload_dir))
62
-			{
63
-				$result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64
-			}
65
-		}
66
-	}
57
+            if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58
+            {
59
+                $result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60
+            }
61
+            elseif (! empty($upload_dir))
62
+            {
63
+                $result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64
+            }
65
+        }
66
+    }
67 67
 }
68 68
 elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
69 69
 {
@@ -84,39 +84,39 @@  discard block
 block discarded – undo
84 84
         $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);				// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
85 85
         if (GETPOST('section', 'alpha')) 	// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
86 86
         {
87
-        	$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
87
+            $file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
88 88
         }
89 89
         else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
90
-		{
91
-       		$urlfile=basename($urlfile);
92
-       		$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
-			if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
94
-		}
90
+        {
91
+                $urlfile=basename($urlfile);
92
+                $file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
+            if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
94
+        }
95 95
         $linkid = GETPOST('linkid', 'int');
96 96
 
97 97
         if ($urlfile)		// delete of a file
98 98
         {
99
-	        $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
100
-	        $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
99
+            $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
100
+            $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
101 101
 
102
-	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
102
+            $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
103 103
             if (! empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));     // Delete file using old path
104 104
 
105
-	        // Si elle existe, on efface la vignette
106
-	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
107
-	        {
108
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_small'.$regs[0]);
109
-		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
110
-		        {
111
-			        dol_delete_file($dirthumb.$photo_vignette);
112
-		        }
105
+            // Si elle existe, on efface la vignette
106
+            if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
107
+            {
108
+                $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_small'.$regs[0]);
109
+                if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
110
+                {
111
+                    dol_delete_file($dirthumb.$photo_vignette);
112
+                }
113 113
 
114
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_mini'.$regs[0]);
115
-		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
116
-		        {
117
-			        dol_delete_file($dirthumb.$photo_vignette);
118
-		        }
119
-	        }
114
+                $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_mini'.$regs[0]);
115
+                if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
116
+                {
117
+                    dol_delete_file($dirthumb.$photo_vignette);
118
+                }
119
+            }
120 120
 
121 121
             if ($ret) setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
122 122
             else setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
@@ -143,16 +143,16 @@  discard block
 block discarded – undo
143 143
 
144 144
         if (is_object($object) && $object->id > 0)
145 145
         {
146
-        	if ($backtopage)
147
-        	{
148
-        		header('Location: ' . $backtopage);
149
-        		exit;
150
-        	}
151
-        	else
152
-        	{
153
-        		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
154
-        		exit;
155
-        	}
146
+            if ($backtopage)
147
+            {
148
+                header('Location: ' . $backtopage);
149
+                exit;
150
+            }
151
+            else
152
+            {
153
+                header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
154
+                exit;
155
+            }
156 156
         }
157 157
 }
158 158
 elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
@@ -183,101 +183,101 @@  discard block
 block discarded – undo
183 183
 }
184 184
 elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
185 185
 {
186
-	// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187
-	if (! empty($upload_dir))
188
-	{
189
-		$filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0);	// Do not remove accents
190
-		$filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0);		// Do not remove accents
186
+    // For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187
+    if (! empty($upload_dir))
188
+    {
189
+        $filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0);	// Do not remove accents
190
+        $filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0);		// Do not remove accents
191 191
 
192 192
         if ($filenamefrom != $filenameto)
193 193
         {
194
-	        // Security:
195
-	        // Disallow file with some extensions. We rename them.
196
-	        // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
197
-	        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
198
-	        {
199
-	            $filenameto.= '.noexe';
200
-	        }
194
+            // Security:
195
+            // Disallow file with some extensions. We rename them.
196
+            // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
197
+            if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
198
+            {
199
+                $filenameto.= '.noexe';
200
+            }
201 201
 
202
-	        if ($filenamefrom && $filenameto)
203
-	        {
204
-	            $srcpath = $upload_dir.'/'.$filenamefrom;
205
-	            $destpath = $upload_dir.'/'.$filenameto;
202
+            if ($filenamefrom && $filenameto)
203
+            {
204
+                $srcpath = $upload_dir.'/'.$filenamefrom;
205
+                $destpath = $upload_dir.'/'.$filenameto;
206 206
 
207
-	            $reshook=$hookmanager->initHooks(array('actionlinkedfiles'));
208
-	            $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
-	            $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
207
+                $reshook=$hookmanager->initHooks(array('actionlinkedfiles'));
208
+                $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
+                $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
210 210
 
211
-	            if (empty($reshook))
212
-	            {
213
-	            	if (! file_exists($destpath))
214
-	            	{
215
-	            		$result = dol_move($srcpath, $destpath);
216
-			            if ($result)
217
-			            {
218
-			            	// Define if we have to generate thumbs or not
219
-			            	$generatethumbs = 1;
220
-			            	// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221
-			            	// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222
-			            	// but when we rename from a tab "Documents", we must regenerate thumbs
223
-			            	if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
211
+                if (empty($reshook))
212
+                {
213
+                    if (! file_exists($destpath))
214
+                    {
215
+                        $result = dol_move($srcpath, $destpath);
216
+                        if ($result)
217
+                        {
218
+                            // Define if we have to generate thumbs or not
219
+                            $generatethumbs = 1;
220
+                            // When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221
+                            // When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222
+                            // but when we rename from a tab "Documents", we must regenerate thumbs
223
+                            if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
224 224
 
225
-			            	if ($generatethumbs)
226
-			            	{
227
-			            		if ($object->id)
228
-				            	{
229
-				                	$object->addThumbs($destpath);
230
-				            	}
225
+                            if ($generatethumbs)
226
+                            {
227
+                                if ($object->id)
228
+                                {
229
+                                    $object->addThumbs($destpath);
230
+                                }
231 231
 
232
-				                // TODO Add revert function of addThumbs to remove thumbs with old name
233
-				                //$object->delThumbs($srcpath);
234
-			            	}
232
+                                // TODO Add revert function of addThumbs to remove thumbs with old name
233
+                                //$object->delThumbs($srcpath);
234
+                            }
235 235
 
236
-			                setEventMessages($langs->trans("FileRenamed"), null);
237
-			            }
238
-			            else
239
-			            {
240
-			                $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
241
-			                setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
242
-			            }
243
-	            	}
244
-	            	else
245
-	            	{
246
-	            		$langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
247
-	            		setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
248
-	            	}
249
-	            }
250
-	        }
236
+                            setEventMessages($langs->trans("FileRenamed"), null);
237
+                        }
238
+                        else
239
+                        {
240
+                            $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
241
+                            setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
242
+                        }
243
+                    }
244
+                    else
245
+                    {
246
+                        $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
247
+                        setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
248
+                    }
249
+                }
250
+            }
251 251
         }
252 252
     }
253 253
 
254 254
     // Update properties in ECM table
255 255
     if (GETPOST('ecmfileid', 'int') > 0)
256 256
     {
257
-    	$shareenabled = GETPOST('shareenabled', 'alpha');
257
+        $shareenabled = GETPOST('shareenabled', 'alpha');
258 258
 
259
-    	include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
260
-	    $ecmfile=new EcmFiles($db);
261
-	    $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
262
-	    if ($result > 0)
263
-	    {
264
-	    	if ($shareenabled)
265
-		    {
266
-		    	if (empty($ecmfile->share))
267
-		    	{
268
-		    		require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
269
-		    		$ecmfile->share = getRandomPassword(true);
270
-		    	}
271
-		    }
272
-		    else
273
-		    {
274
-		    	$ecmfile->share = '';
275
-		    }
276
-		    $result = $ecmfile->update($user);
277
-		    if ($result < 0)
278
-		    {
279
-		    	setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
280
-		    }
281
-	    }
259
+        include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
260
+        $ecmfile=new EcmFiles($db);
261
+        $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
262
+        if ($result > 0)
263
+        {
264
+            if ($shareenabled)
265
+            {
266
+                if (empty($ecmfile->share))
267
+                {
268
+                    require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
269
+                    $ecmfile->share = getRandomPassword(true);
270
+                }
271
+            }
272
+            else
273
+            {
274
+                $ecmfile->share = '';
275
+            }
276
+            $result = $ecmfile->update($user);
277
+            if ($result < 0)
278
+            {
279
+                setEventMessages($ecmfile->error, $ecmfile->errors, 'warnings');
280
+            }
281
+        }
282 282
     }
283 283
 }
Please login to merge, or discard this patch.
Spacing   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -27,19 +27,19 @@  discard block
 block discarded – undo
27 27
 
28 28
 
29 29
 // Submit file/link
30
-if (GETPOST('sendit','alpha') && ! empty($conf->global->MAIN_UPLOAD_DOC))
30
+if (GETPOST('sendit', 'alpha') && !empty($conf->global->MAIN_UPLOAD_DOC))
31 31
 {
32
-	if (! empty($_FILES))
32
+	if (!empty($_FILES))
33 33
 	{
34
-		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
-		else $userfiles=array($_FILES['userfile']['tmp_name']);
34
+		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles = $_FILES['userfile']['tmp_name'];
35
+		else $userfiles = array($_FILES['userfile']['tmp_name']);
36 36
 
37
-		foreach($userfiles as $key => $userfile)
37
+		foreach ($userfiles as $key => $userfile)
38 38
 		{
39 39
 			if (empty($_FILES['userfile']['tmp_name'][$key]))
40 40
 			{
41 41
 				$error++;
42
-				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
42
+				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2) {
43 43
 					setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44 44
 				}
45 45
 				else {
@@ -48,30 +48,30 @@  discard block
 block discarded – undo
48 48
 			}
49 49
 		}
50 50
 
51
-		if (! $error)
51
+		if (!$error)
52 52
 		{
53 53
 			// Define if we have to generate thumbs or not
54 54
 			$generatethumbs = 1;
55
-			if (GETPOST('section_dir')) $generatethumbs=0;
55
+			if (GETPOST('section_dir')) $generatethumbs = 0;
56 56
 
57
-			if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
57
+			if (!empty($upload_dirold) && !empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58 58
 			{
59 59
 				$result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60 60
 			}
61
-			elseif (! empty($upload_dir))
61
+			elseif (!empty($upload_dir))
62 62
 			{
63 63
 				$result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64 64
 			}
65 65
 		}
66 66
 	}
67 67
 }
68
-elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
68
+elseif (GETPOST('linkit', 'none') && !empty($conf->global->MAIN_UPLOAD_DOC))
69 69
 {
70 70
     $link = GETPOST('link', 'alpha');
71 71
     if ($link)
72 72
     {
73 73
         if (substr($link, 0, 7) != 'http://' && substr($link, 0, 8) != 'https://' && substr($link, 0, 7) != 'file://') {
74
-            $link = 'http://' . $link;
74
+            $link = 'http://'.$link;
75 75
         }
76 76
         dol_add_file_process($upload_dir, 0, 1, 'userfile', null, $link, '', 0);
77 77
     }
@@ -81,37 +81,37 @@  discard block
 block discarded – undo
81 81
 // Delete file/link
82 82
 if ($action == 'confirm_deletefile' && $confirm == 'yes')
83 83
 {
84
-        $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);				// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
84
+        $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1); // Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
85 85
         if (GETPOST('section', 'alpha')) 	// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
86 86
         {
87
-        	$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
87
+        	$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
88 88
         }
89 89
         else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
90 90
 		{
91
-       		$urlfile=basename($urlfile);
92
-       		$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
-			if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
91
+       		$urlfile = basename($urlfile);
92
+       		$file = $upload_dir.(preg_match('/\/$/', $upload_dir) ? '' : '/').$urlfile;
93
+			if (!empty($upload_dirold)) $fileold = $upload_dirold."/".$urlfile;
94 94
 		}
95 95
         $linkid = GETPOST('linkid', 'int');
96 96
 
97 97
         if ($urlfile)		// delete of a file
98 98
         {
99
-	        $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
100
-	        $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
99
+	        $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
100
+	        $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette (if file is an image)
101 101
 
102
-	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
103
-            if (! empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));     // Delete file using old path
102
+	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object) ? $object : null));
103
+            if (!empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object) ? $object : null)); // Delete file using old path
104 104
 
105 105
 	        // Si elle existe, on efface la vignette
106
-	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
106
+	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i', $file, $regs))
107 107
 	        {
108
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_small'.$regs[0]);
108
+		        $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_small'.$regs[0]);
109 109
 		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
110 110
 		        {
111 111
 			        dol_delete_file($dirthumb.$photo_vignette);
112 112
 		        }
113 113
 
114
-		        $photo_vignette=basename(preg_replace('/'.$regs[0].'/i','',$file).'_mini'.$regs[0]);
114
+		        $photo_vignette = basename(preg_replace('/'.$regs[0].'/i', '', $file).'_mini'.$regs[0]);
115 115
 		        if (file_exists(dol_osencode($dirthumb.$photo_vignette)))
116 116
 		        {
117 117
 			        dol_delete_file($dirthumb.$photo_vignette);
@@ -123,7 +123,7 @@  discard block
 block discarded – undo
123 123
         }
124 124
         elseif ($linkid)	// delete of external link
125 125
         {
126
-            require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
126
+            require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
127 127
             $link = new Link($db);
128 128
             $link->id = $linkid;
129 129
             $link->fetch();
@@ -145,19 +145,19 @@  discard block
 block discarded – undo
145 145
         {
146 146
         	if ($backtopage)
147 147
         	{
148
-        		header('Location: ' . $backtopage);
148
+        		header('Location: '.$backtopage);
149 149
         		exit;
150 150
         	}
151 151
         	else
152 152
         	{
153
-        		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
153
+        		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir', 'alpha') ? '&section_dir='.urlencode(GETPOST('section_dir', 'alpha')) : '').(!empty($withproject) ? '&withproject=1' : ''));
154 154
         		exit;
155 155
         	}
156 156
         }
157 157
 }
158
-elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
158
+elseif ($action == 'confirm_updateline' && GETPOST('save', 'alpha') && GETPOST('link', 'alpha'))
159 159
 {
160
-    require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
160
+    require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
161 161
     $langs->load('link');
162 162
     $link = new Link($db);
163 163
     $link->id = GETPOST('linkid', 'int');
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
         $link->url = GETPOST('link', 'alpha');
168 168
         if (substr($link->url, 0, 7) != 'http://' && substr($link->url, 0, 8) != 'https://' && substr($link->url, 0, 7) != 'file://')
169 169
         {
170
-            $link->url = 'http://' . $link->url;
170
+            $link->url = 'http://'.$link->url;
171 171
         }
172 172
         $link->label = GETPOST('label', 'alpha');
173 173
         $res = $link->update($user);
@@ -181,22 +181,22 @@  discard block
 block discarded – undo
181 181
         //error fetching
182 182
     }
183 183
 }
184
-elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
184
+elseif ($action == 'renamefile' && GETPOST('renamefilesave', 'alpha'))
185 185
 {
186 186
 	// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187
-	if (! empty($upload_dir))
187
+	if (!empty($upload_dir))
188 188
 	{
189
-		$filenamefrom=dol_sanitizeFileName(GETPOST('renamefilefrom','alpha'), '_', 0);	// Do not remove accents
190
-		$filenameto=dol_sanitizeFileName(GETPOST('renamefileto','alpha'), '_', 0);		// Do not remove accents
189
+		$filenamefrom = dol_sanitizeFileName(GETPOST('renamefilefrom', 'alpha'), '_', 0); // Do not remove accents
190
+		$filenameto = dol_sanitizeFileName(GETPOST('renamefileto', 'alpha'), '_', 0); // Do not remove accents
191 191
 
192 192
         if ($filenamefrom != $filenameto)
193 193
         {
194 194
 	        // Security:
195 195
 	        // Disallow file with some extensions. We rename them.
196 196
 	        // Because if we put the documents directory into a directory inside web root (very bad), this allows to execute on demand arbitrary code.
197
-	        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i',$filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
197
+	        if (preg_match('/(\.htm|\.html|\.php|\.pl|\.cgi)$/i', $filenameto) && empty($conf->global->MAIN_DOCUMENT_IS_OUTSIDE_WEBROOT_SO_NOEXE_NOT_REQUIRED))
198 198
 	        {
199
-	            $filenameto.= '.noexe';
199
+	            $filenameto .= '.noexe';
200 200
 	        }
201 201
 
202 202
 	        if ($filenamefrom && $filenameto)
@@ -204,13 +204,13 @@  discard block
 block discarded – undo
204 204
 	            $srcpath = $upload_dir.'/'.$filenamefrom;
205 205
 	            $destpath = $upload_dir.'/'.$filenameto;
206 206
 
207
-	            $reshook=$hookmanager->initHooks(array('actionlinkedfiles'));
208
-	            $parameters=array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
-	            $reshook=$hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
207
+	            $reshook = $hookmanager->initHooks(array('actionlinkedfiles'));
208
+	            $parameters = array('filenamefrom' => $filenamefrom, 'filenameto' => $filenameto, 'upload_dir' => $upload_dir);
209
+	            $reshook = $hookmanager->executeHooks('renameUploadedFile', $parameters, $object);
210 210
 
211 211
 	            if (empty($reshook))
212 212
 	            {
213
-	            	if (! file_exists($destpath))
213
+	            	if (!file_exists($destpath))
214 214
 	            	{
215 215
 	            		$result = dol_move($srcpath, $destpath);
216 216
 			            if ($result)
@@ -220,7 +220,7 @@  discard block
 block discarded – undo
220 220
 			            	// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221 221
 			            	// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222 222
 			            	// but when we rename from a tab "Documents", we must regenerate thumbs
223
-			            	if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
223
+			            	if (GETPOST('modulepart') == 'medias') $generatethumbs = 0;
224 224
 
225 225
 			            	if ($generatethumbs)
226 226
 			            	{
@@ -257,7 +257,7 @@  discard block
 block discarded – undo
257 257
     	$shareenabled = GETPOST('shareenabled', 'alpha');
258 258
 
259 259
     	include_once DOL_DOCUMENT_ROOT.'/ecm/class/ecmfiles.class.php';
260
-	    $ecmfile=new EcmFiles($db);
260
+	    $ecmfile = new EcmFiles($db);
261 261
 	    $result = $ecmfile->fetch(GETPOST('ecmfileid', 'int'));
262 262
 	    if ($result > 0)
263 263
 	    {
Please login to merge, or discard this patch.
Braces   +44 added lines, -34 removed lines patch added patch discarded remove patch
@@ -31,8 +31,11 @@  discard block
 block discarded – undo
31 31
 {
32 32
 	if (! empty($_FILES))
33 33
 	{
34
-		if (is_array($_FILES['userfile']['tmp_name'])) $userfiles=$_FILES['userfile']['tmp_name'];
35
-		else $userfiles=array($_FILES['userfile']['tmp_name']);
34
+		if (is_array($_FILES['userfile']['tmp_name'])) {
35
+		    $userfiles=$_FILES['userfile']['tmp_name'];
36
+		} else {
37
+		    $userfiles=array($_FILES['userfile']['tmp_name']);
38
+		}
36 39
 
37 40
 		foreach($userfiles as $key => $userfile)
38 41
 		{
@@ -41,8 +44,7 @@  discard block
 block discarded – undo
41 44
 				$error++;
42 45
 				if ($_FILES['userfile']['error'][$key] == 1 || $_FILES['userfile']['error'][$key] == 2){
43 46
 					setEventMessages($langs->trans('ErrorFileSizeTooLarge'), null, 'errors');
44
-				}
45
-				else {
47
+				} else {
46 48
 					setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("File")), null, 'errors');
47 49
 				}
48 50
 			}
@@ -52,20 +54,20 @@  discard block
 block discarded – undo
52 54
 		{
53 55
 			// Define if we have to generate thumbs or not
54 56
 			$generatethumbs = 1;
55
-			if (GETPOST('section_dir')) $generatethumbs=0;
57
+			if (GETPOST('section_dir')) {
58
+			    $generatethumbs=0;
59
+			}
56 60
 
57 61
 			if (! empty($upload_dirold) && ! empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO))
58 62
 			{
59 63
 				$result = dol_add_file_process($upload_dirold, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
60
-			}
61
-			elseif (! empty($upload_dir))
64
+			} elseif (! empty($upload_dir))
62 65
 			{
63 66
 				$result = dol_add_file_process($upload_dir, 0, 1, 'userfile', GETPOST('savingdocmask', 'alpha'), null, '', $generatethumbs);
64 67
 			}
65 68
 		}
66 69
 	}
67
-}
68
-elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
70
+} elseif (GETPOST('linkit','none') && ! empty($conf->global->MAIN_UPLOAD_DOC))
69 71
 {
70 72
     $link = GETPOST('link', 'alpha');
71 73
     if ($link)
@@ -82,25 +84,34 @@  discard block
 block discarded – undo
82 84
 if ($action == 'confirm_deletefile' && $confirm == 'yes')
83 85
 {
84 86
         $urlfile = GETPOST('urlfile', 'alpha', 0, null, null, 1);				// Do not use urldecode here ($_GET and $_REQUEST are already decoded by PHP).
85
-        if (GETPOST('section', 'alpha')) 	// For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
87
+        if (GETPOST('section', 'alpha')) {
88
+            // For a delete from the ECM module, upload_dir is ECM root dir and urlfile contains relative path from upload_dir
86 89
         {
87 90
         	$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
88 91
         }
89
-        else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
92
+        } else								// For a delete from the file manager into another module, or from documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
90 93
 		{
91 94
        		$urlfile=basename($urlfile);
92 95
        		$file = $upload_dir . (preg_match('/\/$/', $upload_dir) ? '' : '/') . $urlfile;
93
-			if (! empty($upload_dirold)) $fileold = $upload_dirold . "/" . $urlfile;
96
+			if (! empty($upload_dirold)) {
97
+			    $fileold = $upload_dirold . "/" . $urlfile;
98
+			}
94 99
 		}
95 100
         $linkid = GETPOST('linkid', 'int');
96 101
 
97
-        if ($urlfile)		// delete of a file
102
+        if ($urlfile) {
103
+            // delete of a file
98 104
         {
99
-	        $dir = dirname($file).'/';		// Chemin du dossier contenant l'image d'origine
105
+	        $dir = dirname($file).'/';
106
+        }
107
+        // Chemin du dossier contenant l'image d'origine
100 108
 	        $dirthumb = $dir.'/thumbs/';	// Chemin du dossier contenant la vignette (if file is an image)
101 109
 
102 110
 	        $ret = dol_delete_file($file, 0, 0, 0, (is_object($object)?$object:null));
103
-            if (! empty($fileold)) dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));     // Delete file using old path
111
+            if (! empty($fileold)) {
112
+                dol_delete_file($fileold, 0, 0, 0, (is_object($object)?$object:null));
113
+            }
114
+            // Delete file using old path
104 115
 
105 116
 	        // Si elle existe, on efface la vignette
106 117
 	        if (preg_match('/(\.jpg|\.jpeg|\.bmp|\.gif|\.png|\.tiff)$/i',$file,$regs))
@@ -118,12 +129,16 @@  discard block
 block discarded – undo
118 129
 		        }
119 130
 	        }
120 131
 
121
-            if ($ret) setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
122
-            else setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
123
-        }
124
-        elseif ($linkid)	// delete of external link
132
+            if ($ret) {
133
+                setEventMessages($langs->trans("FileWasRemoved", $urlfile), null, 'mesgs');
134
+            } else {
135
+                setEventMessages($langs->trans("ErrorFailToDeleteFile", $urlfile), null, 'errors');
136
+            }
137
+        } elseif ($linkid) {
138
+            // delete of external link
125 139
         {
126 140
             require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
141
+        }
127 142
             $link = new Link($db);
128 143
             $link->id = $linkid;
129 144
             $link->fetch();
@@ -147,15 +162,13 @@  discard block
 block discarded – undo
147 162
         	{
148 163
         		header('Location: ' . $backtopage);
149 164
         		exit;
150
-        	}
151
-        	else
165
+        	} else
152 166
         	{
153 167
         		header('Location: '.$_SERVER["PHP_SELF"].'?id='.$object->id.(GETPOST('section_dir','alpha')?'&section_dir='.urlencode(GETPOST('section_dir','alpha')):'').(!empty($withproject)?'&withproject=1':''));
154 168
         		exit;
155 169
         	}
156 170
         }
157
-}
158
-elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
171
+} elseif ($action == 'confirm_updateline' && GETPOST('save','alpha') && GETPOST('link', 'alpha'))
159 172
 {
160 173
     require_once DOL_DOCUMENT_ROOT . '/core/class/link.class.php';
161 174
     $langs->load('link');
@@ -175,13 +188,11 @@  discard block
 block discarded – undo
175 188
         {
176 189
             setEventMessages($langs->trans("ErrorFailedToUpdateLink", $link->label), null, 'mesgs');
177 190
         }
178
-    }
179
-    else
191
+    } else
180 192
     {
181 193
         //error fetching
182 194
     }
183
-}
184
-elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
195
+} elseif ($action == 'renamefile' && GETPOST('renamefilesave','alpha'))
185 196
 {
186 197
 	// For documents pages, upload_dir contains already path to file from module dir, so we clean path into urlfile.
187 198
 	if (! empty($upload_dir))
@@ -220,7 +231,9 @@  discard block
 block discarded – undo
220 231
 			            	// When we rename a file from the file manager in ecm, we must not regenerate thumbs (not a problem, we do pass here)
221 232
 			            	// When we rename a file from the website module, we must not regenerate thumbs (module = medias in such a case)
222 233
 			            	// but when we rename from a tab "Documents", we must regenerate thumbs
223
-			            	if (GETPOST('modulepart') == 'medias') $generatethumbs=0;
234
+			            	if (GETPOST('modulepart') == 'medias') {
235
+			            	    $generatethumbs=0;
236
+			            	}
224 237
 
225 238
 			            	if ($generatethumbs)
226 239
 			            	{
@@ -234,14 +247,12 @@  discard block
 block discarded – undo
234 247
 			            	}
235 248
 
236 249
 			                setEventMessages($langs->trans("FileRenamed"), null);
237
-			            }
238
-			            else
250
+			            } else
239 251
 			            {
240 252
 			                $langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
241 253
 			                setEventMessages($langs->trans("ErrorFailToRenameFile", $filenamefrom, $filenameto), null, 'errors');
242 254
 			            }
243
-	            	}
244
-	            	else
255
+	            	} else
245 256
 	            	{
246 257
 	            		$langs->load("errors"); // key must be loaded because we can't rely on loading during output, we need var substitution to be done now.
247 258
 	            		setEventMessages($langs->trans("ErrorDestinationAlreadyExists", $filenameto), null, 'errors');
@@ -268,8 +279,7 @@  discard block
 block discarded – undo
268 279
 		    		require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
269 280
 		    		$ecmfile->share = getRandomPassword(true);
270 281
 		    	}
271
-		    }
272
-		    else
282
+		    } else
273 283
 		    {
274 284
 		    	$ecmfile->share = '';
275 285
 		    }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/modules/modFTP.class.php 2 patches
Indentation   +89 added lines, -89 removed lines patch added patch discarded remove patch
@@ -33,96 +33,96 @@
 block discarded – undo
33 33
 class modFTP extends DolibarrModules
34 34
 {
35 35
 
36
-   /**
37
-	 *   Constructor. Define names, constants, directories, boxes, permissions
38
-	 *
39
-	 *   @param      DoliDB		$db      Database handler
40
-    */
41
-	function __construct($db)
42
-	{
43
-		$this->db = $db;
44
-
45
-		// Id for module (must be unique).
46
-		// Use here a free id.
47
-		$this->numero = 2800;
48
-
49
-		// Family can be 'crm','financial','hr','projects','product','ecm','technic','other'
50
-		// It is used to sort modules in module setup page
51
-		$this->family = "interface";
52
-		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
53
-		$this->name = preg_replace('/^mod/i','',get_class($this));
54
-		// Module description used if translation string 'ModuleXXXDesc' not found (XXX is id value)
55
-		$this->description = "FTP Client";
56
-		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
57
-		$this->version = 'dolibarr';
58
-		// Key used in llx_const table to save module status enabled/disabled (XXX is id value)
59
-		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
60
-		// Name of png file (without png) used for this module
61
-		$this->picto='dir';
62
-
63
-		// Data directories to create when module is enabled
64
-		$this->dirs = array("/ftp/temp");
65
-
66
-		// Langs file within the module
67
-		$this->langfiles = array("ftp");
68
-
69
-		// Config pages. Put here list of php page names stored in admmin directory used to setup module
70
-		$this->config_page_url = array('ftpclient.php@ftp');
71
-
72
-		// Dependencies
73
-		$this->depends = array();		// List of modules id that must be enabled if this module is enabled
74
-		$this->requiredby = array();	// List of modules id to disable if this one is disabled
75
-
76
-		// Constants
77
-		$this->const = array(
78
-		    1=>array('FTP_CONNECT_WITH_SSL','chaine','0','Use FTPS for FTP module', 1, 'current', 1),
79
-		    2=>array('FTP_CONNECT_WITH_SFTP','chaine','0','Use SFTP for FTP module', 1, 'current', 1)
80
-		);			// List of parameters
81
-
82
-		// Boxes
83
-		$this->boxes = array();			// List of boxes
84
-		$r=0;
85
-
86
-		// Add here list of php file(s) stored in core/boxes that contains class to show a box.
87
-		// Example:
36
+    /**
37
+     *   Constructor. Define names, constants, directories, boxes, permissions
38
+     *
39
+     *   @param      DoliDB		$db      Database handler
40
+     */
41
+    function __construct($db)
42
+    {
43
+        $this->db = $db;
44
+
45
+        // Id for module (must be unique).
46
+        // Use here a free id.
47
+        $this->numero = 2800;
48
+
49
+        // Family can be 'crm','financial','hr','projects','product','ecm','technic','other'
50
+        // It is used to sort modules in module setup page
51
+        $this->family = "interface";
52
+        // Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
53
+        $this->name = preg_replace('/^mod/i','',get_class($this));
54
+        // Module description used if translation string 'ModuleXXXDesc' not found (XXX is id value)
55
+        $this->description = "FTP Client";
56
+        // Possible values for version are: 'development', 'experimental', 'dolibarr' or version
57
+        $this->version = 'dolibarr';
58
+        // Key used in llx_const table to save module status enabled/disabled (XXX is id value)
59
+        $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
60
+        // Name of png file (without png) used for this module
61
+        $this->picto='dir';
62
+
63
+        // Data directories to create when module is enabled
64
+        $this->dirs = array("/ftp/temp");
65
+
66
+        // Langs file within the module
67
+        $this->langfiles = array("ftp");
68
+
69
+        // Config pages. Put here list of php page names stored in admmin directory used to setup module
70
+        $this->config_page_url = array('ftpclient.php@ftp');
71
+
72
+        // Dependencies
73
+        $this->depends = array();		// List of modules id that must be enabled if this module is enabled
74
+        $this->requiredby = array();	// List of modules id to disable if this one is disabled
75
+
76
+        // Constants
77
+        $this->const = array(
78
+            1=>array('FTP_CONNECT_WITH_SSL','chaine','0','Use FTPS for FTP module', 1, 'current', 1),
79
+            2=>array('FTP_CONNECT_WITH_SFTP','chaine','0','Use SFTP for FTP module', 1, 'current', 1)
80
+        );			// List of parameters
81
+
82
+        // Boxes
83
+        $this->boxes = array();			// List of boxes
84
+        $r=0;
85
+
86
+        // Add here list of php file(s) stored in core/boxes that contains class to show a box.
87
+        // Example:
88 88
         //$this->boxes[$r][1] = "myboxa.php";
89
-    	//$r++;
89
+        //$r++;
90 90
         //$this->boxes[$r][1] = "myboxb.php";
91
-    	//$r++;
92
-
93
-		// Permissions
94
-		$this->rights_class = 'ftp';	// Permission key
95
-		$this->rights = array();		// Permission array used by this module
96
-
97
-		$r++;
98
-		$this->rights[$r][0] = 2801;
99
-		$this->rights[$r][1] = 'Use FTP client in read mode (browse and download only)';
100
-		$this->rights[$r][2] = 'r';
101
-		$this->rights[$r][3] = 0;
102
-		$this->rights[$r][4] = 'read';
103
-
104
-		$r++;
105
-		$this->rights[$r][0] = 2802;
106
-		$this->rights[$r][1] = 'Use FTP client in write mode (delete or upload files)';
107
-		$this->rights[$r][2] = 'w';
108
-		$this->rights[$r][3] = 0;
109
-		$this->rights[$r][4] = 'write';
110
-
111
-
112
-		// Menus
113
-		//-------
114
-		$this->menu[$r]=array('fk_menu'=>0,
115
-							  'type'=>'top',
116
-							  'titre'=>'FTP',
117
-							  'mainmenu'=>'ftp',
118
-							  'url'=>'/ftp/index.php',
119
-							  'langs'=>'ftp',
120
-							  'position'=>100,
121
-                              'enabled'=>'$conf->ftp->enabled',
122
-		                      'perms'=>'$user->rights->ftp->read || $user->rights->ftp->write || $user->rights->ftp->setup',
123
-							  'target'=>'',
124
-							  'user'=>2);			// 0=Menu for internal users, 1=external users, 2=both
125
-		$r++;
126
-	}
91
+        //$r++;
92
+
93
+        // Permissions
94
+        $this->rights_class = 'ftp';	// Permission key
95
+        $this->rights = array();		// Permission array used by this module
96
+
97
+        $r++;
98
+        $this->rights[$r][0] = 2801;
99
+        $this->rights[$r][1] = 'Use FTP client in read mode (browse and download only)';
100
+        $this->rights[$r][2] = 'r';
101
+        $this->rights[$r][3] = 0;
102
+        $this->rights[$r][4] = 'read';
103
+
104
+        $r++;
105
+        $this->rights[$r][0] = 2802;
106
+        $this->rights[$r][1] = 'Use FTP client in write mode (delete or upload files)';
107
+        $this->rights[$r][2] = 'w';
108
+        $this->rights[$r][3] = 0;
109
+        $this->rights[$r][4] = 'write';
110
+
111
+
112
+        // Menus
113
+        //-------
114
+        $this->menu[$r]=array('fk_menu'=>0,
115
+                                'type'=>'top',
116
+                                'titre'=>'FTP',
117
+                                'mainmenu'=>'ftp',
118
+                                'url'=>'/ftp/index.php',
119
+                                'langs'=>'ftp',
120
+                                'position'=>100,
121
+                                'enabled'=>'$conf->ftp->enabled',
122
+                                'perms'=>'$user->rights->ftp->read || $user->rights->ftp->write || $user->rights->ftp->setup',
123
+                                'target'=>'',
124
+                                'user'=>2);			// 0=Menu for internal users, 1=external users, 2=both
125
+        $r++;
126
+    }
127 127
 }
128 128
 
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -24,7 +24,7 @@  discard block
 block discarded – undo
24 24
  *      \brief      Description and activation file for module FTP
25 25
  */
26 26
 
27
-include_once DOL_DOCUMENT_ROOT .'/core/modules/DolibarrModules.class.php';
27
+include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';
28 28
 
29 29
 
30 30
 /**
@@ -50,7 +50,7 @@  discard block
 block discarded – undo
50 50
 		// It is used to sort modules in module setup page
51 51
 		$this->family = "interface";
52 52
 		// Module label (no space allowed), used if translation string 'ModuleXXXName' not found (where XXX is value of numeric property 'numero' of module)
53
-		$this->name = preg_replace('/^mod/i','',get_class($this));
53
+		$this->name = preg_replace('/^mod/i', '', get_class($this));
54 54
 		// Module description used if translation string 'ModuleXXXDesc' not found (XXX is id value)
55 55
 		$this->description = "FTP Client";
56 56
 		// Possible values for version are: 'development', 'experimental', 'dolibarr' or version
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
 		// Key used in llx_const table to save module status enabled/disabled (XXX is id value)
59 59
 		$this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
60 60
 		// Name of png file (without png) used for this module
61
-		$this->picto='dir';
61
+		$this->picto = 'dir';
62 62
 
63 63
 		// Data directories to create when module is enabled
64 64
 		$this->dirs = array("/ftp/temp");
@@ -70,18 +70,18 @@  discard block
 block discarded – undo
70 70
 		$this->config_page_url = array('ftpclient.php@ftp');
71 71
 
72 72
 		// Dependencies
73
-		$this->depends = array();		// List of modules id that must be enabled if this module is enabled
74
-		$this->requiredby = array();	// List of modules id to disable if this one is disabled
73
+		$this->depends = array(); // List of modules id that must be enabled if this module is enabled
74
+		$this->requiredby = array(); // List of modules id to disable if this one is disabled
75 75
 
76 76
 		// Constants
77 77
 		$this->const = array(
78
-		    1=>array('FTP_CONNECT_WITH_SSL','chaine','0','Use FTPS for FTP module', 1, 'current', 1),
79
-		    2=>array('FTP_CONNECT_WITH_SFTP','chaine','0','Use SFTP for FTP module', 1, 'current', 1)
80
-		);			// List of parameters
78
+		    1=>array('FTP_CONNECT_WITH_SSL', 'chaine', '0', 'Use FTPS for FTP module', 1, 'current', 1),
79
+		    2=>array('FTP_CONNECT_WITH_SFTP', 'chaine', '0', 'Use SFTP for FTP module', 1, 'current', 1)
80
+		); // List of parameters
81 81
 
82 82
 		// Boxes
83
-		$this->boxes = array();			// List of boxes
84
-		$r=0;
83
+		$this->boxes = array(); // List of boxes
84
+		$r = 0;
85 85
 
86 86
 		// Add here list of php file(s) stored in core/boxes that contains class to show a box.
87 87
 		// Example:
@@ -91,8 +91,8 @@  discard block
 block discarded – undo
91 91
     	//$r++;
92 92
 
93 93
 		// Permissions
94
-		$this->rights_class = 'ftp';	// Permission key
95
-		$this->rights = array();		// Permission array used by this module
94
+		$this->rights_class = 'ftp'; // Permission key
95
+		$this->rights = array(); // Permission array used by this module
96 96
 
97 97
 		$r++;
98 98
 		$this->rights[$r][0] = 2801;
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 
112 112
 		// Menus
113 113
 		//-------
114
-		$this->menu[$r]=array('fk_menu'=>0,
114
+		$this->menu[$r] = array('fk_menu'=>0,
115 115
 							  'type'=>'top',
116 116
 							  'titre'=>'FTP',
117 117
 							  'mainmenu'=>'ftp',
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
                               'enabled'=>'$conf->ftp->enabled',
122 122
 		                      'perms'=>'$user->rights->ftp->read || $user->rights->ftp->write || $user->rights->ftp->setup',
123 123
 							  'target'=>'',
124
-							  'user'=>2);			// 0=Menu for internal users, 1=external users, 2=both
124
+							  'user'=>2); // 0=Menu for internal users, 1=external users, 2=both
125 125
 		$r++;
126 126
 	}
127 127
 }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/modules/expedition/doc/pdf_rouget.modules.php 3 patches
Indentation   +910 added lines, -910 removed lines patch added patch discarded remove patch
@@ -51,154 +51,154 @@  discard block
 block discarded – undo
51 51
      */
52 52
     public $description;
53 53
 
54
-	/**
54
+    /**
55 55
      * @var string document type
56 56
      */
57 57
     public $type;
58 58
 
59
-	/**
59
+    /**
60 60
      * @var array() Minimum version of PHP required by module.
61
-	 * e.g.: PHP ≥ 5.4 = array(5, 4)
61
+     * e.g.: PHP ≥ 5.4 = array(5, 4)
62 62
      */
63
-	public $phpmin = array(5, 4);
63
+    public $phpmin = array(5, 4);
64 64
 
65
-	/**
65
+    /**
66 66
      * Dolibarr version of the loaded document
67 67
      * @public string
68 68
      */
69
-	public $version = 'dolibarr';
69
+    public $version = 'dolibarr';
70 70
 
71
-	/**
71
+    /**
72 72
      * @var int page_largeur
73 73
      */
74 74
     public $page_largeur;
75 75
 
76
-	/**
76
+    /**
77 77
      * @var int page_hauteur
78 78
      */
79 79
     public $page_hauteur;
80 80
 
81
-	/**
81
+    /**
82 82
      * @var array format
83 83
      */
84 84
     public $format;
85 85
 
86
-	/**
86
+    /**
87 87
      * @var int marge_gauche
88 88
      */
89
-	public $marge_gauche;
89
+    public $marge_gauche;
90 90
 
91
-	/**
91
+    /**
92 92
      * @var int marge_droite
93 93
      */
94
-	public $marge_droite;
94
+    public $marge_droite;
95 95
 
96
-	/**
96
+    /**
97 97
      * @var int marge_haute
98 98
      */
99
-	public $marge_haute;
99
+    public $marge_haute;
100 100
 
101
-	/**
101
+    /**
102 102
      * @var int marge_basse
103 103
      */
104
-	public $marge_basse;
105
-
106
-	/**
107
-	 * Issuer
108
-	 * @var Company object that emits
109
-	 */
110
-	public $emetteur;
111
-
112
-
113
-	/**
114
-	 *	Constructor
115
-	 *
116
-	 *	@param	DoliDB	$db		Database handler
117
-	 */
118
-	function __construct($db=0)
119
-	{
120
-		global $conf,$langs,$mysoc;
121
-
122
-		$this->db = $db;
123
-		$this->name = "rouget";
124
-		$this->description = $langs->trans("DocumentModelStandardPDF");
125
-
126
-		$this->type = 'pdf';
127
-		$formatarray=pdf_getFormat();
128
-		$this->page_largeur = $formatarray['width'];
129
-		$this->page_hauteur = $formatarray['height'];
130
-		$this->format = array($this->page_largeur,$this->page_hauteur);
131
-		$this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10;
132
-		$this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10;
133
-		$this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10;
134
-		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
135
-
136
-		$this->option_logo = 1;
137
-
138
-		// Get source company
139
-		$this->emetteur=$mysoc;
140
-		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default if not defined
141
-
142
-		// Define position of columns
143
-		$this->posxdesc=$this->marge_gauche+1;
144
-		$this->posxweightvol=$this->page_largeur - $this->marge_droite - 78;
145
-		$this->posxqtyordered=$this->page_largeur - $this->marge_droite - 56;
146
-		$this->posxqtytoship=$this->page_largeur - $this->marge_droite - 28;
147
-		$this->posxpuht=$this->page_largeur - $this->marge_droite;
148
-
149
-		if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT)) {	// Show also the prices
150
-			$this->posxweightvol=$this->page_largeur - $this->marge_droite - 118;
151
-			$this->posxqtyordered=$this->page_largeur - $this->marge_droite - 96;
152
-			$this->posxqtytoship=$this->page_largeur - $this->marge_droite - 68;
153
-			$this->posxpuht=$this->page_largeur - $this->marge_droite - 40;
154
-			$this->posxtotalht=$this->page_largeur - $this->marge_droite - 20;
155
-		}
156
-
157
-		$this->posxpicture=$this->posxweightvol - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
158
-
159
-		if ($this->page_largeur < 210) // To work with US executive format
160
-		{
161
-		    $this->posxweightvol-=20;
162
-		    $this->posxpicture-=20;
163
-		    $this->posxqtyordered-=20;
164
-		    $this->posxqtytoship-=20;
165
-		}
104
+    public $marge_basse;
166 105
 
167
-		if (! empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
168
-		{
169
-		    $this->posxweightvol += ($this->posxqtytoship - $this->posxqtyordered);
170
-		    $this->posxpicture += ($this->posxqtytoship - $this->posxqtyordered);
171
-		    $this->posxqtyordered = $this->posxqtytoship;
172
-		}
173
-	}
174
-
175
-	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
176
-	/**
177
-	 *	Function to build pdf onto disk
178
-	 *
179
-	 *	@param		Object		$object			Object expedition to generate (or id if old method)
180
-	 *	@param		Translate	$outputlangs		Lang output object
106
+    /**
107
+     * Issuer
108
+     * @var Company object that emits
109
+     */
110
+    public $emetteur;
111
+
112
+
113
+    /**
114
+     *	Constructor
115
+     *
116
+     *	@param	DoliDB	$db		Database handler
117
+     */
118
+    function __construct($db=0)
119
+    {
120
+        global $conf,$langs,$mysoc;
121
+
122
+        $this->db = $db;
123
+        $this->name = "rouget";
124
+        $this->description = $langs->trans("DocumentModelStandardPDF");
125
+
126
+        $this->type = 'pdf';
127
+        $formatarray=pdf_getFormat();
128
+        $this->page_largeur = $formatarray['width'];
129
+        $this->page_hauteur = $formatarray['height'];
130
+        $this->format = array($this->page_largeur,$this->page_hauteur);
131
+        $this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10;
132
+        $this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10;
133
+        $this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10;
134
+        $this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
135
+
136
+        $this->option_logo = 1;
137
+
138
+        // Get source company
139
+        $this->emetteur=$mysoc;
140
+        if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default if not defined
141
+
142
+        // Define position of columns
143
+        $this->posxdesc=$this->marge_gauche+1;
144
+        $this->posxweightvol=$this->page_largeur - $this->marge_droite - 78;
145
+        $this->posxqtyordered=$this->page_largeur - $this->marge_droite - 56;
146
+        $this->posxqtytoship=$this->page_largeur - $this->marge_droite - 28;
147
+        $this->posxpuht=$this->page_largeur - $this->marge_droite;
148
+
149
+        if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT)) {	// Show also the prices
150
+            $this->posxweightvol=$this->page_largeur - $this->marge_droite - 118;
151
+            $this->posxqtyordered=$this->page_largeur - $this->marge_droite - 96;
152
+            $this->posxqtytoship=$this->page_largeur - $this->marge_droite - 68;
153
+            $this->posxpuht=$this->page_largeur - $this->marge_droite - 40;
154
+            $this->posxtotalht=$this->page_largeur - $this->marge_droite - 20;
155
+        }
156
+
157
+        $this->posxpicture=$this->posxweightvol - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
158
+
159
+        if ($this->page_largeur < 210) // To work with US executive format
160
+        {
161
+            $this->posxweightvol-=20;
162
+            $this->posxpicture-=20;
163
+            $this->posxqtyordered-=20;
164
+            $this->posxqtytoship-=20;
165
+        }
166
+
167
+        if (! empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
168
+        {
169
+            $this->posxweightvol += ($this->posxqtytoship - $this->posxqtyordered);
170
+            $this->posxpicture += ($this->posxqtytoship - $this->posxqtyordered);
171
+            $this->posxqtyordered = $this->posxqtytoship;
172
+        }
173
+    }
174
+
175
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
176
+    /**
177
+     *	Function to build pdf onto disk
178
+     *
179
+     *	@param		Object		$object			Object expedition to generate (or id if old method)
180
+     *	@param		Translate	$outputlangs		Lang output object
181 181
      *  @param		string		$srctemplatepath	Full path of source filename for generator using a template file
182 182
      *  @param		int			$hidedetails		Do not show line details
183 183
      *  @param		int			$hidedesc			Do not show desc
184 184
      *  @param		int			$hideref			Do not show ref
185 185
      *  @return     int         	    			1=OK, 0=KO
186
-	 */
187
-	function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
188
-	{
189
-		// phpcs:enable
190
-		global $user,$conf,$langs,$hookmanager;
186
+     */
187
+    function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
188
+    {
189
+        // phpcs:enable
190
+        global $user,$conf,$langs,$hookmanager;
191 191
 
192
-		$object->fetch_thirdparty();
192
+        $object->fetch_thirdparty();
193 193
 
194
-		if (! is_object($outputlangs)) $outputlangs=$langs;
195
-		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
196
-		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
194
+        if (! is_object($outputlangs)) $outputlangs=$langs;
195
+        // For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
196
+        if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
197 197
 
198
-		// Load traductions files requiredby by page
199
-		$outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch"));
198
+        // Load traductions files requiredby by page
199
+        $outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch"));
200 200
 
201
-		$nblignes = count($object->lines);
201
+        $nblignes = count($object->lines);
202 202
 
203 203
         // Loop on each lines to detect if there is at least one image to show
204 204
         $realpatharray=array();
@@ -210,13 +210,13 @@  discard block
 block discarded – undo
210 210
             {
211 211
                 if (empty($object->lines[$i]->fk_product)) continue;
212 212
 
213
-				$objphoto = new Product($this->db);
214
-				$objphoto->fetch($object->lines[$i]->fk_product);
213
+                $objphoto = new Product($this->db);
214
+                $objphoto->fetch($object->lines[$i]->fk_product);
215 215
 
216
-				$pdir = get_exdir($object->lines[$i]->fk_product,2,0,0,$objphoto,'product') . $object->lines[$i]->fk_product ."/photos/";
217
-				$dir = $conf->product->dir_output.'/'.$pdir;
216
+                $pdir = get_exdir($object->lines[$i]->fk_product,2,0,0,$objphoto,'product') . $object->lines[$i]->fk_product ."/photos/";
217
+                $dir = $conf->product->dir_output.'/'.$pdir;
218 218
 
219
-				$realpath='';
219
+                $realpath='';
220 220
 
221 221
                 foreach ($objphoto->liste_photos($dir,1) as $key => $obj)
222 222
                         {
@@ -246,52 +246,52 @@  discard block
 block discarded – undo
246 246
 
247 247
         if (count($realpatharray) == 0) $this->posxpicture=$this->posxweightvol;
248 248
 
249
-		if ($conf->expedition->dir_output)
250
-		{
251
-			// Definition de $dir et $file
252
-			if ($object->specimen)
253
-			{
254
-				$dir = $conf->expedition->dir_output."/sending";
255
-				$file = $dir . "/SPECIMEN.pdf";
256
-			}
257
-			else
258
-			{
259
-				$expref = dol_sanitizeFileName($object->ref);
260
-				$dir = $conf->expedition->dir_output."/sending/" . $expref;
261
-				$file = $dir . "/" . $expref . ".pdf";
262
-			}
263
-
264
-			if (! file_exists($dir))
265
-			{
266
-				if (dol_mkdir($dir) < 0)
267
-				{
268
-					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
269
-					return 0;
270
-				}
271
-			}
272
-
273
-			if (file_exists($dir))
274
-			{
275
-				// Add pdfgeneration hook
276
-				if (! is_object($hookmanager))
277
-				{
278
-					include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
279
-					$hookmanager=new HookManager($this->db);
280
-				}
281
-				$hookmanager->initHooks(array('pdfgeneration'));
282
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
283
-				global $action;
284
-				$reshook=$hookmanager->executeHooks('beforePDFCreation',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
285
-
286
-				// Set nblignes with the new facture lines content after hook
287
-				$nblignes = count($object->lines);
288
-
289
-				$pdf=pdf_getInstance($this->format);
290
-				$default_font_size = pdf_getPDFFontSize($outputlangs);
291
-				$heightforinfotot = 8;	// Height reserved to output the info and total part
292
-		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
293
-	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
294
-	            if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
249
+        if ($conf->expedition->dir_output)
250
+        {
251
+            // Definition de $dir et $file
252
+            if ($object->specimen)
253
+            {
254
+                $dir = $conf->expedition->dir_output."/sending";
255
+                $file = $dir . "/SPECIMEN.pdf";
256
+            }
257
+            else
258
+            {
259
+                $expref = dol_sanitizeFileName($object->ref);
260
+                $dir = $conf->expedition->dir_output."/sending/" . $expref;
261
+                $file = $dir . "/" . $expref . ".pdf";
262
+            }
263
+
264
+            if (! file_exists($dir))
265
+            {
266
+                if (dol_mkdir($dir) < 0)
267
+                {
268
+                    $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
269
+                    return 0;
270
+                }
271
+            }
272
+
273
+            if (file_exists($dir))
274
+            {
275
+                // Add pdfgeneration hook
276
+                if (! is_object($hookmanager))
277
+                {
278
+                    include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
279
+                    $hookmanager=new HookManager($this->db);
280
+                }
281
+                $hookmanager->initHooks(array('pdfgeneration'));
282
+                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
283
+                global $action;
284
+                $reshook=$hookmanager->executeHooks('beforePDFCreation',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
285
+
286
+                // Set nblignes with the new facture lines content after hook
287
+                $nblignes = count($object->lines);
288
+
289
+                $pdf=pdf_getInstance($this->format);
290
+                $default_font_size = pdf_getPDFFontSize($outputlangs);
291
+                $heightforinfotot = 8;	// Height reserved to output the info and total part
292
+                $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
293
+                $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
294
+                if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
295 295
                 $pdf->SetAutoPageBreak(1,0);
296 296
 
297 297
                 if (class_exists('TCPDF'))
@@ -307,814 +307,814 @@  discard block
 block discarded – undo
307 307
                     $tplidx = $pdf->importPage(1);
308 308
                 }
309 309
 
310
-				$pdf->Open();
311
-				$pagenb=0;
312
-				$pdf->SetDrawColor(128,128,128);
313
-
314
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
315
-
316
-				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
317
-				$pdf->SetSubject($outputlangs->transnoentities("Shipment"));
318
-				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
319
-				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
320
-				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Shipment"));
321
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
322
-
323
-				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
324
-
325
-				// New page
326
-				$pdf->AddPage();
327
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
328
-				$pagenb++;
329
-				$this->_pagehead($pdf, $object, 1, $outputlangs);
330
-				$pdf->SetFont('','', $default_font_size - 1);
331
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
332
-				$pdf->SetTextColor(0,0,0);
333
-
334
-				$tab_top = 90;
335
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
336
-				$tab_height = 130;
337
-				$tab_height_newpage = 150;
338
-
339
-				// Incoterm
340
-				$height_incoterms = 0;
341
-				if ($conf->incoterm->enabled)
342
-				{
343
-					$desc_incoterms = $object->getIncotermsForPDF();
344
-					if ($desc_incoterms)
345
-					{
346
-						$tab_top = 88;
347
-
348
-						$pdf->SetFont('','', $default_font_size - 1);
349
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
350
-						$nexY = $pdf->GetY();
351
-						$height_incoterms=$nexY-$tab_top;
352
-
353
-						// Rect prend une longueur en 3eme param
354
-						$pdf->SetDrawColor(192,192,192);
355
-						$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1);
356
-
357
-						$tab_top = $nexY+6;
358
-						$height_incoterms += 4;
359
-					}
360
-				}
361
-
362
-				if (! empty($object->note_public) || ! empty($object->tracking_number))
363
-				{
364
-					$tab_top = 88 + $height_incoterms;
365
-					$tab_top_alt = $tab_top;
366
-
367
-					$pdf->SetFont('','B', $default_font_size - 2);
368
-					$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top-1, $outputlangs->transnoentities("TrackingNumber")." : " . $object->tracking_number, 0, 1, false, true, 'L');
369
-
370
-					$tab_top_alt = $pdf->GetY();
371
-					//$tab_top_alt += 1;
372
-
373
-					// Tracking number
374
-					if (! empty($object->tracking_number))
375
-					{
376
-						$object->getUrlTrackingStatus($object->tracking_number);
377
-						if (! empty($object->tracking_url))
378
-						{
379
-							if ($object->shipping_method_id > 0)
380
-							{
381
-								// Get code using getLabelFromKey
382
-								$code=$outputlangs->getLabelFromKey($this->db,$object->shipping_method_id,'c_shipment_mode','rowid','code');
383
-								$label='';
384
-								if ($object->tracking_url != $object->tracking_number) $label.=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
385
-								$label.=$outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
386
-								//var_dump($object->tracking_url != $object->tracking_number);exit;
387
-								if ($object->tracking_url != $object->tracking_number)
388
-								{
389
-									$label.=" : ";
390
-									$label.=$object->tracking_url;
391
-								}
392
-								$pdf->SetFont('','B', $default_font_size - 2);
393
-								$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top_alt, $label, 0, 1, false, true, 'L');
394
-
395
-								$tab_top_alt = $pdf->GetY();
396
-							}
397
-						}
398
-					}
399
-
400
-					// Notes
401
-					if (! empty($object->note_public))
402
-					{
403
-						$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
404
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1);
405
-					}
406
-
407
-					$nexY = $pdf->GetY();
408
-					$height_note=$nexY-$tab_top;
409
-
410
-					// Rect prend une longueur en 3eme param
411
-					$pdf->SetDrawColor(192,192,192);
412
-					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
413
-
414
-					$tab_height = $tab_height - $height_note;
415
-					$tab_top = $nexY+6;
416
-				}
417
-				else
418
-				{
419
-					$height_note=0;
420
-				}
421
-
422
-				$iniY = $tab_top + 7;
423
-				$curY = $tab_top + 7;
424
-				$nexY = $tab_top + 7;
425
-
426
-				// Loop on each lines
427
-				for ($i = 0; $i < $nblignes; $i++)
428
-				{
429
-					$curY = $nexY;
430
-					$pdf->SetFont('','', $default_font_size - 1);   // Into loop to work with multipage
431
-					$pdf->SetTextColor(0,0,0);
432
-
433
-					// Define size of image if we need it
434
-					$imglinesize=array();
435
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
436
-
437
-					$pdf->setTopMargin($tab_top_newpage);
438
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
439
-					$pageposbefore=$pdf->getPage();
440
-
441
-					$showpricebeforepagebreak=1;
442
-					$posYAfterImage=0;
443
-					$posYAfterDescription=0;
444
-
445
-					// We start with Photo of product line
446
-					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot)))	// If photo too high, we moved completely on new page
447
-					{
448
-						$pdf->AddPage('','',true);
449
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
450
-						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
451
-						$pdf->setPage($pageposbefore+1);
452
-
453
-						$curY = $tab_top_newpage;
454
-						$showpricebeforepagebreak=0;
455
-					}
456
-
457
-					if (isset($imglinesize['width']) && isset($imglinesize['height']))
458
-					{
459
-						$curX = $this->posxpicture-1;
460
-						$pdf->Image($realpatharray[$i], $curX + (($this->posxweightvol-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
461
-						// $pdf->Image does not increase value return by getY, so we save it manually
462
-						$posYAfterImage=$curY+$imglinesize['height'];
463
-					}
464
-
465
-					// Description of product line
466
-					$curX = $this->posxdesc-1;
467
-
468
-					$pdf->startTransaction();
469
-					pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
470
-
471
-					$pageposafter=$pdf->getPage();
472
-					if ($pageposafter > $pageposbefore)	// There is a pagebreak
473
-					{
474
-						$pdf->rollbackTransaction(true);
475
-						$pageposafter=$pageposbefore;
476
-						//print $pageposafter.'-'.$pageposbefore;exit;
477
-						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
478
-						pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
479
-
480
-						$pageposafter=$pdf->getPage();
481
-						$posyafter=$pdf->GetY();
482
-						//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
483
-						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
484
-						{
485
-							if ($i == ($nblignes-1))	// No more lines, and no space left to show total, so we create a new page
486
-							{
487
-								$pdf->AddPage('','',true);
488
-								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
489
-								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
490
-								$pdf->setPage($pageposafter+1);
491
-							}
492
-						}
493
-						else
494
-						{
495
-							// We found a page break
496
-							$showpricebeforepagebreak=0;
497
-						}
498
-					}
499
-					else	// No pagebreak
500
-					{
501
-						$pdf->commitTransaction();
502
-					}
503
-					$posYAfterDescription=$pdf->GetY();
504
-
505
-					$nexY = $pdf->GetY();
506
-					$pageposafter=$pdf->getPage();
507
-
508
-					$pdf->setPage($pageposbefore);
509
-					$pdf->setTopMargin($this->marge_haute);
510
-					$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
511
-
512
-					// We suppose that a too long description or photo were moved completely on next page
513
-					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
514
-						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
515
-					}
516
-
517
-					// We suppose that a too long description is moved completely on next page
518
-					if ($pageposafter > $pageposbefore) {
519
-						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
520
-					}
521
-
522
-					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
523
-
524
-					$pdf->SetXY($this->posxweightvol, $curY);
525
-					$weighttxt='';
526
-					if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->weight)
527
-					{
528
-					    $weighttxt=round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->weight_units,"weight");
529
-					}
530
-					$voltxt='';
531
-					if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->volume)
532
-					{
533
-					    $voltxt=round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->volume_units?$object->lines[$i]->volume_units:0,"volume");
534
-					}
535
-
536
-					if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
537
-					{
538
-						$pdf->writeHTMLCell($this->posxqtyordered - $this->posxweightvol + 2, 3, $this->posxweightvol - 1, $curY, $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt, 0, 0, false, true, 'C');
539
-						//$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 3, $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt,'','C');
540
-					}
541
-
542
-					if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
543
-					{
544
-					   $pdf->SetXY($this->posxqtyordered, $curY);
545
-					   $pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 3, $object->lines[$i]->qty_asked,'','C');
546
-					}
547
-
548
-					if (empty($conf->global->SHIPPING_PDF_HIDE_QTYTOSHIP))
549
-					{
550
-						$pdf->SetXY($this->posxqtytoship, $curY);
551
-						$pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 3, $object->lines[$i]->qty_shipped,'','C');
552
-					}
553
-
554
-					if(!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT))
555
-					{
556
-						$pdf->SetXY($this->posxpuht, $curY);
557
-						$pdf->MultiCell(($this->posxtotalht - $this->posxpuht-1), 3, price($object->lines[$i]->subprice, 0, $outputlangs),'','R');
558
-
559
-						$pdf->SetXY($this->posxtotalht, $curY);
560
-						$pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 3, price($object->lines[$i]->total_ht, 0, $outputlangs),'','R');
561
-					}
562
-
563
-					$nexY+=3;
564
-					if ($weighttxt && $voltxt) $nexY+=2;
565
-
566
-					// Add line
567
-					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
568
-					{
569
-						$pdf->setPage($pageposafter);
570
-						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80)));
571
-						//$pdf->SetDrawColor(190,190,200);
572
-						$pdf->line($this->marge_gauche, $nexY-1, $this->page_largeur - $this->marge_droite, $nexY-1);
573
-						$pdf->SetLineStyle(array('dash'=>0));
574
-					}
575
-
576
-					// Detect if some page were added automatically and output _tableau for past pages
577
-					while ($pagenb < $pageposafter)
578
-					{
579
-						$pdf->setPage($pagenb);
580
-						if ($pagenb == 1)
581
-						{
582
-							$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
583
-						}
584
-						else
585
-						{
586
-							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
587
-						}
588
-						$this->_pagefoot($pdf,$object,$outputlangs,1);
589
-						$pagenb++;
590
-						$pdf->setPage($pagenb);
591
-						$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
592
-						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
593
-					}
594
-					if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak)
595
-					{
596
-						if ($pagenb == 1)
597
-						{
598
-							$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
599
-						}
600
-						else
601
-						{
602
-							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
603
-						}
604
-						$this->_pagefoot($pdf,$object,$outputlangs,1);
605
-						// New page
606
-						$pdf->AddPage();
607
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
608
-						$pagenb++;
609
-						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
610
-					}
611
-				}
612
-
613
-				// Show square
614
-				if ($pagenb == 1)
615
-				{
616
-					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
617
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
618
-				}
619
-				else
620
-				{
621
-					$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
622
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
623
-				}
624
-
625
-				// Affiche zone totaux
626
-				$posy=$this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs);
627
-
628
-				// Pied de page
629
-				$this->_pagefoot($pdf,$object,$outputlangs);
630
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
631
-
632
-				$pdf->Close();
633
-
634
-				$pdf->Output($file,'F');
635
-
636
-				// Add pdfgeneration hook
637
-				$hookmanager->initHooks(array('pdfgeneration'));
638
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
639
-				global $action;
640
-				$reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
641
-
642
-				if (! empty($conf->global->MAIN_UMASK))
643
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
644
-
645
-				$this->result = array('fullpath'=>$file);
646
-
647
-				return 1;	// No error
648
-			}
649
-			else
650
-			{
651
-				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
652
-				return 0;
653
-			}
654
-		}
655
-		else
656
-		{
657
-			$this->error=$langs->transnoentities("ErrorConstantNotDefined","EXP_OUTPUTDIR");
658
-			return 0;
659
-		}
660
-	}
661
-
662
-	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
663
-	/**
664
-	 *	Show total to pay
665
-	 *
666
-	 *	@param	PDF			$pdf           Object PDF
667
-	 *	@param  Facture		$object         Object invoice
668
-	 *	@param  int			$deja_regle     Montant deja regle
669
-	 *	@param	int			$posy			Position depart
670
-	 *	@param	Translate	$outputlangs	Objet langs
671
-	 *	@return int							Position pour suite
672
-	 */
673
-	function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs)
674
-	{
675
-		// phpcs:enable
676
-		global $conf,$mysoc;
310
+                $pdf->Open();
311
+                $pagenb=0;
312
+                $pdf->SetDrawColor(128,128,128);
313
+
314
+                if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
315
+
316
+                $pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
317
+                $pdf->SetSubject($outputlangs->transnoentities("Shipment"));
318
+                $pdf->SetCreator("Dolibarr ".DOL_VERSION);
319
+                $pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
320
+                $pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Shipment"));
321
+                if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
322
+
323
+                $pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
324
+
325
+                // New page
326
+                $pdf->AddPage();
327
+                if (! empty($tplidx)) $pdf->useTemplate($tplidx);
328
+                $pagenb++;
329
+                $this->_pagehead($pdf, $object, 1, $outputlangs);
330
+                $pdf->SetFont('','', $default_font_size - 1);
331
+                $pdf->MultiCell(0, 3, '');		// Set interline to 3
332
+                $pdf->SetTextColor(0,0,0);
333
+
334
+                $tab_top = 90;
335
+                $tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
336
+                $tab_height = 130;
337
+                $tab_height_newpage = 150;
338
+
339
+                // Incoterm
340
+                $height_incoterms = 0;
341
+                if ($conf->incoterm->enabled)
342
+                {
343
+                    $desc_incoterms = $object->getIncotermsForPDF();
344
+                    if ($desc_incoterms)
345
+                    {
346
+                        $tab_top = 88;
347
+
348
+                        $pdf->SetFont('','', $default_font_size - 1);
349
+                        $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
350
+                        $nexY = $pdf->GetY();
351
+                        $height_incoterms=$nexY-$tab_top;
352
+
353
+                        // Rect prend une longueur en 3eme param
354
+                        $pdf->SetDrawColor(192,192,192);
355
+                        $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1);
356
+
357
+                        $tab_top = $nexY+6;
358
+                        $height_incoterms += 4;
359
+                    }
360
+                }
361
+
362
+                if (! empty($object->note_public) || ! empty($object->tracking_number))
363
+                {
364
+                    $tab_top = 88 + $height_incoterms;
365
+                    $tab_top_alt = $tab_top;
366
+
367
+                    $pdf->SetFont('','B', $default_font_size - 2);
368
+                    $pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top-1, $outputlangs->transnoentities("TrackingNumber")." : " . $object->tracking_number, 0, 1, false, true, 'L');
369
+
370
+                    $tab_top_alt = $pdf->GetY();
371
+                    //$tab_top_alt += 1;
372
+
373
+                    // Tracking number
374
+                    if (! empty($object->tracking_number))
375
+                    {
376
+                        $object->getUrlTrackingStatus($object->tracking_number);
377
+                        if (! empty($object->tracking_url))
378
+                        {
379
+                            if ($object->shipping_method_id > 0)
380
+                            {
381
+                                // Get code using getLabelFromKey
382
+                                $code=$outputlangs->getLabelFromKey($this->db,$object->shipping_method_id,'c_shipment_mode','rowid','code');
383
+                                $label='';
384
+                                if ($object->tracking_url != $object->tracking_number) $label.=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
385
+                                $label.=$outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
386
+                                //var_dump($object->tracking_url != $object->tracking_number);exit;
387
+                                if ($object->tracking_url != $object->tracking_number)
388
+                                {
389
+                                    $label.=" : ";
390
+                                    $label.=$object->tracking_url;
391
+                                }
392
+                                $pdf->SetFont('','B', $default_font_size - 2);
393
+                                $pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top_alt, $label, 0, 1, false, true, 'L');
394
+
395
+                                $tab_top_alt = $pdf->GetY();
396
+                            }
397
+                        }
398
+                    }
399
+
400
+                    // Notes
401
+                    if (! empty($object->note_public))
402
+                    {
403
+                        $pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
404
+                        $pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1);
405
+                    }
406
+
407
+                    $nexY = $pdf->GetY();
408
+                    $height_note=$nexY-$tab_top;
409
+
410
+                    // Rect prend une longueur en 3eme param
411
+                    $pdf->SetDrawColor(192,192,192);
412
+                    $pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
413
+
414
+                    $tab_height = $tab_height - $height_note;
415
+                    $tab_top = $nexY+6;
416
+                }
417
+                else
418
+                {
419
+                    $height_note=0;
420
+                }
421
+
422
+                $iniY = $tab_top + 7;
423
+                $curY = $tab_top + 7;
424
+                $nexY = $tab_top + 7;
425
+
426
+                // Loop on each lines
427
+                for ($i = 0; $i < $nblignes; $i++)
428
+                {
429
+                    $curY = $nexY;
430
+                    $pdf->SetFont('','', $default_font_size - 1);   // Into loop to work with multipage
431
+                    $pdf->SetTextColor(0,0,0);
432
+
433
+                    // Define size of image if we need it
434
+                    $imglinesize=array();
435
+                    if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
436
+
437
+                    $pdf->setTopMargin($tab_top_newpage);
438
+                    $pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
439
+                    $pageposbefore=$pdf->getPage();
440
+
441
+                    $showpricebeforepagebreak=1;
442
+                    $posYAfterImage=0;
443
+                    $posYAfterDescription=0;
444
+
445
+                    // We start with Photo of product line
446
+                    if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot)))	// If photo too high, we moved completely on new page
447
+                    {
448
+                        $pdf->AddPage('','',true);
449
+                        if (! empty($tplidx)) $pdf->useTemplate($tplidx);
450
+                        if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
451
+                        $pdf->setPage($pageposbefore+1);
452
+
453
+                        $curY = $tab_top_newpage;
454
+                        $showpricebeforepagebreak=0;
455
+                    }
456
+
457
+                    if (isset($imglinesize['width']) && isset($imglinesize['height']))
458
+                    {
459
+                        $curX = $this->posxpicture-1;
460
+                        $pdf->Image($realpatharray[$i], $curX + (($this->posxweightvol-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
461
+                        // $pdf->Image does not increase value return by getY, so we save it manually
462
+                        $posYAfterImage=$curY+$imglinesize['height'];
463
+                    }
464
+
465
+                    // Description of product line
466
+                    $curX = $this->posxdesc-1;
467
+
468
+                    $pdf->startTransaction();
469
+                    pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
470
+
471
+                    $pageposafter=$pdf->getPage();
472
+                    if ($pageposafter > $pageposbefore)	// There is a pagebreak
473
+                    {
474
+                        $pdf->rollbackTransaction(true);
475
+                        $pageposafter=$pageposbefore;
476
+                        //print $pageposafter.'-'.$pageposbefore;exit;
477
+                        $pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
478
+                        pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
479
+
480
+                        $pageposafter=$pdf->getPage();
481
+                        $posyafter=$pdf->GetY();
482
+                        //var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
483
+                        if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
484
+                        {
485
+                            if ($i == ($nblignes-1))	// No more lines, and no space left to show total, so we create a new page
486
+                            {
487
+                                $pdf->AddPage('','',true);
488
+                                if (! empty($tplidx)) $pdf->useTemplate($tplidx);
489
+                                if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
490
+                                $pdf->setPage($pageposafter+1);
491
+                            }
492
+                        }
493
+                        else
494
+                        {
495
+                            // We found a page break
496
+                            $showpricebeforepagebreak=0;
497
+                        }
498
+                    }
499
+                    else	// No pagebreak
500
+                    {
501
+                        $pdf->commitTransaction();
502
+                    }
503
+                    $posYAfterDescription=$pdf->GetY();
504
+
505
+                    $nexY = $pdf->GetY();
506
+                    $pageposafter=$pdf->getPage();
507
+
508
+                    $pdf->setPage($pageposbefore);
509
+                    $pdf->setTopMargin($this->marge_haute);
510
+                    $pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
511
+
512
+                    // We suppose that a too long description or photo were moved completely on next page
513
+                    if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
514
+                        $pdf->setPage($pageposafter); $curY = $tab_top_newpage;
515
+                    }
516
+
517
+                    // We suppose that a too long description is moved completely on next page
518
+                    if ($pageposafter > $pageposbefore) {
519
+                        $pdf->setPage($pageposafter); $curY = $tab_top_newpage;
520
+                    }
521
+
522
+                    $pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
523
+
524
+                    $pdf->SetXY($this->posxweightvol, $curY);
525
+                    $weighttxt='';
526
+                    if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->weight)
527
+                    {
528
+                        $weighttxt=round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->weight_units,"weight");
529
+                    }
530
+                    $voltxt='';
531
+                    if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->volume)
532
+                    {
533
+                        $voltxt=round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->volume_units?$object->lines[$i]->volume_units:0,"volume");
534
+                    }
535
+
536
+                    if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
537
+                    {
538
+                        $pdf->writeHTMLCell($this->posxqtyordered - $this->posxweightvol + 2, 3, $this->posxweightvol - 1, $curY, $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt, 0, 0, false, true, 'C');
539
+                        //$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 3, $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt,'','C');
540
+                    }
541
+
542
+                    if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
543
+                    {
544
+                        $pdf->SetXY($this->posxqtyordered, $curY);
545
+                        $pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 3, $object->lines[$i]->qty_asked,'','C');
546
+                    }
547
+
548
+                    if (empty($conf->global->SHIPPING_PDF_HIDE_QTYTOSHIP))
549
+                    {
550
+                        $pdf->SetXY($this->posxqtytoship, $curY);
551
+                        $pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 3, $object->lines[$i]->qty_shipped,'','C');
552
+                    }
553
+
554
+                    if(!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT))
555
+                    {
556
+                        $pdf->SetXY($this->posxpuht, $curY);
557
+                        $pdf->MultiCell(($this->posxtotalht - $this->posxpuht-1), 3, price($object->lines[$i]->subprice, 0, $outputlangs),'','R');
558
+
559
+                        $pdf->SetXY($this->posxtotalht, $curY);
560
+                        $pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 3, price($object->lines[$i]->total_ht, 0, $outputlangs),'','R');
561
+                    }
562
+
563
+                    $nexY+=3;
564
+                    if ($weighttxt && $voltxt) $nexY+=2;
565
+
566
+                    // Add line
567
+                    if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
568
+                    {
569
+                        $pdf->setPage($pageposafter);
570
+                        $pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80)));
571
+                        //$pdf->SetDrawColor(190,190,200);
572
+                        $pdf->line($this->marge_gauche, $nexY-1, $this->page_largeur - $this->marge_droite, $nexY-1);
573
+                        $pdf->SetLineStyle(array('dash'=>0));
574
+                    }
575
+
576
+                    // Detect if some page were added automatically and output _tableau for past pages
577
+                    while ($pagenb < $pageposafter)
578
+                    {
579
+                        $pdf->setPage($pagenb);
580
+                        if ($pagenb == 1)
581
+                        {
582
+                            $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
583
+                        }
584
+                        else
585
+                        {
586
+                            $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
587
+                        }
588
+                        $this->_pagefoot($pdf,$object,$outputlangs,1);
589
+                        $pagenb++;
590
+                        $pdf->setPage($pagenb);
591
+                        $pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
592
+                        if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
593
+                    }
594
+                    if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak)
595
+                    {
596
+                        if ($pagenb == 1)
597
+                        {
598
+                            $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
599
+                        }
600
+                        else
601
+                        {
602
+                            $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
603
+                        }
604
+                        $this->_pagefoot($pdf,$object,$outputlangs,1);
605
+                        // New page
606
+                        $pdf->AddPage();
607
+                        if (! empty($tplidx)) $pdf->useTemplate($tplidx);
608
+                        $pagenb++;
609
+                        if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
610
+                    }
611
+                }
612
+
613
+                // Show square
614
+                if ($pagenb == 1)
615
+                {
616
+                    $this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
617
+                    $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
618
+                }
619
+                else
620
+                {
621
+                    $this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
622
+                    $bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
623
+                }
624
+
625
+                // Affiche zone totaux
626
+                $posy=$this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs);
627
+
628
+                // Pied de page
629
+                $this->_pagefoot($pdf,$object,$outputlangs);
630
+                if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
631
+
632
+                $pdf->Close();
633
+
634
+                $pdf->Output($file,'F');
635
+
636
+                // Add pdfgeneration hook
637
+                $hookmanager->initHooks(array('pdfgeneration'));
638
+                $parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
639
+                global $action;
640
+                $reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
641
+
642
+                if (! empty($conf->global->MAIN_UMASK))
643
+                @chmod($file, octdec($conf->global->MAIN_UMASK));
644
+
645
+                $this->result = array('fullpath'=>$file);
646
+
647
+                return 1;	// No error
648
+            }
649
+            else
650
+            {
651
+                $this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
652
+                return 0;
653
+            }
654
+        }
655
+        else
656
+        {
657
+            $this->error=$langs->transnoentities("ErrorConstantNotDefined","EXP_OUTPUTDIR");
658
+            return 0;
659
+        }
660
+    }
661
+
662
+    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
663
+    /**
664
+     *	Show total to pay
665
+     *
666
+     *	@param	PDF			$pdf           Object PDF
667
+     *	@param  Facture		$object         Object invoice
668
+     *	@param  int			$deja_regle     Montant deja regle
669
+     *	@param	int			$posy			Position depart
670
+     *	@param	Translate	$outputlangs	Objet langs
671
+     *	@return int							Position pour suite
672
+     */
673
+    function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs)
674
+    {
675
+        // phpcs:enable
676
+        global $conf,$mysoc;
677 677
 
678 678
         $sign=1;
679 679
 
680 680
         $default_font_size = pdf_getPDFFontSize($outputlangs);
681 681
 
682
-		$tab2_top = $posy;
683
-		$tab2_hl = 4;
684
-		$pdf->SetFont('','B', $default_font_size - 1);
682
+        $tab2_top = $posy;
683
+        $tab2_hl = 4;
684
+        $pdf->SetFont('','B', $default_font_size - 1);
685 685
 
686
-		// Tableau total
687
-		$col1x = $this->posxweightvol-50; $col2x = $this->posxweightvol;
688
-		/*if ($this->page_largeur < 210) // To work with US executive format
686
+        // Tableau total
687
+        $col1x = $this->posxweightvol-50; $col2x = $this->posxweightvol;
688
+        /*if ($this->page_largeur < 210) // To work with US executive format
689 689
 		{
690 690
 			$col2x-=20;
691 691
 		}*/
692
-		if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED)) $largcol2 = ($this->posxqtyordered - $this->posxweightvol);
693
-		else $largcol2 = ($this->posxqtytoship - $this->posxweightvol);
694
-
695
-		$useborder=0;
696
-		$index = 0;
697
-
698
-		$totalWeighttoshow='';
699
-		$totalVolumetoshow='';
700
-
701
-		// Load dim data
702
-		$tmparray=$object->getTotalWeightVolume();
703
-		$totalWeight=$tmparray['weight'];
704
-		$totalVolume=$tmparray['volume'];
705
-		$totalOrdered=$tmparray['ordered'];
706
-		$totalToShip=$tmparray['toship'];
707
-		// Set trueVolume and volume_units not currently stored into database
708
-		if ($object->trueWidth && $object->trueHeight && $object->trueDepth)
709
-		{
710
-		    $object->trueVolume=price(($object->trueWidth * $object->trueHeight * $object->trueDepth), 0, $outputlangs, 0, 0);
711
-		    $object->volume_units=$object->size_units * 3;
712
-		}
692
+        if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED)) $largcol2 = ($this->posxqtyordered - $this->posxweightvol);
693
+        else $largcol2 = ($this->posxqtytoship - $this->posxweightvol);
694
+
695
+        $useborder=0;
696
+        $index = 0;
697
+
698
+        $totalWeighttoshow='';
699
+        $totalVolumetoshow='';
700
+
701
+        // Load dim data
702
+        $tmparray=$object->getTotalWeightVolume();
703
+        $totalWeight=$tmparray['weight'];
704
+        $totalVolume=$tmparray['volume'];
705
+        $totalOrdered=$tmparray['ordered'];
706
+        $totalToShip=$tmparray['toship'];
707
+        // Set trueVolume and volume_units not currently stored into database
708
+        if ($object->trueWidth && $object->trueHeight && $object->trueDepth)
709
+        {
710
+            $object->trueVolume=price(($object->trueWidth * $object->trueHeight * $object->trueDepth), 0, $outputlangs, 0, 0);
711
+            $object->volume_units=$object->size_units * 3;
712
+        }
713 713
 
714
-		if ($totalWeight!='') $totalWeighttoshow=showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs);
715
-		if ($totalVolume!='') $totalVolumetoshow=showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs);
716
-		if ($object->trueWeight) $totalWeighttoshow=showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs);
717
-		if ($object->trueVolume) $totalVolumetoshow=showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs);
714
+        if ($totalWeight!='') $totalWeighttoshow=showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs);
715
+        if ($totalVolume!='') $totalVolumetoshow=showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs);
716
+        if ($object->trueWeight) $totalWeighttoshow=showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs);
717
+        if ($object->trueVolume) $totalVolumetoshow=showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs);
718 718
 
719
-    	$pdf->SetFillColor(255,255,255);
720
-    	$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
721
-    	$pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("Total"), 0, 'L', 1);
719
+        $pdf->SetFillColor(255,255,255);
720
+        $pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
721
+        $pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("Total"), 0, 'L', 1);
722 722
 
723 723
         if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
724 724
         {
725 725
             $pdf->SetXY($this->posxqtyordered, $tab2_top + $tab2_hl * $index);
726
-        	$pdf->MultiCell($this->posxqtytoship - $this->posxqtyordered, $tab2_hl, $totalOrdered, 0, 'C', 1);
726
+            $pdf->MultiCell($this->posxqtytoship - $this->posxqtyordered, $tab2_hl, $totalOrdered, 0, 'C', 1);
727 727
         }
728 728
 
729 729
         if (empty($conf->global->SHIPPING_PDF_HIDE_QTYTOSHIP))
730 730
         {
731
-        	$pdf->SetXY($this->posxqtytoship, $tab2_top + $tab2_hl * $index);
732
-        	$pdf->MultiCell($this->posxpuht - $this->posxqtytoship, $tab2_hl, $totalToShip, 0, 'C', 1);
731
+            $pdf->SetXY($this->posxqtytoship, $tab2_top + $tab2_hl * $index);
732
+            $pdf->MultiCell($this->posxpuht - $this->posxqtytoship, $tab2_hl, $totalToShip, 0, 'C', 1);
733 733
         }
734 734
 
735
-		if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT))
736
-		{
737
-	    	$pdf->SetXY($this->posxpuht, $tab2_top + $tab2_hl * $index);
738
-	    	$pdf->MultiCell($this->posxtotalht - $this->posxpuht, $tab2_hl, '', 0, 'C', 1);
735
+        if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT))
736
+        {
737
+            $pdf->SetXY($this->posxpuht, $tab2_top + $tab2_hl * $index);
738
+            $pdf->MultiCell($this->posxtotalht - $this->posxpuht, $tab2_hl, '', 0, 'C', 1);
739 739
 
740
-	    	$pdf->SetXY($this->posxtotalht, $tab2_top + $tab2_hl * $index);
741
-	    	$pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxtotalht, $tab2_hl, price($object->total_ht, 0, $outputlangs), 0, 'C', 1);
742
-		}
740
+            $pdf->SetXY($this->posxtotalht, $tab2_top + $tab2_hl * $index);
741
+            $pdf->MultiCell($this->page_largeur - $this->marge_droite - $this->posxtotalht, $tab2_hl, price($object->total_ht, 0, $outputlangs), 0, 'C', 1);
742
+        }
743 743
 
744
-		if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
745
-		{
746
-			// Total Weight
747
-			if ($totalWeighttoshow)
748
-			{
749
-	    		$pdf->SetXY($this->posxweightvol, $tab2_top + $tab2_hl * $index);
750
-	    		$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), $tab2_hl, $totalWeighttoshow, 0, 'C', 1);
751
-
752
-	    		$index++;
753
-			}
754
-			if ($totalVolumetoshow)
755
-			{
756
-	    		$pdf->SetXY($this->posxweightvol, $tab2_top + $tab2_hl * $index);
757
-	    		$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), $tab2_hl, $totalVolumetoshow, 0, 'C', 1);
758
-
759
-			    $index++;
760
-			}
761
-			if (! $totalWeighttoshow && ! $totalVolumetoshow) $index++;
762
-		}
763
-
764
-		$pdf->SetTextColor(0,0,0);
765
-
766
-		return ($tab2_top + ($tab2_hl * $index));
767
-	}
768
-
769
-	/**
770
-	 *   Show table for lines
771
-	 *
772
-	 *   @param		PDF			$pdf     		Object PDF
773
-	 *   @param		string		$tab_top		Top position of table
774
-	 *   @param		string		$tab_height		Height of table (rectangle)
775
-	 *   @param		int			$nexY			Y
776
-	 *   @param		Translate	$outputlangs	Langs object
777
-	 *   @param		int			$hidetop		Hide top bar of array
778
-	 *   @param		int			$hidebottom		Hide bottom bar of array
779
-	 *   @return	void
780
-	 */
781
-	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop=0, $hidebottom=0)
782
-	{
783
-		global $conf;
784
-
785
-		// Force to disable hidetop and hidebottom
786
-		$hidebottom=0;
787
-		if ($hidetop) $hidetop=-1;
788
-
789
-		$default_font_size = pdf_getPDFFontSize($outputlangs);
790
-
791
-		// Amount in (at tab_top - 1)
792
-		$pdf->SetTextColor(0,0,0);
793
-		$pdf->SetFont('','',$default_font_size - 2);
794
-
795
-		// Output Rect
796
-		$this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param
797
-
798
-		$pdf->SetDrawColor(128,128,128);
799
-		$pdf->SetFont('','', $default_font_size - 1);
800
-
801
-		if (empty($hidetop))
802
-		{
803
-			$pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);
744
+        if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
745
+        {
746
+            // Total Weight
747
+            if ($totalWeighttoshow)
748
+            {
749
+                $pdf->SetXY($this->posxweightvol, $tab2_top + $tab2_hl * $index);
750
+                $pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), $tab2_hl, $totalWeighttoshow, 0, 'C', 1);
804 751
 
805
-			$pdf->SetXY($this->posxdesc-1, $tab_top+1);
806
-			$pdf->MultiCell($this->posxqtyordered - $this->posxdesc, 2, $outputlangs->transnoentities("Description"), '', 'L');
807
-		}
752
+                $index++;
753
+            }
754
+            if ($totalVolumetoshow)
755
+            {
756
+                $pdf->SetXY($this->posxweightvol, $tab2_top + $tab2_hl * $index);
757
+                $pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), $tab2_hl, $totalVolumetoshow, 0, 'C', 1);
808 758
 
809
-		if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
810
-		{
811
-			$pdf->line($this->posxweightvol-1, $tab_top, $this->posxweightvol-1, $tab_top + $tab_height);
812
-			if (empty($hidetop))
813
-			{
814
-				$pdf->SetXY($this->posxweightvol-1, $tab_top+1);
815
-				$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 2, $outputlangs->transnoentities("WeightVolShort"),'','C');
816
-			}
817
-		}
759
+                $index++;
760
+            }
761
+            if (! $totalWeighttoshow && ! $totalVolumetoshow) $index++;
762
+        }
763
+
764
+        $pdf->SetTextColor(0,0,0);
765
+
766
+        return ($tab2_top + ($tab2_hl * $index));
767
+    }
768
+
769
+    /**
770
+     *   Show table for lines
771
+     *
772
+     *   @param		PDF			$pdf     		Object PDF
773
+     *   @param		string		$tab_top		Top position of table
774
+     *   @param		string		$tab_height		Height of table (rectangle)
775
+     *   @param		int			$nexY			Y
776
+     *   @param		Translate	$outputlangs	Langs object
777
+     *   @param		int			$hidetop		Hide top bar of array
778
+     *   @param		int			$hidebottom		Hide bottom bar of array
779
+     *   @return	void
780
+     */
781
+    function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop=0, $hidebottom=0)
782
+    {
783
+        global $conf;
784
+
785
+        // Force to disable hidetop and hidebottom
786
+        $hidebottom=0;
787
+        if ($hidetop) $hidetop=-1;
788
+
789
+        $default_font_size = pdf_getPDFFontSize($outputlangs);
790
+
791
+        // Amount in (at tab_top - 1)
792
+        $pdf->SetTextColor(0,0,0);
793
+        $pdf->SetFont('','',$default_font_size - 2);
794
+
795
+        // Output Rect
796
+        $this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param
797
+
798
+        $pdf->SetDrawColor(128,128,128);
799
+        $pdf->SetFont('','', $default_font_size - 1);
800
+
801
+        if (empty($hidetop))
802
+        {
803
+            $pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);
804
+
805
+            $pdf->SetXY($this->posxdesc-1, $tab_top+1);
806
+            $pdf->MultiCell($this->posxqtyordered - $this->posxdesc, 2, $outputlangs->transnoentities("Description"), '', 'L');
807
+        }
808
+
809
+        if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
810
+        {
811
+            $pdf->line($this->posxweightvol-1, $tab_top, $this->posxweightvol-1, $tab_top + $tab_height);
812
+            if (empty($hidetop))
813
+            {
814
+                $pdf->SetXY($this->posxweightvol-1, $tab_top+1);
815
+                $pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 2, $outputlangs->transnoentities("WeightVolShort"),'','C');
816
+            }
817
+        }
818 818
 
819 819
         if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
820 820
         {
821 821
             $pdf->line($this->posxqtyordered-1, $tab_top, $this->posxqtyordered-1, $tab_top + $tab_height);
822
-    		if (empty($hidetop))
823
-    		{
824
-    			$pdf->SetXY($this->posxqtyordered-1, $tab_top+1);
825
-    			$pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 2, $outputlangs->transnoentities("QtyOrdered"),'','C');
826
-    		}
822
+            if (empty($hidetop))
823
+            {
824
+                $pdf->SetXY($this->posxqtyordered-1, $tab_top+1);
825
+                $pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 2, $outputlangs->transnoentities("QtyOrdered"),'','C');
826
+            }
827 827
         }
828 828
 
829 829
         if (empty($conf->global->SHIPPING_PDF_HIDE_QTYTOSHIP))
830 830
         {
831
-			$pdf->line($this->posxqtytoship-1, $tab_top, $this->posxqtytoship-1, $tab_top + $tab_height);
832
-			if (empty($hidetop))
833
-			{
834
-				$pdf->SetXY($this->posxqtytoship, $tab_top+1);
835
-				$pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 2, $outputlangs->transnoentities("QtyToShip"),'','C');
836
-			}
831
+            $pdf->line($this->posxqtytoship-1, $tab_top, $this->posxqtytoship-1, $tab_top + $tab_height);
832
+            if (empty($hidetop))
833
+            {
834
+                $pdf->SetXY($this->posxqtytoship, $tab_top+1);
835
+                $pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 2, $outputlangs->transnoentities("QtyToShip"),'','C');
836
+            }
837 837
         }
838 838
 
839
-		if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT)) {
840
-
841
-			$pdf->line($this->posxpuht-1, $tab_top, $this->posxpuht-1, $tab_top + $tab_height);
842
-			if (empty($hidetop))
843
-			{
844
-				$pdf->SetXY($this->posxpuht-1, $tab_top+1);
845
-				$pdf->MultiCell(($this->posxtotalht - $this->posxpuht), 2, $outputlangs->transnoentities("PriceUHT"),'','C');
846
-			}
847
-
848
-			$pdf->line($this->posxtotalht-1, $tab_top, $this->posxtotalht-1, $tab_top + $tab_height);
849
-			if (empty($hidetop))
850
-			{
851
-				$pdf->SetXY($this->posxtotalht-1, $tab_top+1);
852
-				$pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 2, $outputlangs->transnoentities("TotalHT"),'','C');
853
-			}
854
-		}
855
-	}
856
-
857
-	/**
858
-	 *  Show top header of page.
859
-	 *
860
-	 *  @param	PDF			$pdf     		Object PDF
861
-	 *  @param  Object		$object     	Object to show
862
-	 *  @param  int	    	$showaddress    0=no, 1=yes
863
-	 *  @param  Translate	$outputlangs	Object lang for output
864
-	 *  @return	void
865
-	 */
866
-	function _pagehead(&$pdf, $object, $showaddress, $outputlangs)
867
-	{
868
-		global $conf,$langs,$mysoc;
869
-
870
-		$langs->load("orders");
871
-
872
-		$default_font_size = pdf_getPDFFontSize($outputlangs);
873
-
874
-		pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
875
-
876
-		// Show Draft Watermark
877
-		if($object->statut==0 && (! empty($conf->global->SHIPPING_DRAFT_WATERMARK)) )
878
-		{
879
-            		pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->SHIPPING_DRAFT_WATERMARK);
880
-		}
839
+        if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT)) {
881 840
 
882
-		//Prepare la suite
883
-		$pdf->SetTextColor(0,0,60);
884
-		$pdf->SetFont('','B', $default_font_size + 3);
841
+            $pdf->line($this->posxpuht-1, $tab_top, $this->posxpuht-1, $tab_top + $tab_height);
842
+            if (empty($hidetop))
843
+            {
844
+                $pdf->SetXY($this->posxpuht-1, $tab_top+1);
845
+                $pdf->MultiCell(($this->posxtotalht - $this->posxpuht), 2, $outputlangs->transnoentities("PriceUHT"),'','C');
846
+            }
885 847
 
886
-		$w = 110;
848
+            $pdf->line($this->posxtotalht-1, $tab_top, $this->posxtotalht-1, $tab_top + $tab_height);
849
+            if (empty($hidetop))
850
+            {
851
+                $pdf->SetXY($this->posxtotalht-1, $tab_top+1);
852
+                $pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 2, $outputlangs->transnoentities("TotalHT"),'','C');
853
+            }
854
+        }
855
+    }
887 856
 
888
-		$posy=$this->marge_haute;
889
-		$posx=$this->page_largeur-$this->marge_droite-$w;
857
+    /**
858
+     *  Show top header of page.
859
+     *
860
+     *  @param	PDF			$pdf     		Object PDF
861
+     *  @param  Object		$object     	Object to show
862
+     *  @param  int	    	$showaddress    0=no, 1=yes
863
+     *  @param  Translate	$outputlangs	Object lang for output
864
+     *  @return	void
865
+     */
866
+    function _pagehead(&$pdf, $object, $showaddress, $outputlangs)
867
+    {
868
+        global $conf,$langs,$mysoc;
890 869
 
891
-		$pdf->SetXY($this->marge_gauche,$posy);
870
+        $langs->load("orders");
892 871
 
893
-		// Logo
894
-		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
895
-		if ($this->emetteur->logo)
896
-		{
897
-			if (is_readable($logo))
898
-			{
899
-			    $height=pdf_getHeightForLogo($logo);
900
-			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
901
-			}
902
-			else
903
-			{
904
-				$pdf->SetTextColor(200,0,0);
905
-				$pdf->SetFont('','B', $default_font_size - 2);
906
-				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
907
-				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
908
-			}
909
-		}
910
-		else
911
-		{
912
-			$text=$this->emetteur->name;
913
-			$pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
914
-		}
872
+        $default_font_size = pdf_getPDFFontSize($outputlangs);
915 873
 
916
-		// Show barcode
917
-		if (! empty($conf->barcode->enabled))
918
-		{
919
-			$posx=105;
920
-		}
921
-		else
922
-		{
923
-			$posx=$this->marge_gauche+3;
924
-		}
925
-		//$pdf->Rect($this->marge_gauche, $this->marge_haute, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 30);
926
-		if (! empty($conf->barcode->enabled))
927
-		{
928
-			// TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
929
-			//$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
930
-			//$pdf->Image($logo,10, 5, 0, 24);
931
-		}
874
+        pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
932 875
 
933
-		$pdf->SetDrawColor(128,128,128);
934
-		if (! empty($conf->barcode->enabled))
935
-		{
936
-			// TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
937
-			//$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
938
-			//$pdf->Image($logo,10, 5, 0, 24);
939
-		}
876
+        // Show Draft Watermark
877
+        if($object->statut==0 && (! empty($conf->global->SHIPPING_DRAFT_WATERMARK)) )
878
+        {
879
+                    pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->SHIPPING_DRAFT_WATERMARK);
880
+        }
881
+
882
+        //Prepare la suite
883
+        $pdf->SetTextColor(0,0,60);
884
+        $pdf->SetFont('','B', $default_font_size + 3);
885
+
886
+        $w = 110;
887
+
888
+        $posy=$this->marge_haute;
889
+        $posx=$this->page_largeur-$this->marge_droite-$w;
940 890
 
891
+        $pdf->SetXY($this->marge_gauche,$posy);
941 892
 
942
-		$posx=$this->page_largeur - $w - $this->marge_droite;
943
-		$posy=$this->marge_haute;
893
+        // Logo
894
+        $logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
895
+        if ($this->emetteur->logo)
896
+        {
897
+            if (is_readable($logo))
898
+            {
899
+                $height=pdf_getHeightForLogo($logo);
900
+                $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
901
+            }
902
+            else
903
+            {
904
+                $pdf->SetTextColor(200,0,0);
905
+                $pdf->SetFont('','B', $default_font_size - 2);
906
+                $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
907
+                $pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
908
+            }
909
+        }
910
+        else
911
+        {
912
+            $text=$this->emetteur->name;
913
+            $pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
914
+        }
944 915
 
945
-		$pdf->SetFont('','B', $default_font_size + 2);
946
-		$pdf->SetXY($posx,$posy);
947
-		$pdf->SetTextColor(0,0,60);
948
-		$title=$outputlangs->transnoentities("SendingSheet");
949
-		$pdf->MultiCell($w, 4, $title, '', 'R');
916
+        // Show barcode
917
+        if (! empty($conf->barcode->enabled))
918
+        {
919
+            $posx=105;
920
+        }
921
+        else
922
+        {
923
+            $posx=$this->marge_gauche+3;
924
+        }
925
+        //$pdf->Rect($this->marge_gauche, $this->marge_haute, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 30);
926
+        if (! empty($conf->barcode->enabled))
927
+        {
928
+            // TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
929
+            //$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
930
+            //$pdf->Image($logo,10, 5, 0, 24);
931
+        }
950 932
 
951
-		$pdf->SetFont('','', $default_font_size + 1);
933
+        $pdf->SetDrawColor(128,128,128);
934
+        if (! empty($conf->barcode->enabled))
935
+        {
936
+            // TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
937
+            //$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
938
+            //$pdf->Image($logo,10, 5, 0, 24);
939
+        }
952 940
 
953
-		$posy+=5;
954 941
 
955
-		$pdf->SetXY($posx,$posy);
956
-		$pdf->SetTextColor(0,0,60);
957
-		$pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending") ." : ".$object->ref, '', 'R');
942
+        $posx=$this->page_largeur - $w - $this->marge_droite;
943
+        $posy=$this->marge_haute;
958 944
 
959
-		// Date planned delivery
960
-		if (! empty($object->date_delivery))
961
-		{
962
-    			$posy+=4;
963
-    			$pdf->SetXY($posx,$posy);
964
-    			$pdf->SetTextColor(0,0,60);
965
-    			$pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_delivery,"day",false,$outputlangs,true), '', 'R');
966
-		}
945
+        $pdf->SetFont('','B', $default_font_size + 2);
946
+        $pdf->SetXY($posx,$posy);
947
+        $pdf->SetTextColor(0,0,60);
948
+        $title=$outputlangs->transnoentities("SendingSheet");
949
+        $pdf->MultiCell($w, 4, $title, '', 'R');
967 950
 
968
-		if (! empty($object->thirdparty->code_client))
969
-		{
970
-			$posy+=4;
971
-			$pdf->SetXY($posx,$posy);
972
-			$pdf->SetTextColor(0,0,60);
973
-			$pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
974
-		}
951
+        $pdf->SetFont('','', $default_font_size + 1);
975 952
 
953
+        $posy+=5;
976 954
 
977
-		$pdf->SetFont('','', $default_font_size + 3);
978
-		$Yoff=25;
955
+        $pdf->SetXY($posx,$posy);
956
+        $pdf->SetTextColor(0,0,60);
957
+        $pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending") ." : ".$object->ref, '', 'R');
979 958
 
980
-		// Add list of linked orders
981
-		$origin 	= $object->origin;
982
-		$origin_id 	= $object->origin_id;
959
+        // Date planned delivery
960
+        if (! empty($object->date_delivery))
961
+        {
962
+                $posy+=4;
963
+                $pdf->SetXY($posx,$posy);
964
+                $pdf->SetTextColor(0,0,60);
965
+                $pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_delivery,"day",false,$outputlangs,true), '', 'R');
966
+        }
983 967
 
984
-	    // TODO move to external function
985
-		if (! empty($conf->$origin->enabled))     // commonly $origin='commande'
986
-		{
987
-			$outputlangs->load('orders');
988
-
989
-			$classname = ucfirst($origin);
990
-			$linkedobject = new $classname($this->db);
991
-			$result=$linkedobject->fetch($origin_id);
992
-			if ($result >= 0)
993
-			{
994
-			    //$linkedobject->fetchObjectLinked()   Get all linked object to the $linkedobject (commonly order) into $linkedobject->linkedObjects
995
-
996
-				$pdf->SetFont('','', $default_font_size - 2);
997
-				$text=$linkedobject->ref;
998
-				if ($linkedobject->ref_client) $text.=' ('.$linkedobject->ref_client.')';
999
-				$Yoff = $Yoff+8;
1000
-				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1001
-				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder") ." : ".$outputlangs->transnoentities($text), 0, 'R');
1002
-				$Yoff = $Yoff+3;
1003
-				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1004
-				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date,"day",false,$outputlangs,true), 0, 'R');
1005
-			}
1006
-		}
1007
-
1008
-		if ($showaddress)
1009
-		{
1010
-			// Sender properties
1011
-			$carac_emetteur='';
1012
-		 	// Add internal contact of origin element if defined
1013
-			$arrayidcontact=array();
1014
-			if (! empty($origin) && is_object($object->$origin)) $arrayidcontact=$object->$origin->getIdContact('internal','SALESREPFOLL');
1015
-		 	if (count($arrayidcontact) > 0)
1016
-		 	{
1017
-		 		$object->fetch_user(reset($arrayidcontact));
1018
-		 		$carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n";
1019
-		 	}
1020
-
1021
-		 	$carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object);
1022
-
1023
-			// Show sender
1024
-			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1025
-			$posx=$this->marge_gauche;
1026
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
1027
-
1028
-			$hautcadre=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
1029
-			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
1030
-
1031
-			// Show sender frame
1032
-			$pdf->SetTextColor(0,0,0);
1033
-			$pdf->SetFont('','', $default_font_size - 2);
1034
-			$pdf->SetXY($posx,$posy-5);
1035
-			$pdf->MultiCell(66,5, $outputlangs->transnoentities("Sender").":", 0, 'L');
1036
-			$pdf->SetXY($posx,$posy);
1037
-			$pdf->SetFillColor(230,230,230);
1038
-			$pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1);
1039
-			$pdf->SetTextColor(0,0,60);
1040
-			$pdf->SetFillColor(255,255,255);
1041
-
1042
-			// Show sender name
1043
-			$pdf->SetXY($posx+2,$posy+3);
1044
-			$pdf->SetFont('','B',$default_font_size);
1045
-			$pdf->MultiCell($widthrecbox-2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
1046
-			$posy=$pdf->getY();
1047
-
1048
-			// Show sender information
1049
-			$pdf->SetXY($posx+2,$posy);
1050
-			$pdf->SetFont('','', $default_font_size - 1);
1051
-			$pdf->MultiCell($widthrecbox-2, 4, $carac_emetteur, 0, 'L');
1052
-
1053
-
1054
-			// If SHIPPING contact defined, we use it
1055
-			$usecontact=false;
1056
-			$arrayidcontact=$object->$origin->getIdContact('external','SHIPPING');
1057
-			if (count($arrayidcontact) > 0)
1058
-			{
1059
-				$usecontact=true;
1060
-				$result=$object->fetch_contact($arrayidcontact[0]);
1061
-			}
1062
-
1063
-			//Recipient name
1064
-			// On peut utiliser le nom de la societe du contact
1065
-			if ($usecontact && !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) {
1066
-				$thirdparty = $object->contact;
1067
-			} else {
1068
-				$thirdparty = $object->thirdparty;
1069
-			}
1070
-
1071
-			$carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs);
1072
-
1073
-			$carac_client=pdf_build_address($outputlangs,$this->emetteur,$object->thirdparty,(!empty($object->contact)?$object->contact:null),$usecontact,'targetwithdetails',$object);
1074
-
1075
-			// Show recipient
1076
-			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
1077
-			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
1078
-			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1079
-			$posx=$this->page_largeur - $this->marge_droite - $widthrecbox;
1080
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
1081
-
1082
-			// Show recipient frame
1083
-			$pdf->SetTextColor(0,0,0);
1084
-			$pdf->SetFont('','', $default_font_size - 2);
1085
-			$pdf->SetXY($posx+2,$posy-5);
1086
-			$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L');
1087
-			$pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);
1088
-
1089
-			// Show recipient name
1090
-			$pdf->SetXY($posx+2,$posy+3);
1091
-			$pdf->SetFont('','B', $default_font_size);
1092
-			$pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L');
1093
-
1094
-			$posy = $pdf->getY();
1095
-
1096
-			// Show recipient information
1097
-			$pdf->SetFont('','', $default_font_size - 1);
1098
-			$pdf->SetXY($posx+2,$posy);
1099
-			$pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
1100
-		}
1101
-
1102
-		$pdf->SetTextColor(0,0,0);
1103
-	}
1104
-
1105
-	/**
1106
-	 *   	Show footer of page. Need this->emetteur object
968
+        if (! empty($object->thirdparty->code_client))
969
+        {
970
+            $posy+=4;
971
+            $pdf->SetXY($posx,$posy);
972
+            $pdf->SetTextColor(0,0,60);
973
+            $pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
974
+        }
975
+
976
+
977
+        $pdf->SetFont('','', $default_font_size + 3);
978
+        $Yoff=25;
979
+
980
+        // Add list of linked orders
981
+        $origin 	= $object->origin;
982
+        $origin_id 	= $object->origin_id;
983
+
984
+        // TODO move to external function
985
+        if (! empty($conf->$origin->enabled))     // commonly $origin='commande'
986
+        {
987
+            $outputlangs->load('orders');
988
+
989
+            $classname = ucfirst($origin);
990
+            $linkedobject = new $classname($this->db);
991
+            $result=$linkedobject->fetch($origin_id);
992
+            if ($result >= 0)
993
+            {
994
+                //$linkedobject->fetchObjectLinked()   Get all linked object to the $linkedobject (commonly order) into $linkedobject->linkedObjects
995
+
996
+                $pdf->SetFont('','', $default_font_size - 2);
997
+                $text=$linkedobject->ref;
998
+                if ($linkedobject->ref_client) $text.=' ('.$linkedobject->ref_client.')';
999
+                $Yoff = $Yoff+8;
1000
+                $pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1001
+                $pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder") ." : ".$outputlangs->transnoentities($text), 0, 'R');
1002
+                $Yoff = $Yoff+3;
1003
+                $pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1004
+                $pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date,"day",false,$outputlangs,true), 0, 'R');
1005
+            }
1006
+        }
1007
+
1008
+        if ($showaddress)
1009
+        {
1010
+            // Sender properties
1011
+            $carac_emetteur='';
1012
+                // Add internal contact of origin element if defined
1013
+            $arrayidcontact=array();
1014
+            if (! empty($origin) && is_object($object->$origin)) $arrayidcontact=$object->$origin->getIdContact('internal','SALESREPFOLL');
1015
+                if (count($arrayidcontact) > 0)
1016
+                {
1017
+                    $object->fetch_user(reset($arrayidcontact));
1018
+                    $carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n";
1019
+                }
1020
+
1021
+                $carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object);
1022
+
1023
+            // Show sender
1024
+            $posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1025
+            $posx=$this->marge_gauche;
1026
+            if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
1027
+
1028
+            $hautcadre=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
1029
+            $widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
1030
+
1031
+            // Show sender frame
1032
+            $pdf->SetTextColor(0,0,0);
1033
+            $pdf->SetFont('','', $default_font_size - 2);
1034
+            $pdf->SetXY($posx,$posy-5);
1035
+            $pdf->MultiCell(66,5, $outputlangs->transnoentities("Sender").":", 0, 'L');
1036
+            $pdf->SetXY($posx,$posy);
1037
+            $pdf->SetFillColor(230,230,230);
1038
+            $pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1);
1039
+            $pdf->SetTextColor(0,0,60);
1040
+            $pdf->SetFillColor(255,255,255);
1041
+
1042
+            // Show sender name
1043
+            $pdf->SetXY($posx+2,$posy+3);
1044
+            $pdf->SetFont('','B',$default_font_size);
1045
+            $pdf->MultiCell($widthrecbox-2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
1046
+            $posy=$pdf->getY();
1047
+
1048
+            // Show sender information
1049
+            $pdf->SetXY($posx+2,$posy);
1050
+            $pdf->SetFont('','', $default_font_size - 1);
1051
+            $pdf->MultiCell($widthrecbox-2, 4, $carac_emetteur, 0, 'L');
1052
+
1053
+
1054
+            // If SHIPPING contact defined, we use it
1055
+            $usecontact=false;
1056
+            $arrayidcontact=$object->$origin->getIdContact('external','SHIPPING');
1057
+            if (count($arrayidcontact) > 0)
1058
+            {
1059
+                $usecontact=true;
1060
+                $result=$object->fetch_contact($arrayidcontact[0]);
1061
+            }
1062
+
1063
+            //Recipient name
1064
+            // On peut utiliser le nom de la societe du contact
1065
+            if ($usecontact && !empty($conf->global->MAIN_USE_COMPANY_NAME_OF_CONTACT)) {
1066
+                $thirdparty = $object->contact;
1067
+            } else {
1068
+                $thirdparty = $object->thirdparty;
1069
+            }
1070
+
1071
+            $carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs);
1072
+
1073
+            $carac_client=pdf_build_address($outputlangs,$this->emetteur,$object->thirdparty,(!empty($object->contact)?$object->contact:null),$usecontact,'targetwithdetails',$object);
1074
+
1075
+            // Show recipient
1076
+            $widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
1077
+            if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
1078
+            $posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1079
+            $posx=$this->page_largeur - $this->marge_droite - $widthrecbox;
1080
+            if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
1081
+
1082
+            // Show recipient frame
1083
+            $pdf->SetTextColor(0,0,0);
1084
+            $pdf->SetFont('','', $default_font_size - 2);
1085
+            $pdf->SetXY($posx+2,$posy-5);
1086
+            $pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L');
1087
+            $pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);
1088
+
1089
+            // Show recipient name
1090
+            $pdf->SetXY($posx+2,$posy+3);
1091
+            $pdf->SetFont('','B', $default_font_size);
1092
+            $pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L');
1093
+
1094
+            $posy = $pdf->getY();
1095
+
1096
+            // Show recipient information
1097
+            $pdf->SetFont('','', $default_font_size - 1);
1098
+            $pdf->SetXY($posx+2,$posy);
1099
+            $pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
1100
+        }
1101
+
1102
+        $pdf->SetTextColor(0,0,0);
1103
+    }
1104
+
1105
+    /**
1106
+     *   	Show footer of page. Need this->emetteur object
1107 1107
      *
1108
-	 *   	@param	PDF			$pdf     			PDF
1109
-	 * 		@param	Object		$object				Object to show
1110
-	 *      @param	Translate	$outputlangs		Object lang for output
1111
-	 *      @param	int			$hidefreetext		1=Hide free text
1112
-	 *      @return	int								Return height of bottom margin including footer text
1113
-	 */
1114
-	function _pagefoot(&$pdf,$object,$outputlangs,$hidefreetext=0)
1115
-	{
1116
-		global $conf;
1117
-		$showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
1118
-		return pdf_pagefoot($pdf,$outputlangs,'SHIPPING_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,$showdetails,$hidefreetext);
1119
-	}
1108
+     *   	@param	PDF			$pdf     			PDF
1109
+     * 		@param	Object		$object				Object to show
1110
+     *      @param	Translate	$outputlangs		Object lang for output
1111
+     *      @param	int			$hidefreetext		1=Hide free text
1112
+     *      @return	int								Return height of bottom margin including footer text
1113
+     */
1114
+    function _pagefoot(&$pdf,$object,$outputlangs,$hidefreetext=0)
1115
+    {
1116
+        global $conf;
1117
+        $showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
1118
+        return pdf_pagefoot($pdf,$outputlangs,'SHIPPING_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,$showdetails,$hidefreetext);
1119
+    }
1120 1120
 }
Please login to merge, or discard this patch.
Spacing   +312 added lines, -312 removed lines patch added patch discarded remove patch
@@ -115,56 +115,56 @@  discard block
 block discarded – undo
115 115
 	 *
116 116
 	 *	@param	DoliDB	$db		Database handler
117 117
 	 */
118
-	function __construct($db=0)
118
+	function __construct($db = 0)
119 119
 	{
120
-		global $conf,$langs,$mysoc;
120
+		global $conf, $langs, $mysoc;
121 121
 
122 122
 		$this->db = $db;
123 123
 		$this->name = "rouget";
124 124
 		$this->description = $langs->trans("DocumentModelStandardPDF");
125 125
 
126 126
 		$this->type = 'pdf';
127
-		$formatarray=pdf_getFormat();
127
+		$formatarray = pdf_getFormat();
128 128
 		$this->page_largeur = $formatarray['width'];
129 129
 		$this->page_hauteur = $formatarray['height'];
130
-		$this->format = array($this->page_largeur,$this->page_hauteur);
131
-		$this->marge_gauche=isset($conf->global->MAIN_PDF_MARGIN_LEFT)?$conf->global->MAIN_PDF_MARGIN_LEFT:10;
132
-		$this->marge_droite=isset($conf->global->MAIN_PDF_MARGIN_RIGHT)?$conf->global->MAIN_PDF_MARGIN_RIGHT:10;
133
-		$this->marge_haute =isset($conf->global->MAIN_PDF_MARGIN_TOP)?$conf->global->MAIN_PDF_MARGIN_TOP:10;
134
-		$this->marge_basse =isset($conf->global->MAIN_PDF_MARGIN_BOTTOM)?$conf->global->MAIN_PDF_MARGIN_BOTTOM:10;
130
+		$this->format = array($this->page_largeur, $this->page_hauteur);
131
+		$this->marge_gauche = isset($conf->global->MAIN_PDF_MARGIN_LEFT) ? $conf->global->MAIN_PDF_MARGIN_LEFT : 10;
132
+		$this->marge_droite = isset($conf->global->MAIN_PDF_MARGIN_RIGHT) ? $conf->global->MAIN_PDF_MARGIN_RIGHT : 10;
133
+		$this->marge_haute = isset($conf->global->MAIN_PDF_MARGIN_TOP) ? $conf->global->MAIN_PDF_MARGIN_TOP : 10;
134
+		$this->marge_basse = isset($conf->global->MAIN_PDF_MARGIN_BOTTOM) ? $conf->global->MAIN_PDF_MARGIN_BOTTOM : 10;
135 135
 
136 136
 		$this->option_logo = 1;
137 137
 
138 138
 		// Get source company
139
-		$this->emetteur=$mysoc;
140
-		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default if not defined
139
+		$this->emetteur = $mysoc;
140
+		if (!$this->emetteur->country_code) $this->emetteur->country_code = substr($langs->defaultlang, -2); // By default if not defined
141 141
 
142 142
 		// Define position of columns
143
-		$this->posxdesc=$this->marge_gauche+1;
144
-		$this->posxweightvol=$this->page_largeur - $this->marge_droite - 78;
145
-		$this->posxqtyordered=$this->page_largeur - $this->marge_droite - 56;
146
-		$this->posxqtytoship=$this->page_largeur - $this->marge_droite - 28;
147
-		$this->posxpuht=$this->page_largeur - $this->marge_droite;
143
+		$this->posxdesc = $this->marge_gauche + 1;
144
+		$this->posxweightvol = $this->page_largeur - $this->marge_droite - 78;
145
+		$this->posxqtyordered = $this->page_largeur - $this->marge_droite - 56;
146
+		$this->posxqtytoship = $this->page_largeur - $this->marge_droite - 28;
147
+		$this->posxpuht = $this->page_largeur - $this->marge_droite;
148 148
 
149 149
 		if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT)) {	// Show also the prices
150
-			$this->posxweightvol=$this->page_largeur - $this->marge_droite - 118;
151
-			$this->posxqtyordered=$this->page_largeur - $this->marge_droite - 96;
152
-			$this->posxqtytoship=$this->page_largeur - $this->marge_droite - 68;
153
-			$this->posxpuht=$this->page_largeur - $this->marge_droite - 40;
154
-			$this->posxtotalht=$this->page_largeur - $this->marge_droite - 20;
150
+			$this->posxweightvol = $this->page_largeur - $this->marge_droite - 118;
151
+			$this->posxqtyordered = $this->page_largeur - $this->marge_droite - 96;
152
+			$this->posxqtytoship = $this->page_largeur - $this->marge_droite - 68;
153
+			$this->posxpuht = $this->page_largeur - $this->marge_droite - 40;
154
+			$this->posxtotalht = $this->page_largeur - $this->marge_droite - 20;
155 155
 		}
156 156
 
157
-		$this->posxpicture=$this->posxweightvol - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
157
+		$this->posxpicture = $this->posxweightvol - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH) ? 20 : $conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH); // width of images
158 158
 
159 159
 		if ($this->page_largeur < 210) // To work with US executive format
160 160
 		{
161
-		    $this->posxweightvol-=20;
162
-		    $this->posxpicture-=20;
163
-		    $this->posxqtyordered-=20;
164
-		    $this->posxqtytoship-=20;
161
+		    $this->posxweightvol -= 20;
162
+		    $this->posxpicture -= 20;
163
+		    $this->posxqtyordered -= 20;
164
+		    $this->posxqtytoship -= 20;
165 165
 		}
166 166
 
167
-		if (! empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
167
+		if (!empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
168 168
 		{
169 169
 		    $this->posxweightvol += ($this->posxqtytoship - $this->posxqtyordered);
170 170
 		    $this->posxpicture += ($this->posxqtytoship - $this->posxqtyordered);
@@ -184,16 +184,16 @@  discard block
 block discarded – undo
184 184
      *  @param		int			$hideref			Do not show ref
185 185
      *  @return     int         	    			1=OK, 0=KO
186 186
 	 */
187
-	function write_file($object,$outputlangs,$srctemplatepath='',$hidedetails=0,$hidedesc=0,$hideref=0)
187
+	function write_file($object, $outputlangs, $srctemplatepath = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
188 188
 	{
189 189
 		// phpcs:enable
190
-		global $user,$conf,$langs,$hookmanager;
190
+		global $user, $conf, $langs, $hookmanager;
191 191
 
192 192
 		$object->fetch_thirdparty();
193 193
 
194
-		if (! is_object($outputlangs)) $outputlangs=$langs;
194
+		if (!is_object($outputlangs)) $outputlangs = $langs;
195 195
 		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
196
-		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
196
+		if (!empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output = 'ISO-8859-1';
197 197
 
198 198
 		// Load traductions files requiredby by page
199 199
 		$outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch"));
@@ -201,50 +201,50 @@  discard block
 block discarded – undo
201 201
 		$nblignes = count($object->lines);
202 202
 
203 203
         // Loop on each lines to detect if there is at least one image to show
204
-        $realpatharray=array();
205
-        if (! empty($conf->global->MAIN_GENERATE_SHIPMENT_WITH_PICTURE))
204
+        $realpatharray = array();
205
+        if (!empty($conf->global->MAIN_GENERATE_SHIPMENT_WITH_PICTURE))
206 206
         {
207 207
             $objphoto = new Product($this->db);
208 208
 
209
-            for ($i = 0 ; $i < $nblignes ; $i++)
209
+            for ($i = 0; $i < $nblignes; $i++)
210 210
             {
211 211
                 if (empty($object->lines[$i]->fk_product)) continue;
212 212
 
213 213
 				$objphoto = new Product($this->db);
214 214
 				$objphoto->fetch($object->lines[$i]->fk_product);
215 215
 
216
-				$pdir = get_exdir($object->lines[$i]->fk_product,2,0,0,$objphoto,'product') . $object->lines[$i]->fk_product ."/photos/";
216
+				$pdir = get_exdir($object->lines[$i]->fk_product, 2, 0, 0, $objphoto, 'product').$object->lines[$i]->fk_product."/photos/";
217 217
 				$dir = $conf->product->dir_output.'/'.$pdir;
218 218
 
219
-				$realpath='';
219
+				$realpath = '';
220 220
 
221
-                foreach ($objphoto->liste_photos($dir,1) as $key => $obj)
221
+                foreach ($objphoto->liste_photos($dir, 1) as $key => $obj)
222 222
                         {
223 223
                             if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES))		// If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo
224 224
                             {
225 225
                                 if ($obj['photo_vignette'])
226 226
                                 {
227
-                                    $filename= $obj['photo_vignette'];
227
+                                    $filename = $obj['photo_vignette'];
228 228
                                 }
229 229
                                 else
230 230
                                 {
231
-                                    $filename=$obj['photo'];
231
+                                    $filename = $obj['photo'];
232 232
                                 }
233 233
                             }
234 234
                             else
235 235
                             {
236
-                                $filename=$obj['photo'];
236
+                                $filename = $obj['photo'];
237 237
                             }
238 238
 
239 239
                             $realpath = $dir.$filename;
240 240
                             break;
241 241
                 }
242 242
 
243
-                if ($realpath) $realpatharray[$i]=$realpath;
243
+                if ($realpath) $realpatharray[$i] = $realpath;
244 244
             }
245 245
         }
246 246
 
247
-        if (count($realpatharray) == 0) $this->posxpicture=$this->posxweightvol;
247
+        if (count($realpatharray) == 0) $this->posxpicture = $this->posxweightvol;
248 248
 
249 249
 		if ($conf->expedition->dir_output)
250 250
 		{
@@ -252,20 +252,20 @@  discard block
 block discarded – undo
252 252
 			if ($object->specimen)
253 253
 			{
254 254
 				$dir = $conf->expedition->dir_output."/sending";
255
-				$file = $dir . "/SPECIMEN.pdf";
255
+				$file = $dir."/SPECIMEN.pdf";
256 256
 			}
257 257
 			else
258 258
 			{
259 259
 				$expref = dol_sanitizeFileName($object->ref);
260
-				$dir = $conf->expedition->dir_output."/sending/" . $expref;
261
-				$file = $dir . "/" . $expref . ".pdf";
260
+				$dir = $conf->expedition->dir_output."/sending/".$expref;
261
+				$file = $dir."/".$expref.".pdf";
262 262
 			}
263 263
 
264
-			if (! file_exists($dir))
264
+			if (!file_exists($dir))
265 265
 			{
266 266
 				if (dol_mkdir($dir) < 0)
267 267
 				{
268
-					$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
268
+					$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
269 269
 					return 0;
270 270
 				}
271 271
 			}
@@ -273,26 +273,26 @@  discard block
 block discarded – undo
273 273
 			if (file_exists($dir))
274 274
 			{
275 275
 				// Add pdfgeneration hook
276
-				if (! is_object($hookmanager))
276
+				if (!is_object($hookmanager))
277 277
 				{
278 278
 					include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
279
-					$hookmanager=new HookManager($this->db);
279
+					$hookmanager = new HookManager($this->db);
280 280
 				}
281 281
 				$hookmanager->initHooks(array('pdfgeneration'));
282
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
282
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
283 283
 				global $action;
284
-				$reshook=$hookmanager->executeHooks('beforePDFCreation',$parameters,$object,$action);    // Note that $action and $object may have been modified by some hooks
284
+				$reshook = $hookmanager->executeHooks('beforePDFCreation', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
285 285
 
286 286
 				// Set nblignes with the new facture lines content after hook
287 287
 				$nblignes = count($object->lines);
288 288
 
289
-				$pdf=pdf_getInstance($this->format);
289
+				$pdf = pdf_getInstance($this->format);
290 290
 				$default_font_size = pdf_getPDFFontSize($outputlangs);
291
-				$heightforinfotot = 8;	// Height reserved to output the info and total part
292
-		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
293
-	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
294
-	            if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
295
-                $pdf->SetAutoPageBreak(1,0);
291
+				$heightforinfotot = 8; // Height reserved to output the info and total part
292
+		        $heightforfreetext = (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT) ? $conf->global->MAIN_PDF_FREETEXT_HEIGHT : 5); // Height reserved to output the free text on last page
293
+	            $heightforfooter = $this->marge_basse + 8; // Height reserved to output the footer (value include bottom margin)
294
+	            if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS > 0) $heightforfooter += 6;
295
+                $pdf->SetAutoPageBreak(1, 0);
296 296
 
297 297
                 if (class_exists('TCPDF'))
298 298
                 {
@@ -301,38 +301,38 @@  discard block
 block discarded – undo
301 301
                 }
302 302
                 $pdf->SetFont(pdf_getPDFFont($outputlangs));
303 303
                 // Set path to the background PDF File
304
-                if (! empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
304
+                if (!empty($conf->global->MAIN_ADD_PDF_BACKGROUND))
305 305
                 {
306 306
                     $pagecount = $pdf->setSourceFile($conf->mycompany->dir_output.'/'.$conf->global->MAIN_ADD_PDF_BACKGROUND);
307 307
                     $tplidx = $pdf->importPage(1);
308 308
                 }
309 309
 
310 310
 				$pdf->Open();
311
-				$pagenb=0;
312
-				$pdf->SetDrawColor(128,128,128);
311
+				$pagenb = 0;
312
+				$pdf->SetDrawColor(128, 128, 128);
313 313
 
314
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
314
+				if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages();
315 315
 
316 316
 				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
317 317
 				$pdf->SetSubject($outputlangs->transnoentities("Shipment"));
318 318
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
319 319
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
320 320
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Shipment"));
321
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
321
+				if (!empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
322 322
 
323
-				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
323
+				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite); // Left, Top, Right
324 324
 
325 325
 				// New page
326 326
 				$pdf->AddPage();
327
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
327
+				if (!empty($tplidx)) $pdf->useTemplate($tplidx);
328 328
 				$pagenb++;
329 329
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
330
-				$pdf->SetFont('','', $default_font_size - 1);
331
-				$pdf->MultiCell(0, 3, '');		// Set interline to 3
332
-				$pdf->SetTextColor(0,0,0);
330
+				$pdf->SetFont('', '', $default_font_size - 1);
331
+				$pdf->MultiCell(0, 3, ''); // Set interline to 3
332
+				$pdf->SetTextColor(0, 0, 0);
333 333
 
334 334
 				$tab_top = 90;
335
-				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)?42:10);
335
+				$tab_top_newpage = (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD) ? 42 : 10);
336 336
 				$tab_height = 130;
337 337
 				$tab_height_newpage = 150;
338 338
 
@@ -345,52 +345,52 @@  discard block
 block discarded – undo
345 345
 					{
346 346
 						$tab_top = 88;
347 347
 
348
-						$pdf->SetFont('','', $default_font_size - 1);
349
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top-1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
348
+						$pdf->SetFont('', '', $default_font_size - 1);
349
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top - 1, dol_htmlentitiesbr($desc_incoterms), 0, 1);
350 350
 						$nexY = $pdf->GetY();
351
-						$height_incoterms=$nexY-$tab_top;
351
+						$height_incoterms = $nexY - $tab_top;
352 352
 
353 353
 						// Rect prend une longueur en 3eme param
354
-						$pdf->SetDrawColor(192,192,192);
355
-						$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_incoterms+1);
354
+						$pdf->SetDrawColor(192, 192, 192);
355
+						$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_incoterms + 1);
356 356
 
357
-						$tab_top = $nexY+6;
357
+						$tab_top = $nexY + 6;
358 358
 						$height_incoterms += 4;
359 359
 					}
360 360
 				}
361 361
 
362
-				if (! empty($object->note_public) || ! empty($object->tracking_number))
362
+				if (!empty($object->note_public) || !empty($object->tracking_number))
363 363
 				{
364 364
 					$tab_top = 88 + $height_incoterms;
365 365
 					$tab_top_alt = $tab_top;
366 366
 
367
-					$pdf->SetFont('','B', $default_font_size - 2);
368
-					$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top-1, $outputlangs->transnoentities("TrackingNumber")." : " . $object->tracking_number, 0, 1, false, true, 'L');
367
+					$pdf->SetFont('', 'B', $default_font_size - 2);
368
+					$pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top - 1, $outputlangs->transnoentities("TrackingNumber")." : ".$object->tracking_number, 0, 1, false, true, 'L');
369 369
 
370 370
 					$tab_top_alt = $pdf->GetY();
371 371
 					//$tab_top_alt += 1;
372 372
 
373 373
 					// Tracking number
374
-					if (! empty($object->tracking_number))
374
+					if (!empty($object->tracking_number))
375 375
 					{
376 376
 						$object->getUrlTrackingStatus($object->tracking_number);
377
-						if (! empty($object->tracking_url))
377
+						if (!empty($object->tracking_url))
378 378
 						{
379 379
 							if ($object->shipping_method_id > 0)
380 380
 							{
381 381
 								// Get code using getLabelFromKey
382
-								$code=$outputlangs->getLabelFromKey($this->db,$object->shipping_method_id,'c_shipment_mode','rowid','code');
383
-								$label='';
384
-								if ($object->tracking_url != $object->tracking_number) $label.=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
385
-								$label.=$outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
382
+								$code = $outputlangs->getLabelFromKey($this->db, $object->shipping_method_id, 'c_shipment_mode', 'rowid', 'code');
383
+								$label = '';
384
+								if ($object->tracking_url != $object->tracking_number) $label .= $outputlangs->trans("LinkToTrackYourPackage")."<br>";
385
+								$label .= $outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
386 386
 								//var_dump($object->tracking_url != $object->tracking_number);exit;
387 387
 								if ($object->tracking_url != $object->tracking_number)
388 388
 								{
389
-									$label.=" : ";
390
-									$label.=$object->tracking_url;
389
+									$label .= " : ";
390
+									$label .= $object->tracking_url;
391 391
 								}
392
-								$pdf->SetFont('','B', $default_font_size - 2);
393
-								$pdf->writeHTMLCell(60, 4, $this->posxdesc-1, $tab_top_alt, $label, 0, 1, false, true, 'L');
392
+								$pdf->SetFont('', 'B', $default_font_size - 2);
393
+								$pdf->writeHTMLCell(60, 4, $this->posxdesc - 1, $tab_top_alt, $label, 0, 1, false, true, 'L');
394 394
 
395 395
 								$tab_top_alt = $pdf->GetY();
396 396
 							}
@@ -398,25 +398,25 @@  discard block
 block discarded – undo
398 398
 					}
399 399
 
400 400
 					// Notes
401
-					if (! empty($object->note_public))
401
+					if (!empty($object->note_public))
402 402
 					{
403
-						$pdf->SetFont('','', $default_font_size - 1);   // Dans boucle pour gerer multi-page
404
-						$pdf->writeHTMLCell(190, 3, $this->posxdesc-1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1);
403
+						$pdf->SetFont('', '', $default_font_size - 1); // Dans boucle pour gerer multi-page
404
+						$pdf->writeHTMLCell(190, 3, $this->posxdesc - 1, $tab_top_alt, dol_htmlentitiesbr($object->note_public), 0, 1);
405 405
 					}
406 406
 
407 407
 					$nexY = $pdf->GetY();
408
-					$height_note=$nexY-$tab_top;
408
+					$height_note = $nexY - $tab_top;
409 409
 
410 410
 					// Rect prend une longueur en 3eme param
411
-					$pdf->SetDrawColor(192,192,192);
412
-					$pdf->Rect($this->marge_gauche, $tab_top-1, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $height_note+1);
411
+					$pdf->SetDrawColor(192, 192, 192);
412
+					$pdf->Rect($this->marge_gauche, $tab_top - 1, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $height_note + 1);
413 413
 
414 414
 					$tab_height = $tab_height - $height_note;
415
-					$tab_top = $nexY+6;
415
+					$tab_top = $nexY + 6;
416 416
 				}
417 417
 				else
418 418
 				{
419
-					$height_note=0;
419
+					$height_note = 0;
420 420
 				}
421 421
 
422 422
 				$iniY = $tab_top + 7;
@@ -427,87 +427,87 @@  discard block
 block discarded – undo
427 427
 				for ($i = 0; $i < $nblignes; $i++)
428 428
 				{
429 429
 					$curY = $nexY;
430
-					$pdf->SetFont('','', $default_font_size - 1);   // Into loop to work with multipage
431
-					$pdf->SetTextColor(0,0,0);
430
+					$pdf->SetFont('', '', $default_font_size - 1); // Into loop to work with multipage
431
+					$pdf->SetTextColor(0, 0, 0);
432 432
 
433 433
 					// Define size of image if we need it
434
-					$imglinesize=array();
435
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
434
+					$imglinesize = array();
435
+					if (!empty($realpatharray[$i])) $imglinesize = pdf_getSizeForImage($realpatharray[$i]);
436 436
 
437 437
 					$pdf->setTopMargin($tab_top_newpage);
438
-					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
439
-					$pageposbefore=$pdf->getPage();
438
+					$pdf->setPageOrientation('', 1, $heightforfooter + $heightforfreetext + $heightforinfotot); // The only function to edit the bottom margin of current page to set it.
439
+					$pageposbefore = $pdf->getPage();
440 440
 
441
-					$showpricebeforepagebreak=1;
442
-					$posYAfterImage=0;
443
-					$posYAfterDescription=0;
441
+					$showpricebeforepagebreak = 1;
442
+					$posYAfterImage = 0;
443
+					$posYAfterDescription = 0;
444 444
 
445 445
 					// We start with Photo of product line
446
-					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot)))	// If photo too high, we moved completely on new page
446
+					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// If photo too high, we moved completely on new page
447 447
 					{
448
-						$pdf->AddPage('','',true);
449
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
448
+						$pdf->AddPage('', '', true);
449
+						if (!empty($tplidx)) $pdf->useTemplate($tplidx);
450 450
 						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
451
-						$pdf->setPage($pageposbefore+1);
451
+						$pdf->setPage($pageposbefore + 1);
452 452
 
453 453
 						$curY = $tab_top_newpage;
454
-						$showpricebeforepagebreak=0;
454
+						$showpricebeforepagebreak = 0;
455 455
 					}
456 456
 
457 457
 					if (isset($imglinesize['width']) && isset($imglinesize['height']))
458 458
 					{
459
-						$curX = $this->posxpicture-1;
460
-						$pdf->Image($realpatharray[$i], $curX + (($this->posxweightvol-$this->posxpicture-$imglinesize['width'])/2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300);	// Use 300 dpi
459
+						$curX = $this->posxpicture - 1;
460
+						$pdf->Image($realpatharray[$i], $curX + (($this->posxweightvol - $this->posxpicture - $imglinesize['width']) / 2), $curY, $imglinesize['width'], $imglinesize['height'], '', '', '', 2, 300); // Use 300 dpi
461 461
 						// $pdf->Image does not increase value return by getY, so we save it manually
462
-						$posYAfterImage=$curY+$imglinesize['height'];
462
+						$posYAfterImage = $curY + $imglinesize['height'];
463 463
 					}
464 464
 
465 465
 					// Description of product line
466
-					$curX = $this->posxdesc-1;
466
+					$curX = $this->posxdesc - 1;
467 467
 
468 468
 					$pdf->startTransaction();
469
-					pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
469
+					pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxpicture - $curX, 3, $curX, $curY, $hideref, $hidedesc);
470 470
 
471
-					$pageposafter=$pdf->getPage();
471
+					$pageposafter = $pdf->getPage();
472 472
 					if ($pageposafter > $pageposbefore)	// There is a pagebreak
473 473
 					{
474 474
 						$pdf->rollbackTransaction(true);
475
-						$pageposafter=$pageposbefore;
475
+						$pageposafter = $pageposbefore;
476 476
 						//print $pageposafter.'-'.$pageposbefore;exit;
477
-						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
478
-						pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
477
+						$pdf->setPageOrientation('', 1, $heightforfooter); // The only function to edit the bottom margin of current page to set it.
478
+						pdf_writelinedesc($pdf, $object, $i, $outputlangs, $this->posxpicture - $curX, 3, $curX, $curY, $hideref, $hidedesc);
479 479
 
480
-						$pageposafter=$pdf->getPage();
481
-						$posyafter=$pdf->GetY();
480
+						$pageposafter = $pdf->getPage();
481
+						$posyafter = $pdf->GetY();
482 482
 						//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
483
-						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
483
+						if ($posyafter > ($this->page_hauteur - ($heightforfooter + $heightforfreetext + $heightforinfotot)))	// There is no space left for total+free text
484 484
 						{
485
-							if ($i == ($nblignes-1))	// No more lines, and no space left to show total, so we create a new page
485
+							if ($i == ($nblignes - 1))	// No more lines, and no space left to show total, so we create a new page
486 486
 							{
487
-								$pdf->AddPage('','',true);
488
-								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
487
+								$pdf->AddPage('', '', true);
488
+								if (!empty($tplidx)) $pdf->useTemplate($tplidx);
489 489
 								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
490
-								$pdf->setPage($pageposafter+1);
490
+								$pdf->setPage($pageposafter + 1);
491 491
 							}
492 492
 						}
493 493
 						else
494 494
 						{
495 495
 							// We found a page break
496
-							$showpricebeforepagebreak=0;
496
+							$showpricebeforepagebreak = 0;
497 497
 						}
498 498
 					}
499 499
 					else	// No pagebreak
500 500
 					{
501 501
 						$pdf->commitTransaction();
502 502
 					}
503
-					$posYAfterDescription=$pdf->GetY();
503
+					$posYAfterDescription = $pdf->GetY();
504 504
 
505 505
 					$nexY = $pdf->GetY();
506
-					$pageposafter=$pdf->getPage();
506
+					$pageposafter = $pdf->getPage();
507 507
 
508 508
 					$pdf->setPage($pageposbefore);
509 509
 					$pdf->setTopMargin($this->marge_haute);
510
-					$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
510
+					$pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it.
511 511
 
512 512
 					// We suppose that a too long description or photo were moved completely on next page
513 513
 					if ($pageposafter > $pageposbefore && empty($showpricebeforepagebreak)) {
@@ -519,57 +519,57 @@  discard block
 block discarded – undo
519 519
 						$pdf->setPage($pageposafter); $curY = $tab_top_newpage;
520 520
 					}
521 521
 
522
-					$pdf->SetFont('','', $default_font_size - 1);   // On repositionne la police par defaut
522
+					$pdf->SetFont('', '', $default_font_size - 1); // On repositionne la police par defaut
523 523
 
524 524
 					$pdf->SetXY($this->posxweightvol, $curY);
525
-					$weighttxt='';
525
+					$weighttxt = '';
526 526
 					if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->weight)
527 527
 					{
528
-					    $weighttxt=round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->weight_units,"weight");
528
+					    $weighttxt = round($object->lines[$i]->weight * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->weight_units, "weight");
529 529
 					}
530
-					$voltxt='';
530
+					$voltxt = '';
531 531
 					if ($object->lines[$i]->fk_product_type == 0 && $object->lines[$i]->volume)
532 532
 					{
533
-					    $voltxt=round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->volume_units?$object->lines[$i]->volume_units:0,"volume");
533
+					    $voltxt = round($object->lines[$i]->volume * $object->lines[$i]->qty_shipped, 5).' '.measuring_units_string($object->lines[$i]->volume_units ? $object->lines[$i]->volume_units : 0, "volume");
534 534
 					}
535 535
 
536 536
 					if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
537 537
 					{
538
-						$pdf->writeHTMLCell($this->posxqtyordered - $this->posxweightvol + 2, 3, $this->posxweightvol - 1, $curY, $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt, 0, 0, false, true, 'C');
538
+						$pdf->writeHTMLCell($this->posxqtyordered - $this->posxweightvol + 2, 3, $this->posxweightvol - 1, $curY, $weighttxt.(($weighttxt && $voltxt) ? '<br>' : '').$voltxt, 0, 0, false, true, 'C');
539 539
 						//$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 3, $weighttxt.(($weighttxt && $voltxt)?'<br>':'').$voltxt,'','C');
540 540
 					}
541 541
 
542 542
 					if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
543 543
 					{
544 544
 					   $pdf->SetXY($this->posxqtyordered, $curY);
545
-					   $pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 3, $object->lines[$i]->qty_asked,'','C');
545
+					   $pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 3, $object->lines[$i]->qty_asked, '', 'C');
546 546
 					}
547 547
 
548 548
 					if (empty($conf->global->SHIPPING_PDF_HIDE_QTYTOSHIP))
549 549
 					{
550 550
 						$pdf->SetXY($this->posxqtytoship, $curY);
551
-						$pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 3, $object->lines[$i]->qty_shipped,'','C');
551
+						$pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 3, $object->lines[$i]->qty_shipped, '', 'C');
552 552
 					}
553 553
 
554
-					if(!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT))
554
+					if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT))
555 555
 					{
556 556
 						$pdf->SetXY($this->posxpuht, $curY);
557
-						$pdf->MultiCell(($this->posxtotalht - $this->posxpuht-1), 3, price($object->lines[$i]->subprice, 0, $outputlangs),'','R');
557
+						$pdf->MultiCell(($this->posxtotalht - $this->posxpuht - 1), 3, price($object->lines[$i]->subprice, 0, $outputlangs), '', 'R');
558 558
 
559 559
 						$pdf->SetXY($this->posxtotalht, $curY);
560
-						$pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 3, price($object->lines[$i]->total_ht, 0, $outputlangs),'','R');
560
+						$pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 3, price($object->lines[$i]->total_ht, 0, $outputlangs), '', 'R');
561 561
 					}
562 562
 
563
-					$nexY+=3;
564
-					if ($weighttxt && $voltxt) $nexY+=2;
563
+					$nexY += 3;
564
+					if ($weighttxt && $voltxt) $nexY += 2;
565 565
 
566 566
 					// Add line
567
-					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
567
+					if (!empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
568 568
 					{
569 569
 						$pdf->setPage($pageposafter);
570
-						$pdf->SetLineStyle(array('dash'=>'1,1','color'=>array(80,80,80)));
570
+						$pdf->SetLineStyle(array('dash'=>'1,1', 'color'=>array(80, 80, 80)));
571 571
 						//$pdf->SetDrawColor(190,190,200);
572
-						$pdf->line($this->marge_gauche, $nexY-1, $this->page_largeur - $this->marge_droite, $nexY-1);
572
+						$pdf->line($this->marge_gauche, $nexY - 1, $this->page_largeur - $this->marge_droite, $nexY - 1);
573 573
 						$pdf->SetLineStyle(array('dash'=>0));
574 574
 					}
575 575
 
@@ -585,13 +585,13 @@  discard block
 block discarded – undo
585 585
 						{
586 586
 							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
587 587
 						}
588
-						$this->_pagefoot($pdf,$object,$outputlangs,1);
588
+						$this->_pagefoot($pdf, $object, $outputlangs, 1);
589 589
 						$pagenb++;
590 590
 						$pdf->setPage($pagenb);
591
-						$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
591
+						$pdf->setPageOrientation('', 1, 0); // The only function to edit the bottom margin of current page to set it.
592 592
 						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
593 593
 					}
594
-					if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak)
594
+					if (isset($object->lines[$i + 1]->pagebreak) && $object->lines[$i + 1]->pagebreak)
595 595
 					{
596 596
 						if ($pagenb == 1)
597 597
 						{
@@ -601,10 +601,10 @@  discard block
 block discarded – undo
601 601
 						{
602 602
 							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
603 603
 						}
604
-						$this->_pagefoot($pdf,$object,$outputlangs,1);
604
+						$this->_pagefoot($pdf, $object, $outputlangs, 1);
605 605
 						// New page
606 606
 						$pdf->AddPage();
607
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
607
+						if (!empty($tplidx)) $pdf->useTemplate($tplidx);
608 608
 						$pagenb++;
609 609
 						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
610 610
 					}
@@ -614,47 +614,47 @@  discard block
 block discarded – undo
614 614
 				if ($pagenb == 1)
615 615
 				{
616 616
 					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
617
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
617
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
618 618
 				}
619 619
 				else
620 620
 				{
621 621
 					$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
622
-					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
622
+					$bottomlasttab = $this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
623 623
 				}
624 624
 
625 625
 				// Affiche zone totaux
626
-				$posy=$this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs);
626
+				$posy = $this->_tableau_tot($pdf, $object, 0, $bottomlasttab, $outputlangs);
627 627
 
628 628
 				// Pied de page
629
-				$this->_pagefoot($pdf,$object,$outputlangs);
630
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
629
+				$this->_pagefoot($pdf, $object, $outputlangs);
630
+				if (method_exists($pdf, 'AliasNbPages')) $pdf->AliasNbPages();
631 631
 
632 632
 				$pdf->Close();
633 633
 
634
-				$pdf->Output($file,'F');
634
+				$pdf->Output($file, 'F');
635 635
 
636 636
 				// Add pdfgeneration hook
637 637
 				$hookmanager->initHooks(array('pdfgeneration'));
638
-				$parameters=array('file'=>$file,'object'=>$object,'outputlangs'=>$outputlangs);
638
+				$parameters = array('file'=>$file, 'object'=>$object, 'outputlangs'=>$outputlangs);
639 639
 				global $action;
640
-				$reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
640
+				$reshook = $hookmanager->executeHooks('afterPDFCreation', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
641 641
 
642
-				if (! empty($conf->global->MAIN_UMASK))
642
+				if (!empty($conf->global->MAIN_UMASK))
643 643
 				@chmod($file, octdec($conf->global->MAIN_UMASK));
644 644
 
645 645
 				$this->result = array('fullpath'=>$file);
646 646
 
647
-				return 1;	// No error
647
+				return 1; // No error
648 648
 			}
649 649
 			else
650 650
 			{
651
-				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
651
+				$this->error = $langs->transnoentities("ErrorCanNotCreateDir", $dir);
652 652
 				return 0;
653 653
 			}
654 654
 		}
655 655
 		else
656 656
 		{
657
-			$this->error=$langs->transnoentities("ErrorConstantNotDefined","EXP_OUTPUTDIR");
657
+			$this->error = $langs->transnoentities("ErrorConstantNotDefined", "EXP_OUTPUTDIR");
658 658
 			return 0;
659 659
 		}
660 660
 	}
@@ -673,18 +673,18 @@  discard block
 block discarded – undo
673 673
 	function _tableau_tot(&$pdf, $object, $deja_regle, $posy, $outputlangs)
674 674
 	{
675 675
 		// phpcs:enable
676
-		global $conf,$mysoc;
676
+		global $conf, $mysoc;
677 677
 
678
-        $sign=1;
678
+        $sign = 1;
679 679
 
680 680
         $default_font_size = pdf_getPDFFontSize($outputlangs);
681 681
 
682 682
 		$tab2_top = $posy;
683 683
 		$tab2_hl = 4;
684
-		$pdf->SetFont('','B', $default_font_size - 1);
684
+		$pdf->SetFont('', 'B', $default_font_size - 1);
685 685
 
686 686
 		// Tableau total
687
-		$col1x = $this->posxweightvol-50; $col2x = $this->posxweightvol;
687
+		$col1x = $this->posxweightvol - 50; $col2x = $this->posxweightvol;
688 688
 		/*if ($this->page_largeur < 210) // To work with US executive format
689 689
 		{
690 690
 			$col2x-=20;
@@ -692,33 +692,33 @@  discard block
 block discarded – undo
692 692
 		if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED)) $largcol2 = ($this->posxqtyordered - $this->posxweightvol);
693 693
 		else $largcol2 = ($this->posxqtytoship - $this->posxweightvol);
694 694
 
695
-		$useborder=0;
695
+		$useborder = 0;
696 696
 		$index = 0;
697 697
 
698
-		$totalWeighttoshow='';
699
-		$totalVolumetoshow='';
698
+		$totalWeighttoshow = '';
699
+		$totalVolumetoshow = '';
700 700
 
701 701
 		// Load dim data
702
-		$tmparray=$object->getTotalWeightVolume();
703
-		$totalWeight=$tmparray['weight'];
704
-		$totalVolume=$tmparray['volume'];
705
-		$totalOrdered=$tmparray['ordered'];
706
-		$totalToShip=$tmparray['toship'];
702
+		$tmparray = $object->getTotalWeightVolume();
703
+		$totalWeight = $tmparray['weight'];
704
+		$totalVolume = $tmparray['volume'];
705
+		$totalOrdered = $tmparray['ordered'];
706
+		$totalToShip = $tmparray['toship'];
707 707
 		// Set trueVolume and volume_units not currently stored into database
708 708
 		if ($object->trueWidth && $object->trueHeight && $object->trueDepth)
709 709
 		{
710
-		    $object->trueVolume=price(($object->trueWidth * $object->trueHeight * $object->trueDepth), 0, $outputlangs, 0, 0);
711
-		    $object->volume_units=$object->size_units * 3;
710
+		    $object->trueVolume = price(($object->trueWidth * $object->trueHeight * $object->trueDepth), 0, $outputlangs, 0, 0);
711
+		    $object->volume_units = $object->size_units * 3;
712 712
 		}
713 713
 
714
-		if ($totalWeight!='') $totalWeighttoshow=showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs);
715
-		if ($totalVolume!='') $totalVolumetoshow=showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs);
716
-		if ($object->trueWeight) $totalWeighttoshow=showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs);
717
-		if ($object->trueVolume) $totalVolumetoshow=showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs);
714
+		if ($totalWeight != '') $totalWeighttoshow = showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs);
715
+		if ($totalVolume != '') $totalVolumetoshow = showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs);
716
+		if ($object->trueWeight) $totalWeighttoshow = showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs);
717
+		if ($object->trueVolume) $totalVolumetoshow = showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs);
718 718
 
719
-    	$pdf->SetFillColor(255,255,255);
719
+    	$pdf->SetFillColor(255, 255, 255);
720 720
     	$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
721
-    	$pdf->MultiCell($col2x-$col1x, $tab2_hl, $outputlangs->transnoentities("Total"), 0, 'L', 1);
721
+    	$pdf->MultiCell($col2x - $col1x, $tab2_hl, $outputlangs->transnoentities("Total"), 0, 'L', 1);
722 722
 
723 723
         if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
724 724
         {
@@ -758,10 +758,10 @@  discard block
 block discarded – undo
758 758
 
759 759
 			    $index++;
760 760
 			}
761
-			if (! $totalWeighttoshow && ! $totalVolumetoshow) $index++;
761
+			if (!$totalWeighttoshow && !$totalVolumetoshow) $index++;
762 762
 		}
763 763
 
764
-		$pdf->SetTextColor(0,0,0);
764
+		$pdf->SetTextColor(0, 0, 0);
765 765
 
766 766
 		return ($tab2_top + ($tab2_hl * $index));
767 767
 	}
@@ -778,78 +778,78 @@  discard block
 block discarded – undo
778 778
 	 *   @param		int			$hidebottom		Hide bottom bar of array
779 779
 	 *   @return	void
780 780
 	 */
781
-	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop=0, $hidebottom=0)
781
+	function _tableau(&$pdf, $tab_top, $tab_height, $nexY, $outputlangs, $hidetop = 0, $hidebottom = 0)
782 782
 	{
783 783
 		global $conf;
784 784
 
785 785
 		// Force to disable hidetop and hidebottom
786
-		$hidebottom=0;
787
-		if ($hidetop) $hidetop=-1;
786
+		$hidebottom = 0;
787
+		if ($hidetop) $hidetop = -1;
788 788
 
789 789
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
790 790
 
791 791
 		// Amount in (at tab_top - 1)
792
-		$pdf->SetTextColor(0,0,0);
793
-		$pdf->SetFont('','',$default_font_size - 2);
792
+		$pdf->SetTextColor(0, 0, 0);
793
+		$pdf->SetFont('', '', $default_font_size - 2);
794 794
 
795 795
 		// Output Rect
796
-		$this->printRect($pdf,$this->marge_gauche, $tab_top, $this->page_largeur-$this->marge_gauche-$this->marge_droite, $tab_height, $hidetop, $hidebottom);	// Rect prend une longueur en 3eme param et 4eme param
796
+		$this->printRect($pdf, $this->marge_gauche, $tab_top, $this->page_largeur - $this->marge_gauche - $this->marge_droite, $tab_height, $hidetop, $hidebottom); // Rect prend une longueur en 3eme param et 4eme param
797 797
 
798
-		$pdf->SetDrawColor(128,128,128);
799
-		$pdf->SetFont('','', $default_font_size - 1);
798
+		$pdf->SetDrawColor(128, 128, 128);
799
+		$pdf->SetFont('', '', $default_font_size - 1);
800 800
 
801 801
 		if (empty($hidetop))
802 802
 		{
803
-			$pdf->line($this->marge_gauche, $tab_top+5, $this->page_largeur-$this->marge_droite, $tab_top+5);
803
+			$pdf->line($this->marge_gauche, $tab_top + 5, $this->page_largeur - $this->marge_droite, $tab_top + 5);
804 804
 
805
-			$pdf->SetXY($this->posxdesc-1, $tab_top+1);
805
+			$pdf->SetXY($this->posxdesc - 1, $tab_top + 1);
806 806
 			$pdf->MultiCell($this->posxqtyordered - $this->posxdesc, 2, $outputlangs->transnoentities("Description"), '', 'L');
807 807
 		}
808 808
 
809 809
 		if (empty($conf->global->SHIPPING_PDF_HIDE_WEIGHT_AND_VOLUME))
810 810
 		{
811
-			$pdf->line($this->posxweightvol-1, $tab_top, $this->posxweightvol-1, $tab_top + $tab_height);
811
+			$pdf->line($this->posxweightvol - 1, $tab_top, $this->posxweightvol - 1, $tab_top + $tab_height);
812 812
 			if (empty($hidetop))
813 813
 			{
814
-				$pdf->SetXY($this->posxweightvol-1, $tab_top+1);
815
-				$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 2, $outputlangs->transnoentities("WeightVolShort"),'','C');
814
+				$pdf->SetXY($this->posxweightvol - 1, $tab_top + 1);
815
+				$pdf->MultiCell(($this->posxqtyordered - $this->posxweightvol), 2, $outputlangs->transnoentities("WeightVolShort"), '', 'C');
816 816
 			}
817 817
 		}
818 818
 
819 819
         if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED))
820 820
         {
821
-            $pdf->line($this->posxqtyordered-1, $tab_top, $this->posxqtyordered-1, $tab_top + $tab_height);
821
+            $pdf->line($this->posxqtyordered - 1, $tab_top, $this->posxqtyordered - 1, $tab_top + $tab_height);
822 822
     		if (empty($hidetop))
823 823
     		{
824
-    			$pdf->SetXY($this->posxqtyordered-1, $tab_top+1);
825
-    			$pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 2, $outputlangs->transnoentities("QtyOrdered"),'','C');
824
+    			$pdf->SetXY($this->posxqtyordered - 1, $tab_top + 1);
825
+    			$pdf->MultiCell(($this->posxqtytoship - $this->posxqtyordered), 2, $outputlangs->transnoentities("QtyOrdered"), '', 'C');
826 826
     		}
827 827
         }
828 828
 
829 829
         if (empty($conf->global->SHIPPING_PDF_HIDE_QTYTOSHIP))
830 830
         {
831
-			$pdf->line($this->posxqtytoship-1, $tab_top, $this->posxqtytoship-1, $tab_top + $tab_height);
831
+			$pdf->line($this->posxqtytoship - 1, $tab_top, $this->posxqtytoship - 1, $tab_top + $tab_height);
832 832
 			if (empty($hidetop))
833 833
 			{
834
-				$pdf->SetXY($this->posxqtytoship, $tab_top+1);
835
-				$pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 2, $outputlangs->transnoentities("QtyToShip"),'','C');
834
+				$pdf->SetXY($this->posxqtytoship, $tab_top + 1);
835
+				$pdf->MultiCell(($this->posxpuht - $this->posxqtytoship), 2, $outputlangs->transnoentities("QtyToShip"), '', 'C');
836 836
 			}
837 837
         }
838 838
 
839 839
 		if (!empty($conf->global->SHIPPING_PDF_DISPLAY_AMOUNT_HT)) {
840 840
 
841
-			$pdf->line($this->posxpuht-1, $tab_top, $this->posxpuht-1, $tab_top + $tab_height);
841
+			$pdf->line($this->posxpuht - 1, $tab_top, $this->posxpuht - 1, $tab_top + $tab_height);
842 842
 			if (empty($hidetop))
843 843
 			{
844
-				$pdf->SetXY($this->posxpuht-1, $tab_top+1);
845
-				$pdf->MultiCell(($this->posxtotalht - $this->posxpuht), 2, $outputlangs->transnoentities("PriceUHT"),'','C');
844
+				$pdf->SetXY($this->posxpuht - 1, $tab_top + 1);
845
+				$pdf->MultiCell(($this->posxtotalht - $this->posxpuht), 2, $outputlangs->transnoentities("PriceUHT"), '', 'C');
846 846
 			}
847 847
 
848
-			$pdf->line($this->posxtotalht-1, $tab_top, $this->posxtotalht-1, $tab_top + $tab_height);
848
+			$pdf->line($this->posxtotalht - 1, $tab_top, $this->posxtotalht - 1, $tab_top + $tab_height);
849 849
 			if (empty($hidetop))
850 850
 			{
851
-				$pdf->SetXY($this->posxtotalht-1, $tab_top+1);
852
-				$pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 2, $outputlangs->transnoentities("TotalHT"),'','C');
851
+				$pdf->SetXY($this->posxtotalht - 1, $tab_top + 1);
852
+				$pdf->MultiCell(($this->page_largeur - $this->marge_droite - $this->posxtotalht), 2, $outputlangs->transnoentities("TotalHT"), '', 'C');
853 853
 			}
854 854
 		}
855 855
 	}
@@ -865,73 +865,73 @@  discard block
 block discarded – undo
865 865
 	 */
866 866
 	function _pagehead(&$pdf, $object, $showaddress, $outputlangs)
867 867
 	{
868
-		global $conf,$langs,$mysoc;
868
+		global $conf, $langs, $mysoc;
869 869
 
870 870
 		$langs->load("orders");
871 871
 
872 872
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
873 873
 
874
-		pdf_pagehead($pdf,$outputlangs,$this->page_hauteur);
874
+		pdf_pagehead($pdf, $outputlangs, $this->page_hauteur);
875 875
 
876 876
 		// Show Draft Watermark
877
-		if($object->statut==0 && (! empty($conf->global->SHIPPING_DRAFT_WATERMARK)) )
877
+		if ($object->statut == 0 && (!empty($conf->global->SHIPPING_DRAFT_WATERMARK)))
878 878
 		{
879
-            		pdf_watermark($pdf,$outputlangs,$this->page_hauteur,$this->page_largeur,'mm',$conf->global->SHIPPING_DRAFT_WATERMARK);
879
+            		pdf_watermark($pdf, $outputlangs, $this->page_hauteur, $this->page_largeur, 'mm', $conf->global->SHIPPING_DRAFT_WATERMARK);
880 880
 		}
881 881
 
882 882
 		//Prepare la suite
883
-		$pdf->SetTextColor(0,0,60);
884
-		$pdf->SetFont('','B', $default_font_size + 3);
883
+		$pdf->SetTextColor(0, 0, 60);
884
+		$pdf->SetFont('', 'B', $default_font_size + 3);
885 885
 
886 886
 		$w = 110;
887 887
 
888
-		$posy=$this->marge_haute;
889
-		$posx=$this->page_largeur-$this->marge_droite-$w;
888
+		$posy = $this->marge_haute;
889
+		$posx = $this->page_largeur - $this->marge_droite - $w;
890 890
 
891
-		$pdf->SetXY($this->marge_gauche,$posy);
891
+		$pdf->SetXY($this->marge_gauche, $posy);
892 892
 
893 893
 		// Logo
894
-		$logo=$conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
894
+		$logo = $conf->mycompany->dir_output.'/logos/'.$this->emetteur->logo;
895 895
 		if ($this->emetteur->logo)
896 896
 		{
897 897
 			if (is_readable($logo))
898 898
 			{
899
-			    $height=pdf_getHeightForLogo($logo);
900
-			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
899
+			    $height = pdf_getHeightForLogo($logo);
900
+			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height); // width=0 (auto)
901 901
 			}
902 902
 			else
903 903
 			{
904
-				$pdf->SetTextColor(200,0,0);
905
-				$pdf->SetFont('','B', $default_font_size - 2);
906
-				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
904
+				$pdf->SetTextColor(200, 0, 0);
905
+				$pdf->SetFont('', 'B', $default_font_size - 2);
906
+				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound", $logo), 0, 'L');
907 907
 				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
908 908
 			}
909 909
 		}
910 910
 		else
911 911
 		{
912
-			$text=$this->emetteur->name;
912
+			$text = $this->emetteur->name;
913 913
 			$pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
914 914
 		}
915 915
 
916 916
 		// Show barcode
917
-		if (! empty($conf->barcode->enabled))
917
+		if (!empty($conf->barcode->enabled))
918 918
 		{
919
-			$posx=105;
919
+			$posx = 105;
920 920
 		}
921 921
 		else
922 922
 		{
923
-			$posx=$this->marge_gauche+3;
923
+			$posx = $this->marge_gauche + 3;
924 924
 		}
925 925
 		//$pdf->Rect($this->marge_gauche, $this->marge_haute, $this->page_largeur-$this->marge_gauche-$this->marge_droite, 30);
926
-		if (! empty($conf->barcode->enabled))
926
+		if (!empty($conf->barcode->enabled))
927 927
 		{
928 928
 			// TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
929 929
 			//$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
930 930
 			//$pdf->Image($logo,10, 5, 0, 24);
931 931
 		}
932 932
 
933
-		$pdf->SetDrawColor(128,128,128);
934
-		if (! empty($conf->barcode->enabled))
933
+		$pdf->SetDrawColor(128, 128, 128);
934
+		if (!empty($conf->barcode->enabled))
935 935
 		{
936 936
 			// TODO Build code bar with function writeBarCode of barcode module for sending ref $object->ref
937 937
 			//$pdf->SetXY($this->marge_gauche+3, $this->marge_haute+3);
@@ -939,125 +939,125 @@  discard block
 block discarded – undo
939 939
 		}
940 940
 
941 941
 
942
-		$posx=$this->page_largeur - $w - $this->marge_droite;
943
-		$posy=$this->marge_haute;
942
+		$posx = $this->page_largeur - $w - $this->marge_droite;
943
+		$posy = $this->marge_haute;
944 944
 
945
-		$pdf->SetFont('','B', $default_font_size + 2);
946
-		$pdf->SetXY($posx,$posy);
947
-		$pdf->SetTextColor(0,0,60);
948
-		$title=$outputlangs->transnoentities("SendingSheet");
945
+		$pdf->SetFont('', 'B', $default_font_size + 2);
946
+		$pdf->SetXY($posx, $posy);
947
+		$pdf->SetTextColor(0, 0, 60);
948
+		$title = $outputlangs->transnoentities("SendingSheet");
949 949
 		$pdf->MultiCell($w, 4, $title, '', 'R');
950 950
 
951
-		$pdf->SetFont('','', $default_font_size + 1);
951
+		$pdf->SetFont('', '', $default_font_size + 1);
952 952
 
953
-		$posy+=5;
953
+		$posy += 5;
954 954
 
955
-		$pdf->SetXY($posx,$posy);
956
-		$pdf->SetTextColor(0,0,60);
957
-		$pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending") ." : ".$object->ref, '', 'R');
955
+		$pdf->SetXY($posx, $posy);
956
+		$pdf->SetTextColor(0, 0, 60);
957
+		$pdf->MultiCell($w, 4, $outputlangs->transnoentities("RefSending")." : ".$object->ref, '', 'R');
958 958
 
959 959
 		// Date planned delivery
960
-		if (! empty($object->date_delivery))
960
+		if (!empty($object->date_delivery))
961 961
 		{
962
-    			$posy+=4;
963
-    			$pdf->SetXY($posx,$posy);
964
-    			$pdf->SetTextColor(0,0,60);
965
-    			$pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_delivery,"day",false,$outputlangs,true), '', 'R');
962
+    			$posy += 4;
963
+    			$pdf->SetXY($posx, $posy);
964
+    			$pdf->SetTextColor(0, 0, 60);
965
+    			$pdf->MultiCell($w, 4, $outputlangs->transnoentities("DateDeliveryPlanned")." : ".dol_print_date($object->date_delivery, "day", false, $outputlangs, true), '', 'R');
966 966
 		}
967 967
 
968
-		if (! empty($object->thirdparty->code_client))
968
+		if (!empty($object->thirdparty->code_client))
969 969
 		{
970
-			$posy+=4;
971
-			$pdf->SetXY($posx,$posy);
972
-			$pdf->SetTextColor(0,0,60);
973
-			$pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : " . $outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
970
+			$posy += 4;
971
+			$pdf->SetXY($posx, $posy);
972
+			$pdf->SetTextColor(0, 0, 60);
973
+			$pdf->MultiCell($w, 3, $outputlangs->transnoentities("CustomerCode")." : ".$outputlangs->transnoentities($object->thirdparty->code_client), '', 'R');
974 974
 		}
975 975
 
976 976
 
977
-		$pdf->SetFont('','', $default_font_size + 3);
978
-		$Yoff=25;
977
+		$pdf->SetFont('', '', $default_font_size + 3);
978
+		$Yoff = 25;
979 979
 
980 980
 		// Add list of linked orders
981
-		$origin 	= $object->origin;
982
-		$origin_id 	= $object->origin_id;
981
+		$origin = $object->origin;
982
+		$origin_id = $object->origin_id;
983 983
 
984 984
 	    // TODO move to external function
985
-		if (! empty($conf->$origin->enabled))     // commonly $origin='commande'
985
+		if (!empty($conf->$origin->enabled))     // commonly $origin='commande'
986 986
 		{
987 987
 			$outputlangs->load('orders');
988 988
 
989 989
 			$classname = ucfirst($origin);
990 990
 			$linkedobject = new $classname($this->db);
991
-			$result=$linkedobject->fetch($origin_id);
991
+			$result = $linkedobject->fetch($origin_id);
992 992
 			if ($result >= 0)
993 993
 			{
994 994
 			    //$linkedobject->fetchObjectLinked()   Get all linked object to the $linkedobject (commonly order) into $linkedobject->linkedObjects
995 995
 
996
-				$pdf->SetFont('','', $default_font_size - 2);
997
-				$text=$linkedobject->ref;
998
-				if ($linkedobject->ref_client) $text.=' ('.$linkedobject->ref_client.')';
999
-				$Yoff = $Yoff+8;
1000
-				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1001
-				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder") ." : ".$outputlangs->transnoentities($text), 0, 'R');
1002
-				$Yoff = $Yoff+3;
1003
-				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1004
-				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date,"day",false,$outputlangs,true), 0, 'R');
996
+				$pdf->SetFont('', '', $default_font_size - 2);
997
+				$text = $linkedobject->ref;
998
+				if ($linkedobject->ref_client) $text .= ' ('.$linkedobject->ref_client.')';
999
+				$Yoff = $Yoff + 8;
1000
+				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff);
1001
+				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder")." : ".$outputlangs->transnoentities($text), 0, 'R');
1002
+				$Yoff = $Yoff + 3;
1003
+				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w, $Yoff);
1004
+				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("OrderDate")." : ".dol_print_date($linkedobject->date, "day", false, $outputlangs, true), 0, 'R');
1005 1005
 			}
1006 1006
 		}
1007 1007
 
1008 1008
 		if ($showaddress)
1009 1009
 		{
1010 1010
 			// Sender properties
1011
-			$carac_emetteur='';
1011
+			$carac_emetteur = '';
1012 1012
 		 	// Add internal contact of origin element if defined
1013
-			$arrayidcontact=array();
1014
-			if (! empty($origin) && is_object($object->$origin)) $arrayidcontact=$object->$origin->getIdContact('internal','SALESREPFOLL');
1013
+			$arrayidcontact = array();
1014
+			if (!empty($origin) && is_object($object->$origin)) $arrayidcontact = $object->$origin->getIdContact('internal', 'SALESREPFOLL');
1015 1015
 		 	if (count($arrayidcontact) > 0)
1016 1016
 		 	{
1017 1017
 		 		$object->fetch_user(reset($arrayidcontact));
1018
-		 		$carac_emetteur .= ($carac_emetteur ? "\n" : '' ).$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n";
1018
+		 		$carac_emetteur .= ($carac_emetteur ? "\n" : '').$outputlangs->transnoentities("Name").": ".$outputlangs->convToOutputCharset($object->user->getFullName($outputlangs))."\n";
1019 1019
 		 	}
1020 1020
 
1021 1021
 		 	$carac_emetteur .= pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, '', 0, 'source', $object);
1022 1022
 
1023 1023
 			// Show sender
1024
-			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1025
-			$posx=$this->marge_gauche;
1026
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
1024
+			$posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1025
+			$posx = $this->marge_gauche;
1026
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->page_largeur - $this->marge_droite - 80;
1027 1027
 
1028
-			$hautcadre=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
1029
-			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
1028
+			$hautcadre = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
1029
+			$widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
1030 1030
 
1031 1031
 			// Show sender frame
1032
-			$pdf->SetTextColor(0,0,0);
1033
-			$pdf->SetFont('','', $default_font_size - 2);
1034
-			$pdf->SetXY($posx,$posy-5);
1035
-			$pdf->MultiCell(66,5, $outputlangs->transnoentities("Sender").":", 0, 'L');
1036
-			$pdf->SetXY($posx,$posy);
1037
-			$pdf->SetFillColor(230,230,230);
1032
+			$pdf->SetTextColor(0, 0, 0);
1033
+			$pdf->SetFont('', '', $default_font_size - 2);
1034
+			$pdf->SetXY($posx, $posy - 5);
1035
+			$pdf->MultiCell(66, 5, $outputlangs->transnoentities("Sender").":", 0, 'L');
1036
+			$pdf->SetXY($posx, $posy);
1037
+			$pdf->SetFillColor(230, 230, 230);
1038 1038
 			$pdf->MultiCell($widthrecbox, $hautcadre, "", 0, 'R', 1);
1039
-			$pdf->SetTextColor(0,0,60);
1040
-			$pdf->SetFillColor(255,255,255);
1039
+			$pdf->SetTextColor(0, 0, 60);
1040
+			$pdf->SetFillColor(255, 255, 255);
1041 1041
 
1042 1042
 			// Show sender name
1043
-			$pdf->SetXY($posx+2,$posy+3);
1044
-			$pdf->SetFont('','B',$default_font_size);
1045
-			$pdf->MultiCell($widthrecbox-2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
1046
-			$posy=$pdf->getY();
1043
+			$pdf->SetXY($posx + 2, $posy + 3);
1044
+			$pdf->SetFont('', 'B', $default_font_size);
1045
+			$pdf->MultiCell($widthrecbox - 2, 4, $outputlangs->convToOutputCharset($this->emetteur->name), 0, 'L');
1046
+			$posy = $pdf->getY();
1047 1047
 
1048 1048
 			// Show sender information
1049
-			$pdf->SetXY($posx+2,$posy);
1050
-			$pdf->SetFont('','', $default_font_size - 1);
1051
-			$pdf->MultiCell($widthrecbox-2, 4, $carac_emetteur, 0, 'L');
1049
+			$pdf->SetXY($posx + 2, $posy);
1050
+			$pdf->SetFont('', '', $default_font_size - 1);
1051
+			$pdf->MultiCell($widthrecbox - 2, 4, $carac_emetteur, 0, 'L');
1052 1052
 
1053 1053
 
1054 1054
 			// If SHIPPING contact defined, we use it
1055
-			$usecontact=false;
1056
-			$arrayidcontact=$object->$origin->getIdContact('external','SHIPPING');
1055
+			$usecontact = false;
1056
+			$arrayidcontact = $object->$origin->getIdContact('external', 'SHIPPING');
1057 1057
 			if (count($arrayidcontact) > 0)
1058 1058
 			{
1059
-				$usecontact=true;
1060
-				$result=$object->fetch_contact($arrayidcontact[0]);
1059
+				$usecontact = true;
1060
+				$result = $object->fetch_contact($arrayidcontact[0]);
1061 1061
 			}
1062 1062
 
1063 1063
 			//Recipient name
@@ -1068,38 +1068,38 @@  discard block
 block discarded – undo
1068 1068
 				$thirdparty = $object->thirdparty;
1069 1069
 			}
1070 1070
 
1071
-			$carac_client_name= pdfBuildThirdpartyName($thirdparty, $outputlangs);
1071
+			$carac_client_name = pdfBuildThirdpartyName($thirdparty, $outputlangs);
1072 1072
 
1073
-			$carac_client=pdf_build_address($outputlangs,$this->emetteur,$object->thirdparty,(!empty($object->contact)?$object->contact:null),$usecontact,'targetwithdetails',$object);
1073
+			$carac_client = pdf_build_address($outputlangs, $this->emetteur, $object->thirdparty, (!empty($object->contact) ? $object->contact : null), $usecontact, 'targetwithdetails', $object);
1074 1074
 
1075 1075
 			// Show recipient
1076
-			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
1077
-			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
1078
-			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1079
-			$posx=$this->page_largeur - $this->marge_droite - $widthrecbox;
1080
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
1076
+			$widthrecbox = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
1077
+			if ($this->page_largeur < 210) $widthrecbox = 84; // To work with US executive format
1078
+			$posy = !empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1079
+			$posx = $this->page_largeur - $this->marge_droite - $widthrecbox;
1080
+			if (!empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx = $this->marge_gauche;
1081 1081
 
1082 1082
 			// Show recipient frame
1083
-			$pdf->SetTextColor(0,0,0);
1084
-			$pdf->SetFont('','', $default_font_size - 2);
1085
-			$pdf->SetXY($posx+2,$posy-5);
1083
+			$pdf->SetTextColor(0, 0, 0);
1084
+			$pdf->SetFont('', '', $default_font_size - 2);
1085
+			$pdf->SetXY($posx + 2, $posy - 5);
1086 1086
 			$pdf->MultiCell($widthrecbox, 5, $outputlangs->transnoentities("Recipient").":", 0, 'L');
1087 1087
 			$pdf->Rect($posx, $posy, $widthrecbox, $hautcadre);
1088 1088
 
1089 1089
 			// Show recipient name
1090
-			$pdf->SetXY($posx+2,$posy+3);
1091
-			$pdf->SetFont('','B', $default_font_size);
1090
+			$pdf->SetXY($posx + 2, $posy + 3);
1091
+			$pdf->SetFont('', 'B', $default_font_size);
1092 1092
 			$pdf->MultiCell($widthrecbox, 2, $carac_client_name, 0, 'L');
1093 1093
 
1094 1094
 			$posy = $pdf->getY();
1095 1095
 
1096 1096
 			// Show recipient information
1097
-			$pdf->SetFont('','', $default_font_size - 1);
1098
-			$pdf->SetXY($posx+2,$posy);
1097
+			$pdf->SetFont('', '', $default_font_size - 1);
1098
+			$pdf->SetXY($posx + 2, $posy);
1099 1099
 			$pdf->MultiCell($widthrecbox, 4, $carac_client, 0, 'L');
1100 1100
 		}
1101 1101
 
1102
-		$pdf->SetTextColor(0,0,0);
1102
+		$pdf->SetTextColor(0, 0, 0);
1103 1103
 	}
1104 1104
 
1105 1105
 	/**
@@ -1111,10 +1111,10 @@  discard block
 block discarded – undo
1111 1111
 	 *      @param	int			$hidefreetext		1=Hide free text
1112 1112
 	 *      @return	int								Return height of bottom margin including footer text
1113 1113
 	 */
1114
-	function _pagefoot(&$pdf,$object,$outputlangs,$hidefreetext=0)
1114
+	function _pagefoot(&$pdf, $object, $outputlangs, $hidefreetext = 0)
1115 1115
 	{
1116 1116
 		global $conf;
1117
-		$showdetails=$conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
1118
-		return pdf_pagefoot($pdf,$outputlangs,'SHIPPING_FREE_TEXT',$this->emetteur,$this->marge_basse,$this->marge_gauche,$this->page_hauteur,$object,$showdetails,$hidefreetext);
1117
+		$showdetails = $conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS;
1118
+		return pdf_pagefoot($pdf, $outputlangs, 'SHIPPING_FREE_TEXT', $this->emetteur, $this->marge_basse, $this->marge_gauche, $this->page_hauteur, $object, $showdetails, $hidefreetext);
1119 1119
 	}
1120 1120
 }
Please login to merge, or discard this patch.
Braces   +138 added lines, -70 removed lines patch added patch discarded remove patch
@@ -137,7 +137,10 @@  discard block
 block discarded – undo
137 137
 
138 138
 		// Get source company
139 139
 		$this->emetteur=$mysoc;
140
-		if (! $this->emetteur->country_code) $this->emetteur->country_code=substr($langs->defaultlang,-2);    // By default if not defined
140
+		if (! $this->emetteur->country_code) {
141
+		    $this->emetteur->country_code=substr($langs->defaultlang,-2);
142
+		}
143
+		// By default if not defined
141 144
 
142 145
 		// Define position of columns
143 146
 		$this->posxdesc=$this->marge_gauche+1;
@@ -156,9 +159,11 @@  discard block
 block discarded – undo
156 159
 
157 160
 		$this->posxpicture=$this->posxweightvol - (empty($conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH)?20:$conf->global->MAIN_DOCUMENTS_WITH_PICTURE_WIDTH);	// width of images
158 161
 
159
-		if ($this->page_largeur < 210) // To work with US executive format
162
+		if ($this->page_largeur < 210) {
163
+		    // To work with US executive format
160 164
 		{
161 165
 		    $this->posxweightvol-=20;
166
+		}
162 167
 		    $this->posxpicture-=20;
163 168
 		    $this->posxqtyordered-=20;
164 169
 		    $this->posxqtytoship-=20;
@@ -191,9 +196,13 @@  discard block
 block discarded – undo
191 196
 
192 197
 		$object->fetch_thirdparty();
193 198
 
194
-		if (! is_object($outputlangs)) $outputlangs=$langs;
199
+		if (! is_object($outputlangs)) {
200
+		    $outputlangs=$langs;
201
+		}
195 202
 		// For backward compatibility with FPDF, force output charset to ISO, because FPDF expect text to be encoded in ISO
196
-		if (! empty($conf->global->MAIN_USE_FPDF)) $outputlangs->charset_output='ISO-8859-1';
203
+		if (! empty($conf->global->MAIN_USE_FPDF)) {
204
+		    $outputlangs->charset_output='ISO-8859-1';
205
+		}
197 206
 
198 207
 		// Load traductions files requiredby by page
199 208
 		$outputlangs->loadLangs(array("main", "bills", "products", "dict", "companies", "propal", "deliveries", "sendings", "productbatch"));
@@ -208,7 +217,9 @@  discard block
 block discarded – undo
208 217
 
209 218
             for ($i = 0 ; $i < $nblignes ; $i++)
210 219
             {
211
-                if (empty($object->lines[$i]->fk_product)) continue;
220
+                if (empty($object->lines[$i]->fk_product)) {
221
+                    continue;
222
+                }
212 223
 
213 224
 				$objphoto = new Product($this->db);
214 225
 				$objphoto->fetch($object->lines[$i]->fk_product);
@@ -220,18 +231,18 @@  discard block
 block discarded – undo
220 231
 
221 232
                 foreach ($objphoto->liste_photos($dir,1) as $key => $obj)
222 233
                         {
223
-                            if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES))		// If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo
234
+                            if (empty($conf->global->CAT_HIGH_QUALITY_IMAGES)) {
235
+                                // If CAT_HIGH_QUALITY_IMAGES not defined, we use thumb if defined and then original photo
224 236
                             {
225 237
                                 if ($obj['photo_vignette'])
226 238
                                 {
227 239
                                     $filename= $obj['photo_vignette'];
228
-                                }
229
-                                else
240
+                            }
241
+                                } else
230 242
                                 {
231 243
                                     $filename=$obj['photo'];
232 244
                                 }
233
-                            }
234
-                            else
245
+                            } else
235 246
                             {
236 247
                                 $filename=$obj['photo'];
237 248
                             }
@@ -240,11 +251,15 @@  discard block
 block discarded – undo
240 251
                             break;
241 252
                 }
242 253
 
243
-                if ($realpath) $realpatharray[$i]=$realpath;
254
+                if ($realpath) {
255
+                    $realpatharray[$i]=$realpath;
256
+                }
244 257
             }
245 258
         }
246 259
 
247
-        if (count($realpatharray) == 0) $this->posxpicture=$this->posxweightvol;
260
+        if (count($realpatharray) == 0) {
261
+            $this->posxpicture=$this->posxweightvol;
262
+        }
248 263
 
249 264
 		if ($conf->expedition->dir_output)
250 265
 		{
@@ -253,8 +268,7 @@  discard block
 block discarded – undo
253 268
 			{
254 269
 				$dir = $conf->expedition->dir_output."/sending";
255 270
 				$file = $dir . "/SPECIMEN.pdf";
256
-			}
257
-			else
271
+			} else
258 272
 			{
259 273
 				$expref = dol_sanitizeFileName($object->ref);
260 274
 				$dir = $conf->expedition->dir_output."/sending/" . $expref;
@@ -291,7 +305,9 @@  discard block
 block discarded – undo
291 305
 				$heightforinfotot = 8;	// Height reserved to output the info and total part
292 306
 		        $heightforfreetext= (isset($conf->global->MAIN_PDF_FREETEXT_HEIGHT)?$conf->global->MAIN_PDF_FREETEXT_HEIGHT:5);	// Height reserved to output the free text on last page
293 307
 	            $heightforfooter = $this->marge_basse + 8;	// Height reserved to output the footer (value include bottom margin)
294
-	            if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) $heightforfooter+= 6;
308
+	            if ($conf->global->MAIN_GENERATE_DOCUMENTS_SHOW_FOOT_DETAILS >0) {
309
+	                $heightforfooter+= 6;
310
+	            }
295 311
                 $pdf->SetAutoPageBreak(1,0);
296 312
 
297 313
                 if (class_exists('TCPDF'))
@@ -311,20 +327,26 @@  discard block
 block discarded – undo
311 327
 				$pagenb=0;
312 328
 				$pdf->SetDrawColor(128,128,128);
313 329
 
314
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
330
+				if (method_exists($pdf,'AliasNbPages')) {
331
+				    $pdf->AliasNbPages();
332
+				}
315 333
 
316 334
 				$pdf->SetTitle($outputlangs->convToOutputCharset($object->ref));
317 335
 				$pdf->SetSubject($outputlangs->transnoentities("Shipment"));
318 336
 				$pdf->SetCreator("Dolibarr ".DOL_VERSION);
319 337
 				$pdf->SetAuthor($outputlangs->convToOutputCharset($user->getFullName($outputlangs)));
320 338
 				$pdf->SetKeyWords($outputlangs->convToOutputCharset($object->ref)." ".$outputlangs->transnoentities("Shipment"));
321
-				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) $pdf->SetCompression(false);
339
+				if (! empty($conf->global->MAIN_DISABLE_PDF_COMPRESSION)) {
340
+				    $pdf->SetCompression(false);
341
+				}
322 342
 
323 343
 				$pdf->SetMargins($this->marge_gauche, $this->marge_haute, $this->marge_droite);   // Left, Top, Right
324 344
 
325 345
 				// New page
326 346
 				$pdf->AddPage();
327
-				if (! empty($tplidx)) $pdf->useTemplate($tplidx);
347
+				if (! empty($tplidx)) {
348
+				    $pdf->useTemplate($tplidx);
349
+				}
328 350
 				$pagenb++;
329 351
 				$this->_pagehead($pdf, $object, 1, $outputlangs);
330 352
 				$pdf->SetFont('','', $default_font_size - 1);
@@ -381,7 +403,9 @@  discard block
 block discarded – undo
381 403
 								// Get code using getLabelFromKey
382 404
 								$code=$outputlangs->getLabelFromKey($this->db,$object->shipping_method_id,'c_shipment_mode','rowid','code');
383 405
 								$label='';
384
-								if ($object->tracking_url != $object->tracking_number) $label.=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
406
+								if ($object->tracking_url != $object->tracking_number) {
407
+								    $label.=$outputlangs->trans("LinkToTrackYourPackage")."<br>";
408
+								}
385 409
 								$label.=$outputlangs->trans("SendingMethod").": ".$outputlangs->trans("SendingMethod".strtoupper($code));
386 410
 								//var_dump($object->tracking_url != $object->tracking_number);exit;
387 411
 								if ($object->tracking_url != $object->tracking_number)
@@ -413,8 +437,7 @@  discard block
 block discarded – undo
413 437
 
414 438
 					$tab_height = $tab_height - $height_note;
415 439
 					$tab_top = $nexY+6;
416
-				}
417
-				else
440
+				} else
418 441
 				{
419 442
 					$height_note=0;
420 443
 				}
@@ -432,7 +455,9 @@  discard block
 block discarded – undo
432 455
 
433 456
 					// Define size of image if we need it
434 457
 					$imglinesize=array();
435
-					if (! empty($realpatharray[$i])) $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
458
+					if (! empty($realpatharray[$i])) {
459
+					    $imglinesize=pdf_getSizeForImage($realpatharray[$i]);
460
+					}
436 461
 
437 462
 					$pdf->setTopMargin($tab_top_newpage);
438 463
 					$pdf->setPageOrientation('', 1, $heightforfooter+$heightforfreetext+$heightforinfotot);	// The only function to edit the bottom margin of current page to set it.
@@ -443,11 +468,17 @@  discard block
 block discarded – undo
443 468
 					$posYAfterDescription=0;
444 469
 
445 470
 					// We start with Photo of product line
446
-					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot)))	// If photo too high, we moved completely on new page
471
+					if (isset($imglinesize['width']) && isset($imglinesize['height']) && ($curY + $imglinesize['height']) > ($this->page_hauteur-($heightforfooter+$heightforfreetext+$heightforinfotot))) {
472
+					    // If photo too high, we moved completely on new page
447 473
 					{
448 474
 						$pdf->AddPage('','',true);
449
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
450
-						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
475
+					}
476
+						if (! empty($tplidx)) {
477
+						    $pdf->useTemplate($tplidx);
478
+						}
479
+						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
480
+						    $this->_pagehead($pdf, $object, 0, $outputlangs);
481
+						}
451 482
 						$pdf->setPage($pageposbefore+1);
452 483
 
453 484
 						$curY = $tab_top_newpage;
@@ -469,9 +500,11 @@  discard block
 block discarded – undo
469 500
 					pdf_writelinedesc($pdf,$object,$i,$outputlangs,$this->posxpicture-$curX,3,$curX,$curY,$hideref,$hidedesc);
470 501
 
471 502
 					$pageposafter=$pdf->getPage();
472
-					if ($pageposafter > $pageposbefore)	// There is a pagebreak
503
+					if ($pageposafter > $pageposbefore) {
504
+					    // There is a pagebreak
473 505
 					{
474 506
 						$pdf->rollbackTransaction(true);
507
+					}
475 508
 						$pageposafter=$pageposbefore;
476 509
 						//print $pageposafter.'-'.$pageposbefore;exit;
477 510
 						$pdf->setPageOrientation('', 1, $heightforfooter);	// The only function to edit the bottom margin of current page to set it.
@@ -480,23 +513,27 @@  discard block
 block discarded – undo
480 513
 						$pageposafter=$pdf->getPage();
481 514
 						$posyafter=$pdf->GetY();
482 515
 						//var_dump($posyafter); var_dump(($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))); exit;
483
-						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot)))	// There is no space left for total+free text
516
+						if ($posyafter > ($this->page_hauteur - ($heightforfooter+$heightforfreetext+$heightforinfotot))) {
517
+						    // There is no space left for total+free text
484 518
 						{
485 519
 							if ($i == ($nblignes-1))	// No more lines, and no space left to show total, so we create a new page
486 520
 							{
487 521
 								$pdf->AddPage('','',true);
488
-								if (! empty($tplidx)) $pdf->useTemplate($tplidx);
489
-								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
522
+						}
523
+								if (! empty($tplidx)) {
524
+								    $pdf->useTemplate($tplidx);
525
+								}
526
+								if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
527
+								    $this->_pagehead($pdf, $object, 0, $outputlangs);
528
+								}
490 529
 								$pdf->setPage($pageposafter+1);
491 530
 							}
492
-						}
493
-						else
531
+						} else
494 532
 						{
495 533
 							// We found a page break
496 534
 							$showpricebeforepagebreak=0;
497 535
 						}
498
-					}
499
-					else	// No pagebreak
536
+					} else	// No pagebreak
500 537
 					{
501 538
 						$pdf->commitTransaction();
502 539
 					}
@@ -561,7 +598,9 @@  discard block
 block discarded – undo
561 598
 					}
562 599
 
563 600
 					$nexY+=3;
564
-					if ($weighttxt && $voltxt) $nexY+=2;
601
+					if ($weighttxt && $voltxt) {
602
+					    $nexY+=2;
603
+					}
565 604
 
566 605
 					// Add line
567 606
 					if (! empty($conf->global->MAIN_PDF_DASH_BETWEEN_LINES) && $i < ($nblignes - 1))
@@ -580,8 +619,7 @@  discard block
 block discarded – undo
580 619
 						if ($pagenb == 1)
581 620
 						{
582 621
 							$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
583
-						}
584
-						else
622
+						} else
585 623
 						{
586 624
 							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
587 625
 						}
@@ -589,24 +627,29 @@  discard block
 block discarded – undo
589 627
 						$pagenb++;
590 628
 						$pdf->setPage($pagenb);
591 629
 						$pdf->setPageOrientation('', 1, 0);	// The only function to edit the bottom margin of current page to set it.
592
-						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
630
+						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
631
+						    $this->_pagehead($pdf, $object, 0, $outputlangs);
632
+						}
593 633
 					}
594 634
 					if (isset($object->lines[$i+1]->pagebreak) && $object->lines[$i+1]->pagebreak)
595 635
 					{
596 636
 						if ($pagenb == 1)
597 637
 						{
598 638
 							$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforfooter, 0, $outputlangs, 0, 1);
599
-						}
600
-						else
639
+						} else
601 640
 						{
602 641
 							$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforfooter, 0, $outputlangs, 1, 1);
603 642
 						}
604 643
 						$this->_pagefoot($pdf,$object,$outputlangs,1);
605 644
 						// New page
606 645
 						$pdf->AddPage();
607
-						if (! empty($tplidx)) $pdf->useTemplate($tplidx);
646
+						if (! empty($tplidx)) {
647
+						    $pdf->useTemplate($tplidx);
648
+						}
608 649
 						$pagenb++;
609
-						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) $this->_pagehead($pdf, $object, 0, $outputlangs);
650
+						if (empty($conf->global->MAIN_PDF_DONOTREPEAT_HEAD)) {
651
+						    $this->_pagehead($pdf, $object, 0, $outputlangs);
652
+						}
610 653
 					}
611 654
 				}
612 655
 
@@ -615,8 +658,7 @@  discard block
 block discarded – undo
615 658
 				{
616 659
 					$this->_tableau($pdf, $tab_top, $this->page_hauteur - $tab_top - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 0, 0);
617 660
 					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
618
-				}
619
-				else
661
+				} else
620 662
 				{
621 663
 					$this->_tableau($pdf, $tab_top_newpage, $this->page_hauteur - $tab_top_newpage - $heightforinfotot - $heightforfreetext - $heightforfooter, 0, $outputlangs, 1, 0);
622 664
 					$bottomlasttab=$this->page_hauteur - $heightforinfotot - $heightforfreetext - $heightforfooter + 1;
@@ -627,7 +669,9 @@  discard block
 block discarded – undo
627 669
 
628 670
 				// Pied de page
629 671
 				$this->_pagefoot($pdf,$object,$outputlangs);
630
-				if (method_exists($pdf,'AliasNbPages')) $pdf->AliasNbPages();
672
+				if (method_exists($pdf,'AliasNbPages')) {
673
+				    $pdf->AliasNbPages();
674
+				}
631 675
 
632 676
 				$pdf->Close();
633 677
 
@@ -639,20 +683,19 @@  discard block
 block discarded – undo
639 683
 				global $action;
640 684
 				$reshook=$hookmanager->executeHooks('afterPDFCreation',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
641 685
 
642
-				if (! empty($conf->global->MAIN_UMASK))
643
-				@chmod($file, octdec($conf->global->MAIN_UMASK));
686
+				if (! empty($conf->global->MAIN_UMASK)) {
687
+								@chmod($file, octdec($conf->global->MAIN_UMASK));
688
+				}
644 689
 
645 690
 				$this->result = array('fullpath'=>$file);
646 691
 
647 692
 				return 1;	// No error
648
-			}
649
-			else
693
+			} else
650 694
 			{
651 695
 				$this->error=$langs->transnoentities("ErrorCanNotCreateDir",$dir);
652 696
 				return 0;
653 697
 			}
654
-		}
655
-		else
698
+		} else
656 699
 		{
657 700
 			$this->error=$langs->transnoentities("ErrorConstantNotDefined","EXP_OUTPUTDIR");
658 701
 			return 0;
@@ -689,8 +732,11 @@  discard block
 block discarded – undo
689 732
 		{
690 733
 			$col2x-=20;
691 734
 		}*/
692
-		if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED)) $largcol2 = ($this->posxqtyordered - $this->posxweightvol);
693
-		else $largcol2 = ($this->posxqtytoship - $this->posxweightvol);
735
+		if (empty($conf->global->SHIPPING_PDF_HIDE_ORDERED)) {
736
+		    $largcol2 = ($this->posxqtyordered - $this->posxweightvol);
737
+		} else {
738
+		    $largcol2 = ($this->posxqtytoship - $this->posxweightvol);
739
+		}
694 740
 
695 741
 		$useborder=0;
696 742
 		$index = 0;
@@ -711,10 +757,18 @@  discard block
 block discarded – undo
711 757
 		    $object->volume_units=$object->size_units * 3;
712 758
 		}
713 759
 
714
-		if ($totalWeight!='') $totalWeighttoshow=showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs);
715
-		if ($totalVolume!='') $totalVolumetoshow=showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs);
716
-		if ($object->trueWeight) $totalWeighttoshow=showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs);
717
-		if ($object->trueVolume) $totalVolumetoshow=showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs);
760
+		if ($totalWeight!='') {
761
+		    $totalWeighttoshow=showDimensionInBestUnit($totalWeight, 0, "weight", $outputlangs);
762
+		}
763
+		if ($totalVolume!='') {
764
+		    $totalVolumetoshow=showDimensionInBestUnit($totalVolume, 0, "volume", $outputlangs);
765
+		}
766
+		if ($object->trueWeight) {
767
+		    $totalWeighttoshow=showDimensionInBestUnit($object->trueWeight, $object->weight_units, "weight", $outputlangs);
768
+		}
769
+		if ($object->trueVolume) {
770
+		    $totalVolumetoshow=showDimensionInBestUnit($object->trueVolume, $object->volume_units, "volume", $outputlangs);
771
+		}
718 772
 
719 773
     	$pdf->SetFillColor(255,255,255);
720 774
     	$pdf->SetXY($col1x, $tab2_top + $tab2_hl * $index);
@@ -758,7 +812,9 @@  discard block
 block discarded – undo
758 812
 
759 813
 			    $index++;
760 814
 			}
761
-			if (! $totalWeighttoshow && ! $totalVolumetoshow) $index++;
815
+			if (! $totalWeighttoshow && ! $totalVolumetoshow) {
816
+			    $index++;
817
+			}
762 818
 		}
763 819
 
764 820
 		$pdf->SetTextColor(0,0,0);
@@ -784,7 +840,9 @@  discard block
 block discarded – undo
784 840
 
785 841
 		// Force to disable hidetop and hidebottom
786 842
 		$hidebottom=0;
787
-		if ($hidetop) $hidetop=-1;
843
+		if ($hidetop) {
844
+		    $hidetop=-1;
845
+		}
788 846
 
789 847
 		$default_font_size = pdf_getPDFFontSize($outputlangs);
790 848
 
@@ -898,16 +956,14 @@  discard block
 block discarded – undo
898 956
 			{
899 957
 			    $height=pdf_getHeightForLogo($logo);
900 958
 			    $pdf->Image($logo, $this->marge_gauche, $posy, 0, $height);	// width=0 (auto)
901
-			}
902
-			else
959
+			} else
903 960
 			{
904 961
 				$pdf->SetTextColor(200,0,0);
905 962
 				$pdf->SetFont('','B', $default_font_size - 2);
906 963
 				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorLogoFileNotFound",$logo), 0, 'L');
907 964
 				$pdf->MultiCell($w, 3, $outputlangs->transnoentities("ErrorGoToGlobalSetup"), 0, 'L');
908 965
 			}
909
-		}
910
-		else
966
+		} else
911 967
 		{
912 968
 			$text=$this->emetteur->name;
913 969
 			$pdf->MultiCell($w, 4, $outputlangs->convToOutputCharset($text), 0, 'L');
@@ -917,8 +973,7 @@  discard block
 block discarded – undo
917 973
 		if (! empty($conf->barcode->enabled))
918 974
 		{
919 975
 			$posx=105;
920
-		}
921
-		else
976
+		} else
922 977
 		{
923 978
 			$posx=$this->marge_gauche+3;
924 979
 		}
@@ -982,9 +1037,11 @@  discard block
 block discarded – undo
982 1037
 		$origin_id 	= $object->origin_id;
983 1038
 
984 1039
 	    // TODO move to external function
985
-		if (! empty($conf->$origin->enabled))     // commonly $origin='commande'
1040
+		if (! empty($conf->$origin->enabled)) {
1041
+		    // commonly $origin='commande'
986 1042
 		{
987 1043
 			$outputlangs->load('orders');
1044
+		}
988 1045
 
989 1046
 			$classname = ucfirst($origin);
990 1047
 			$linkedobject = new $classname($this->db);
@@ -995,7 +1052,9 @@  discard block
 block discarded – undo
995 1052
 
996 1053
 				$pdf->SetFont('','', $default_font_size - 2);
997 1054
 				$text=$linkedobject->ref;
998
-				if ($linkedobject->ref_client) $text.=' ('.$linkedobject->ref_client.')';
1055
+				if ($linkedobject->ref_client) {
1056
+				    $text.=' ('.$linkedobject->ref_client.')';
1057
+				}
999 1058
 				$Yoff = $Yoff+8;
1000 1059
 				$pdf->SetXY($this->page_largeur - $this->marge_droite - $w,$Yoff);
1001 1060
 				$pdf->MultiCell($w, 2, $outputlangs->transnoentities("RefOrder") ." : ".$outputlangs->transnoentities($text), 0, 'R');
@@ -1011,7 +1070,9 @@  discard block
 block discarded – undo
1011 1070
 			$carac_emetteur='';
1012 1071
 		 	// Add internal contact of origin element if defined
1013 1072
 			$arrayidcontact=array();
1014
-			if (! empty($origin) && is_object($object->$origin)) $arrayidcontact=$object->$origin->getIdContact('internal','SALESREPFOLL');
1073
+			if (! empty($origin) && is_object($object->$origin)) {
1074
+			    $arrayidcontact=$object->$origin->getIdContact('internal','SALESREPFOLL');
1075
+			}
1015 1076
 		 	if (count($arrayidcontact) > 0)
1016 1077
 		 	{
1017 1078
 		 		$object->fetch_user(reset($arrayidcontact));
@@ -1023,7 +1084,9 @@  discard block
 block discarded – undo
1023 1084
 			// Show sender
1024 1085
 			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1025 1086
 			$posx=$this->marge_gauche;
1026
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->page_largeur-$this->marge_droite-80;
1087
+			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
1088
+			    $posx=$this->page_largeur-$this->marge_droite-80;
1089
+			}
1027 1090
 
1028 1091
 			$hautcadre=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 38 : 40;
1029 1092
 			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 82;
@@ -1074,10 +1137,15 @@  discard block
 block discarded – undo
1074 1137
 
1075 1138
 			// Show recipient
1076 1139
 			$widthrecbox=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 92 : 100;
1077
-			if ($this->page_largeur < 210) $widthrecbox=84;	// To work with US executive format
1140
+			if ($this->page_largeur < 210) {
1141
+			    $widthrecbox=84;
1142
+			}
1143
+			// To work with US executive format
1078 1144
 			$posy=!empty($conf->global->MAIN_PDF_USE_ISO_LOCATION) ? 40 : 42;
1079 1145
 			$posx=$this->page_largeur - $this->marge_droite - $widthrecbox;
1080
-			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) $posx=$this->marge_gauche;
1146
+			if (! empty($conf->global->MAIN_INVERT_SENDER_RECIPIENT)) {
1147
+			    $posx=$this->marge_gauche;
1148
+			}
1081 1149
 
1082 1150
 			// Show recipient frame
1083 1151
 			$pdf->SetTextColor(0,0,0);
Please login to merge, or discard this patch.