Passed
Push — master ( a56e33...222e44 )
by Alxarafe
36:56
created
dolibarr/htdocs/core/ajax/vatrates.php 3 patches
Indentation   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -43,28 +43,28 @@
 block discarded – undo
43 43
 // Load original field value
44 44
 if (! empty($id) && ! empty($action) && ! empty($htmlname))
45 45
 {
46
-	$form = new Form($db);
47
-	$soc = new Societe($db);
46
+    $form = new Form($db);
47
+    $soc = new Societe($db);
48 48
 
49
-	$soc->fetch($id);
49
+    $soc->fetch($id);
50 50
 
51
-	if ($action == 'getSellerVATRates')
52
-	{
53
-		$seller = $mysoc;
54
-		$buyer = $soc;
55
-	}
56
-	else
57
-	{
58
-		$buyer = $mysoc;
59
-		$seller = $soc;
60
-	}
51
+    if ($action == 'getSellerVATRates')
52
+    {
53
+        $seller = $mysoc;
54
+        $buyer = $soc;
55
+    }
56
+    else
57
+    {
58
+        $buyer = $mysoc;
59
+        $seller = $soc;
60
+    }
61 61
 
62
-	$return=array();
62
+    $return=array();
63 63
 
64
-	$return['value']	= $form->load_tva('tva_tx',$selected,$seller,$buyer,$productid,0,'',true);
65
-	$return['num']		= $form->num;
66
-	$return['error']	= $form->error;
64
+    $return['value']	= $form->load_tva('tva_tx',$selected,$seller,$buyer,$productid,0,'',true);
65
+    $return['num']		= $form->num;
66
+    $return['error']	= $form->error;
67 67
 
68
-	echo json_encode($return);
68
+    echo json_encode($return);
69 69
 }
70 70
 
Please login to merge, or discard this patch.
Braces   +11 added lines, -5 removed lines patch added patch discarded remove patch
@@ -20,9 +20,16 @@  discard block
 block discarded – undo
20 20
  *       \brief      File to load vat rates combobox
21 21
  */
22 22
 
23
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
24
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
25
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
23
+if (! defined('NOTOKENRENEWAL')) {
24
+    define('NOTOKENRENEWAL','1');
25
+}
26
+// Disables token renewal
27
+if (! defined('NOREQUIREMENU')) {
28
+    define('NOREQUIREMENU','1');
29
+}
30
+if (! defined('NOREQUIREAJAX')) {
31
+    define('NOREQUIREAJAX','1');
32
+}
26 33
 
27 34
 
28 35
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
@@ -55,8 +62,7 @@  discard block
 block discarded – undo
55 62
 	{
56 63
 		$seller = $mysoc;
57 64
 		$buyer = $soc;
58
-	}
59
-	else
65
+	} else
60 66
 	{
61 67
 		$buyer = $mysoc;
62 68
 		$seller = $soc;
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -20,20 +20,20 @@  discard block
 block discarded – undo
20 20
  *       \brief      File to load vat rates combobox
21 21
  */
22 22
 
23
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
24
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
25
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
23
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
24
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
25
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
26 26
 
27 27
 
28 28
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
29 29
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
30
-require DOL_BASE_PATH . '/main.inc.php';
30
+require DOL_BASE_PATH.'/main.inc.php';
31 31
 
32
-$id			= GETPOST('id','int');
33
-$action		= GETPOST('action','alpha');
34
-$htmlname	= GETPOST('htmlname','alpha');
35
-$selected	= (GETPOST('selected')?GETPOST('selected'):'-1');
36
-$productid	= (GETPOST('productid','int')?GETPOST('productid','int'):0);
32
+$id = GETPOST('id', 'int');
33
+$action = GETPOST('action', 'alpha');
34
+$htmlname	= GETPOST('htmlname', 'alpha');
35
+$selected	= (GETPOST('selected') ?GETPOST('selected') : '-1');
36
+$productid = (GETPOST('productid', 'int') ?GETPOST('productid', 'int') : 0);
37 37
 
38 38
 /*
39 39
  * View
@@ -44,7 +44,7 @@  discard block
 block discarded – undo
44 44
 //print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
45 45
 
46 46
 // Load original field value
47
-if (! empty($id) && ! empty($action) && ! empty($htmlname))
47
+if (!empty($id) && !empty($action) && !empty($htmlname))
48 48
 {
49 49
 	$form = new Form($db);
50 50
 	$soc = new Societe($db);
@@ -62,10 +62,10 @@  discard block
 block discarded – undo
62 62
 		$seller = $soc;
63 63
 	}
64 64
 
65
-	$return=array();
65
+	$return = array();
66 66
 
67
-	$return['value']	= $form->load_tva('tva_tx',$selected,$seller,$buyer,$productid,0,'',true);
68
-	$return['num']		= $form->num;
67
+	$return['value']	= $form->load_tva('tva_tx', $selected, $seller, $buyer, $productid, 0, '', true);
68
+	$return['num'] = $form->num;
69 69
 	$return['error']	= $form->error;
70 70
 
71 71
 	echo json_encode($return);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/ajax/contacts.php 3 patches
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -43,15 +43,15 @@
 block discarded – undo
43 43
 // Load original field value
44 44
 if (! empty($id) && ! empty($action) && ! empty($htmlname))
45 45
 {
46
-	$form = new Form($db);
46
+    $form = new Form($db);
47 47
 
48
-	$return=array();
49
-	if (empty($showempty)) $showempty=0;
48
+    $return=array();
49
+    if (empty($showempty)) $showempty=0;
50 50
 
51
-	$return['value']	= $form->selectcontacts($id,'',$htmlname,$showempty,'','',0,'',true);
52
-	$return['num']		= $form->num;
53
-	$return['error']	= $form->error;
51
+    $return['value']	= $form->selectcontacts($id,'',$htmlname,$showempty,'','',0,'',true);
52
+    $return['num']		= $form->num;
53
+    $return['error']	= $form->error;
54 54
 
55
-	echo json_encode($return);
55
+    echo json_encode($return);
56 56
 }
57 57
 
Please login to merge, or discard this patch.
Braces   +13 added lines, -4 removed lines patch added patch discarded remove patch
@@ -21,9 +21,16 @@  discard block
 block discarded – undo
21 21
  *       \brief      File to load contacts combobox
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
26
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
24
+if (! defined('NOTOKENRENEWAL')) {
25
+    define('NOTOKENRENEWAL','1');
26
+}
27
+// Disables token renewal
28
+if (! defined('NOREQUIREMENU')) {
29
+    define('NOREQUIREMENU','1');
30
+}
31
+if (! defined('NOREQUIREAJAX')) {
32
+    define('NOREQUIREAJAX','1');
33
+}
27 34
 
28 35
 
29 36
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
@@ -49,7 +56,9 @@  discard block
 block discarded – undo
49 56
 	$form = new Form($db);
50 57
 
51 58
 	$return=array();
52
-	if (empty($showempty)) $showempty=0;
59
+	if (empty($showempty)) {
60
+	    $showempty=0;
61
+	}
53 62
 
54 63
 	$return['value']	= $form->selectcontacts($id,'',$htmlname,$showempty,'','',0,'',true);
55 64
 	$return['num']		= $form->num;
Please login to merge, or discard this patch.
Spacing   +13 added lines, -13 removed lines patch added patch discarded remove patch
@@ -21,19 +21,19 @@  discard block
 block discarded – undo
21 21
  *       \brief      File to load contacts combobox
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
26
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
24
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
25
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
26
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
27 27
 
28 28
 
29 29
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
30 30
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
31
-require DOL_BASE_PATH . '/main.inc.php';
31
+require DOL_BASE_PATH.'/main.inc.php';
32 32
 
33
-$id			= GETPOST('id','int');
34
-$action		= GETPOST('action','alpha');
35
-$htmlname	= GETPOST('htmlname','alpha');
36
-$showempty	= GETPOST('showempty','int');
33
+$id = GETPOST('id', 'int');
34
+$action = GETPOST('action', 'alpha');
35
+$htmlname = GETPOST('htmlname', 'alpha');
36
+$showempty = GETPOST('showempty', 'int');
37 37
 
38 38
 /*
39 39
  * View
@@ -44,15 +44,15 @@  discard block
 block discarded – undo
44 44
 //print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
45 45
 
46 46
 // Load original field value
47
-if (! empty($id) && ! empty($action) && ! empty($htmlname))
47
+if (!empty($id) && !empty($action) && !empty($htmlname))
48 48
 {
49 49
 	$form = new Form($db);
50 50
 
51
-	$return=array();
52
-	if (empty($showempty)) $showempty=0;
51
+	$return = array();
52
+	if (empty($showempty)) $showempty = 0;
53 53
 
54
-	$return['value']	= $form->selectcontacts($id,'',$htmlname,$showempty,'','',0,'',true);
55
-	$return['num']		= $form->num;
54
+	$return['value']	= $form->selectcontacts($id, '', $htmlname, $showempty, '', '', 0, '', true);
55
+	$return['num'] = $form->num;
56 56
 	$return['error']	= $form->error;
57 57
 
58 58
 	echo json_encode($return);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/ajax/saveinplace.php 3 patches
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -58,175 +58,175 @@
 block discarded – undo
58 58
 // Load original field value
59 59
 if (! empty($field) && ! empty($element) && ! empty($table_element) && ! empty($fk_element))
60 60
 {
61
-	$ext_element		= GETPOST('ext_element','alpha',2);
62
-	$field				= substr($field, 8); // remove prefix val_
63
-	$type				= GETPOST('type','alpha',2);
64
-	$value				= ($type == 'ckeditor' ? GETPOST('value','',2) : GETPOST('value','alpha',2));
65
-	$loadmethod			= GETPOST('loadmethod','alpha',2);
66
-	$savemethod			= GETPOST('savemethod','alpha',2);
67
-	$savemethodname		= (! empty($savemethod) ? $savemethod : 'setValueFrom');
68
-	$newelement			= $element;
69
-
70
-	$view='';
71
-	$format='text';
72
-	$return=array();
73
-	$error=0;
74
-
75
-	if ($element != 'order_supplier' && $element != 'invoice_supplier' && preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
76
-	{
77
-		$element = $regs[1];
78
-		$subelement = $regs[2];
79
-	}
80
-
81
-	if ($element == 'propal') $newelement = 'propale';
82
-	else if ($element == 'fichinter') $newelement = 'ficheinter';
83
-	else if ($element == 'product') $newelement = 'produit';
84
-	else if ($element == 'member') $newelement = 'adherent';
85
-	else if ($element == 'order_supplier') {
86
-		$newelement = 'fournisseur';
87
-		$subelement = 'commande';
88
-	}
89
-	else if ($element == 'invoice_supplier') {
90
-		$newelement = 'fournisseur';
91
-		$subelement = 'facture';
92
-	}
93
-	else $newelement = $element;
94
-
95
-	$_POST['action']='update';	// Hack so restrictarea will test permissions on write too
96
-	$feature = $newelement;
97
-	$feature2 = $subelement;
98
-	$object_id = $fk_element;
99
-	if ($feature == 'expedition' || $feature == 'shipping')
100
-	{
101
-		$feature = 'commande';
102
-		$object_id = 0;
103
-	}
104
-	if ($feature == 'shipping') $feature = 'commande';
105
-	if ($feature == 'payment') { $feature = 'facture'; }
106
-	if ($feature == 'payment_supplier') { $feature = 'fournisseur'; $feature2 = 'facture'; }
107
-	//var_dump(GETPOST('action','aZ09'));
108
-	//var_dump($newelement.'-'.$subelement."-".$feature."-".$object_id);
109
-	$check_access = restrictedArea($user, $feature, $object_id, '', $feature2);
110
-	//var_dump($user->rights);
111
-	/*
61
+    $ext_element		= GETPOST('ext_element','alpha',2);
62
+    $field				= substr($field, 8); // remove prefix val_
63
+    $type				= GETPOST('type','alpha',2);
64
+    $value				= ($type == 'ckeditor' ? GETPOST('value','',2) : GETPOST('value','alpha',2));
65
+    $loadmethod			= GETPOST('loadmethod','alpha',2);
66
+    $savemethod			= GETPOST('savemethod','alpha',2);
67
+    $savemethodname		= (! empty($savemethod) ? $savemethod : 'setValueFrom');
68
+    $newelement			= $element;
69
+
70
+    $view='';
71
+    $format='text';
72
+    $return=array();
73
+    $error=0;
74
+
75
+    if ($element != 'order_supplier' && $element != 'invoice_supplier' && preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
76
+    {
77
+        $element = $regs[1];
78
+        $subelement = $regs[2];
79
+    }
80
+
81
+    if ($element == 'propal') $newelement = 'propale';
82
+    else if ($element == 'fichinter') $newelement = 'ficheinter';
83
+    else if ($element == 'product') $newelement = 'produit';
84
+    else if ($element == 'member') $newelement = 'adherent';
85
+    else if ($element == 'order_supplier') {
86
+        $newelement = 'fournisseur';
87
+        $subelement = 'commande';
88
+    }
89
+    else if ($element == 'invoice_supplier') {
90
+        $newelement = 'fournisseur';
91
+        $subelement = 'facture';
92
+    }
93
+    else $newelement = $element;
94
+
95
+    $_POST['action']='update';	// Hack so restrictarea will test permissions on write too
96
+    $feature = $newelement;
97
+    $feature2 = $subelement;
98
+    $object_id = $fk_element;
99
+    if ($feature == 'expedition' || $feature == 'shipping')
100
+    {
101
+        $feature = 'commande';
102
+        $object_id = 0;
103
+    }
104
+    if ($feature == 'shipping') $feature = 'commande';
105
+    if ($feature == 'payment') { $feature = 'facture'; }
106
+    if ($feature == 'payment_supplier') { $feature = 'fournisseur'; $feature2 = 'facture'; }
107
+    //var_dump(GETPOST('action','aZ09'));
108
+    //var_dump($newelement.'-'.$subelement."-".$feature."-".$object_id);
109
+    $check_access = restrictedArea($user, $feature, $object_id, '', $feature2);
110
+    //var_dump($user->rights);
111
+    /*
112 112
 	if (! empty($user->rights->$newelement->creer) || ! empty($user->rights->$newelement->create) || ! empty($user->rights->$newelement->write)
113 113
 		|| (isset($subelement) && (! empty($user->rights->$newelement->$subelement->creer) || ! empty($user->rights->$newelement->$subelement->write)))
114 114
 		|| ($element == 'payment' && $user->rights->facture->paiement)
115 115
 		|| ($element == 'payment_supplier' && $user->rights->fournisseur->facture->creer))
116 116
 	*/
117 117
 
118
-	if ($check_access)
119
-	{
120
-		// Clean parameters
121
-		$newvalue = trim($value);
122
-
123
-		if ($type == 'numeric')
124
-		{
125
-			$newvalue = price2num($newvalue);
126
-
127
-			// Check parameters
128
-			if (! is_numeric($newvalue))
129
-			{
130
-				$error++;
131
-				$return['error'] = $langs->trans('ErrorBadValue');
132
-			}
133
-		}
134
-		else if ($type == 'datepicker')
135
-		{
136
-			$timestamp	= GETPOST('timestamp','int',2);
137
-			$format		= 'date';
138
-			$newvalue	= ($timestamp / 1000);
139
-		}
140
-		else if ($type == 'select')
141
-		{
142
-			$loadmethodname	= 'load_cache_'.$loadmethod;
143
-			$loadcachename	= 'cache_'.$loadmethod;
144
-			$loadviewname	= 'view_'.$loadmethod;
145
-
146
-			$form = new Form($db);
147
-			if (method_exists($form, $loadmethodname))
148
-			{
149
-				$ret = $form->$loadmethodname();
150
-				if ($ret > 0)
151
-				{
152
-					$loadcache = $form->$loadcachename;
153
-					$value = $loadcache[$newvalue];
154
-
155
-					if (! empty($form->$loadviewname))
156
-					{
157
-						$loadview = $form->$loadviewname;
158
-						$view = $loadview[$newvalue];
159
-					}
160
-				}
161
-				else
162
-				{
163
-					$error++;
164
-					$return['error'] = $form->error;
165
-				}
166
-			}
167
-			else
168
-			{
169
-				$module = $subelement = $ext_element;
170
-				if (preg_match('/^([^_]+)_([^_]+)/i',$ext_element,$regs))
171
-				{
172
-					$module = $regs[1];
173
-					$subelement = $regs[2];
174
-				}
175
-
176
-				dol_include_once('/'.$module.'/class/actions_'.$subelement.'.class.php');
177
-				$classname = 'Actions'.ucfirst($subelement);
178
-				$object = new $classname($db);
179
-				$ret = $object->$loadmethodname();
180
-				if ($ret > 0)
181
-				{
182
-					$loadcache = $object->$loadcachename;
183
-					$value = $loadcache[$newvalue];
184
-
185
-					if (! empty($object->$loadviewname))
186
-					{
187
-						$loadview = $object->$loadviewname;
188
-						$view = $loadview[$newvalue];
189
-					}
190
-				}
191
-				else
192
-				{
193
-					$error++;
194
-					$return['error'] = $object->error;
195
-				}
196
-			}
197
-		}
198
-
199
-		if (! $error)
200
-		{
201
-			if ((isset($object) && ! is_object($object)) || empty($savemethod)) $object = new GenericObject($db);
202
-
203
-			// Specific for add_object_linked()
204
-			// TODO add a function for variable treatment
205
-			$object->ext_fk_element = $newvalue;
206
-			$object->ext_element = $ext_element;
207
-			$object->fk_element = $fk_element;
208
-			$object->element = $element;
209
-
210
-			$ret=$object->$savemethodname($field, $newvalue, $table_element, $fk_element, $format);
211
-			if ($ret > 0)
212
-			{
213
-				if ($type == 'numeric') $value = price($newvalue);
214
-				else if ($type == 'textarea') $value = dol_nl2br($newvalue);
215
-
216
-				$return['value'] = $value;
217
-				$return['view'] = (! empty($view) ? $view : $value);
218
-			}
219
-			else
220
-			{
221
-				$return['error'] = $object->error;
222
-			}
223
-		}
224
-
225
-		echo json_encode($return);
226
-	}
227
-	else
228
-	{
229
-		echo $langs->trans('NotEnoughPermissions');
230
-	}
118
+    if ($check_access)
119
+    {
120
+        // Clean parameters
121
+        $newvalue = trim($value);
122
+
123
+        if ($type == 'numeric')
124
+        {
125
+            $newvalue = price2num($newvalue);
126
+
127
+            // Check parameters
128
+            if (! is_numeric($newvalue))
129
+            {
130
+                $error++;
131
+                $return['error'] = $langs->trans('ErrorBadValue');
132
+            }
133
+        }
134
+        else if ($type == 'datepicker')
135
+        {
136
+            $timestamp	= GETPOST('timestamp','int',2);
137
+            $format		= 'date';
138
+            $newvalue	= ($timestamp / 1000);
139
+        }
140
+        else if ($type == 'select')
141
+        {
142
+            $loadmethodname	= 'load_cache_'.$loadmethod;
143
+            $loadcachename	= 'cache_'.$loadmethod;
144
+            $loadviewname	= 'view_'.$loadmethod;
145
+
146
+            $form = new Form($db);
147
+            if (method_exists($form, $loadmethodname))
148
+            {
149
+                $ret = $form->$loadmethodname();
150
+                if ($ret > 0)
151
+                {
152
+                    $loadcache = $form->$loadcachename;
153
+                    $value = $loadcache[$newvalue];
154
+
155
+                    if (! empty($form->$loadviewname))
156
+                    {
157
+                        $loadview = $form->$loadviewname;
158
+                        $view = $loadview[$newvalue];
159
+                    }
160
+                }
161
+                else
162
+                {
163
+                    $error++;
164
+                    $return['error'] = $form->error;
165
+                }
166
+            }
167
+            else
168
+            {
169
+                $module = $subelement = $ext_element;
170
+                if (preg_match('/^([^_]+)_([^_]+)/i',$ext_element,$regs))
171
+                {
172
+                    $module = $regs[1];
173
+                    $subelement = $regs[2];
174
+                }
175
+
176
+                dol_include_once('/'.$module.'/class/actions_'.$subelement.'.class.php');
177
+                $classname = 'Actions'.ucfirst($subelement);
178
+                $object = new $classname($db);
179
+                $ret = $object->$loadmethodname();
180
+                if ($ret > 0)
181
+                {
182
+                    $loadcache = $object->$loadcachename;
183
+                    $value = $loadcache[$newvalue];
184
+
185
+                    if (! empty($object->$loadviewname))
186
+                    {
187
+                        $loadview = $object->$loadviewname;
188
+                        $view = $loadview[$newvalue];
189
+                    }
190
+                }
191
+                else
192
+                {
193
+                    $error++;
194
+                    $return['error'] = $object->error;
195
+                }
196
+            }
197
+        }
198
+
199
+        if (! $error)
200
+        {
201
+            if ((isset($object) && ! is_object($object)) || empty($savemethod)) $object = new GenericObject($db);
202
+
203
+            // Specific for add_object_linked()
204
+            // TODO add a function for variable treatment
205
+            $object->ext_fk_element = $newvalue;
206
+            $object->ext_element = $ext_element;
207
+            $object->fk_element = $fk_element;
208
+            $object->element = $element;
209
+
210
+            $ret=$object->$savemethodname($field, $newvalue, $table_element, $fk_element, $format);
211
+            if ($ret > 0)
212
+            {
213
+                if ($type == 'numeric') $value = price($newvalue);
214
+                else if ($type == 'textarea') $value = dol_nl2br($newvalue);
215
+
216
+                $return['value'] = $value;
217
+                $return['view'] = (! empty($view) ? $view : $value);
218
+            }
219
+            else
220
+            {
221
+                $return['error'] = $object->error;
222
+            }
223
+        }
224
+
225
+        echo json_encode($return);
226
+    }
227
+    else
228
+    {
229
+        echo $langs->trans('NotEnoughPermissions');
230
+    }
231 231
 }
232 232
 
Please login to merge, or discard this patch.
Braces   +43 added lines, -30 removed lines patch added patch discarded remove patch
@@ -20,10 +20,19 @@  discard block
 block discarded – undo
20 20
  *       \brief      File to save field value
21 21
  */
22 22
 
23
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
24
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
25
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
26
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
23
+if (! defined('NOTOKENRENEWAL')) {
24
+    define('NOTOKENRENEWAL','1');
25
+}
26
+// Disables token renewal
27
+if (! defined('NOREQUIREMENU')) {
28
+    define('NOREQUIREMENU','1');
29
+}
30
+if (! defined('NOREQUIREAJAX')) {
31
+    define('NOREQUIREAJAX','1');
32
+}
33
+if (! defined('NOREQUIRESOC')) {
34
+    define('NOREQUIRESOC','1');
35
+}
27 36
 
28 37
 
29 38
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
@@ -81,19 +90,23 @@  discard block
 block discarded – undo
81 90
 		$subelement = $regs[2];
82 91
 	}
83 92
 
84
-	if ($element == 'propal') $newelement = 'propale';
85
-	else if ($element == 'fichinter') $newelement = 'ficheinter';
86
-	else if ($element == 'product') $newelement = 'produit';
87
-	else if ($element == 'member') $newelement = 'adherent';
88
-	else if ($element == 'order_supplier') {
93
+	if ($element == 'propal') {
94
+	    $newelement = 'propale';
95
+	} else if ($element == 'fichinter') {
96
+	    $newelement = 'ficheinter';
97
+	} else if ($element == 'product') {
98
+	    $newelement = 'produit';
99
+	} else if ($element == 'member') {
100
+	    $newelement = 'adherent';
101
+	} else if ($element == 'order_supplier') {
89 102
 		$newelement = 'fournisseur';
90 103
 		$subelement = 'commande';
91
-	}
92
-	else if ($element == 'invoice_supplier') {
104
+	} else if ($element == 'invoice_supplier') {
93 105
 		$newelement = 'fournisseur';
94 106
 		$subelement = 'facture';
107
+	} else {
108
+	    $newelement = $element;
95 109
 	}
96
-	else $newelement = $element;
97 110
 
98 111
 	$_POST['action']='update';	// Hack so restrictarea will test permissions on write too
99 112
 	$feature = $newelement;
@@ -104,7 +117,9 @@  discard block
 block discarded – undo
104 117
 		$feature = 'commande';
105 118
 		$object_id = 0;
106 119
 	}
107
-	if ($feature == 'shipping') $feature = 'commande';
120
+	if ($feature == 'shipping') {
121
+	    $feature = 'commande';
122
+	}
108 123
 	if ($feature == 'payment') { $feature = 'facture'; }
109 124
 	if ($feature == 'payment_supplier') { $feature = 'fournisseur'; $feature2 = 'facture'; }
110 125
 	//var_dump(GETPOST('action','aZ09'));
@@ -133,14 +148,12 @@  discard block
 block discarded – undo
133 148
 				$error++;
134 149
 				$return['error'] = $langs->trans('ErrorBadValue');
135 150
 			}
136
-		}
137
-		else if ($type == 'datepicker')
151
+		} else if ($type == 'datepicker')
138 152
 		{
139 153
 			$timestamp	= GETPOST('timestamp','int',2);
140 154
 			$format		= 'date';
141 155
 			$newvalue	= ($timestamp / 1000);
142
-		}
143
-		else if ($type == 'select')
156
+		} else if ($type == 'select')
144 157
 		{
145 158
 			$loadmethodname	= 'load_cache_'.$loadmethod;
146 159
 			$loadcachename	= 'cache_'.$loadmethod;
@@ -160,14 +173,12 @@  discard block
 block discarded – undo
160 173
 						$loadview = $form->$loadviewname;
161 174
 						$view = $loadview[$newvalue];
162 175
 					}
163
-				}
164
-				else
176
+				} else
165 177
 				{
166 178
 					$error++;
167 179
 					$return['error'] = $form->error;
168 180
 				}
169
-			}
170
-			else
181
+			} else
171 182
 			{
172 183
 				$module = $subelement = $ext_element;
173 184
 				if (preg_match('/^([^_]+)_([^_]+)/i',$ext_element,$regs))
@@ -190,8 +201,7 @@  discard block
 block discarded – undo
190 201
 						$loadview = $object->$loadviewname;
191 202
 						$view = $loadview[$newvalue];
192 203
 					}
193
-				}
194
-				else
204
+				} else
195 205
 				{
196 206
 					$error++;
197 207
 					$return['error'] = $object->error;
@@ -201,7 +211,9 @@  discard block
 block discarded – undo
201 211
 
202 212
 		if (! $error)
203 213
 		{
204
-			if ((isset($object) && ! is_object($object)) || empty($savemethod)) $object = new GenericObject($db);
214
+			if ((isset($object) && ! is_object($object)) || empty($savemethod)) {
215
+			    $object = new GenericObject($db);
216
+			}
205 217
 
206 218
 			// Specific for add_object_linked()
207 219
 			// TODO add a function for variable treatment
@@ -213,21 +225,22 @@  discard block
 block discarded – undo
213 225
 			$ret=$object->$savemethodname($field, $newvalue, $table_element, $fk_element, $format);
214 226
 			if ($ret > 0)
215 227
 			{
216
-				if ($type == 'numeric') $value = price($newvalue);
217
-				else if ($type == 'textarea') $value = dol_nl2br($newvalue);
228
+				if ($type == 'numeric') {
229
+				    $value = price($newvalue);
230
+				} else if ($type == 'textarea') {
231
+				    $value = dol_nl2br($newvalue);
232
+				}
218 233
 
219 234
 				$return['value'] = $value;
220 235
 				$return['view'] = (! empty($view) ? $view : $value);
221
-			}
222
-			else
236
+			} else
223 237
 			{
224 238
 				$return['error'] = $object->error;
225 239
 			}
226 240
 		}
227 241
 
228 242
 		echo json_encode($return);
229
-	}
230
-	else
243
+	} else
231 244
 	{
232 245
 		echo $langs->trans('NotEnoughPermissions');
233 246
 	}
Please login to merge, or discard this patch.
Spacing   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -20,21 +20,21 @@  discard block
 block discarded – undo
20 20
  *       \brief      File to save field value
21 21
  */
22 22
 
23
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
24
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
25
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
26
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
23
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
24
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
25
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
26
+if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
27 27
 
28 28
 
29 29
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
30 30
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
31
-require DOL_BASE_PATH . '/main.inc.php';
31
+require DOL_BASE_PATH.'/main.inc.php';
32 32
 require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php';
33 33
 
34
-$field			= GETPOST('field','alpha',2);
35
-$element		= GETPOST('element','alpha',2);
36
-$table_element	= GETPOST('table_element','alpha',2);
37
-$fk_element		= GETPOST('fk_element','alpha',2);
34
+$field = GETPOST('field', 'alpha', 2);
35
+$element = GETPOST('element', 'alpha', 2);
36
+$table_element = GETPOST('table_element', 'alpha', 2);
37
+$fk_element = GETPOST('fk_element', 'alpha', 2);
38 38
 
39 39
 /* Example:
40 40
 field:editval_ref_customer (8 first chars will removed to know name of property)
@@ -59,23 +59,23 @@  discard block
 block discarded – undo
59 59
 //print_r($_POST);
60 60
 
61 61
 // Load original field value
62
-if (! empty($field) && ! empty($element) && ! empty($table_element) && ! empty($fk_element))
62
+if (!empty($field) && !empty($element) && !empty($table_element) && !empty($fk_element))
63 63
 {
64
-	$ext_element		= GETPOST('ext_element','alpha',2);
64
+	$ext_element = GETPOST('ext_element', 'alpha', 2);
65 65
 	$field				= substr($field, 8); // remove prefix val_
66
-	$type				= GETPOST('type','alpha',2);
67
-	$value				= ($type == 'ckeditor' ? GETPOST('value','',2) : GETPOST('value','alpha',2));
68
-	$loadmethod			= GETPOST('loadmethod','alpha',2);
69
-	$savemethod			= GETPOST('savemethod','alpha',2);
70
-	$savemethodname		= (! empty($savemethod) ? $savemethod : 'setValueFrom');
66
+	$type = GETPOST('type', 'alpha', 2);
67
+	$value				= ($type == 'ckeditor' ? GETPOST('value', '', 2) : GETPOST('value', 'alpha', 2));
68
+	$loadmethod			= GETPOST('loadmethod', 'alpha', 2);
69
+	$savemethod			= GETPOST('savemethod', 'alpha', 2);
70
+	$savemethodname = (!empty($savemethod) ? $savemethod : 'setValueFrom');
71 71
 	$newelement			= $element;
72 72
 
73
-	$view='';
74
-	$format='text';
75
-	$return=array();
76
-	$error=0;
73
+	$view = '';
74
+	$format = 'text';
75
+	$return = array();
76
+	$error = 0;
77 77
 
78
-	if ($element != 'order_supplier' && $element != 'invoice_supplier' && preg_match('/^([^_]+)_([^_]+)/i',$element,$regs))
78
+	if ($element != 'order_supplier' && $element != 'invoice_supplier' && preg_match('/^([^_]+)_([^_]+)/i', $element, $regs))
79 79
 	{
80 80
 		$element = $regs[1];
81 81
 		$subelement = $regs[2];
@@ -95,7 +95,7 @@  discard block
 block discarded – undo
95 95
 	}
96 96
 	else $newelement = $element;
97 97
 
98
-	$_POST['action']='update';	// Hack so restrictarea will test permissions on write too
98
+	$_POST['action'] = 'update'; // Hack so restrictarea will test permissions on write too
99 99
 	$feature = $newelement;
100 100
 	$feature2 = $subelement;
101 101
 	$object_id = $fk_element;
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
 			$newvalue = price2num($newvalue);
129 129
 
130 130
 			// Check parameters
131
-			if (! is_numeric($newvalue))
131
+			if (!is_numeric($newvalue))
132 132
 			{
133 133
 				$error++;
134 134
 				$return['error'] = $langs->trans('ErrorBadValue');
@@ -136,15 +136,15 @@  discard block
 block discarded – undo
136 136
 		}
137 137
 		else if ($type == 'datepicker')
138 138
 		{
139
-			$timestamp	= GETPOST('timestamp','int',2);
140
-			$format		= 'date';
141
-			$newvalue	= ($timestamp / 1000);
139
+			$timestamp = GETPOST('timestamp', 'int', 2);
140
+			$format = 'date';
141
+			$newvalue = ($timestamp / 1000);
142 142
 		}
143 143
 		else if ($type == 'select')
144 144
 		{
145
-			$loadmethodname	= 'load_cache_'.$loadmethod;
146
-			$loadcachename	= 'cache_'.$loadmethod;
147
-			$loadviewname	= 'view_'.$loadmethod;
145
+			$loadmethodname = 'load_cache_'.$loadmethod;
146
+			$loadcachename = 'cache_'.$loadmethod;
147
+			$loadviewname = 'view_'.$loadmethod;
148 148
 
149 149
 			$form = new Form($db);
150 150
 			if (method_exists($form, $loadmethodname))
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 					$loadcache = $form->$loadcachename;
156 156
 					$value = $loadcache[$newvalue];
157 157
 
158
-					if (! empty($form->$loadviewname))
158
+					if (!empty($form->$loadviewname))
159 159
 					{
160 160
 						$loadview = $form->$loadviewname;
161 161
 						$view = $loadview[$newvalue];
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 			else
171 171
 			{
172 172
 				$module = $subelement = $ext_element;
173
-				if (preg_match('/^([^_]+)_([^_]+)/i',$ext_element,$regs))
173
+				if (preg_match('/^([^_]+)_([^_]+)/i', $ext_element, $regs))
174 174
 				{
175 175
 					$module = $regs[1];
176 176
 					$subelement = $regs[2];
@@ -185,7 +185,7 @@  discard block
 block discarded – undo
185 185
 					$loadcache = $object->$loadcachename;
186 186
 					$value = $loadcache[$newvalue];
187 187
 
188
-					if (! empty($object->$loadviewname))
188
+					if (!empty($object->$loadviewname))
189 189
 					{
190 190
 						$loadview = $object->$loadviewname;
191 191
 						$view = $loadview[$newvalue];
@@ -199,9 +199,9 @@  discard block
 block discarded – undo
199 199
 			}
200 200
 		}
201 201
 
202
-		if (! $error)
202
+		if (!$error)
203 203
 		{
204
-			if ((isset($object) && ! is_object($object)) || empty($savemethod)) $object = new GenericObject($db);
204
+			if ((isset($object) && !is_object($object)) || empty($savemethod)) $object = new GenericObject($db);
205 205
 
206 206
 			// Specific for add_object_linked()
207 207
 			// TODO add a function for variable treatment
@@ -210,14 +210,14 @@  discard block
 block discarded – undo
210 210
 			$object->fk_element = $fk_element;
211 211
 			$object->element = $element;
212 212
 
213
-			$ret=$object->$savemethodname($field, $newvalue, $table_element, $fk_element, $format);
213
+			$ret = $object->$savemethodname($field, $newvalue, $table_element, $fk_element, $format);
214 214
 			if ($ret > 0)
215 215
 			{
216 216
 				if ($type == 'numeric') $value = price($newvalue);
217 217
 				else if ($type == 'textarea') $value = dol_nl2br($newvalue);
218 218
 
219 219
 				$return['value'] = $value;
220
-				$return['view'] = (! empty($view) ? $view : $value);
220
+				$return['view'] = (!empty($view) ? $view : $value);
221 221
 			}
222 222
 			else
223 223
 			{
Please login to merge, or discard this patch.
dolibarr/htdocs/core/ajax/extraparams.php 3 patches
Indentation   +22 added lines, -22 removed lines patch added patch discarded remove patch
@@ -43,35 +43,35 @@
 block discarded – undo
43 43
 
44 44
 if(! empty($id) && ! empty($element) && ! empty($htmlelement) && ! empty($type))
45 45
 {
46
-	$value = GETPOST('value','alpha');
47
-	$params=array();
46
+    $value = GETPOST('value','alpha');
47
+    $params=array();
48 48
 
49
-	dol_syslog("AjaxSetExtraParameters id=".$id." element=".$element." htmlelement=".$htmlelement." type=".$type." value=".$value, LOG_DEBUG);
49
+    dol_syslog("AjaxSetExtraParameters id=".$id." element=".$element." htmlelement=".$htmlelement." type=".$type." value=".$value, LOG_DEBUG);
50 50
 
51
-	$classpath = $subelement = $element;
51
+    $classpath = $subelement = $element;
52 52
 
53
-	// For compatibility
54
-	if ($element == 'order' || $element == 'commande')    { $classpath = $subelement = 'commande'; }
55
-	else if ($element == 'propal')				{ $classpath = 'comm/propal'; $subelement = 'propal'; }
56
-	else if ($element == 'facture')				{ $classpath = 'compta/facture'; $subelement = 'facture'; }
57
-	else if ($element == 'contract')			{ $classpath = $subelement = 'contrat'; }
58
-	else if ($element == 'shipping')			{ $classpath = $subelement = 'expedition'; }
59
-	else if ($element == 'deplacement')			{ $classpath = 'compta/deplacement'; $subelement = 'deplacement'; }
60
-	else if ($element == 'order_supplier')		{ $classpath = 'fourn'; $subelement = 'fournisseur.commande'; }
61
-	else if ($element == 'invoice_supplier')	{ $classpath = 'fourn'; $subelement = 'fournisseur.facture'; }
53
+    // For compatibility
54
+    if ($element == 'order' || $element == 'commande')    { $classpath = $subelement = 'commande'; }
55
+    else if ($element == 'propal')				{ $classpath = 'comm/propal'; $subelement = 'propal'; }
56
+    else if ($element == 'facture')				{ $classpath = 'compta/facture'; $subelement = 'facture'; }
57
+    else if ($element == 'contract')			{ $classpath = $subelement = 'contrat'; }
58
+    else if ($element == 'shipping')			{ $classpath = $subelement = 'expedition'; }
59
+    else if ($element == 'deplacement')			{ $classpath = 'compta/deplacement'; $subelement = 'deplacement'; }
60
+    else if ($element == 'order_supplier')		{ $classpath = 'fourn'; $subelement = 'fournisseur.commande'; }
61
+    else if ($element == 'invoice_supplier')	{ $classpath = 'fourn'; $subelement = 'fournisseur.facture'; }
62 62
 
63
-	dol_include_once('/'.$classpath.'/class/'.$subelement.'.class.php');
63
+    dol_include_once('/'.$classpath.'/class/'.$subelement.'.class.php');
64 64
 
65
-	if ($element == 'order_supplier')			{ $classname = 'CommandeFournisseur'; }
66
-	else if ($element == 'invoice_supplier')	{ $classname = 'FactureFournisseur'; }
67
-	else $classname = ucfirst($subelement);
65
+    if ($element == 'order_supplier')			{ $classname = 'CommandeFournisseur'; }
66
+    else if ($element == 'invoice_supplier')	{ $classname = 'FactureFournisseur'; }
67
+    else $classname = ucfirst($subelement);
68 68
 
69
-	$object	= new $classname($db);
70
-	$object->fetch($id);
69
+    $object	= new $classname($db);
70
+    $object->fetch($id);
71 71
 
72
-	$params[$htmlelement] = array($type => $value);
73
-	$object->extraparams = array_merge($object->extraparams, $params);
72
+    $params[$htmlelement] = array($type => $value);
73
+    $object->extraparams = array_merge($object->extraparams, $params);
74 74
 
75
-	$result=$object->setExtraParameters();
75
+    $result=$object->setExtraParameters();
76 76
 }
77 77
 
Please login to merge, or discard this patch.
Spacing   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -20,17 +20,17 @@  discard block
 block discarded – undo
20 20
  *	\brief      File to return Ajax response on set extra parameters of elements
21 21
  */
22 22
 
23
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
24
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
25
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
26
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
27
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
23
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
24
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
25
+if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
26
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
27
+if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
28 28
 
29 29
 include '../../main.inc.php';
30 30
 
31
-$id = GETPOST('id','int');
32
-$element = GETPOST('element','alpha');
33
-$htmlelement = GETPOST('htmlelement','alpha');
31
+$id = GETPOST('id', 'int');
32
+$element = GETPOST('element', 'alpha');
33
+$htmlelement = GETPOST('htmlelement', 'alpha');
34 34
 $type = GETPOST('type', 'alpha');
35 35
 
36 36
 /*
@@ -41,37 +41,37 @@  discard block
 block discarded – undo
41 41
 
42 42
 print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
43 43
 
44
-if(! empty($id) && ! empty($element) && ! empty($htmlelement) && ! empty($type))
44
+if (!empty($id) && !empty($element) && !empty($htmlelement) && !empty($type))
45 45
 {
46
-	$value = GETPOST('value','alpha');
47
-	$params=array();
46
+	$value = GETPOST('value', 'alpha');
47
+	$params = array();
48 48
 
49 49
 	dol_syslog("AjaxSetExtraParameters id=".$id." element=".$element." htmlelement=".$htmlelement." type=".$type." value=".$value, LOG_DEBUG);
50 50
 
51 51
 	$classpath = $subelement = $element;
52 52
 
53 53
 	// For compatibility
54
-	if ($element == 'order' || $element == 'commande')    { $classpath = $subelement = 'commande'; }
55
-	else if ($element == 'propal')				{ $classpath = 'comm/propal'; $subelement = 'propal'; }
56
-	else if ($element == 'facture')				{ $classpath = 'compta/facture'; $subelement = 'facture'; }
57
-	else if ($element == 'contract')			{ $classpath = $subelement = 'contrat'; }
58
-	else if ($element == 'shipping')			{ $classpath = $subelement = 'expedition'; }
59
-	else if ($element == 'deplacement')			{ $classpath = 'compta/deplacement'; $subelement = 'deplacement'; }
60
-	else if ($element == 'order_supplier')		{ $classpath = 'fourn'; $subelement = 'fournisseur.commande'; }
61
-	else if ($element == 'invoice_supplier')	{ $classpath = 'fourn'; $subelement = 'fournisseur.facture'; }
54
+	if ($element == 'order' || $element == 'commande') { $classpath = $subelement = 'commande'; }
55
+	else if ($element == 'propal') { $classpath = 'comm/propal'; $subelement = 'propal'; }
56
+	else if ($element == 'facture') { $classpath = 'compta/facture'; $subelement = 'facture'; }
57
+	else if ($element == 'contract') { $classpath = $subelement = 'contrat'; }
58
+	else if ($element == 'shipping') { $classpath = $subelement = 'expedition'; }
59
+	else if ($element == 'deplacement') { $classpath = 'compta/deplacement'; $subelement = 'deplacement'; }
60
+	else if ($element == 'order_supplier') { $classpath = 'fourn'; $subelement = 'fournisseur.commande'; }
61
+	else if ($element == 'invoice_supplier') { $classpath = 'fourn'; $subelement = 'fournisseur.facture'; }
62 62
 
63 63
 	dol_include_once('/'.$classpath.'/class/'.$subelement.'.class.php');
64 64
 
65
-	if ($element == 'order_supplier')			{ $classname = 'CommandeFournisseur'; }
66
-	else if ($element == 'invoice_supplier')	{ $classname = 'FactureFournisseur'; }
65
+	if ($element == 'order_supplier') { $classname = 'CommandeFournisseur'; }
66
+	else if ($element == 'invoice_supplier') { $classname = 'FactureFournisseur'; }
67 67
 	else $classname = ucfirst($subelement);
68 68
 
69
-	$object	= new $classname($db);
69
+	$object = new $classname($db);
70 70
 	$object->fetch($id);
71 71
 
72 72
 	$params[$htmlelement] = array($type => $value);
73 73
 	$object->extraparams = array_merge($object->extraparams, $params);
74 74
 
75
-	$result=$object->setExtraParameters();
75
+	$result = $object->setExtraParameters();
76 76
 }
77 77
 
Please login to merge, or discard this patch.
Braces   +20 added lines, -16 removed lines patch added patch discarded remove patch
@@ -20,11 +20,22 @@  discard block
 block discarded – undo
20 20
  *	\brief      File to return Ajax response on set extra parameters of elements
21 21
  */
22 22
 
23
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
24
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
25
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
26
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
27
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
23
+if (! defined('NOTOKENRENEWAL')) {
24
+    define('NOTOKENRENEWAL','1');
25
+}
26
+// Disables token renewal
27
+if (! defined('NOREQUIREMENU')) {
28
+    define('NOREQUIREMENU','1');
29
+}
30
+if (! defined('NOREQUIREHTML')) {
31
+    define('NOREQUIREHTML','1');
32
+}
33
+if (! defined('NOREQUIREAJAX')) {
34
+    define('NOREQUIREAJAX','1');
35
+}
36
+if (! defined('NOREQUIRESOC')) {
37
+    define('NOREQUIRESOC','1');
38
+}
28 39
 
29 40
 include '../../main.inc.php';
30 41
 
@@ -51,20 +62,13 @@  discard block
 block discarded – undo
51 62
 	$classpath = $subelement = $element;
52 63
 
53 64
 	// For compatibility
54
-	if ($element == 'order' || $element == 'commande')    { $classpath = $subelement = 'commande'; }
55
-	else if ($element == 'propal')				{ $classpath = 'comm/propal'; $subelement = 'propal'; }
56
-	else if ($element == 'facture')				{ $classpath = 'compta/facture'; $subelement = 'facture'; }
57
-	else if ($element == 'contract')			{ $classpath = $subelement = 'contrat'; }
58
-	else if ($element == 'shipping')			{ $classpath = $subelement = 'expedition'; }
59
-	else if ($element == 'deplacement')			{ $classpath = 'compta/deplacement'; $subelement = 'deplacement'; }
60
-	else if ($element == 'order_supplier')		{ $classpath = 'fourn'; $subelement = 'fournisseur.commande'; }
61
-	else if ($element == 'invoice_supplier')	{ $classpath = 'fourn'; $subelement = 'fournisseur.facture'; }
65
+	if ($element == 'order' || $element == 'commande')    { $classpath = $subelement = 'commande'; } else if ($element == 'propal')				{ $classpath = 'comm/propal'; $subelement = 'propal'; } else if ($element == 'facture')				{ $classpath = 'compta/facture'; $subelement = 'facture'; } else if ($element == 'contract')			{ $classpath = $subelement = 'contrat'; } else if ($element == 'shipping')			{ $classpath = $subelement = 'expedition'; } else if ($element == 'deplacement')			{ $classpath = 'compta/deplacement'; $subelement = 'deplacement'; } else if ($element == 'order_supplier')		{ $classpath = 'fourn'; $subelement = 'fournisseur.commande'; } else if ($element == 'invoice_supplier')	{ $classpath = 'fourn'; $subelement = 'fournisseur.facture'; }
62 66
 
63 67
 	dol_include_once('/'.$classpath.'/class/'.$subelement.'.class.php');
64 68
 
65
-	if ($element == 'order_supplier')			{ $classname = 'CommandeFournisseur'; }
66
-	else if ($element == 'invoice_supplier')	{ $classname = 'FactureFournisseur'; }
67
-	else $classname = ucfirst($subelement);
69
+	if ($element == 'order_supplier')			{ $classname = 'CommandeFournisseur'; } else if ($element == 'invoice_supplier')	{ $classname = 'FactureFournisseur'; } else {
70
+	    $classname = ucfirst($subelement);
71
+	}
68 72
 
69 73
 	$object	= new $classname($db);
70 74
 	$object->fetch($id);
Please login to merge, or discard this patch.
dolibarr/htdocs/core/ajax/box.php 3 patches
Indentation   +16 added lines, -16 removed lines patch added patch discarded remove patch
@@ -53,28 +53,28 @@
 block discarded – undo
53 53
 // Add a box
54 54
 if ($boxid > 0 && $zone !='' && $userid > 0)
55 55
 {
56
-	$tmp=explode('-',$boxorder);
57
-	$nbboxonleft=substr_count($tmp[0],',');
58
-	$nbboxonright=substr_count($tmp[1],',');
59
-	print $nbboxonleft.'-'.$nbboxonright;
60
-	if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
56
+    $tmp=explode('-',$boxorder);
57
+    $nbboxonleft=substr_count($tmp[0],',');
58
+    $nbboxonright=substr_count($tmp[1],',');
59
+    print $nbboxonleft.'-'.$nbboxonright;
60
+    if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
61 61
     else $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);    // Insert id of new box into list
62 62
 }
63 63
 
64 64
 // Registering the location of boxes after a move
65 65
 if ($boxorder && $zone != '' &&  $userid > 0)
66 66
 {
67
-	// boxorder value is the target order: "A:idboxA1,idboxA2,A-B:idboxB1,idboxB2,B"
68
-	dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG);
67
+    // boxorder value is the target order: "A:idboxA1,idboxA2,A-B:idboxB1,idboxB2,B"
68
+    dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG);
69 69
 
70
-	$result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid);
71
-	if ($result > 0)
72
-	{
73
-	    $langs->load("boxes");
74
-	    if (! GETPOST('closing'))
75
-	    {
76
-	       setEventMessages($langs->trans("BoxAdded"), null);
77
-	    }
78
-	}
70
+    $result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid);
71
+    if ($result > 0)
72
+    {
73
+        $langs->load("boxes");
74
+        if (! GETPOST('closing'))
75
+        {
76
+            setEventMessages($langs->trans("BoxAdded"), null);
77
+        }
78
+    }
79 79
 }
80 80
 
Please login to merge, or discard this patch.
Braces   +24 added lines, -7 removed lines patch added patch discarded remove patch
@@ -21,11 +21,22 @@  discard block
 block discarded – undo
21 21
  *       \brief      File to return Ajax response on Box move or close
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
26
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
27
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
28
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
24
+if (! defined('NOTOKENRENEWAL')) {
25
+    define('NOTOKENRENEWAL','1');
26
+}
27
+// Disables token renewal
28
+if (! defined('NOREQUIREMENU')) {
29
+    define('NOREQUIREMENU','1');
30
+}
31
+if (! defined('NOREQUIREHTML')) {
32
+    define('NOREQUIREHTML','1');
33
+}
34
+if (! defined('NOREQUIREAJAX')) {
35
+    define('NOREQUIREAJAX','1');
36
+}
37
+if (! defined('NOREQUIRESOC')) {
38
+    define('NOREQUIRESOC','1');
39
+}
29 40
 
30 41
 
31 42
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
@@ -60,8 +71,14 @@  discard block
 block discarded – undo
60 71
 	$nbboxonleft=substr_count($tmp[0],',');
61 72
 	$nbboxonright=substr_count($tmp[1],',');
62 73
 	print $nbboxonleft.'-'.$nbboxonright;
63
-	if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
64
-    else $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);    // Insert id of new box into list
74
+	if ($nbboxonleft > $nbboxonright) {
75
+	    $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);
76
+	}
77
+	// Insert id of new box into list
78
+    else {
79
+        $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);
80
+    }
81
+    // Insert id of new box into list
65 82
 }
66 83
 
67 84
 // Registering the location of boxes after a move
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -21,23 +21,23 @@  discard block
 block discarded – undo
21 21
  *       \brief      File to return Ajax response on Box move or close
22 22
  */
23 23
 
24
-if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL','1'); // Disables token renewal
25
-if (! defined('NOREQUIREMENU'))  define('NOREQUIREMENU','1');
26
-if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1');
27
-if (! defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX','1');
28
-if (! defined('NOREQUIRESOC'))   define('NOREQUIRESOC','1');
24
+if (!defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Disables token renewal
25
+if (!defined('NOREQUIREMENU'))  define('NOREQUIREMENU', '1');
26
+if (!defined('NOREQUIREHTML'))  define('NOREQUIREHTML', '1');
27
+if (!defined('NOREQUIREAJAX'))  define('NOREQUIREAJAX', '1');
28
+if (!defined('NOREQUIRESOC'))   define('NOREQUIRESOC', '1');
29 29
 
30 30
 
31 31
 // Copyright (C) 2018 Alxarafe/Alixar  <[email protected]>
32 32
 defined('BASE_PATH') or die('Single entry point through the index.php of the main folder');
33
-require DOL_BASE_PATH . '/main.inc.php';
33
+require DOL_BASE_PATH.'/main.inc.php';
34 34
 require_once DOL_DOCUMENT_ROOT.'/core/class/infobox.class.php';
35 35
 
36
-$boxid=GETPOST('boxid','int');
37
-$boxorder=GETPOST('boxorder');
38
-$userid=GETPOST('userid');
39
-$zone=GETPOST('zone','int');
40
-$userid=GETPOST('userid','int');
36
+$boxid = GETPOST('boxid', 'int');
37
+$boxorder = GETPOST('boxorder');
38
+$userid = GETPOST('userid');
39
+$zone = GETPOST('zone', 'int');
40
+$userid = GETPOST('userid', 'int');
41 41
 
42 42
 
43 43
 /*
@@ -54,27 +54,27 @@  discard block
 block discarded – undo
54 54
 print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
55 55
 
56 56
 // Add a box
57
-if ($boxid > 0 && $zone !='' && $userid > 0)
57
+if ($boxid > 0 && $zone != '' && $userid > 0)
58 58
 {
59
-	$tmp=explode('-',$boxorder);
60
-	$nbboxonleft=substr_count($tmp[0],',');
61
-	$nbboxonright=substr_count($tmp[1],',');
59
+	$tmp = explode('-', $boxorder);
60
+	$nbboxonleft = substr_count($tmp[0], ',');
61
+	$nbboxonright = substr_count($tmp[1], ',');
62 62
 	print $nbboxonleft.'-'.$nbboxonright;
63
-	if ($nbboxonleft > $nbboxonright) $boxorder=preg_replace('/B:/','B:'.$boxid.',',$boxorder);    // Insert id of new box into list
64
-    else $boxorder=preg_replace('/^A:/','A:'.$boxid.',',$boxorder);    // Insert id of new box into list
63
+	if ($nbboxonleft > $nbboxonright) $boxorder = preg_replace('/B:/', 'B:'.$boxid.',', $boxorder); // Insert id of new box into list
64
+    else $boxorder = preg_replace('/^A:/', 'A:'.$boxid.',', $boxorder); // Insert id of new box into list
65 65
 }
66 66
 
67 67
 // Registering the location of boxes after a move
68
-if ($boxorder && $zone != '' &&  $userid > 0)
68
+if ($boxorder && $zone != '' && $userid > 0)
69 69
 {
70 70
 	// boxorder value is the target order: "A:idboxA1,idboxA2,A-B:idboxB1,idboxB2,B"
71 71
 	dol_syslog("AjaxBox boxorder=".$boxorder." zone=".$zone." userid=".$userid, LOG_DEBUG);
72 72
 
73
-	$result=InfoBox::saveboxorder($db,$zone,$boxorder,$userid);
73
+	$result = InfoBox::saveboxorder($db, $zone, $boxorder, $userid);
74 74
 	if ($result > 0)
75 75
 	{
76 76
 	    $langs->load("boxes");
77
-	    if (! GETPOST('closing'))
77
+	    if (!GETPOST('closing'))
78 78
 	    {
79 79
 	       setEventMessages($langs->trans("BoxAdded"), null);
80 80
 	    }
Please login to merge, or discard this patch.
dolibarr/htdocs/core/actions_printing.inc.php 2 patches
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -30,12 +30,12 @@  discard block
 block discarded – undo
30 30
 // Print file
31 31
 if ($action == 'print_file' && $user->rights->printing->read) {
32 32
     $langs->load("printing");
33
-    require_once DOL_DOCUMENT_ROOT . '/core/modules/printing/modules_printing.php';
33
+    require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/modules_printing.php';
34 34
     $objectprint = new PrintingDriver($db);
35 35
     $list = $objectprint->listDrivers($db, 10);
36
-    if (! empty($list)) {
37
-        $errorprint=0;
38
-        $printerfound=0;
36
+    if (!empty($list)) {
37
+        $errorprint = 0;
38
+        $printerfound = 0;
39 39
         foreach ($list as $driver) {
40 40
             require_once DOL_DOCUMENT_ROOT.'/core/modules/printing/'.$driver.'.modules.php';
41 41
             $langs->load($driver);
@@ -43,13 +43,13 @@  discard block
 block discarded – undo
43 43
             $printer = new $classname($db);
44 44
             //print '<pre>'.print_r($printer, true).'</pre>';
45 45
 
46
-            if (! empty($conf->global->{$printer->active}))
46
+            if (!empty($conf->global->{$printer->active}))
47 47
             {
48 48
                 $printerfound++;
49 49
 
50
-                $subdir='';
50
+                $subdir = '';
51 51
                 $module = GETPOST('printer', 'alpha');
52
-                switch ($module )
52
+                switch ($module)
53 53
                 {
54 54
                     case 'livraison' :
55 55
                         $subdir = 'receipt';
@@ -69,21 +69,21 @@  discard block
 block discarded – undo
69 69
                         //print '<pre>'.print_r($printer->errors, true).'</pre>';
70 70
                         setEventMessages($printer->error, $printer->errors, 'errors');
71 71
                     }
72
-                    if ($ret==0)
72
+                    if ($ret == 0)
73 73
                     {
74 74
                         //print '<pre>'.print_r($printer->errors, true).'</pre>';
75 75
                         setEventMessages($printer->error, $printer->errors);
76 76
                         setEventMessages($langs->transnoentitiesnoconv("FileWasSentToPrinter", basename(GETPOST('file', 'alpha'))).' '.$langs->transnoentitiesnoconv("ViaModule").' '.$printer->name, null);
77 77
                     }
78 78
                 }
79
-                catch(Exception $e)
79
+                catch (Exception $e)
80 80
                 {
81 81
                     $ret = 1;
82 82
                     setEventMessages($e->getMessage(), null, 'errors');
83 83
                 }
84 84
             }
85 85
         }
86
-        if ($printerfound==0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
86
+        if ($printerfound == 0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
87 87
     } else {
88 88
         setEventMessages($langs->trans("NoModuleFound"), null, 'warnings');
89 89
     }
Please login to merge, or discard this patch.
Braces   +4 added lines, -3 removed lines patch added patch discarded remove patch
@@ -75,15 +75,16 @@
 block discarded – undo
75 75
                         setEventMessages($printer->error, $printer->errors);
76 76
                         setEventMessages($langs->transnoentitiesnoconv("FileWasSentToPrinter", basename(GETPOST('file', 'alpha'))).' '.$langs->transnoentitiesnoconv("ViaModule").' '.$printer->name, null);
77 77
                     }
78
-                }
79
-                catch(Exception $e)
78
+                } catch(Exception $e)
80 79
                 {
81 80
                     $ret = 1;
82 81
                     setEventMessages($e->getMessage(), null, 'errors');
83 82
                 }
84 83
             }
85 84
         }
86
-        if ($printerfound==0) setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
85
+        if ($printerfound==0) {
86
+            setEventMessages($langs->trans("NoActivePrintingModuleFound", $langs->transnoentities("Module64000Name")), null, 'warnings');
87
+        }
87 88
     } else {
88 89
         setEventMessages($langs->trans("NoModuleFound"), null, 'warnings');
89 90
     }
Please login to merge, or discard this patch.
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.